rpc: Manual prune lock management (Take 2)

bitcoin/bitcoin: PR #34534

1 minor finding · 6 suggestions

Findings

Link

[minor] · -prunelock is installed after IPC block submission becomes available

With -ipcbind and over-target automatic pruning, a trusted client's startup block submission can delete data before -prunelock is installed; this unobserved gap leaves the new option's guarantee incomplete rather than regressing existing startup behavior.

Location: src/init.cpp:2078 (head).

Details and suggested fix

In a multiprocess build, the IPC listener is already running when setChainstateLoaded(true) releases MakeMining, before index initialization and wallet loading. A new valid-PoW block submitted through submitBlock can then reach AcceptBlock and its FlushStateToDisk(NONE). When writing the block allocates a chunk, m_check_for_pruning enables file selection without the configured user locks, which are not registered until Step 10. An over-target store with otherwise-prunable files, such as one retained by a height-0 lock during the previous run, can therefore lose blocks needed for a later rescan. Installing the lock afterwards cannot recover them; the data must be downloaded again. Register the configured locks inside InitAndLoadChainstate before setChainstateLoaded(true), on each initialization attempt.


Optional improvements

Link

[suggestion] · setprunelock success does not indicate block availability

Successful setprunelock creation does not certify block availability, but the help's availability wording does not state that a lock only prevents subsequent pruning.

Location: src/rpc/blockchain.cpp:1050 (head).

Details and suggested fix

The add branch accepts any nonnegative int height without checking block availability, and listprunelocks reports the stored boundary rather than the retained range. A wallet whose required blocks are already absent can therefore still fail to load after successful lock creation. State in the RPC help and release note that a lock only prevents subsequent pruning and neither restores nor certifies existing data. This preserves the ability to create or lower a prospective retention boundary.


Link

[suggestion] · Startup -prunelock test never puts block data at risk

The startup retention check uses -prune=1, so no automatic deletion can occur and the assertions cannot distinguish effective protection from a lock that is merely registered and logged.

Location: test/functional/rpc_prunelock.py:235 (head).

Details and suggested fix

-prune=1 maps to PRUNE_TARGET_MANUAL (UINT64_MAX), so FindFilesToPrune cannot reach its deletion loop for this fixture. Comparing the two log positions would still pass if an earlier automatic-pruning path deleted protected data; the other retention assertions only exercise pruneblockchain. Add a finite-target restart case with enough eligible block data to exceed the target, preferably using the existing large-chain pruning fixture. Assert that a protected block remains readable with the startup lock and is pruned after a control restart without it. The log-order assertion can remain as a supplementary check.


Link

[suggestion] · User prune-lock rollback is documented but untested

The help promises that reorgs lower affected user locks to the common ancestor and leave them there, but rpc_prunelock.py never disconnects blocks or checks the resulting boundaries.

Location: test/functional/rpc_prunelock.py:142 (head).

Details and suggested fix

DisconnectTip lowers every lock above the disconnected block's parent, including user: entries. The at-tip case only adds, lists and removes its lock, so it would not catch rollback skipping user locks or reconnecting blocks restoring their previous heights. Reuse the existing chain to set locks below the intended fork, at the tip and above the tip. Invalidate a recent block and check that only the affected locks move to the common ancestor, then reconsider it and verify that those boundaries stay lowered until an explicit setprunelock update.


Link

[suggestion] · RPC help omits the default lock's pruning and disk effects

By default, setprunelock <id> add uses height 0, preventing pruning while the node can exceed its -prune target, but the RPC help does not explain either operational consequence.

Location: src/rpc/blockchain.cpp:1012 (head).

Details and suggested fix

FlushStateToDisk applies the lock's height limit before either pruning path, and FindFilesToPrune skips protected files even while above target. A stationary manual lock can therefore retain an increasing span of blocks rather than letting the disk target override it. Copy the existing -prunelock help's height-0 and target-exceeded explanations into setprunelock help and the RPC release-note entry.


Link

[suggestion] · RPC help omits how to recreate protection at startup

RPC locks disappear on restart and cannot be recreated through RPC before the explicit startup prune, but setprunelock help does not point to -prunelock or explain that the configured height replaces the last RPC-set height.

Location: src/rpc/blockchain.cpp:1003 (head).

Details and suggested fix

Step 10 calls PruneAndFlush, whereas SetRPCWarmupFinished occurs at Step 13; until then the server rejects setprunelock with RPC_IN_WARMUP. A client that simply retries after startup may therefore return too late to retain old blocks. Extend the non-persistence note with -prunelock=<id>[:<height>] using the same id, and explain that each restart reinstalls the configured height. For example, a bare -prunelock=app restores height 0 even after an RPC update to 500. This documents the existing ephemeral contract without requiring persistence.


Link

[suggestion] · RPC commit documents -prunelock before introducing it

1b2c63d documents a nonexistent startup option; moving those references to 8c8e508 would make the RPC and startup-option commits independently understandable without changing the final tree.

Location: src/rpc/blockchain.cpp:955 at 1b2c63d7ff7f (commit) (commit).

Details and suggested fix

In 1b2c63d7ff7f261ad9153c9294b87b5eafd566e4 (RPC addition), listprunelocks refers to -prunelock and IsValidPruneLockId explains : as a config separator, but src/init.cpp still registers -prune immediately followed by -reindex. The option and ParsePruneLockArg arrive only in 8c8e50880ddcba1563c59a949de1f440aaf2cc6c (startup-option addition). Keep RPC-only wording in the former and move the startup-option references and config-separator rationale into the latter. This preserves the separate feature commits and moves only strings and comments, leaving the final tree and intermediate code paths unchanged.


Coverage details

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

The ten-block prune-lock buffer is a practical reorg margin, not a protocol-derived safety threshold. Its introducing commit says there is nothing special about ten: it exceeds expected ordinary mainnet reorgs while remaining small enough not to noticeably interfere with pruning. Callers were explicitly told not to assume a particular buffer size.

The pinned pruning path subtracts PRUNE_LOCK_BUFFER and one additional block from height_first to obtain the last prunable height. External wallet applications therefore inherit a small defensive margin below their declared boundary, not a guaranteed recovery window on which to base their scan position.

Source 1 · Source 2

Reorg rollback is centralized so protection moves before consumers can react. Luke Dashjr explained that keeping locks in BlockManager lets it shift affected locks backward during a reorganization, preventing pruning before clients even know they need an older height.

The base code lowers every affected lock to the parent height on each disconnect, before a possible disk flush. Repeated disconnects lower it to the common ancestor. The new RPC exposes these same semantics, including that the lowered boundary stays there rather than automatically returning to its former height.

Source 1 · Source 2

Backward-moving protection was not intended to guarantee recovery of already-pruned data. In #21726, reviewers distinguished allowing a lock to move backward from the consumer's responsibility to handle unavailable blocks safely while rewinding or syncing.

This bounds the meaning of an externally supplied rescan lock: establishing or lowering a retention boundary is prospective protection, not evidence that all required historical blocks remain available. The ordinary-reorg buffer and rollback rule address different parts of that problem.

Source 1 · Source 2 · Source 3

Persistence was left outside the scope of the internal-index implementation, rather than rejected as unsuitable for all locks. #21726 explicitly contrasted its narrower design with #19463's persistent blockers and RPC management, saying those additional features were unnecessary for its internal-index goal. The external proposal specifically included offline wallets and applications.

Existing in-memory internal locks do not by themselves establish the appropriate restart contract for external wallet protection. The current RPC explicitly promises restart-ephemeral locks, while the startup option provides a separate way to recreate protection.

Source 1 · Source 2 · Source 3

Operator control over stale locks was an explicit external-lock design goal. #19463 allowed users to remove application locks because the application that created a lock might no longer be used.

Manual removal is part of retention ownership, not merely an administrative convenience. The pinned interface separates user-created names from internal names and permits user-lock updates and removal, while internally managed indexes continue advancing their own boundaries.

Source 1

Startup ordering has long protected rescans from destructive maintenance. The 2015 change delaying initial pruning until after wallet initialization explicitly aimed to avoid deleting blocks that a wallet rescan still needed.

The head retains that ordering: indexes initialize, wallets load, then explicit initial blockstore pruning occurs. The startup locks are installed immediately before that pruning step. The historical principle is that protection or consumption of required data must precede deletion; runtime RPC availability alone does not establish that ordering.

Source 1

Retaining blocks for consumers already took priority over immediate pruning. The earlier blockfilter-index proposal explicitly disabled manual pruning during index synchronization and delayed automatic pruning; the generalized lock design required consumers to advance their boundaries when ready to permit further pruning.

Locks constraining both manual and automatic pruning are inherited behavior. The new external interface exposes that retention priority to application-managed boundaries rather than introducing a fundamentally different relationship between consumer progress and deletion.

Source 1 · Source 2

Ralph's inferences

The historical reorg assumptions transfer most directly to external wallets that follow a chain and maintain an earliest-needed block boundary. Central rollback remains useful when such a client is disconnected or slow to receive notifications. The ten-block buffer does not, however, represent how long that wallet may remain offline: continued retention comes from leaving its lock in place.

The RPC feeds the same height-based lock map used by indexes. Historical evidence supports this chain-following retention model, but does not establish that ten blocks suffice for every wallet's rescan policy or unusually deep reorg requirements.

Source 1 · Source 2

An ephemeral internal lock can still provide restart-spanning protection when its owner reconstructs it from durable progress before pruning. That is distinct from persisting the lock itself: index initialization reads its saved best-block locator and calls the method that installs its prune lock. An external owner needs a separate restart contract because the node does not perform that reconstruction on its behalf.

The new runtime lock disappears on restart. The startup option recreates a configured boundary before the explicit startup prune; it does not persist the RPC-updated height. Thus internal precedent explains how ephemeral state can work, but not why an absent external client would remain protected automatically.

The prune target is subordinate to the eligible deletion range, not an unconditional disk ceiling. The base implementation skips protected files even while above target. A stationary external lock can therefore retain an increasing span of blocks; its principal disk cost is consumer inactivity, not the small reorg buffer.

Exposing locks transfers progress and cleanup responsibility to the application or operator. The historical concern about abandoned applications is consequently material to disk-target expectations, without implying that retention should be silently overridden.

Source 1