Skip to content

fix(dash-spv): hedge all filter batches held by silent peers - #1532

Merged
ZocoLini merged 1 commit into
devfrom
fix/frozen-peer-hedges
Nov 26, 2026
Merged

ZocoLini merged 1 commit into
devfrom
fix/frozen-peer-hedges

Conversation

@xdustinface

@xdustinface xdustinface commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

When peers froze during filter sync, only the lowest filter batch they owed got a second copy from another peer, and the next copy waited for the previous one to arrive, at most one per 250 ms flow tick. The peer left answering sat idle in between, so two frozen peers owing a dozen batches or more were repaid too slowly and the request timeout dropped one of them. This is the test_filter_sync_passes_frozen_peers flake on CI.

Now every batch whose peer is silent gets a copy, lowest first, and the flow controller sends all of them in one tick. Only the lowest batch may go past the answering peer's cap. A higher batch needs its peer to have sent no bytes at all, so a peer midway through a big block keeps its batches.

With the answering dashd slowed to CI speed, the test failed 10 of 48 runs on dev and none of 48 with this change.

Closes #1530

PR Hygiene · 5555f01

  • Bots — coderabbitai not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — 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

  • Bug Fixes
    • Filter batches can now be hedged across multiple heights in a single tick, while respecting queued lower-height requests and peer capacity.
    • Peers already responding to a batch are handled appropriately during hedging.
    • Newly joined peers can receive multiple eligible filter batches during the first hedge tick.

@coderabbitai

coderabbitai Bot commented Nov 25, 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 59 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 0d96916 and 5555f01.

Files selected for processing: 2

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

No actionable comments were generated in the recent review.

Walkthrough

The broker now considers multiple eligible on-wire filter batches for hedging, subject to timing, queued-request, and peer-cap rules. The flow controller repeats hedge requests until the broker returns no height. Tests cover batch eligibility and delivery to a newly joined peer.

Changes: Filter batch hedging

Layer / File(s) Summary
Broker hedge eligibility
dash-spv/src/network/broker.rs
The broker evaluates on-wire filter batches in height order. It applies different timing and peer-cap rules to the lowest batch and higher batches, and stops before batches above a lower queued request. Tests cover repeated hedges, answering peers, capacity limits, and queued lower batches.
Repeated hedge requests
dash-spv/src/network/manager.rs
The flow controller calls hedge_filters repeatedly until it returns no height. A test checks that a newly joined peer receives multiple copied batches.

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

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant FlowController
  participant Broker
  participant Peer
  FlowController->>Broker: Call hedge_filters
  Broker->>Peer: Send eligible filter batch
  Broker-->>FlowController: Return eligible height
  FlowController->>Broker: Call hedge_filters again
  Broker-->>FlowController: Return no height when none remain
Loading

Possibly related issues

Possibly related PRs

Suggested reviewers: zocolini, manki-review

Merge Risk: Minimal · previous review 0d969

This change lets filter sync copy all eligible batches from silent peers in one tick, which should reduce intermittent timeouts. No concrete defect remains after review, and the change is behavior-bounded and covered by new tests.

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 fix and its scope: hedging filter batches held by silent peers in dash-spv. The change makes Broker::hedge_filters consider all eligible on-wire batches in height order, and the fl…
Linked Issues check Passed Issue #1530 (direct) reports that filter batches owed by silent peers are copied one at a time, so the 10 s request timeout drops a peer before the answering peer delivers them. The PR implements the …
Out of Scope Changes check Passed All changes described in the summary connect to the flake in #1530. Changes are in dash-spv/src/network/broker.rs (Broker::hedge_filters multi-batch hedging, cap and queued-lower-batch rules, docume…
Full details: Title check

Explanation

The title names the fix and its scope: hedging filter batches held by silent peers in dash-spv. The change makes Broker::hedge_filters consider all eligible on-wire batches in height order, and the flow controller hedges repeatedly per tick, which matches the title. The title is specific, short, and free of file lists or vague terms.

Full details: Linked Issues check

Explanation

Issue #1530 (direct) reports that filter batches owed by silent peers are copied one at a time, so the 10 s request timeout drops a peer before the answering peer delivers them. The PR implements the issue's second option: every eligible on-wire filter batch of a silent peer is copied in height order, and the flow controller repeats Broker::hedge_filters until it returns no height in the same tick (dash-spv/src/network/manager.rs, per summary). The head file dash-spv/src/network/broker.rs shows the OnWire hedge model (hedges, hedge_to, last_answer, last_progress) and the requeue_from cleanup of lost hedge copies, which support the design. The lowest batch may exceed the answering peer's cap. Higher batches need spare capacity and a peer with no bytes sent, so a peer mid-block keeps its batches. The summary reports new tests for repeated hedging, cap limits, queued lower batches, and peers still receiving bytes. The PR description reports 10 of 48 failing runs before the change and 0 of 48 after, under slowed CI-speed dashd. Limits: the hedge_filters body and the new tests were not read directly, because the diff tool was unavailable and the head file view was truncated before that function. The verdict relies on the summary and PR description for that code.

Full details: Out of Scope Changes check

Explanation

All changes described in the summary connect to the flake in #1530. Changes are in dash-spv/src/network/broker.rs (Broker::hedge_filters multi-batch hedging, cap and queued-lower-batch rules, documentation, tests, and a tokio::time test import) and dash-spv/src/network/manager.rs (flow controller loop and a test for multiple copies in the first tick). Supporting tests and documentation for the hedging rule are a legitimate part of the fix. No public declarations changed, per the summary. The head file view of broker.rs showed no unrelated hunks in the read portion. The diff tool was unavailable, so the unread portion of the changes was not checked directly.

Finishing Touches

Generate unit tests (beta)

  • 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 6b002e9 and 0d96916.

Files selected for processing: 2

  • dash-spv/src/network/broker.rs
  • dash-spv/src/network/manager.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.

@github-actions

github-actions Bot commented Nov 25, 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 25, 2026
@manki-review

manki-review Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

✅ Review complete in 13m 44s

Planner (4s)
    feat · 143 lines · 2 agents
    judge effort: high

Review (behavior · full): 7 findings
    ✅ Claude Opus 5.5 · high: 1 finding (5m 42s)
    ✅ GPT 6.2 Sol · high: 6 findings (2m 46s)
    ✅ Related checks, claim checks and fix checks: 12 of 12 done (1m 14s)
    ✅ Second reads: 1 of 1 done (1m 30s)

Judge (5m 36s)
    graded 7 findings: 6 kept · 1 dropped
    dropped, as the finders filed them: 1 warning
    refuter: 1 checked · 1 unsettled
    origin checks: 3 checked · 1 older than this PR
    verdict reader: read the diff (30s)

Posted: 3 findings
    3 suggestions
    not posted: 1 older than this PR · 2 no realistic trigger

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 79% (resets 2026-12-01 05:00 UTC)
  • ChatGPT subscription: weekly 2% (resets 2026-12-02 01:49 UTC)

Judge decisions:

  • Not listed, on code this PR did not change: "When filter work is still queued, the router fills the answering peer first, so higher hedges seldom go out" (warning): "warning. route keeps sending while p.in_flight_bytes() < p.cap() (broker.rs:333), so whenever the queue holds more filter work the answering peer ends each routing pass at or above its cap. The new filter at broker.rs:452 lets a batch above the lowest go only to a peer below its cap. In that state only the lowest batch is ever hedged. Once its copy is on the answering peer, it is skipped (broker.rs:442), and every higher batch is refused, which is the one-at-a-time behaviour the PR sets out to remove. The pipeline declares every ready batch at once (pipeline.rs:152), so a large backlog is the normal case outside regtest. The outcome is slower sync and frozen peers dropped on timeout, with no wrong result: the degraded row. Whether the router refills the peer before each tick rests on arrived, which is not shown, so it is listed as a doubt.
    Refutation confirmed: The mechanism holds. Every completed batch wakes the router, the router refills the answering peer up to its cap from the backlog the pipeline declares, and line 452 then refuses every batch above the lowest. The cost is a delay, not a wrong result. A frozen peer that sends no bytes is expired after REQUEST_TIMEOUT (10 s) and its batches are requeued, so the limit only matters between HEDGE_AFTER (2 s) and that timeout. The cap probe in ByteLimiter::tick also raises a bound peer's cap just bef... Rule checked: A router that sends while in_flight_bytes() < cap() leaves each peer at or above its cap after every pass while work is queued, so a check that needs the peer below its cap fails at almost every flow tick.
  • Premise "Broker::arrived (dash-spv/src/network/broker.rs:228) wakes the router, which refills the answering peer from the queue up to its cap before the next FLOW_TICK runs hedge_filters" confirmed. When a batch's last filter arrives, the reader calls broker.arrived and the in-flight bytes are released. arrived then wakes the router, which routes while the queue is non-empty and keeps sending until the peer reaches its cap. A cap change at a tick does not wake the router, so the peer is normally full when hedge_filters runs.
  • Premise "This trigger happens in realistic use: when two peers freeze during filter sync on testnet or mainnet while the broker queue still holds many higher getcfilters batches" confirmed. The code side holds: init makes one tracker per 1000-block batch up to the filter header tip, and send_pending declares every ready batch to the broker queue at once. On a real chain the queue therefore holds a large backlog of higher getcfilters while any peer freezes. Whether peers actually freeze is run-time behaviour that no code here can show.
    Pair refutation disproved: A full answering peer can take only the lowest hedge, so missing batches can hold up storage while later batches accumulate. But the flow controller recalculates caps before hedging, independently of the router, so a queued backlog alone does not establish that higher hedges are usually blocked. Rule checked: A hedge above the lowest on-wire batch needs an answering peer below its current byte cap when the hedge is selected.
  • Premise "Broker::arrived (dash-spv/src/network/broker.rs:228) wakes the router, which refills the answering peer from the queue up to its cap before the next FLOW_TICK runs hedge_filters" disproved. An accepted stop-filter reply wakes the router, but the router and flow controller run in separate tasks, with no requirement that the refill finish before the next hedge.
  • Premise "This trigger happens in realistic use: when two peers freeze during filter sync on testnet or mainnet while the broker queue still holds many higher getcfilters batches" confirmed. The sync path declares every ready batch through the filter-header tip without limiting the queue, and the three-peer integration test supplies two silent peers during that same download phase."
  • Kept: "Each successful hedge repeats an unbounded registry scan and sort" (suggestion): "note. The while let loop at manager.rs:724 calls hedge_filters once per copy. Each call scans the request map and sorts the on-wire filter batches again (broker.rs:420-429). Each successful hedge adds the peer to hedges, so the loop ends after at most the number of on-wire batches below the queue head, a few dozen. A map scan of a few thousand entries per copy is a cost nobody would notice. enqueue is called by the sync managers, not by outside input, so this is no exhaustion defect. Building the sorted list once per tick would be tidier."
  • Dropped: "Higher filter hedges can exceed the destination's byte cap" (ignore): "ignore. The cap is a soft limit everywhere in the broker. The router itself sends a whole batch to any peer with in_flight_bytes() < cap() (broker.rs:333), so passing the cap by up to one message is how both paths are built. Project memory records that hedges are kept without a reservation, and that batch boundaries are fixed, so no two getcfilters share a stop hash or a start height. The race with the router overshoots by one batch at most, the same as the router alone."
  • Not listed, it names no trigger that happens in realistic use: "Higher batches can be copied from a peer that is still delivering replies" (warning): "warning, posted only if the trigger is confirmed. broker.progress runs only for CFilter, CFHeaders, Block, Headers and Headers2 (manager.rs:1329-1337). Byte growth counts only while a message is partial (manager.rs:1077). A peer serving masternode replies can therefore look silent to the new last_progress check at broker.rs:440, and its higher batches get downloaded twice. The cost is duplicate bandwidth with the right result. A large qrinfo is likely to be partial at some sample, so the realistic trigger is unclear and trigger is left empty."
  • Not listed, it names no trigger that happens in realistic use: "A higher hedge can pass a lower batch the router has not sent yet" (warning): "warning row with no realistic trigger. A batch popped by pop_guaranteed (broker.rs:324) is neither in the queue nor OnWire until line 360. A hedge_filters call in that window does not see it through lowest_queued (broker.rs:410). It can then send a higher copy ahead of it, because the new scan moves past an already-hedged lowest batch (broker.rs:442). The window is the router's send loop, much shorter than the 250 ms tick. The effect is at most one batch of extra queueing ahead of the lower request, with no wrong result."
  • Kept: "A failed hedge write ends the tick even when other copies are eligible" (suggestion): "note. A send error becomes None (broker.rs:458), so the while let loop at manager.rs:724 stops. The failing peer is cancelled (peer.rs:353) and drops out of the candidates on the next tick 250 ms later, where hedging resumes. The delay of one tick after a rare write failure is a cost nobody would notice. Telling a failed write apart from no work left would let the burst continue."
  • Kept: "The regression tests set connection and flow state by hand" (suggestion): "note. The rule in AGENTS.md is a requirement. The broker test writes the internal cap field directly with set_cap (broker.rs:1031 and the later answering.set_cap calls), which store into handle.cap (peer.rs:418). The finding itself notes that reverting broker.rs:440 or manager.rs:724 fails these tests, so nothing goes untested. Only how the tests are built is in question."

Timing:

  • Parse: 4.5s
  • Review agents: 483.7s
  • Judge: 335.7s
  • Total: 823.9s

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 25, 2026
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.63%. Comparing base (81a75a6) to head (5555f01).

Additional details and impacted files
@@            Coverage Diff             @@
##              dev    #1532      +/-   ##
==========================================
- Coverage   87.64%   87.63%   -0.02%     
==========================================
  Files         270      270              
  Lines       71891    71973      +82     
==========================================
+ Hits        63009    63073      +64     
- Misses       8882     8900      +18     
Flag Coverage Δ
core 83.38% <ø> (ø)
rpc 83.38% <ø> (ø)
spv 95.06% <100.00%> (-0.06%) ⬇️
wallet 83.38% <ø> (ø)
Files with missing lines Coverage Δ
dash-spv/src/network/broker.rs 98.47% <100.00%> (-0.40%) ⬇️
dash-spv/src/network/manager.rs 96.57% <100.00%> (+0.10%) ⬆️

... and 2 files with indirect coverage changes

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved. 3 suggestions, none of which block.

What this does: When peers stop delivering filter batches, the client used to ask a working peer for only one of their batches per tick. Now each tick it asks for every stuck batch the working peer has room for, plus the lowest one regardless of room, so filter sync recovers faster.


What to test

The review model wrote these steps. Check what a step runs before you follow it.

Setup: Run a filter-syncing client on testnet with several peers and peer_speed and dash_spv::network debug logging enabled.

  1. Freeze one peer mid filter sync, for example by blocking its traffic with a firewall rule. Expect several hedged filter batch lines in the same tick, not one per tick.
  2. Keep that peer frozen. Expect each of its batches to be hedged once, not repeatedly every tick.
  3. Let a healthy peer serve its own batches normally. Expect none of its batches to be hedged while it keeps answering.
  4. Freeze a peer while a lower filter batch is still queued. Expect no hedge of batches above the queued one.
  5. Freeze every peer at once. Expect no hedges, since no peer is answering.
About this review
  • Reviewed 0d96916, round 1
  • 143 changed lines read in 13m 44s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 4.8M in (3.8M from cache) · 97k out · about $6.67 at API prices
  • Runner: self-hosted · started after 3m 26s · peak memory 3.5 GiB of 30.0 GiB
  • How Manki reviews

Comment thread dash-spv/src/network/manager.rs Outdated
// Sent even while our link looks stalled: two frozen peers look the same, and
// another peer may be idle only because the batch they owe blocks the store.
if let Some(height) = broker.hedge_filters(&handles).await {
while let Some(height) = broker.hedge_filters(&handles).await {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✨ Suggestion, not blocking · Reliability · Quick fix

A failed hedge write ends the tick even when other copies are eligible

Why: If a selected peer disconnects or its write fails during a hedge burst, hedge_filters returns the same None as it does when there is no work. The controller stops the burst even if another peer can take that copy or the remaining eligible batches.

How to fix it and 5 places read

How to fix it
Distinguish a failed write from an exhausted candidate list. On failure, exclude that connection for the rest of the bounded pass, clear its failed reservation if it is still present, and continue selecting among the remaining peers.

Checked in the code
On the commented line: Treats every None as the end of the batch pass

  • Records the destination with o.hedge_to(peer) before the write
  • Converts every send error to None with peer.send(&msg).await.ok().map(|()| height)

let peer = choose_peer(others, MsgClass::Headers)?;
Some(o.hedge_to(peer))
})?
};
peer.send(&msg).await.ok().map(|()| height)
}
#[cfg(test)]

Handles write errors and a five-second WRITE_TIMEOUT

};
let outcome = match tokio::time::timeout(WRITE_TIMEOUT, write).await {
Ok(Ok(())) => Ok(()),
Ok(Err(e)) => Err(format!("Write failed: {}", e)),
// The peer stopped reading; treat it as a failed write.

Cancels the failing connection with self.token.cancel()

tracing::warn!("Disconnecting {} due to write error: {}", self.id, reason);
self.token.cancel();
return Err(NetworkError::ConnectionFailed(reason));
}
Ok(())

  • Create an issue for this
  • Dismiss this finding

let others = answering.into_iter().filter(|p| p.id() != o.peer && !p.is_closed());
let peer = choose_peer(others, MsgClass::Headers)?;
o.hedge_to(peer)
let mut batches: Vec<&mut OnWire> = reqs

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✨ Suggestion, not blocking · Performance · Moderate

Each successful hedge repeats an unbounded registry scan and sort

Why: A large filter backlog can monopolize the flow controller: each copy takes the shared request lock, scans the whole registry, and allocates and sorts the same on-wire batch list again. The public enqueue API accepts arbitrarily many distinct request keys, and the new drain loop multiplies that cost by the number of successful hedges before returning to flow control.

How to fix it and 6 places read

How to fix it
Build the ordered candidate list once per pass and process a bounded number of candidates or sends per tick. Revalidate each candidate and its destination before sending, and do not hold the registry lock during sorting or socket I/O.

Checked in the code
Exposes async fn enqueue(&self, height: u32, msg: NetworkMessage) to library callers

/// Within a message class, the lowest `height` is sent first. Use [`SendRequest::send`].
async fn enqueue(&self, height: u32, msg: NetworkMessage);
/// Returns `false` if the peer is not connected or the write failed.
async fn send_to(&self, addr: SocketAddr, msg: NetworkMessage) -> bool;

Inserts distinct keys with reqs.insert(key, ReqState::Queued(0))

}
pub async fn notified(&self) {
self.queue.notify.notified().await
}

Takes self.requests.lock().await before collecting on-wire batches from the whole registry

let (msg, height, peer) = {
let mut reqs = self.requests.lock().await;
let mut batches: Vec<&mut OnWire> = reqs
.iter_mut()
.filter_map(|(key, state)| match state {

  • Create an issue for this
  • Dismiss this finding

let answering = ConnectedPeer::for_test(conn(3, 0)).await;
let peers = [holders[0].handle(), holders[1].handle(), answering.handle()];
for (n, peer) in holders.iter().enumerate() {
peer.set_cap(1 << 30);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✨ Suggestion, not blocking · Testing · Larger change

The regression tests set connection and flow state by hand

Why: The broker test sets peer caps directly and calls receiving without delivering bytes. The controller test admits synthetic connections and enqueues directly into its private broker. Reverting broker.rs:440 to last_answer fails the receiving case and reverting manager.rs:724 to if let fails the burst assertion, but neither test checks the real path that produces the connection and receive state.

How to fix it and 7 places read · breaks a repository rule

How to fix it
Use the existing loopback handshake harness to start the manager and enqueue through NetworkManager. Drive cap changes and partial receives through loopback traffic, then assert on the filter requests observed by the answering peer.

Repository rule
This PR breaks a required rule of AGENTS.md: Don't set internal fields or states by hand: a test that builds a state production never reaches proves nothing.

Checked in the code
On the commented line: Forces a cap with peer.set_cap(1 << 30)

Simulates receive progress by calling broker.receiving(...) directly

if receiving {
broker.receiving(&[holders[0].id(), holders[1].id()]).await;
}
time::advance(HEDGE_AFTER / 2).await;
broker.enqueue(5000, get_cfilters(5000)).await;

And line 1056 overwrite the destination cap with answering.set_cap(...)

// The lowest goes out past the cap, the next fills it.
answering.set_cap(answering.in_flight_bytes() * 3);
let mut rounds = vec![hedge_all().await];
// A lower batch still queued goes out before any batch above it.
answering.set_cap(u64::MAX);
broker.enqueue(3500, get_cfilters(3500)).await;
rounds.push(hedge_all().await);
// The answering peer delivers its own batch.

Inserts a test peer with net.state.connected.admit(...)

let admitted =
net.state.connected.admit(peer, &session, net.state.max_peers, None).await;
assert!(matches!(admitted, Admission::Joined));
if n == 2 {
for start in [0, 1000, 2000, 3000] {

  • Create an issue for this
  • Dismiss this finding

@xdustinface
xdustinface requested a review from ZocoLini November 26, 2026 02:01
@github-actions github-actions Bot added the merge-conflict The PR conflicts with the target branch. label Nov 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR has merge conflicts with the base branch. Please rebase or merge the base branch into your branch to resolve them.

`Broker::hedge_filters` only ever copied the lowest filter batch on the wire, and the flow controller called it once per 250 ms tick. The next batch could only get a copy after the previous copy was delivered, so the batches of silent peers were repaid one round trip at a time, rounded up to the next tick, while the peer left answering sat idle in between. When two frozen peers owed a dozen or more batches, the request timeout dropped one of them before the store caught up.

Every batch whose peer is silent for `HEDGE_AFTER` is now eligible, in height order. The lowest batch on the wire keeps its rule: a copy once its peer answered nothing, past any cap, since it holds back the store. A higher batch needs its peer to have sent no bytes at all, so a peer midway through a big block keeps its batches, and it only goes to a peer with room in its cap, so the answering peer is kept busy up to what the flow controller sizes it for and is not flooded. The flow controller hedges until nothing more is eligible in a tick. Batches above a lower one still queued are left alone, as before for the lowest.

Closes #1530
@xdustinface
xdustinface force-pushed the fix/frozen-peer-hedges branch from 0d96916 to 5555f01 Compare November 26, 2026 11:59
@github-actions github-actions Bot removed the merge-conflict The PR conflicts with the target branch. label Nov 26, 2026
@manki-review

manki-review Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

✅ Review complete in 11m 45s

Planner (5s)
    fix · 143 lines · 2 agents
    judge effort: high

Review (behavior · full): 7 findings
    ✅ Claude Opus 5.5 · high: 0 findings (4m 19s)
    ✅ GPT 6.2 Sol · high: 6 findings (4m 4s)
    ✅ Related checks, claim checks and fix checks: 9 of 9 done (1m 5s)
    ✅ Second reads: 1 of 1 done, 1 finding (2m 4s)

Judge (4m 37s)
    graded 7 findings: 6 kept · 1 dropped
    dropped, as the finders filed them: 1 blocker
    origin checks: 3 checked
    verdict reader: read the diff (43s)

Posted: 4 findings
    4 suggestions
    not posted: 2 no realistic trigger

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 83% (resets 2026-12-01 05:00 UTC)
  • ChatGPT subscription: weekly 3% (resets 2026-12-02 01:49 UTC)

Judge decisions:

  • Kept: "A single hedge tick can repeatedly sort an unbounded request backlog" (suggestion): "note. This is the same defect as P2, and the code at broker.rs:420-429 has not changed: every call collects and sorts all on-wire filter batches under the requests lock. The hedger loop at manager.rs:761 repeats that call once per copy. In practice the filter pipeline keeps only a small number of batches on the wire, so the cost stays small. The cell is kept from the earlier round."
  • Dropped: "Filter hedges can exceed the answering peer's byte cap" (ignore): "ignore. The check p.in_flight_bytes() < p.cap() at broker.rs:452 is the same room test the router applies to every message at broker.rs:333. A one-message overshoot past the cap is therefore the existing design, and it is not new to this change. Project memory records that hedges are kept without a reservation and that their overshoot is accepted. The tie case at the lowest height needs two filter batches with distinct stop hashes at one height. Memory also records that batch boundaries are fixed, and the only consequence would be a few extra in-flight bytes on one peer."
  • Kept: "Higher filter batches can be copied while their original peer is streaming a reply" (suggestion): "warning cell with no realistic trigger. Higher batches are timed from o.last_progress at broker.rs:440. Streaming bytes are noticed only when the monitor samples growth at manager.rs:1121. A holder that starts a reply inside that sampling gap, just before HEDGE_AFTER runs out, can have a higher batch copied to an answering peer with free cap. The cost is one duplicate batch download. The case needs both that timing and a spare-cap peer, and it is unclear anyone would notice, so trigger is left empty."
  • Not listed, it names no trigger that happens in realistic use: "The hedger overlooks lower filter batches that the router has popped but not sent" (warning): "warning cell with no realistic trigger. route pops messages at broker.rs:324 and marks them OnWire only after its writes, at broker.rs:349. During that window a popped lower batch is visible neither to lowest_height (broker.rs:410) nor to the OnWire scan (broker.rs:423). The window lasts only as long as a few small socket writes, which is much shorter than the 250 ms hedge tick. The worst result is that the lower batch goes back to the queue for the next route pass. trigger is left empty."
  • Kept: "An optional filter write can hold up urgent hedges to other peers" (suggestion): "note. The failed-write part is P1. A send error still maps to None at broker.rs:458, which ends the while let at manager.rs:761. The failed peer is cancelled (peer.rs:353), so the next tick 250 ms later resumes with the remaining peers. The stalled-write part is not realistic. The chosen peer must have answered within HEDGE_AFTER, and a getcfilters message is tiny. Filling its socket buffer for the full 5 s WRITE_TIMEOUT would take such a peer stopping reading right after it answered. Hedging also now runs in its own task, so flow measurement is not blocked. The cell is kept from P1."
  • Kept: "The new hedge tests set up peer state outside the public API" (suggestion): "note. This is the same as P3. The broker test sets caps by hand at broker.rs:1031 and injects receiving at broker.rs:1039. The manager test admits ConnectedPeer::for_test connections directly at manager.rs:2641. That breaks the AGENTS.md rule to test through the public API. Both tests still fail when the changed lines are reverted, so revertGap is empty."
  • Not listed, it names no trigger that happens in realistic use: "A healthy peer whose first reply takes over 2 s now has every batch it holds copied" (warning): "warning cell with no realistic trigger. last_progress is set at route time (broker.rs:364), and higher batches qualify once silent_since.elapsed() >= HEDGE_AFTER (broker.rs:443). The holder's own silent_for is not checked. A holder that sends nothing for 2 s after being given idle work therefore has all its batches copied. That matches the PR's stated rule that a peer which sent no bytes is treated as frozen. A dashd peer that sends nothing for 2 s on a filter request is uncommon, and the copy also needs a peer with spare cap. trigger is left empty."

Timing:

  • Parse: 7.6s
  • Review agents: 420.4s
  • Judge: 277.3s
  • Total: 705.2s

Last reviewed 5555f01 · head 5555f01 · up to date

  • Pause automatic reviews
  • Review again
  • Deeper review

@github-actions

github-actions Bot commented Nov 26, 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 waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 26, 2026

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved. 1 suggestion, which doesn't block.

What this does: When peers stop answering, the client used to ask a helper peer for only one missing filter batch per tick. It now asks an idle peer for several stuck batches at once, up to that peer's capacity.


1 suggestion · not blocking
✨ Higher filter batches can be copied while their original peer is streaming a reply
Suggestion, not blocking · Performance · Moderate · dash-spv/src/network/broker.rs:440

Why: A peer that starts streaming a large reply just before the two-second hedge deadline can still look silent to the hedger until the next one-second timeout sample. The hedger can fill the answering peer's spare capacity with duplicate higher batches during that gap, even though the original peer is already sending bytes.

o.last_answer
} else {
o.last_progress
};
!answering.iter().any(|p| o.hedges.contains(&p.id()))

How to fix it
Use a per-connection receive timestamp updated when bytes are read for higher-batch eligibility. Keep the request-age guard so an idle peer is not treated as stalled on its first request, and keep the separate completed-answer rule for the lowest batch.

Checked in the code
Uses o.last_answer for the lowest height and o.last_progress for higher heights

// lowest batch is worth a copy then, any other would be downloaded twice.
let silent_since = if o.height == lowest {
o.last_answer
} else {
o.last_progress

Records streaming peers only when the timeout monitor samples growth and sees p.partial

entry.bytes = p.bytes;
if p.partial {
streaming.push(p.id);
}
}

Can issue multiple copies before the timeout monitor takes its next sample

// another peer may be idle only because the batch they owe blocks the store.
while let Some(height) = broker.hedge_filters(&handles).await {
tracing::debug!(target: "dash_spv::network", "hedged filter batch {}", height);
}
}

  • Create an issue for this

What to test

The review model wrote these steps. Check what a step runs before you follow it.

Setup: Run filter sync against several peers, for example with the CLI on testnet with --data-dir set and peer_speed and dash_spv::network debug logs on.

  1. Freeze two peers that hold filter batches, for example by blocking their traffic with a firewall rule, while a third peer is idle. Expect several hedged filter batch lines in the same tick, not one per 250 ms.
  2. Keep the frozen peers blocked. Expect the idle peer to receive no more batch copies than its cap allows, apart from the lowest batch, which goes out past the cap.
  3. Let a frozen peer resume while it still holds a large batch in progress. Expect only its lowest batch to be hedged, not the batches behind it.
  4. Requeue a lower filter batch while higher ones are stuck, for example by dropping a peer. Expect no batch above the queued one to be hedged until it goes out.
  5. Edge case: freeze all peers at once so the link looks stalled. Expect hedges only to peers that are idle, and none once no peer is answering.
  6. Edge case: disconnect the peer that received a hedge. Expect its batches to be hedged again to another answering peer on a later tick.
About this review
  • Reviewed 5555f01, round 2
  • 143 changed lines read in 11m 45s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 4.2M in (3.2M from cache) · 78k out · about $5.95 at API prices
  • Runner: self-hosted · started after 8s · peak memory 3.8 GiB of 30.0 GiB
  • How Manki reviews

@ZocoLini
ZocoLini merged commit 0a75049 into dev Nov 26, 2026
28 of 29 checks passed
@ZocoLini
ZocoLini deleted the fix/frozen-peer-hedges branch November 26, 2026 16:14
manki-review Bot added a commit to manki-review/review-memory that referenced this pull request Nov 26, 2026
ZocoLini added a commit that referenced this pull request Nov 26, 2026
#1483 added a `Bans` parameter to `PeerSet::admit` while #1532 added a test calling it without one. Both merged, so the `dash-spv` test target does not compile on `dev`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

waiting-bots Waiting for the review bots to report on this head

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test_filter_sync_passes_frozen_peers fails when the frozen peers owe many batches

2 participants