utxo split/7 async handoff

willcl-ark/bitcoin: PR #46

1 minor finding · 8 suggestions

Findings

Link

[minor] · IBD request budgeting traps high-latency peers at one outstanding block

During IBD, consistently greater-than-two-second request latency keeps the download budget at one despite possible pipelined throughput; the impact on real Tor/I2P connections has not been measured.

Location: src/net_processing.cpp:7052 (head).

Details and suggested fix

SendMessages() starts a fresh delivery measurement whenever the peer has nothing left on the wire. With one request outstanding, each sample therefore includes the entire round trip, transfer and remote processing time. If those samples remain above two seconds, smoothing keeps m_block_delivery_time above that threshold and integer division in BlocksToAskFor() keeps returning one. The node never obtains pipelined samples that could reveal the peer's actual delivery rate, whereas the base allowed sixteen outstanding requests. p2p_ibd_request_rule.py asserts the four-second case but does not distinguish high latency from low throughput. Estimate sustained delivery from pipelined inter-arrival samples, allowing probe requests to obtain them, rather than letting idle request latency permanently determine the budget.


Optional improvements

Link

[suggestion] · IBD-exit ordering lacks a gated receive-task test

The added tests do not distinguish draining receive tasks before capturing the connector ticket from waiting only on the connector when IBD ends.

Location: src/net_processing.cpp:4161 (head).

Details and suggested fix

PeerManagerImpl::WaitForPendingBlocks() must drain receive tasks before the chain manager captures its ticket, because an outstanding task may not have handed its block to the connector yet. The handoff test keeps genesis-dated tips, while the tip-connector test leaves IBD before its scenarios and uses one worker; neither holds a task across the transition. Add a gated multi-worker test that pauses a requested block before FinishNewBlock(), lets another block end IBD, and sends a valid transaction spending an output created by the held block. Verify that processing waits for both the task and its activation, then admits the transaction without first storing it as an orphan. Arrange the gates so deleting the drain or capturing the ticket before it makes the test fail.


Link

[suggestion] · GETBLOCKTXN read-failure handling has no regression test

Existing tests do not force the new disconnect-on-read-failure path, so they do not distinguish it from the previous assert.

Location: src/net_processing.cpp:5098 (head).

Details and suggested fix

feature_io_errors.py already renames blk00000.dat to force read failures, but checks only RPC and REST. Extend that scenario with a nonempty GETBLOCKTXN request, such as transaction index 0, for a stored block within MAX_BLOCKTXN_DEPTH that is not the cached most-recent block. Assert that the requester disconnects, receives no BLOCKTXN, and leaves the node responsive. Restore the file and verify that a fresh peer receives the requested transactions. This exercises the changed error handling deterministically without timing a pruning race.


Link

[suggestion] · Being-stored GETDATA and source retention lack gated coverage

The added tests observe blocks only after storage, leaving the GETDATA retry and being-stored source-retention branches without a controlled regression test.

Location: src/net_processing.cpp:2770 (head).

Details and suggested fix

p2p_failed_block_not_served.py requests blocks after the sender's pong or disconnect, and p2p_block_source_duplicate.py waits for A's pong before B sends its copy. Neither observes the being-stored interval, when GETDATA must remain queued without spinning and BlockProcessed() must retain the first recorded source. Add a staged fixture or hook that holds a tip block after AcceptNewBlock(), processes a request and a duplicate from separate peers, then completes storage. Check source retention and eventual serving or refusal after activation, including retry progress through the handler's periodic wake when a non-receive-task producer finishes. Outside IBD the network handler performs its own write, so this needs a concurrent producer or a hook. The fixture must also record the peer source explicitly, since AcceptNewBlock() alone does not.


Link

[suggestion] · Receive-task lifetime lacks a gated regression test

Without a stage-gated test, early task-set removal could escape deterministic coverage of both the reserved-worker bound and shutdown drain.

Location: test/functional/p2p_ibd_block_handoff.py:84 (head).

Details and suggested fix

A task in RunBlockIO() still owns a finishing continuation that takes cs_main. Its task-set entry must continue reserving a slot, and FinishBlockTasks() must not treat the owner as quiescent before that continuation and its bookkeeping finish. The implementation keeps this ordering, but p2p_ibd_block_handoff.py only sends bursts without stage gates. Add a two-worker test that pauses a task during I/O and before finishing, verifies its slot remains occupied while another handoff waits, and checks that unrelated validation can still run. In a separate drain phase, verify that FinishBlockTasks() cannot return until the finishing work is released.


Link

[suggestion] · Most functional tests disable the default IBD receive-task path

Most functional tests use prevoutfetchthreads=1, unlike production defaults, so existing requested-block scenarios usually exercise only the handler path during IBD.

Location: test/functional/p2p_ibd_stalling_handoff.py:8 (head).

Details and suggested fix

util.py gives test nodes one connect worker, making LockTaskLimit() zero and causing HandOffBlock() to decline every block. Production defaults to at least two workers. The explicit larger-pool coverage is confined to p2p_ibd_block_handoff.py, p2p_ibd_stalling_handoff.py, feature_connect_window.py and feature_block.py. Add a runner or CI variant that runs the existing P2P and IBD tests with at least two workers, while retaining the resource-saving default for ordinary runs. This would apply existing requested-block error and permission scenarios to receive tasks as well. One worker still covers connector activation outside IBD; the missing breadth concerns receive-task processing.


Link

[suggestion] · Total-completion state has no production reader

The connector records total completion, but production scheduling and waiters use only the taken and active-chain marks.

Location: src/validation.cpp:7547 (head).

Details and suggested fix

m_done is written by AllAttempted() and read only through Attempted() and AnyUnattempted(), whose callers are confined to handoff_machine_tests.cpp. Unlike the base loop, ConnectorLoop() now schedules work with AnyQueued(). Its end-of-pass YieldHistoricalActivation() recheck only decides whether to update this unobserved completion state; the actual yielding already happens during activation. Remove m_done, its total-completion methods and this recheck, and simplify the documented state machine and tests accordingly. Keep the active-attempt ordering assertion in Take(). This removes a completion contract and extra synchronization without changing production behavior.


Link

[suggestion] · The adaptive request policy shares the handoff commit

c90f3b00c41d combines handoff mechanics with an independent request policy, preventing separate review and bisection of their behavior changes.

Location: src/net_processing.cpp:145 at c90f3b00c41d (commit) (commit).

Details and suggested fix

c90f3b00c41d0bdf8e52873cfb2000ca047271c4 introduces the handoff together with BLOCK_DOWNLOAD_QUEUE_TIME, delivery-time smoothing and BlocksToAskFor(). The policy runs before handoff selection, and p2p_ibd_request_rule.py tests it with the single-worker default. Extract that policy and its test into a following commit, leaving with_pool accounting and the tip-based download window with the handoff. The intermediate state would retain up to sixteen requests per peer, a performance tradeoff rather than a safety or build failure. Keep 8366a1a37d5d006e7f3cd82e021698dda5b3840c, which moves previous relay-data destruction off the block path, separate as it is now. This would isolate request-policy review from task lifetime, pong ordering and shutdown.


Link

[suggestion] · reduce-memory.md understates receive-task retention

The guide gives only a task count and says blocks wait for a thread, but tasks retain parsed blocks through storage and their memory grows with -prevoutfetchthreads.

Location: doc/reduce-memory.md:52 (head).

Details and suggested fix

A queued receive task can hold a wire message of up to 4 MB, and during parsing it also holds the parsed block. The raw message is released after the first stage, but the parsed-block reference remains through the I/O write and finishing step. This is bounded by workers minus one, up to 1023 tasks, rather than by an independent byte budget. Document the peak message-plus-parsed-form cost and that task-held blocks remain until storage finishes, not merely until a worker starts. That would let users choosing a large thread count account for this memory alongside the guide's other IBD consumers.


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

Early compact-block relay deliberately separates announcement from full UTXO validation. The corresponding punishment exemption is necessary because an honest relayer may not yet know that a transaction spends nonexistent or already-spent outputs.

Historical PR #9026 expressly fixed punishment after compact-block reconstruction and introduced protocol-version discrimination for the changed behavior. This makes block-source identity and the full-versus-compact provenance flag security-relevant across asynchronous processing, rather than incidental bookkeeping.

Source 1 · Source 2

The historical early-relay design retained a separate validity gate for ordinary block requests. Caching an announced block avoided repeated deserialization, but did not make that block safe to serve indiscriminately.

PR #9375 explicitly said other requests still needed cs_main and a check that the block had not been rejected. A later change moved ActivateBestChain outside cs_main while retaining activation before relay eligibility checks. The head's announced-block storage wait and subsequent activation/eligibility checks address this existing contract; connector completion alone is not the storage-publication gate.

Source 1 · Source 2

Validation-queue backpressure exists to prevent memory growth when connection outruns subscribers, but waiting for that queue creates deadlock constraints on callers and callbacks.

The 2018 documentation change explicitly warned that ActivateBestChain from a validation callback could deadlock. The antecedent ordering proposal extends that principle to queued work and locks. The base connector contract consequently excludes cs_main-held waits and explains why wallet-originated BroadcastTransaction must not acquire the peer-message ordering barrier: the scheduler may need the wallet lock to drain callbacks.

Source 1 · Source 2

The antecedent concurrency design preserved two publication boundaries: a block advertised as stored must be complete, and committed coins must correspond to the published tip whenever cs_main is released.

PR #43 describes the intermediate 'being stored' state, duplicate suppression, and pruning pins. PR #45 requires commit and publication in one lock hold, ordered subscriber notifications, and authoritative retry of provisional window failures. Receive-side concurrency therefore inherits storage, tip, and verdict boundaries; distributing work among threads does not replace them.

Source 1 · Source 2

Ralph's inferences

Synchronous handling supplied an implicit message-order barrier, not a guarantee that every received block had itself been fully validated.

At the base, peer blocks use ProcessNewBlock's synchronous default, which returns after the best known valid chain is activated but explicitly does not promise validation of the particular supplied block. The head replaces this implicit sequencing with explicit waits for tip-dependent messages: transaction inputs, tip-reset reject filters, active-chain header/filter responses, and compact-block distance decisions. These are local processing guarantees, not new wire-protocol rules.

Invalid-block attribution must survive until the eventual connection verdict, including when a block arrives before its parent or another peer supplies a duplicate.

The base BlockChecked uses the recorded source and provenance to decide punishment and then erases the record, while the base duplicate-processing path can also erase it. Thus synchronous handling was not an unconditional first-sender-attribution guarantee. The head deliberately retains the first source while a stored or being-stored block awaits a verdict, and checks the peer's bad-block mark before queued getdata, orphan work, or another message.

The receive-task bound is a pool-liveness condition, not merely throughput tuning: at least one worker must remain outside tasks that can block on cs_main.

DrainWindow waits for validation workers while holding cs_main and releases dependent views only after they finish. If all shared-pool workers instead waited for cs_main in receive tasks, those validations could not run. The head limits outstanding receive tasks to workers minus one, including their I/O and finishing stages. Writes run on separate I/O threads; cs_main-taking completion returns to the worker pool. With fewer than two workers, handoff is declined.

Historical-chainstate yielding balances foreground latency against historical-validation starvation, and active completion must remain distinct from completion of both chainstates.

The base explains that, outside IBD, messages wait for active blocks and a historical backlog may be long; during IBD, yielding to every arriving block would starve historical validation. Its connector already maintained active and total completion counters. The head's tickets preserve that distinction, but pongs and stalling now observe active-attempt completion rather than the old total-completion predicate. A ticket records an activation attempt, not proof that its block became valid or entered the active chain.

IBD exit requires a barrier covering work not yet visible to the connector; a connector ticket by itself cannot cover receive tasks that have not stored and handed over their blocks.

The head reads one processing-mode snapshot for an operation. A tip-mode message first waits for outstanding receive tasks, then snapshots and waits for connector completion; download-mode operations omit both waits. This makes the transition obligation explicit. Pongs separately wait for their peer's tasks before capturing a ticket, with a documented exception for duplicate blocks being stored by another producer.

Shutdown completion is a lifetime and quiescence guarantee, not a promise to connect every accepted block before exit.

The head stops message production, drains receive tasks while their dependencies still exist, then stops the connector before the scheduler and chainstate teardown. Task-set membership lasts through final storage bookkeeping and handoff. Connector waits can terminate on stop, interrupted passes skip activation, and late external submissions after connector stop remain stored for a later node start. Consequently, preservation through shutdown means avoiding stranded waits and access to destroyed owners, not treating every completed ticket as successful validation.