Skip to content

net: defer compact filter requests that race the filter index - #35354

Open
randomlogin wants to merge 4 commits into
bitcoin:masterfrom
randomlogin:p2p-cbf-wait-for-indexed
Open

randomlogin wants to merge 4 commits into
bitcoin:masterfrom
randomlogin:p2p-cbf-wait-for-indexed

Conversation

@randomlogin

@randomlogin randomlogin commented May 21, 2026 •

Copy link
Copy Markdown

This PR defers cfilter-related P2P messages if they ask for information from a new block which has been validated, but compact filters are not yet constructed. This PR is a prerequisite for a bigger change of decoupling index construction from block connection to make block announcement faster.

Fixes: #29655, #27085
Related discussion: 1

When a new block arrives, block connection has several steps (described very broadly):

  1. block connection to the active chain
  2. and then comes indices construction (compact block filters index, txdindex) and also wallet updates

If a light peer sends getheaders after the first step has passed, but the second has not, the light peer would
then send getcfheaders (or another cfilter request) with the stop hash of the new block. Core has no filters yet and thus doesn't answer, and the light peer thinks Core misbehaves and disconnects.

This race condition is extremely rare right now, because normally headers are received via BIP130 and in that case the light client would not receive a new header until Core is ready to serve the filters (Core does not announce block until the filters are constructed, but can respond with a new header if explicitly asked). So to hit the race condition, the light client has to actively poll the Core node with getheaders.

Active polling is not prohibited by BIP157 and in my opinion it should not be (at the very least, light clients need
to sync and have to send getheaders with a zero stop hash, which might hit the race). Once Core has sent the block in a headers reply, the stop hash "is known to belong to a block accepted by the receiving peer".

This race condition would occur far more frequently (on every new block if light client is fast enough) if new header
announcements were made without waiting for index construction (which we'd love to see in the future). It is discussed here: #35023. In that case light clients would receive new header announcements from Core without the need to actively poll it.

The approach used (via #35023 (comment)) is to stop processing all messages from a peer if there is a request from it which we cannot answer right now, but will be able to shortly. So this PR introduces a way to stop processing requests from a peer, which later can be used to park a peer who sent us a new block (#35354 (comment)).

What it adds:

A getcfilters, getcfheaders or getcfcheckpt request that is racing the filter index is parked instead of being ignored:

  1. PeerManagerImpl::ShouldDeferCFilterRequest checks whether a request is racing the index construction: the index is synced, but has not yet caught up with the tip, and does not cover the requested stop hash yet. It never defers during IBD, where the index can lag the tip for a long time.
  2. If so, the request is stored in the peer's m_pending_request and we stop processing further messages from that peer. This keeps responses in order; other peers and outgoing messages are not affected.
  3. The parked request is retried whenever we process that peer's messages, at most once every 100ms (PARKED_CF_RETRY_INTERVAL) to avoid taking cs_main too often.
  4. If the request is still parked after 5s (MAX_CF_PARK_INTERVAL), we stop waiting and serve what we can: the peer gets the answer if the filters exist by then, otherwise the request is ignored, as it was before this PR. The peer then continues to be processed normally.

A new cfilter_race_tests suite (src/test/cfilter_race_tests.cpp) uses a PreFilterBlocker CValidationInterface registered before the filter index, so its own BlockConnected fires first on the scheduler thread and stalls it before the filter index gets to run CustomAppend. This reproduces the race window deterministically. The tests drive the real message processing path via ConnmanTestMsg and advance the mocked clock where time matters.

Cases covered:

  • deferred_cfilter_response_reaches_peer — a racing getcfilters is parked, not answered and not dropped, and is answered once the index catches up.
  • deferred_cfheaders_response_reaches_peer — the same for getcfheaders.
  • pending_request_pauses_message_processing — while a request is parked, a later ping from the same peer is not processed, and the responses come back in request order.
  • parked_request_retries_are_throttled — a parked request is not retried before the retry interval has passed, even if the filter is ready.
  • parked_request_is_released_after_timeout — after the park timeout the peer is no longer paused (a later ping is answered), and no filter is sent for a filter that does not exist.

I've used Claude Code for this PR.

P.S. Light clients (kyoto, neutrino) also do cross-polling: they ask for filters from a peer that didn't announce the
block, naturally receive no answer, and might disconnect it. Disconnection due to cross-polling occurs more frequently than those due to active polling and this PR does not address it directly, as it IMO is a mistake by light clients, not Core's one. Still, this PR gives such cross-polled filter requests an additional window to resolve if the asked node is in the process of filter construction.
Related neutrino discussion: lightninglabs/neutrino#338.

@DrahtBot DrahtBot added the P2P label May 21, 2026
@DrahtBot

DrahtBot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Conflicts

No conflicts as of last run.

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/26255963544/job/77353717155
LLM reason (✨ experimental): CI failed because ctest detected a test failure in cfilter_race_tests (1 test failed).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@randomlogin
randomlogin force-pushed the p2p-cbf-wait-for-indexed branch from fff4fe5 to b68a721 Compare May 22, 2026 10:50
@randomlogin

Copy link
Copy Markdown
Author

Squashed two commits in one (previously there was a distinct commit for tests addition).

@sedited

sedited commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Reading through this, I don't think this should be handled on the index level. While I'm still not sold that this is not something that is just a bit flawed in the spec, I would prefer an approach where net_processing dealt with this directly in the case of an index query returning nothing by checking if the requested block lies in the two block tolerance range and if so syncing the validation interface queue.

@sedited

sedited commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

@randomlogin how do you want to proceed here?

@randomlogin

Copy link
Copy Markdown
Author

@sedited sorry for a long response.

There are two ways: the first one is simply to move race-window check logic to net_processing and then again wait for SyncWithValidationInterfaceQueue.

On the other hand, instead of blocking the caller (msghand) on SyncWithValidationInterfaceQueue completion, on a request and hitting the race-window (known block, no filters yet) we could remember the peer awaiting response, move on to other work happening and once the filters are constructed send a response.

Something like PeerManagerImpl::ProcessPendingCFilterRequests.

This will not block other p2p messages while we wait for filters being constructed.

However I'm not sure that it's worth, as with the window gap being small enough we'd save only fractions of second. Additionally we could use WakeMessageHandler to avoid waiting next loop iteration (up to 100ms).

Does that sound right to you?

@ajtowns

ajtowns commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

On the other hand, instead of blocking the caller (msghand) on SyncWithValidationInterfaceQueue completion, on a request and hitting the race-window (known block, no filters yet) we could remember the peer awaiting response, move on to other work happening and once the filters are constructed send a response.

That seems like a plausible approach to me, fwiw. Just set a flag in ProcessMessage when you receive the request that this peer wants a a cfilter response, then in SendMessages attempt to handle the cfilter requests, deferring it to a later call if the block is pending.

That will mean cfilter responses for that peer may be out of order vs other messages on that connection, but I think that's okay?

@mzumsande mzumsande left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem formulation in the OP is not precise: Currently, when we receive a block, we first build the filter and then advertise the block, so there usually is no race.The race can only happen if the client asks for the newest headers themselves unprompted. This could happen because they just newly connected, or because they do active getheaders polling for some other reason. But this explains why this is very rare.

In my opinion, both a SyncWithValidationInterfaceQueue call in net_processing (it's not like we have anything more urgent to do than processing the block anyway?) and to schedule it for later sound fine.

@randomlogin

randomlogin commented Jul 29, 2026 •

Copy link
Copy Markdown
Author

The problem formulation in the OP is not precise: Currently, when we receive a block, we first build the filter and then advertise the block, so there usually is no race.

OP is precise for BIP152 block transmission, when we go through BIP152, we transmit compact block header to peers before we run BlockConnected which internally calls filters construction. (To be accurate, I wrongly called it advertising, but rather it is an actual sending of the header).

Also I took a moment to review how other requests are handled when we announced compact block header:

  • if a peer asks getheaders in the moment we have not yet connected the block, they will receive stale response
  • getdata for a block - we synchronously connect the block and then respond (which blocks all other peers for the time block connects)

Then maybe it is better to have some kind of a unified approach for both getdata and getcfilters, for example both block and wait for block connection/filters constructions to complete?

Deferring and responding later does not increase blocking time, and personally is more appealing and I'd go this way.

@mzumsande

mzumsande commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

OP is precise for BIP152 block transmission

But how does this make sense / how is this a relevant use case? To be chosen as a high-bandwidth block relay peer, you need to be a full node. In this case you don't need to download the blockfilters for new blocks from peers - this is a feature meant for light clients.

@randomlogin

Copy link
Copy Markdown
Author

@mzumsande you are right, I confused BIP152 with BIP130 (light clients use BIP130). And as you pointed, this bug cannot happen with BIP130 header transmission.

@ajtowns

ajtowns commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

In my opinion, both a SyncWithValidationInterfaceQueue call in net_processing (it's not like we have anything more urgent to do than processing the block anyway?)

My understanding is that the way we currently work is:

  • send the compact block info to peers that have requested high bandwidth cb relay ASAP
  • pause the message handling thread to validate the block
  • queue the cfilter updates for another thread
  • send headers and inv messages to non-cb and low-bandwidth cb peers
  • resume the message handling thread
  • message handling thread "immediately" processes a cfilter request, and we attempt to respond before the cfilter updates have finished

Apart from the hb compact block path, we don't announce blocks until we've validated them, but we do announce them before we've calculated their compact filter.

I don't think we should block the message handling thread further, because we do have more important things to do: responding to getblocktxn requests that came in while we were validating the block (ideally we'd be responding to those requests while validating the block), and getdata requests that came in after our headers message.

Those "immediate" requests could come from peers that selected us as hb for cb, or could just be a very quick response to a headers announcement compared to the calculations required to update the compact filters. I think those calcs are slow enough that this is likely to occur occasionally even for peers that aren't getting the high-bandwidth compact block path, so is worth handling, but it would probably good to confirm the exact flow and timings? (How long does calculating the compact filters actually take? How much does that vary across blocks? What's the real turn-around time for real compact filter clients between seeing a header and requesting the compact filter?)

@mzumsande

Copy link
Copy Markdown
Contributor

Yes, that makes sense - I hadn't thought of getblocktxn requests.

  • send headers and inv messages to non-cb and low-bandwidth cb peers
  • resume the message handling thread

I'd say it's

  • queue the headers and inv message to non-cb and low-bandwidth cb peers for the other thread (UpdatedBlockTip())
  • resume the message handling thread which sends out headers and inv messages to non-cb and low-bandwidth cb peers once the queue entry has been processed

@randomlogin
randomlogin force-pushed the p2p-cbf-wait-for-indexed branch from b68a721 to 6c325d0 Compare August 5, 2026 01:29
@randomlogin

Copy link
Copy Markdown
Author

Changes

Added deferring of a response, we store the racing request in a PendingCFilterRequest struct in a Peer and then check it in SendMessages.

To avoid code repetition, added a helper TryRespondToCFilterRequest which is used in both original ProcessGetCFilters and SendMessages handlings of a request.

Rewrote the test.

If we receive two requests while the first one has not yet been responded, we do not overwrite it, thus responding only to the first one.

Benchmarks

Added benchmarks commit (b1d4868) to this PR (I'll squash it later).

Here is the data for the initial filter construction since genesis as well as for processing during normal operation, i.e. I have an already running node in which I turned on filters and measured the times. Initial blocks' measurements are shown over latest 100k blocks, since ~861k).

Metric mean median p90 p99 max
Cfilters construction (from 861k initial) 4.50ms 4.50ms 6.74ms 8.04ms 112.86ms
Cfilters construction (212 live blocks) 5.92ms 6.10ms 8.35ms 11.33ms 13.96ms
Connect block (212 live blocks) 172.85ms 51.14ms 63.89ms 4408.39ms 10423.97ms

Maximum time (112 ms for filters construction) is perhaps some I/O problem or something else not connected to normal behaviour. All times include I/O.

We can say filters processing takes around 10% of block processing.

Computer that runs benchmarks has the following specs:

  • CPU: Intel Xeon E5-2686 v4 (Broadwell) — 2 vCPUs, 2.30GHz, 1 thread/core
  • RAM: 3.8GB

Going further

  1. Currently only added handling getcfilters, but the same bug stands for other bip157 requests: getcfheaders and getcfcheckpt. It is even less likely for them to encounter a race, do we want them handled in the same way?

  2. Should we call m_connman.WakeMessageHandler() in block connection, or the current approach is fine?

@randomlogin
randomlogin force-pushed the p2p-cbf-wait-for-indexed branch from cef32b9 to 1526b81 Compare August 26, 2026 14:26
@randomlogin

randomlogin commented Aug 26, 2026 •

Copy link
Copy Markdown
Author

I took some time to gain more understanding on how net_processing works and your comments make a perfect sense.

Some suggestions on top of your commit:

  1. Added a guard for initial block download.
    On a fresh node with enabled compact filters PeerManagerImpl::CFilterIndexMayBeRacing would return true, meaning we pause the peer for the whole duration needed to construct filters from the genesis block, which takes hours.
    Also we could store a timestamp when parking occured and release the pause if it takes too long, though I am not sure if it is really needed.

  2. Now we have several cases where we process peer's messages not in a "usual" way, when we might return early and not poll any new peer's messages.

    These cases are:

    • continue responding to a huge getdata message
    • parked a compact filter related message
    • we processed an orphan tx and have a result
    • in future here will be a case when we validate a block broadcast by this peer, we early exit if we haven't finished yet

    Should we combine all of the above into something like PreprocessMessages or ProcessAwaitingMessages or ProcessPausedPeer?

  3. Made minor renamings in your code.

  4. Here are some claude-coded benchmarks, I ran them locally on my computer.

  • AttemptParkedRequest() is retried on every ProcessMessages() pass for a peer with a pending
    request, not gated on new traffic — so n parked peers add n extra cs_main acquisitions to every
    message-handler sweep for as long as they stay parked.

    Per-call cost (bench_bitcoin, isolated — both paths take cs_main, differ in what's done under it):

    path ns/op
    not racing (Tip() compare only) 66
    racing (2 lookups + ancestor walk) 99

    Negligible alone — microseconds/sec even at high parked-peer counts. The real cost is repetition,
    not the call.

  • Retry-rate impact (regtest, P2P sim). Natural race windows are sub-ms, too short to observe
    anything here, so the filter index's per-block indexing was artificially delayed ~200ms to hold the window open long enough to measure — this is a stress test of what happens if the window ever widens (slow index, edge case), not a description of current behavior.

    With that delay in place: ThreadMessageHandler's idle sleep is 100ms, so n parked peers add up to 10·n acquisitions/sec. n peers parked on getcfilters vs. n peers sending an ordinary getdata (control — resolves immediately, no repeat cost), measuring an unrelated peer's ping RTT:

    n +cs_main acq/s racing max control max
    10 100 101ms 51ms
    50 500 152ms 52ms
    100 1,000 302ms 51ms

    Control stays flat; racing tail grows with the acquisition rate — isolates the effect to parking, not to connection count. Since this depends on an artificially widened window rather than natural behavior, it supports bounding max parked duration with a timeout rather than leaving it open-ended, but isn't evidence of a problem today.

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task macOS native, fuzz: https://github.com/bitcoin/bitcoin/actions/runs/32980342303/job/98234423973
LLM reason (✨ experimental): CI failed because the fuzz target rpc hit an error (“Error processing input …”), returning exit code 1.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@maflcko maflcko closed this Aug 27, 2026
@maflcko maflcko reopened this Aug 27, 2026
@randomlogin
randomlogin force-pushed the p2p-cbf-wait-for-indexed branch from 1526b81 to 4849c05 Compare August 27, 2026 07:11
@randomlogin
randomlogin requested a review from ajtowns September 7, 2026 10:36
@randomlogin

Copy link
Copy Markdown
Author

@ajtowns what do you think?

@ajtowns ajtowns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, I think. PR description needs an update.

Comment thread src/net_processing.cpp Resolved
Comment thread src/net_processing.cpp Resolved
Comment thread src/net_processing.cpp Resolved
Comment thread src/net_processing.cpp Resolved
randomlogin and others added 4 commits November 5, 2026 02:37
…sing

Move the serving logic of the getcfilters/getcfheaders/getcfcheckpt
handlers into ServeGetCFilters()/ServeGetCFHeaders()/ServeGetCFCheckPt(),
so they can be reused when the request gets parked in the next commit.
No behavior change.

Co-authored-by: Anthony Towns <[email protected]>
Previously compact filters requests might falsely be ignored because
the requested block has been connected to the chain, but the filters
have not yet been constructed.

This commit adds deferring of such racing requests. We store the pending
request in a per-peer `m_pending_request`, and defer processing further
messages from that peer until the pending request can be dealt with.

Checking if we have a race condition is done via inspecting `GetSummary`
of the index. Pending requests are resolved when the index catches up
with the tip, or when the requested stop hash is covered by the index.

Also adds a unit test for the race-condition.

Co-authored-by: Anthony Towns <[email protected]>
During IBD, answer cfilter requests immediately instead of parking them

Co-authored-by: Anthony Towns <[email protected]>
Changed PendingRequest into a struct. Added `park_time` and
`last_retry_time` fields to a parked cf request.

We prevent retrying to respond to the same parked request if the
previous attempt was less than `PARKED_CF_RETRY_INTERVAL`.

If a request is parked for longer than `MAX_CF_PARK_INTERVAL`, we serve
what we can (and clear the parked request) to start processing further
peer's messages.

Added two tests for the above behaviour.

Co-authored-by: Anthony Towns <[email protected]>
@randomlogin
randomlogin force-pushed the p2p-cbf-wait-for-indexed branch from 0dc77bc to 8520f9c Compare November 5, 2026 01:45
@randomlogin randomlogin changed the title net: wait for validation queue flush for missing compact filter for an already known block net: defer compact filter requests that race the filter index Nov 5, 2026
@randomlogin
randomlogin requested a review from ajtowns November 5, 2026 02:13
@DrahtBot DrahtBot closed this Nov 19, 2026
@DrahtBot DrahtBot reopened this Nov 19, 2026

@mzumsande mzumsande left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The OP is still not describing the problem correctly, as I mentioned in #35354 (review).

Given the extent of the changes to net_processing for what seems like a special-case problem to me (only light clients doing active polling for headers instead of waiting for block notifications are affected), I think this need a better and more precise motivation as to why this is important enough.
If the goal is enabling cross-polling, i.e. asking BIP157 peer A for a filter of a block that only peer B announced to us (which is currently not permitted by the BIP but apparently still done by some implementations) is the goal, this should be stated and the BIP should be adjusted.
Alternatively, this could be motivated as a step towards a major change of the net_processing code towards more async behavior to tackle problems like #35023 (this is @ajtowns angle in #35354 (comment)), but this should also be stated explicitly in the OP.

@randomlogin

Copy link
Copy Markdown
Author

@mzumsande thanks for your comments, I changed the PR description in favor of a prerequisite step towards more async block validation and block broadcast.

About changing the BIP:

  1. Cross-polling is light clients' implementation bug, they have to be sure they ask only a peer who advertised a
    block, so they should not cross-poll or do it carefully, not disconnecting a slow peer (and slow peers naturally occur).

    And yes, there are implementations which do cross-polling (for example https://github.com/2140-dev/kyoto, also Neutrino), I've opened an issue there about that.

    This is correctly specified in the BIP (StopHash MUST be known to belong to a block accepted by the receiving peer). So in general it seems we should not address it here or in any other PR.

  2. Active polling (light clients do that, both Neutrino and Kyoto).
    It is allowed by the BIP and I don't see a good way to fix it there: I think specifying the way a light peer gets to know about a new block (via listening to headers instead active polling) would go too much into implementation detail and supposes the way headers arrive to the light node. In case there will be another way of obtaining headers, it would need to address it too (but maybe it is okay?).

    If we try to model desired situation in which light clients only listen to headers, this can work with a long-living peer. But if a light client connects to a new peer and sends sendheaders, Core wouldn't know what is light client's tip and fallback to inv with subsequent getheaders from a light peer. In that sense at least some getheaders are inevitable and can trigger the PR's bug (though quite rare to say the least).

Still I thought we could

  1. explicitly prohibit naive cross-polling in the BIP.
  2. another thought is that we could add zero stop hash to filter-related requests in the same fashion it is done for getheaders. Though I am not 100% sure it is safe to do so and it needs some additional brainstorming.

Also I when opened this PR I emailed BIPs authors, but received no response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CFilters reject and disconnect peers with a valid block hash

6 participants