Skip to content

fix(dash-spv): hedge the filter batch that blocks the store - #1473

Merged
ZocoLini merged 8 commits into
devfrom
fix/hedge-filter-batch
Nov 25, 2026
Merged

ZocoLini merged 8 commits into
devfrom
fix/hedge-filter-batch

Conversation

@xdustinface

@xdustinface xdustinface commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Filters are verified and stored in height order, so one filter batch stuck at a silent peer holds back every batch downloaded above it. Nothing asked another peer for it until the request timed out. Blocks already get a second copy in this case (Broker::hedge), filter batches did not.

The flow controller now calls Broker::hedge_filters, which sends a second copy of the lowest filter batch not yet delivered once its peer has answered nothing for HEDGE_AFTER. A lower batch still queued goes out next, so it suppresses the hedge. The copy goes to the peer that answers soonest rather than the one with the most free cap, because bulk download keeps every peer at its cap. Peers that owe a reply and answered nothing for HEDGE_AFTER are skipped, since a frozen peer keeps the rate it had, and a batch is hedged again once its second peer falls silent too. The first copy to arrive settles the request, and dropping a peer clears the hedges it held, so a lost copy can be sent again.

Router and hedge can now send getcfilters to one peer at the same time, so PeerHandle::send charges a request under the writer lock. Filter replies settle in the order their requests are written, and charging earlier could leave later batches charged to the peer forever.

PR Hygiene · d231830

  • Bots — coderabbitai skipped after its own rate limit
  • Self-review — address ZocoLini requested changes, then post /self-reviewed
  • Build green
  • Approvals — you own every area touched; none needed

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

Summary by CodeRabbit

  • Improvements
    • Filter synchronization can continue through responsive peers when other peers are silent or paused, without unnecessarily disconnecting them.
    • Requests can be reassigned when a hedging peer disconnects, helping synchronization continue while the original peer remains connected.
    • Improved handling of concurrent requests keeps network activity and reply tracking more consistent, including when replies arrive out of order.

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 46 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 1348013 and d231830.

Files selected for processing: 1

  • dash-spv/src/network/broker.rs

No actionable comments were generated in the recent review.

Walkthrough

The ledger now tracks peer answer timing and exposes silence duration. The broker uses that timing to hedge eligible filter requests, and the flow controller checks for filter hedges on each iteration. Peer sends charge the ledger in write-lock order. Unit and sync tests cover these changes.

Changes: Filter hedging

Layer / File(s) Summary
Peer silence timing
dash-spv/src/network/costs.rs, dash-spv/src/network/peer.rs
The ledger tracks the latest answer time and reports silence duration while replies are outstanding. PeerHandle exposes this duration. A paused-time test checks silence timing, including partial filter replies.
Write-ordered ledger charging
dash-spv/src/network/peer.rs
PeerHandle::send charges the ledger after it acquires the writer lock. A concurrency test checks that replies settle charges after sends complete in write order.
Broker hedge selection and lifecycle
dash-spv/src/network/broker.rs, dash-spv/src/network/manager.rs, dash-spv/tests/dashd_sync/tests_stall.rs
The broker selects eligible block and filter requests, records hedge assignments before sending, and clears assignments when hedge peers disconnect. The flow controller checks for filter hedges on each iteration. Tests cover hedge selection, retries, filter progress, and paused peers.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant FlowController
  participant Broker
  participant PeerHandle
  FlowController->>Broker: Call hedge_filters
  Broker->>PeerHandle: Read silence duration and send duplicate filter request
Loading

Possibly related issues

  • dashpay/rust-dashcore#1464 — The issue concerns how CFilter replies settle requests, which is related to the hedged filter batches and their replies.
  • dashpay/rust-dashcore#1230 — The new filter hedge path can retry a batch when its peer has not answered within HEDGE_AFTER.
  • dashpay/rust-dashcore#1237 — The changes affect peer sending and hedge peer selection, which are also involved in the reported stalled-write behavior.
  • dashpay/rust-dashcore#1232 — The changes affect CFilter request charging and reply settlement in the ledger.

Possibly related PRs

Suggested reviewers: zocolini, pastapastapasta

Merge Risk: Minimal · previous review 13480

The change hedges the lowest undelivered filter batch so one silent peer no longer holds up ordered filter storage, and it charges peer sends in write-lock order. No concrete merge-blocking defect remains after review. One minor edge case exists where a late reply from a replaced hedge peer is ignored, and the other copies still settle the request. The reported build failure should be confirmed before merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: filter batch hedging aimed at the lowest undelivered batch that blocks ordered filter storage. The changeset adds Broker::hedge_filters, a filter-hedging selector, a l…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: filter batch hedging aimed at the lowest undelivered batch that blocks ordered filter storage. The changeset adds Broker::hedge_filters, a filter-hedging selector, a lowest_height queue helper, and a Ledger silent_for timer, all in service of that goal. The title is specific, follows the conventional-commit style, and does not claim anything absent from the diff. The PR objectives also describe the same aim, with the peer-selection and concurrent getcfilters safety changes as supporting work.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between dc3a1a3 and 1348013.

Files selected for processing: 4

  • dash-spv/src/network/broker.rs
  • dash-spv/src/network/costs.rs
  • dash-spv/src/network/peer.rs
  • dash-spv/tests/dashd_sync/tests_stall.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@manki-review

manki-review Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

✅ Review complete in 11m 28s

Planner (4s)
    feat · 152 lines · 2 agents
    judge effort: medium

Review (behavior · full): 13 findings
    ✅ Claude Opus 5.5 · high: 3 findings (3m 21s)
    ✅ GPT 6.2 Sol · high: 10 findings (4m 20s)
    ✅ Claim checks, pattern checks and fix checks: 10 of 10 done (1m 36s)
    ✅ Second reads: 1 of 1 done (1m 58s)

Judge: 5 kept · 6 dropped · 2 merged (3m 27s)
    kept: 1 blocker · 1 warning · 3 suggestions
    dropped: 1 blocker · 1 warning · 4 suggestions
    sweeps: 1 of 1 done (31s)

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 26% (resets 2026-11-27 01:00 UTC)
  • ChatGPT subscription: weekly 2% (resets 2026-11-25 01:21 UTC)

Judge decisions:

  • Kept: "No dashd test covers the new filter hedge, and no test reaches the flow controller call" (suggestion): "note. The rule in dash-spv/AGENTS.md asks for a dashd test for any change to sync or disconnect handling. This PR changes filter sync (manager.rs:768 now hedges filter batches) and disconnect handling (requeue_from clears hedges). The changed files list holds only broker.rs and manager.rs, so no file under tests/dashd_sync/ or tests/dashd_masternode/ can hold the test, and the rule is broken. A missing test is the improvement row."
  • Kept: "New tests set the broker's internal registry and queue by hand" (suggestion): "note. broker.queue.pop_n(1) at broker.rs:961 reaches into the private MsgQueue. It is redundant, since release of a Queued key already calls drop_queued (broker.rs:132). The other two tests build ReqState::OnWire directly through mark_on_wire, which hardcodes height: 0 (broker.rs:452). The root AGENTS.md forbids setting internal state by hand, so the rule is broken. The tests still run the real hedge_filters and requeue_from, so they can fail when that code breaks. That makes this the improvement row."
  • Not listed, over the review.notes limit: "Doc comment of hedge_filters runs past the three-line limit" (suggestion): "note. The root AGENTS.md sets three lines as the ceiling for a comment. The new doc comment at broker.rs:401-404 has four /// lines, so the rule is broken. This is a comment-length rule, so it is the style row."
  • Kept: "Losing filter hedges can pile up beyond both byte caps" (warning): "warning, if confirmed. The candidate filter at broker.rs:419 checks only id and is_closed, and no global budget is passed at manager.rs:768. So a hedge can go over the backup peer's cap. When the original copy wins, arrived marks the request Arrived (broker.rs:218), but the backup still owes its batch, and that batch stays charged in its ledger until it drains. Ignoring the cap is a stated choice. What the choice does not account for is how losing copies add up during a long stall. One hedge goes out per stuck batch, each up to 1000 filters. The code shown does not show how much this slows ordinary requests, so it stays a warning pending that check.
    Refutation unsettled: arrived overwrites the request with Arrived when either copy wins (broker.rs:218), so the broker forgets the backup's copy. hedge_filters picks the backup with only an id check and an is-closed check (broker.rs:419) and sends without testing the peer's cap or the global cap (broker.rs:433). Nothing therefore stops a peer from carrying several losing batches above its cap. The only thing that slows it is choose_peer, which prefers the peer with the shortest queued time. Rule checked: A hedge counts against the backup peer's in-flight bytes until that peer's reply drains, so a broker that forgets the hedge once the other copy wins, and checks no cap when it sends a hedge, does not limit how many losing copies one peer can be carrying.
  • Premise "The duplicate filter replies of hedges that lost, still charged in the backup peer's ledger after the original peer settled the request, delay that peer's other requests long enough for sync to slow noticeably" unsettled. Two things soften the effect. choose_peer with the Headers class sends each new hedge to the peer with the fewest queued seconds, and those seconds include the leftover hedge bytes (broker.rs:530-533, 544-548), so a peer with a backlog is avoided. route also keeps sending ordinary requests to any other peer below its cap (broker.rs:329). Whether sync slows noticeably depends on peer timing and serving rates that reading the code cannot measure.
    Pair refutation unsettled: When the original peer’s final filter arrives, the broker marks the request Arrived without releasing the backup peer’s charge. On a later flow tick, another stalled batch can use the same backup even if both byte caps are already full: peer selection ranks candidates by load but does not reject an over-cap peer, and the send adds another charge. Rule checked: Settling a logical request does not release the byte charge for a physical copy still outstanding on another connection.
  • Premise "The duplicate filter replies of hedges that lost, still charged in the backup peer's ledger after the original peer settled the request, delay that peer's other requests long enough for sync to slow noticeably" unsettled. The charges can keep ordinary requests off the backup or block routing globally, but the code does not establish how long that lasts or whether sync slows noticeably; that depends on how quickly replies drain and how much room remains on other peers."
  • Kept: "Concurrent filter sends can leave an answered batch charged forever" (blocker): "blocker, held to warning by open doubts on test 2 (the failure path). PeerHandle::send charges the ledger (peer.rs:322) before it takes the writer lock (peer.rs:325). Before this PR, GetCFilters was sent only from the router's sequential loop (broker.rs:334). The new hedge adds a second sender (broker.rs:433) on the flow controller task. Suppose batch A is charged, then hedge batch B is charged, but B wins the writer lock. The peer then answers B first. settle picks the first awaited CFilters entry, which is A (costs.rs:215), and returns at costs.rs:220 because B's stop hash does not match. B's charge is never released. Every later batch behind it gets the same treatment, so the peer's in_flight_bytes grows until the router stops using it. Concurrent use is not an internal state, so the column is normal.
    Refutation confirmed: PeerHandle::send charges the ledger before it takes the writer lock, and the router task and the flow controller's new filter hedge both send GetCFilters through it. If charge order differs from wire order, settle tries each CFilter against the first awaited CFilters entry, sees a stop-hash mismatch and returns, so the batch answered first stays charged and every later batch to that peer is blocked behind it. Rule checked: Tokio tasks on a multi-threaded runtime run concurrently, so when one step (charging the ledger) and a later step (taking the writer lock) are not done atomically, two senders can do the first in one order and the second in the other; an order-dependent matcher then mismatches.
  • Premise "The router task and the flow controller task run concurrently and can both call PeerHandle::send with a GetCFilters to the same peer" confirmed. The router loop and the flow controller run as separately spawned tasks; the router sends GetCFilters via route and the flow controller now sends them via hedge_filters → send_hedge, to any other open peer regardless of caps.
  • Premise "No code outside Ledger::settle expires or removes a stale Reply::CFilters entry from awaited while the connection stays open" confirmed. The awaited list is only touched in Ledger::charge, Ledger::settle and its NotFound branch; no other code expires or removes an entry while the peer is connected.
    Pair refutation confirmed: If A is charged first but B takes the writer first, B's stop hash is checked only against A's entry and does not release B's charge. A's later stop hash releases A alone, leaving B charged after both batches have arrived; subsequent batches with different stop hashes cannot clear that entry. Rule checked: Two separate mutexes do not preserve ordering across concurrent operations, so a FIFO reply ledger can disagree with socket write order.
  • Premise "The router task and the flow controller task run concurrently and can both call PeerHandle::send with a GetCFilters to the same peer" confirmed. The router and flow controller run in separate tasks, and a live peer below its cap can be both the router's target for a new filter batch and the hedge target for a stalled batch assigned to another peer.
  • Premise "No code outside Ledger::settle expires or removes a stale Reply::CFilters entry from awaited while the connection stays open" confirmed. The private ledger queue has no expiry path: charging only appends entries, and only settlement removes them."
  • Not listed, a tool check could not confirm it: "Hedge bookkeeping can lose a live copy or record a copy that is already gone" (warning): "warning, if confirmed. send_hedge writes first (broker.rs:433) and only then records o.hedge (broker.rs:436). arrived accepts an on-wire reply only from o.peer or o.hedge (broker.rs:211). The bigger case is a primary that drops while its backup is in flight. requeue_from requeues the request anyway (broker.rs:187), and the router re-sends it with hedge: None (broker.rs:362), so the backup's later reply is ignored and a third copy goes out. Every result is still right. The cost is duplicate traffic and possibly a delay, which depends on how the filter manager consumes the data, and that code is not shown.
    Refutation unsettled: The bookkeeping defect is real. send_hedge writes at line 433 and records the hedge only at line 436, so arrived (line 211) drops a reply that comes earlier. requeue_from requeues a departed primary at line 187 even when its backup is still in flight, and route then gives the new attempt hedge: None at line 362, so a third copy can go out and the backup's reply is not counted. The cost is only bookkeeping and duplicate traffic: the data itself is not lost. Rule checked: A broker that writes to the wire before it records the write, and then re-routes a request with a fresh state, can be looked up by a reply before its record exists, or can match a reply against a newer attempt than the one that caused it.
  • Premise "When arrived ignores a backup's reply, because the hedge is not yet registered or because the primary's disconnect re-routed the request, the filter batch waits for another copy instead of the filter manager storing the backup's data and releasing the key" disproved. arrived only updates broker state and does not gate delivery: the manager loop sends every cfilter to its subscribers whatever arrived decided. The filter sync manager buffers it without checking which peer sent it and releases the key once the batch is complete, and release removes an OnWire entry too, so the batch does not wait for another copy.
    Pair refutation unsettled: Hedge registration checks only the key and whether its current on-wire state has an empty hedge slot, so it can miss an early reply or record a disconnected peer or a hedge from an earlier attempt. A primary disconnect also requeues the request despite a live backup; if the router installs a new attempt on a different peer before the backup replies, it sends a third copy and the broker ignores the backup's completion. Rule checked: An asynchronous send and a later update under a separate lock are not atomic with reply handling, disconnect handling, or rerouting.
  • Premise "When arrived ignores a backup's reply, because the hedge is not yet registered or because the primary's disconnect re-routed the request, the filter batch waits for another copy instead of the filter manager storing the backup's data and releasing the key" disproved. The pump forwards filters regardless of whether the broker settles the request, so a complete valid backup batch can release the key and be stored in height order without waiting for another copy."
  • Kept: "A lower filter batch disappears from hedge selection while the router dispatches it" (suggestion): "note. The router pops messages (broker.rs:320) and records them as on wire only after its send loop (broker.rs:356). During that window, hedge_filters can see neither a lower batch's queue entry nor its on-wire state. The worst result is one extra hedge of a higher batch. That batch has itself been silent for HEDGE_AFTER (broker.rs:412), so the copy is not useless, and the lower batch can still be hedged later. This is a small, bounded cost."
  • Not listed, over the review.notes limit: "One unmeasured peer makes filter hedges ignore all measured response speeds" (suggestion): "note. choose_peer for Headers gives up on wait estimates when any candidate is busy with no serving rate (broker.rs:530, 547) and then compares cap ratios (broker.rs:536). This is the existing documented behaviour of choose_peer (broker.rs:523-524), which the PR reuses. It only affects new peers that have no rate measured yet, and the hedge still goes to a live peer. The comment at broker.rs:418 overstates how soon the chosen peer answers."
  • Not listed, over the review.notes limit: "A slow hedge write suspends the flow controller during bulk sync" (suggestion): "note. hedge_filters awaits the socket write inline (manager.rs:768, broker.rs:433), and the existing block hedge at manager.rs:764 already does the same. The pause is capped by WRITE_TIMEOUT of 5 seconds (peer.rs:90), and a write that stalls that long cancels the peer (peer.rs:336). So the cost is at most one short pause per misbehaving peer."
  • Not listed, over the review.notes limit: "The new hedge method is visible beyond the network module" (suggestion): "note. mod broker is private, and only RequestKey is re-exported (network/mod.rs:2, 20). The only caller is the sibling manager.rs:768, so pub(super) would compile. The new item breaks the visibility rule in the root AGENTS.md. This is a naming and visibility point with no runtime effect."
  • Dropped: "A rejected filter batch may leave the store waiting at a height the pipeline no longer requests" (ignore): "ignore. The lead concerns dash-spv/src/sync/filters/manager.rs, which this PR does not change. The lead gives no path by which the hedge produces a batch that fails verification where none could before, so this PR neither causes nor exposes it, and test 1 fails."

Timing:

  • Parse: 6.7s
  • Review agents: 475.1s
  • Judge: 206.7s
  • Total: 688.5s

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — coderabbitai not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Nov 21, 2026
manki-review[bot]
manki-review Bot previously requested changes Nov 21, 2026

@manki-review manki-review Bot left a comment

Copy link