mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 14:08:37 +00:00
net: defer compact filter requests that race the filter index #35354
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35354
Loading…
Reference in a new issue
No description provided.
Delete branch "p2p-cbf-wait-for-indexed"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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: https://github.com/bitcoin/bitcoin/issues/29655, https://github.com/bitcoin/bitcoin/issues/27085
Related discussion: 1
When a new block arrives, block connection has several steps (described very broadly):
If a light peer sends
getheadersafter the first step has passed, but the second has not, the light peer wouldthen 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
getheaderswith a zero stop hash, which might hit the race). Once Core has sent the block in aheadersreply, 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: https://github.com/bitcoin/bitcoin/issues/35023. In that case light clients would receive new header announcements from Core without the need to actively poll it.
The approach used (via https://github.com/bitcoin/bitcoin/issues/35023#issuecomment-4332885607) 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 (https://github.com/bitcoin/bitcoin/pull/35354#issuecomment-5363737198).
What it adds:
A
getcfilters,getcfheadersorgetcfcheckptrequest that is racing the filter index is parked instead of being ignored:PeerManagerImpl::ShouldDeferCFilterRequestchecks 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.m_pending_requestand we stop processing further messages from that peer. This keeps responses in order; other peers and outgoing messages are not affected.PARKED_CF_RETRY_INTERVAL) to avoid takingcs_maintoo often.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_testssuite (src/test/cfilter_race_tests.cpp) uses aPreFilterBlockerCValidationInterfaceregistered before the filter index, so its ownBlockConnectedfires first on the scheduler thread and stalls it before the filter index gets to runCustomAppend. This reproduces the race window deterministically. The tests drive the real message processing path viaConnmanTestMsgand advance the mocked clock where time matters.Cases covered:
deferred_cfilter_response_reaches_peer— a racinggetcfiltersis parked, not answered and not dropped, and is answered once the index catches up.deferred_cfheaders_response_reaches_peer— the same forgetcfheaders.pending_request_pauses_message_processing— while a request is parked, a laterpingfrom 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 laterpingis 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: https://github.com/lightninglabs/neutrino/issues/338.
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.
🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/26255963544/job/77353717155LLM reason (✨ experimental): CI failed because
ctestdetected a test failure incfilter_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.
Squashed two commits in one (previously there was a distinct commit for tests addition).
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.
@randomlogin how do you want to proceed here?
@sedited sorry for a long response.
There are two ways: the first one is simply to move race-window check logic to
net_processingand then again wait forSyncWithValidationInterfaceQueue.On the other hand, instead of blocking the caller (
msghand) onSyncWithValidationInterfaceQueuecompletion, 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
WakeMessageHandlerto avoid waiting next loop iteration (up to 100ms).Does that sound right to you?
That seems like a plausible approach to me, fwiw. Just set a flag in
ProcessMessagewhen you receive the request that this peer wants a a cfilter response, then inSendMessagesattempt 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?
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
getheaderspolling for some other reason. But this explains why this is very rare.In my opinion, both a
SyncWithValidationInterfaceQueuecall innet_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.OP is precise for BIP152 block transmission, when we go through BIP152, we transmit compact block header to peers before we run
BlockConnectedwhich 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:
getheadersin the moment we have not yet connected the block, they will receive stale responsegetdatafor 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
getdataandgetcfilters, 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.
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.
@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.
My understanding is that the way we currently work is:
headersandinvmessages to non-cb and low-bandwidth cb peersApart 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
getblocktxnrequests that came in while we were validating the block (ideally we'd be responding to those requests while validating the block), andgetdatarequests that came in after ourheadersmessage.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?)
Yes, that makes sense - I hadn't thought of
getblocktxnrequests.I'd say it's
UpdatedBlockTip())Changes
Added deferring of a response, we store the racing request in a
PendingCFilterRequeststruct in aPeerand then check it inSendMessages.To avoid code repetition, added a helper
TryRespondToCFilterRequestwhich is used in both originalProcessGetCFiltersandSendMessageshandlings 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 (b1d4868485770777e46950460852d61f9ad4b6c2) 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).
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:
Going further
Currently only added handling
getcfilters, but the same bug stands for other bip157 requests:getcfheadersandgetcfcheckpt. It is even less likely for them to encounter a race, do we want them handled in the same way?Should we call
m_connman.WakeMessageHandler()in block connection, or the current approach is fine?The benchmarking commit should be removed, not squashed, presumably? It doesn't seem like it'll be useful beyond developing this PR?
I think this PR should be marked as draft if it has commits that need updating/replacing prior to merge.
Rather than an optional, I'd suggest considering
std::list<PendingCFilterREquest>and usingpush_backto add requests to the end, andfrontto get the oldest request in order to attempt to service it. Allows handling multiple requests, though still needs a limit to avoid growing unbounded. Also wastes a little less memory than an optional if there's nothing queued, which should be true for most peers for most of the time.Races in
net_processingshouldn't be the business of indexes, andGetSummary()should have enough info (or we could add more if not), so I'd prefer if the index code was not touched at all for this and thenet_processingcode would decide whether there is a possible race.Originally I thought it might be useful on its own.
Removed benchmark commit.
Changed an optional in favor of a list with up to
MAX_PENDING_CFILTER_REQUESTS=2entries.Removed
IsRacing, now usingGetSummary. No changes inGetSummarywere required.🐙 This pull request conflicts with the target branch and needs rebase.
Sorry for repeatedly requesting changes.
Based on the logs in #29655 this seems backwards -- there were more disconnects for getcfheaders than getcfilters? So I think this ought to be handled for all the cases? Not at all clear to me why it's not, so maybe I've missed something?
I wonder if it wouldn't be better to adopt the "pause this peer" approach, rather than queueing messages but continuing. Here's a somewhat vibecoded branch that demos that (and delays all the messages when needed): https://github.com/ajtowns/bitcoin/commits/202608-cfilter-park/
The idea is that you add a single "hey, I'm working on an answer to this request" queued item for the peer, and refrain from processing any further messages from that peer (without interfering with outgoing messages like block announcements or other peers in general). Not sure if checking the index for updates every msgproc loop is okay or there should be an additional pause there.
I didn't implement it as wanted to receive feedback for the approach itself first.
I also checked my logs when I encountered this bug with https://github.com/2140-dev/kyoto, and indeed I also encountered it with
getcfheaders.Yes, all three cbf messages should be handled the same way.
It seems this approach is conceptually simpler, but as we defer all other messages from a peer including
pingorgetdatamy concerns are:getdataduring the race window. (Though it's quite questionable why bip157 peer would ask for a full block without having filters/cfheaders for it first, but it's a presupposition what a bip157 peer has to be.)If we try to specify which messages we still should process after a request is parked during the racing window (e.g.
getdata), it defeats the whole idea of simplicity. It seems it's the same as to specify which requests we should defer (as in my commit).Also I'm not sure that preserving the order of responses is important, it seems any (reasonable) client matches the response by its content.
I'll try to benchmark that.
I think that's very unlikely -- compact block filters are for light clients; so any node requesting compact filters isn't going to have every block and isn't going to be a reliable part of the fast path for block relay. I'd suspect most such nodes wouldn't even store full blocks for the ones they request, instead just keeping the txs they're interested in and a merkle path back to the block header?
I would say that by pausing that peer until we can reply to its request we avoid mixing handling of compact filter messages with other ones.
Right, the point is to pause all message processing for that peer, so that message processing for that peer remains in order.
Preserving the order is valuable for our own tests (if we send message X followed by PING, we won't receive the PONG corresponding to our PING until X has been dealt with), and possibly for state updates.
I've been thinking about it in terms of separating out block validation into a separate thread from message processing (suggested by @sipa offline, see also A and B), where it would be a nice win if we could respond to compactblock requests while validating the block, while still pausing nodes that send us messages that need to wait for the validation to finish (so that observable behaviour doesn't change at a logical level, and in particular so that our own tests don't get heavily impacted). I think getting the "pause" part of that change in here would be nice, particularly if it's simple.
I took some time to gain more understanding on how
net_processingworks and your comments make a perfect sense.Some suggestions on top of your commit:
Added a guard for initial block download.
On a fresh node with enabled compact filters
PeerManagerImpl::CFilterIndexMayBeRacingwould 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.
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:
getdatamessageShould we combine all of the above into something like
PreprocessMessagesorProcessAwaitingMessagesorProcessPausedPeer?Made minor renamings in your code.
Here are some claude-coded benchmarks, I ran them locally on my computer.
AttemptParkedRequest()is retried on everyProcessMessages()pass for a peer with a pendingrequest, not gated on new traffic — so n parked peers add n extra
cs_mainacquisitions to everymessage-handler sweep for as long as they stay parked.
Per-call cost (
bench_bitcoin, isolated — both paths takecs_main, differ in what's done under it):Tip()compare only)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 ongetcfiltersvs. n peers sending an ordinarygetdata(control — resolves immediately, no repeat cost), measuring an unrelated peer's ping RTT: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.
🚧 At least one of the CI tasks failed.
Task
macOS native, fuzz: https://github.com/bitcoin/bitcoin/actions/runs/32980342303/job/98234423973LLM reason (✨ experimental): CI failed because the
fuzztargetrpchit 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.
@ajtowns what do you think?
1 additional verified finding in the full report.
🟠 Minor · Persistent index lag is mistaken for an in-flight filter append
With -peerblockfilters, a synced index following an assumeutxo historical chain can make recent filter requests pause the requesting peer until timeout without supplying the missing filters.
Location:
src/net_processing.cpp:3608(head).🟠 Minor · Deferred filter responses bypass the message exception handler
A local filter-index database read error during deferred serving can terminate the node instead of being caught and logged as it was before this change.
Location:
src/net_processing.cpp:5659(head).🟠 Minor · A backward clock step can extend the parked-peer timeout
A backward wall-clock step while a request is parked bypasses both readiness checks and the five-second timeout until the clock catches up, delaying that peer's later messages.
Location:
src/net_processing.cpp:3845(head).🔵 Suggestion · Requests that should be rejected are parked before validation
A BASIC request for a known uncovered stop can pause its peer before service, range, or block-access checks reject it, delaying disconnection until catch-up or the parking timeout.
Location:
src/net_processing.cpp:3682(head).🔵 Suggestion · Fatal assertions can hang race-test teardown and leave the capture hook dangling
A fatal assertion before cleanup can leave the scheduler blocked and the global CaptureMessage hook referencing destroyed test locals.
Location:
src/test/cfilter_race_tests.cpp:579(head).🔵 Suggestion · The deferred cfheaders test does not verify the response contents
cfilter_race_tests.cpp:358 records only the CFHEADERS message type and ignores the payload. A retry that forwarded the wrong start height or stop hash would still send a CFHEADERS message, and the test would pass.
Location:
src/test/cfilter_race_tests.cpp:356(head).Review coverage was incomplete.
Reviewed:
8520f9c00278· Full review report · Previous reportspermalink
🐙 This pull request conflicts with the target branch and needs rebase.
Looks good to me, I think. PR description needs an update.
These renames should be squashed. (And make yourself the author and add me as a co-authored-by or so if you like?)
Having this be:
so that we can more easily debug how long a request was delayed, and automatically abort/drop requests that sit idle for an extended period is probably a good idea.
You should update the comment on the declaration of
CfilterIndexMayBeRacingto match this change in behaviour.I think maybe change the name as well -- it's really answering something more like
ShouldDeferCFilterRequest()now, I think. In that case the comment should become "during IBD always answer CFilter requests immediately, we can't give accurate data vs the tip without potentially very long delays, so just respond as best we can" ?If
cs_mainis held by another thread, we'll block msg processing if we hit a node that's waiting on an update here. That's probably not a problem in practice -- we hit the same case as soon as a peer sends us an INV. Could have two timers associated with the request so that as well as tracking when the peer was parked, we only do retries of parked peers when it's been 100ms or so since the last retry.Squashed that change and set the author.
Renamed and changed the comment.
Changed to a struct.
I'd use more detailed field titles:
request_dataandpark_time, as abbreviationreqthroughout the codebase in other places means "required", not "request"; alsopark_timeis more expressive.When choosing where to construct
PendingRequestwith its fields, there are two options: either pass a constructed struct with times toParkPendingRequestor to set it insideParkPendingRequest.I'd stick to former, as it makes possible to debug with artificial parking/retry times (thoigh we have some repeating code), also in the latter case
ParkPendingRequeststops being a pure function.We (serve what we can and) drop a request which was parked for more than
MAX_CF_PARK_INTERVAL=5s.Also added
last_retry_timefield.Added
last_retry_timeandPARKED_CF_RETRY_INTERVAL=100ms, now we don't retry if the previous attempt was too recent.The OP is still not describing the problem correctly, as I mentioned in https://github.com/bitcoin/bitcoin/pull/35354#pullrequestreview-4806824241.
Given the extent of the changes to
net_processingfor 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_processingcode towards more async behavior to tackle problems like #35023 (this is @ajtowns angle in https://github.com/bitcoin/bitcoin/pull/35354#issuecomment-5363737198), but this should also be stated explicitly in the OP.@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:
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.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
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.