Repository navigation
fix: bound the requester's fetch loop, and classify what comes back (#1088, #1144, #1134, #1143) - #1145
Conversation
`ChunkData` had no minimum-length validation, so a peer could send an unbounded stream of empty frames before `StreamEnd`. Each one leaves the receiver's `cumulative` / `bytes_since_voucher` untouched, so the `cumulative > expected_wire` overrun guard — which only ever trips on bytes — never fires, and both receive loops spin without making application-level progress. No integrity or payment impact (0 bytes are billed, no vouchers signed, the content hash is still verified on exit), but the loops were bounded only by the QUIC idle timeout, not by application logic. Add `ChunkData::validate`, bounding the payload on both sides (1..=CHUNK_SIZE), and call it from `receive_and_pay` and `UpstreamPull::next_chunk` in place of their ad-hoc ceiling checks. The floor is load-bearing beyond this fix: it is what lets the inactivity deadline (#1134) rest on frame arrival, since with empty frames banned "a frame arrived" and "bytes made progress" become the same statement and a peer cannot refresh the deadline with padding. Emitting an empty frame was already impossible on the serve side — the payload is chunked with `slice::chunks`, which yields nothing for an empty slice, so even the empty blob (bao wire length 0) goes straight to `StreamEnd`. Rejection is therefore safe with no carve-out for #1054. Rejecting at the receive loop rather than at decode follows this module's existing convention (validation is separate from decode so a handler can build a message before signing it), so the codec still round-trips an empty frame; `chunk_data_empty_roundtrip` is renamed and its comment corrected — it had asserted a zero-length chunk was "a real on-wire case", which is the premise this fixes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…1144) #1129 made the serve path report `InternalError` ("do not retry this node") rather than `NotFound` ("node lacks the blob") when a node is degraded by an origin/store fault. That distinction was inert on the requester side: both pull paths bailed identically on every refusal, formatting the `StreamError` into a string and discarding it, so `classify_pull_failure` saw no typed sentinel and fell through to `Outcome::Unreachable`. Two consequences, one of them wrong on its own terms independent of #1129: a node that honestly reports a clean `NotFound` was tarred exactly as hard as a dead one — an `Unreachable` hit on the local EWMA *and* a gossiped observation, for truthfully saying it does not hold a blob. And the `InternalError` signal could not change requester behavior at all. Add `UpstreamRefused`, carrying the wire `StreamError` verbatim (mirroring `UpstreamVoucherRejected`'s typed reason rather than a lossy stringification), raised by both open stages through one shared helper so they cannot drift. `classify_pull_failure` now splits on the code: `InternalError` scores `Unreachable` (a peer reporting its own degradation — which the EWMA then uses to deprioritise it), while `NotFound` / `EvictedSinceProbe` / `Overloaded` / `BlobTooLarge` are metered and skipped without touching reputation. A refusal is proof the peer is reachable and answering; only the one code by which a peer reports itself degraded may score it. The predicate is an exhaustive match, not a `matches!`, so a new `StreamError` variant cannot silently inherit either verdict. Only the wire code is ever recoverable — never the finer `ServeRejectReason`, which deliberately collapses seven reasons onto `NotFound` so channel existence cannot be probed. `wire_error`'s doc claimed the requester already discriminated; it did not. That is now true rather than aspirational. Two consumers stop sniffing `Display` strings and downcast instead: - the CLI's unbound-cache-miss hint, which matched any error whose text contained both "delivery refused" and "NotFound". Its test built the error with `anyhow!("delivery refused: Some(NotFound)")` — a look-alike string, so it would have passed vacuously against a hint that never fired in production. It now constructs the real sentinel. - the e2e retry loop, which treated *every* refusal as retryable — including a hard `InternalError` it would spin on until the deadline. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`--timeout-ms` was an overall deadline for the entire blob fetch, which makes it near-useless as a health signal: an overall deadline has to be sized against `blob size × link speed`, so it killed legitimate large or slow-but-healthy transfers, while a value small enough to catch a dead node quickly could not serve a big blob at all. Operators were tuning a number tied to content size rather than to node health — and the CLI had already grown a `scaled_timeout` hack (a hardcoded 35 MiB/s bandwidth guess) purely to paper over it. That hack is deleted. Give each stage the bound that fits it, via a `PullDeadlines` type that makes the model explicit: - OPEN (dial → request → verified `StreamResponse`): wall clock. Bounded work whose duration does not scale with the blob, so a slow one is a stall. - STREAMING: INACTIVITY. The clock resets on every byte, so it trips only when a provider stops delivering — indifferent to size and link speed. - OVERALL: an optional hard cap, off by default. The open bound lives inside the shared `open_stream` helper rather than being left to callers, and that is load-bearing: the production paths now run with no overall cap (so a blob of any size can complete), so "the caller wraps us in a timeout" would mean the handshake is *unbounded* — and the open is exactly where a peer can accept a connection, take the request, and then say nothing. Making `open` a field of `PullDeadlines` means that state cannot be expressed. `open_stream` also de-duplicates the handshake the buffered and progressive paths had each been carrying. New `PullStalled` sentinel, kept separate from `PullTimeout` because they now deserve opposite verdicts. `PullTimeout` (our own budget) stays reputation-exonerating; `PullStalled` scores `Outcome::Unreachable`. That inversion is only sound because of the split above: a whole-transfer deadline fired on healthy transfers and so *had* to be exonerating, whereas a stall bound can only fire on a peer that went silent while we waited. Rests on #1088: with empty `ChunkData` banned, a peer cannot refresh the inactivity deadline with padding that carries no bytes. Belt-and-braces, the deadline resets only where `cumulative` advances, never merely on frame arrival. `self_pay`'s voucher-ack read is bounded too — otherwise a peer that takes a voucher and goes quiet would hang a pull that has no overall cap. Also fixes a latent ceiling nothing had filed: the node's buffered pull-through wrapped the *whole* fetch in `pull_timeout` (20 s), so a node could not pull through any blob needing more than ~20 s of transfer — and the background warm that should have rescued it was capped by the same derived deadline. The foreground serve path keeps `outer_pull_deadline` (it bounds how long a *client* waits, and on expiry still yields a clean miss plus a detached warm), but the warm itself now runs uncapped, because the stall bound is what stops it hanging. `--timeout-ms` is now an off-by-default opt-in cap; `--stall-timeout-ms` (30 s) is the primary. Node-side: new `cache.node_pull_stall_timeout_sec`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…1143) `open_or_reuse_channel` was unbounded, and it runs BEFORE the per-candidate `pull_timeout` that #1141/#1142 added. So a candidate whose on-chain open wedged — an unresponsive RPC endpoint, an `openChannel` tx that never mines — consumed the caller's entire outer deadline, candidates #2..N were never reached, and the serve path refused a blob the honest fallback held. `PULL_THROUGH_OUTER_SLACK`'s doc already conceded this; that concession is now deleted rather than reworded. The obvious fix is wrong, and #1143 says so: a `tokio::time::timeout` around the call drops the future with an `openChannel` possibly in the mempool, so the tx can still land and escrow a deposit for a channel nobody tracks. It is worse than the issue states. `InFlightOpenGuard` is in-memory and was held by the CALLER, so a dropped future also released the provider's open slot — and the next cache miss would open a SECOND channel to the same provider. When the first tx mined, the boot reconcile scan would classify it `DeferredSecondOpen` and warn WITHOUT recovering, deferring to "a later boot once the live row clears": at a 90-day channel expiry against a ~1-2 day (700k-block) event lookback, that means never. Two deposits escrowed, one unreclaimable. There is also a budget conflict no single timeout can resolve. A cache miss must abandon a provider in seconds so the candidate loop can try the next one; a broadcast tx may legitimately need minutes to mine on a slow L2. So: don't cancel the open — stop waiting on it. - Opens are singleflighted per provider: `opens_in_flight` becomes a map to a shared handle on a DETACHED task. A caller arriving mid-open joins it rather than starting a second `openChannel`. - The task owns the tx and holds the in-flight slot for its whole life, so a caller that gives up cannot release the slot with a tx still in flight. The double-open hazard is gone by construction. - The caller waits only `budget` (the per-candidate `pull_timeout`), then gets a typed `ChannelOpenPending` and moves to the next candidate. The open keeps running; if it lands, the channel is persisted and the next pull reuses it. Nothing is abandoned — the issue's second acceptance criterion. - `ChannelOpenPending` scores NO reputation. A wedged open is our own chain lane, not evidence about the peer. The task's success path returns `()`, not a `ChannelContext`: a successful open persists, and every waiter reads it back from the store — so "I opened it" and "someone else opened it" share one code path. The store re-check lives inside the task, which is what closes the window where a previous open lands between a caller's fast-path miss and its taking of the map lock. `OPEN_RECEIPT_TIMEOUT` (3 min) bounds the receipt wait inside the task so a stuck tx cannot pin a provider's slot forever, mirroring `APPROVE_RECEIPT_TIMEOUT` (#1109). The kernel takes it as `Option<Duration>`: the node passes `Some(_)`, the CLI `None` — `decdn fetch` has no reclaim sweep and no reconcile scan, so an open it stopped waiting on that later mined would strand a deposit with nothing but a tx hash in stderr. The anvil concurrent-open race test now sees BOTH callers succeed (they join one open) rather than one bailing for retry; the invariant it guards — exactly one deposit escrowed, one channel tracked — is unchanged and still asserted. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThe pull pipeline separates OPEN, streaming-stall, and hard-cap deadlines, adds typed refusal and stall classification, bounds channel-opening waits, updates configuration and metrics, and rejects invalid chunk payloads. ChangesPull pipeline
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant PullCandidate
participant BuyerChannelService
participant PullEngine
participant Upstream
PullCandidate->>BuyerChannelService: request channel with caller budget
BuyerChannelService->>PullEngine: start or join upstream pull
PullEngine->>Upstream: open stream within OPEN deadline
Upstream-->>PullEngine: response and chunk frames
PullEngine->>PullEngine: reset stall deadline on byte progress
PullEngine-->>PullCandidate: blob, refusal, stall, or pending result
Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 88.71% (2452/2764 lines) |
There was a problem hiding this comment.
Code Review
This pull request refactors the pull deadline mechanism by splitting it into a wall-clock bound for the connection/handshake stage and an inactivity-based stall timeout for the streaming stage, preventing healthy large transfers from timing out. It also detaches channel-opening tasks to prevent orphaned on-chain deposits and introduces typed sentinels (UpstreamRefused and PullStalled) to allow precise reputation scoring. The review comments provide valuable, actionable feedback, suggesting a simplification of the error rehydration logic in buyer_channel.rs to avoid double formatting, and recommending passing StreamError by value to the refusal helper in client-pull/src/lib.rs to eliminate unnecessary cloning.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Pull request overview
This PR addresses several coupled defects in the requester/pull-through pipeline by (1) enforcing protocol-level progress invariants, (2) propagating typed refusal/timeout/stall signals end-to-end, and (3) bounding each stage of pulling with the deadline that matches its failure mode (wall-clock for open, inactivity for streaming, optional hard cap overall). It also makes buyer-channel opens singleflighted and budget-aware so a wedged on-chain open can’t starve candidate fallbacks.
Changes:
- Add
ChunkData::validate(+ new validation errors) and use it to reject zero-length and oversized chunk frames. - Introduce stage-specific pull deadlines (
PullDeadlines), add inactivity-based streaming bounds (PullStalled), and add a typed refusal sentinel (UpstreamRefused) so callers can classify outcomes correctly. - Singleflight buyer-channel
open_or_reuse_channelwith caller budgets and a detached open task, plus new metrics/config knobs to support the new behavior.
Reviewed changes
Copilot reviewed 25 out of 25 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/protocol/tests/snapshots/public_api__public_api.snap | Updates the protocol public-API snapshot to include ChunkData::validate and new validation error variants. |
| crates/protocol/src/message.rs | Adds EmptyChunk / ChunkTooLarge to MessageValidationError with rationale and error messages. |
| crates/protocol/src/client.rs | Documents + implements ChunkData::validate; updates tests to ensure empty chunks decode but fail validation. |
| crates/node/tests/sighup_signal.rs | Extends resolved-config test seed to include node_pull_stall_timeout_sec. |
| crates/node/tests/node_origin_pull.rs | Updates opener trait signature, adds a “wedged channel open” fixture/test, and plumbs stall timeout into origins. |
| crates/node/tests/client_loopback.rs | Adapts loopback tests to pass PullDeadlines instead of a single timeout Duration. |
| crates/node/tests/anvil_settlement_e2e.rs | Adds an explicit open budget for e2e opens and updates concurrent-open expectations post-singleflight change. |
| crates/node/src/selection.rs | Updates outer-deadline documentation to reflect open-vs-stream bounds and the uncapped warm behavior. |
| crates/node/src/runtime/reload.rs | Adds node_pull_stall_timeout_sec into runtime reload defaults/tests. |
| crates/node/src/runtime/mod.rs | Wires node_pull_stall_timeout_sec into NodeOriginConfig and makes background fill uncapped (None). |
| crates/node/src/node_origin.rs | Integrates PullDeadlines, PullStalled, UpstreamRefused, and ChannelOpenPending; refines failure classification + metrics. |
| crates/node/src/metrics.rs | Adds counters for refused pulls, stalled pulls, and channel-open-pending events. |
| crates/node/src/handlers/client.rs | Makes background fill optionally deadline-capped and defaults it to uncapped; adds helper with_optional_deadline. |
| crates/node/src/buyer_channel.rs | Implements detached, singleflight channel opens with per-caller budgets and a typed ChannelOpenPending sentinel. |
| crates/e2e/src/client.rs | Updates retryability logic to downcast UpstreamRefused and branch on StreamError instead of string-sniffing. |
| crates/common/src/config/types.rs | Adds cache.node_pull_stall_timeout_sec config field and documents stage-specific semantics. |
| crates/common/src/config/resolved.rs | Adds resolved node_pull_stall_timeout_sec with documentation. |
| crates/common/src/config/mod.rs | Defines DEFAULT_NODE_PULL_STALL_TIMEOUT_SEC and resolves it into ResolvedCache. |
| crates/common/src/cli/fetch.rs | Replaces overall --timeout-ms default with --stall-timeout-ms (default 30s) and makes hard cap opt-in. |
| crates/client-pull/src/lib.rs | Adds UpstreamRefused, PullStalled, PullDeadlines; refactors open stage into open_stream; applies inactivity bounds across streaming and voucher-ack waits. |
| crates/client-pull/src/buyer_channel.rs | Adds optional receipt-wait bounds (await_receipt) and plumbs receipt_timeout into open_channel. |
| crates/cli/tests/config_validate.rs | Extends resolved-config fixtures to include node_pull_stall_timeout_sec. |
| crates/cli/src/commands/fetch.rs | Switches to typed refusal downcast for binding hinting and passes PullDeadlines into fetch. |
| crates/cli/src/commands/config.rs | Prints stall timeout in config summaries and updates the default config template comments. |
| crates/cli/src/commands/bundle_pull.rs | Uses PullDeadlines (stall bound + optional hard cap) for per-entry pulls. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 80.71% (was 80.42%, ▲ +0.29%) — 47103/58361 lines
History
|
Copilot, `client-pull/src/lib.rs`: `UpstreamRefused`'s Display comment claimed the loopback tests match `UnknownChannel` on that string. They cannot — `UnknownChannel` is a node-side `ServeRejectReason` that collapses to the wire `NotFound` in `wire_error` before it ever leaves the server, so a requester can never see it. The comment now says what actually renders (a wire code, never a reject reason) and why matching a reject-reason name would never fire. This was the same stale claim this PR corrected in `e2e/src/client.rs`, reproduced in the new sentinel's doc. Copilot, `node_origin_pull.rs`: `WedgedOpener` was documented as returning the typed `ChannelOpenPending` but bailed with a bare string, which does not `downcast_ref`. So `classify_pull_failure` took its generic channel-open-failure arm, not the pending one, and the test never exercised the path it exists for. It still passed — because NEITHER arm scores reputation, the assertions could not tell the two apart. It now returns the real sentinel and asserts `node_pull_channel_open_pending_total == 1` and `node_pull_channel_open_failures_total == 0`, which is what distinguishes them. Verified the assertion has teeth: restoring the string error fails the test. Gemini, `node/src/buyer_channel.rs`: `rehydrate_open_error` formatted the error chain twice (`map_or_else` rebuilt it in the None arm). Straight `match`. Gemini, `client-pull/src/lib.rs`: `refusal` took `Option<&StreamError>` and cloned. Both call sites return immediately, so the field can be moved out — `Option<StreamError>` by value, no clone. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Three critical findings from the multi-agent review, all in the buyer-channel commit. The first is an own-goal: the "safety backstop" I added created a money-losing path `main` cannot reach. ## OPEN_RECEIPT_TIMEOUT created a permanent deposit-loss path `OPEN_RECEIPT_TIMEOUT` (3 min) bounded the `openChannel` receipt wait inside the detached open task. On timeout: 1. the task errored, so `InFlightOpenGuard` dropped and the provider's slot was RELEASED, with no store row; 2. the broadcast tx was still in the mempool and later mined — deposit escrowed, untracked; 3. the next cache miss saw no row and no in-flight open, so it escrowed a SECOND deposit, and that one got the row; 4. the boot reconcile scan then found the first channel, saw a live row already covering the provider, and classified it `DeferredSecondOpen` — declining to adopt it. Permanently stranded. And the constant was deliberately sized BELOW what a slow L2 needs (#1109 observed ~27 min), so "the tx mines after we gave up" was the expected case, not the exotic one. Two comments in the same file described this scenario and reached opposite conclusions; the pessimistic one was right. The insight I had missed: holding the slot while a tx is outstanding is CORRECT, not a bug. The slot exists to prevent a second escrow. The caller is already unblocked by its own budget — that is what fixes #1143 — so the receipt never needed a bound at all. Bounding it is what broke it. `openChannel`'s receipt wait is unbounded again, now with the reasoning written down: `approve` is idempotent so abandoning its receipt is free, but `openChannel` ESCROWS, and abandoning an escrowing tx does not cancel it. Holding the slot is also what lets the boot scan work: with no second open there is no live row, so an orphan is `Rehydrate`d rather than deferred. ## The detached task's failures were unobservable `run_open` propagated `open_channel`'s error with a bare `?`. The task's `Err` reaches nobody once every waiter has timed out — which, at a 20 s caller budget, was the common case. So a reverted, under-funded, or RPC-failed open could produce zero log lines and zero metric increments. The worst leg had no log of its own at all: "ChannelOpened event not found … the deposit is escrowed on-chain but untracked" is real USDC, and it relied on a caller that was usually gone. The task is now the reporter — it is the only party guaranteed to observe the outcome. It logs with the failure reason and meters, and an `OpenReported` marker keeps a caller that *was* still waiting from double-counting. So `channel_open_failures_total` now counts opens that failed, not opens that failed while someone happened to be listening. ## An unbounded reclaimExpired pinned the provider's slot forever `try_reclaim`'s receipt wait was unbounded, and `run_open` calls it on the rotate leg — inside the detached task. A stuck `reclaimExpired` therefore pinned the task and its in-flight slot for the life of the process, wedging that provider: exactly the starvation #1143 set out to remove, one layer down. Bounded now, and the asymmetry with `openChannel` is the point: a reclaim REFUNDS rather than escrows, so giving up strands nothing — the row stays, the hourly sweep retries, and the open fails retryably. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… backstop Two review findings, both about a bound that wasn't there. ## A zero stall budget would gossip every honest peer as unreachable `cache.node_pull_stall_timeout_sec` and `cache.node_pull_timeout_sec` had no `must be > 0` check, though 21 other knobs in this resolver do. For the stall budget that is newly dangerous, because #1134 made a stall REPUTATION-AFFECTING. A `0` trips `PullStalled` on the first poll of every streaming read, and `classify_pull_failure` scores that `Unreachable` — which `record_outcome` writes to the local EWMA *and* the observation buffer the gossip publisher drains. So one fat-fingered value would not merely break the node: it would broadcast false `Unreachable` observations about every honest peer it touches. Its predecessor, `PullTimeout`, was exonerating, so a bad value used to stop at the local node. Raising the signal's authority raised the cost of getting it wrong, and the validation never followed. ## "Inactivity-bounded" is not the same as "bounded" The background warm was left uncapped, on the argument that it "cannot hang — it can only run as long as an upstream keeps feeding it bytes." That argument has a hole: the inactivity deadline resets on ANY byte, so an upstream trickling one byte per stall-window keeps a warm alive indefinitely without ever tripping it. And a warm that never ends is worse than a leaked task. `arm_background_fill` claims the hash for the task's lifetime, so a permanently-trickling upstream means the node can never warm that blob again for the life of the process — silently, with no error and no timeout metric, because the `Elapsed` arm was dead code under `None`. The fix is a *bigger* cap, not the absence of one. `BACKGROUND_FILL_HARD_CAP` is an hour — ~50× the derived foreground deadline, so it bounds no honest transfer the `max_blob_size_mb` ceiling permits (a 1 GiB blob would have to average under 300 KB/s to hit it) — and exists purely so every warm terminates. Hitting it is pathological, so it now logs at `warn!`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A mutation-testing review reverted each fix in this PR and re-ran the suite. Three of the four stayed green: #1088 receive loops back to a ceiling-only check → 887/887 PASS #1144 every refusal scores Unreachable (the bug) → 725/725 PASS #1134 buffered path back to a whole-blob deadline → 725/725 PASS #1134 `PullStalled` appears in zero test files → no coverage at all #1143 wedged-open budget removed → 1 FAIL ✅ So the suite ratified the OLD behavior for three fixes. The green run reported on this PR would have been just as green with the fixes reverted. The one guard that worked was the one strengthened after an earlier review caught a stub returning a bare string instead of a typed sentinel — the same disease was everywhere else and went unchecked. Six tests, each verified to FAIL when its fix is reverted: - `node_origin_empty_chunk_stream_is_rejected_not_spun_on` (+ the `next_chunk` twin). `ChunkData::validate` was unit-tested, but nothing proved the receive loops CALL it. Needed a real fixture streaming `ChunkData { bytes: [] }`, since an empty-frame stream never trips the inactivity deadline — frames keep arriving, so `validate()` is the only thing between the loop and an infinite spin. - `node_origin_mid_stream_silence_scores_stalled_upstream`. `spawn_a_stalling_server` stalls at the OPEN stage, so it exercises `PullTimeout`, never `PullStalled`. The new fixture opens honestly, delivers real frames, then goes silent. Asserts the EWMA drops AND an observation is gossiped — the only behavioural difference between `PullStalled` and the `PullTimeout` it must not be confused with. - `node_origin_slow_but_healthy_transfer_completes_past_pull_timeout`. The regression guard for the entire PR, and it did not exist. `serve_wire_paced` paces by voucher interval and never sleeps, so nothing in the suite had ever moved a transfer past `pull_timeout`. It now self-checks that its transfer really did outlive the open budget, so it cannot pass vacuously on a fast machine. - `node_origin_not_found_refusal_does_not_tar_upstream` and `node_origin_internal_error_refusal_scores_unreachable`. The predicate was unit-tested; the WIRING was not. Both drive real serving nodes so the refusal travels the wire, and each survives the other's mutation — together they pin both directions of the split. (The pre-existing `client_not_found_is_refused` was never a guard: it asserts `contains("refused")`, which the old code's string also satisfied.) One finding from writing them: at full wire speed the empty-frame stream doesn't merely spin the loop — the reads stay permanently `Ready`, so the task never yields and cannot be preempted by ANY timeout, including its own inactivity deadline. It wedges a worker thread outright. The fixture paces frames so the bug becomes observable as a failure rather than a hang; the underlying attack is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment rot was the actual bug twice in this PR, so these are not cosmetic. Verified against the code rather than reasoned about. - `receive_and_pay`: "This is the ONLY place it moves" — false; the deadline also extends after a completed voucher round trip. The semantic claim it was defending survives (both sites sit past the point `cumulative` advanced, so only byte progress can refresh it), but the absolute was wrong. Say the true thing. - `PullTimeout`: its doc still described the pre-#1134 stage layout — "raised by the buffered delivery", "`open_progressive_pull` applies no timeout of its own". Both now false, and directly contradicted by `open_progressive_pull`'s own doc 950 lines later. It is now raised by our own wall clocks only (the `open_stream` bound and the optional hard cap); the streaming loops raise `PullStalled`. - `UpstreamPull`'s Deadlines paragraph: same rot — "the caller bounds the open phase". #1134 moved that bound inside `open_stream` precisely because leaving it to the caller is how the buffered handshake shipped unbounded once already. - `ChunkData`: "impossible by construction … chunked with `slice::chunks`" is true of the buffered emitter and says nothing about the window-paced one, which forwards upstream frames verbatim and inherits the guarantee from the requester's `validate()` rather than establishing it. That second path is the fragile one, and this is the invariant `PullStalled` rests on, so both now get named. - `InFlightOpenGuard`: "means in practice never" overstated it — an idle cooperative close can clear the live row inside the lookback window. Softened, and tied explicitly to `open_channel`'s unbounded receipt wait, since the two rest on the same argument and must not drift. - `run_open`'s `let _ = try_reclaim(...)`: claimed a failure "surfaces to the caller", which is false once the caller has timed out. The real guarantee is `try_reclaim`'s own `warn!` plus the hourly sweep. Also: `PullDeadlines::whole_transfer` is now `#[doc(hidden)]` and documented as test-only. Because it sets `hard_cap == stall` and the cap's clock starts earlier, the cap ALWAYS elapses first — so `PullStalled` can never fire under it. Every loopback test using the helper is exercising a pull with the stall signal silently disabled, which is worth knowing before anyone reaches for it in production. Plus: the duplicate `# Errors` section on `open_or_reuse_channel` (the first predated the rewrite and was a strict subset of the second), and `node_pull_refused` citing "six more series" when only five wire codes can reach `UpstreamRefused` (`VoucherRejected` is rejected by `StreamResponse::validate`). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Multi-agent review: 4 new commitsRan a five-agent review (code quality, silent failures, test coverage, type design, comment accuracy). It found three criticals and, more importantly, proved by mutation testing that most of this PR's tests were worthless. All addressed in The tests ratified the old behaviorThe reviewer reverted each fix and re-ran the suite:
The green suite I reported would have been just as green with the fixes reverted. Six new tests now guard them, each independently verified by me to fail on revert (not taken on trust). The one guard that already worked was the one strengthened after the earlier bot review caught a stub returning a bare string — the same disease was everywhere else and I hadn't looked.
|
The engineering held up under attack — I could not break the detached-task singleflight — but a five-agent review found the fix was UNGUARDED, the outer deadline arithmetic had quietly become false, and three claims in the PR body no longer matched the code. Each fix below fails on revert; that is the bar, and it is the one the previous round missed. **The singleflight had no test.** Removing the budget bound from the real `BuyerChannelService` left the node suite green at 731/731 — including `a_wedged_channel_open_does_not_starve_the_candidate_loop`, the test named for it. Its `WedgedOpener` mock re-implements the predicate instead of exercising it. Replaced with two tests against the REAL service (wiremock chain that never answers): the caller returns `ChannelOpenPending` on its own budget, the provider's open slot is STILL HELD after it leaves, and a second caller joins rather than escrowing a second deposit. Plus anvil section A0, which disables automine so the `openChannel` genuinely sits in the mempool — the timeout arm no other e2e reaches, because instant mining means no caller ever times out. **`outer_pull_deadline` budgeted one stage per candidate; a candidate costs two.** The channel open (#1143) and the stream open (#1134) are sequential, so at defaults three candidates could need 120s against a 70s ceiling and candidate #3 was never dialled — the exact fallback starvation #859 exists to prevent. `main` conceded this hazard in a comment; this PR had deleted it and asserted the opposite. The channel open now has its own `CHANNEL_OPEN_CALLER_BUDGET` (5s — a caller's willingness to wait, not the open's lifetime) and the deadline covers both stages. The invariant test asserted the formula against itself; it now asserts against what a candidate can actually cost, and the starvation test uses three candidates so it can tell a loop that reaches #2 from one that reaches #3. **`ClientMessage::validate` was blind to the #1088 floor**, while its own doc calls itself the seam a receive loop should call — and a test actively pinned the hole. Dispatched, and the assertion inverted. **Three of `run_open`'s five error legs were silent.** The rotate leg's reclaim receipt wait (3 min) outlives every caller's budget (seconds), so a store fault or an unreclaimable channel fired with nobody listening: a provider could become permanently unusable while emitting zero logs and zero metrics. All legs now report for themselves. `reserved_open`'s bare string — the last stringly-typed outcome in this code — becomes `OpenSlotReserved`, so a benign reconcile hold stops being counted as a channel-open FAILURE on every boot. **Local faults were scoring the peer.** `classify_pull_failure`'s catch-all is the PRIMARY dead-peer signal, so exonerating it wholesale (as suggested) would have gutted reputation. Instead the small, closed set of our-own-fault sites (signer, encode, range) carries `LocalPullFault` and is exonerated: a node with a broken signer no longer gossips `Unreachable` about every honest provider it meets. **An honest `NotFound` had zero consequence.** Every candidate reaching the pull already claimed `has_blob` at probe, so a refusal is a peer contradicting itself. Reputation is still the wrong instrument, but recording nothing let such a peer keep winning the ranker and burn a candidate slot on every miss forever. Now negative- cached per (peer, hash), and `probe_and_rank` consults the cache — the one chokepoint both discovery paths pass through. **The background warm is capped, not uncapped.** `BACKGROUND_FILL_HARD_CAP` landed in a later commit; three docs and the PR body still said otherwise. Corrected. The cap bounds the leak but not the amplification, so warms now take a concurrency permit (`MAX_CONCURRENT_BACKGROUND_FILLS`) — the hour-long lifetime made a slow upstream a memory and spend amplifier. Shedding is the right failure mode: a warm is speculative work for a future request. **`decdn fetch` could hang forever.** `--timeout-ms` defaulted to unset and the stall clock resets on any byte, so a peer trickling one byte per window hung the CLI with no error — and hung a whole `bundle pull` manifest. It now defaults to a 1h leak guard, mirroring the node's own reasoning, and both timeout flags reject zero. Verified: 2240 workspace tests, 738 with anvil-e2e, clippy/fmt/doc/deny clean. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The first round's defect class recurred one stage over: `outer_pull_deadline`
budgeted two of a candidate's three stages, and a comment asserted it budgeted
all of them. Plus a cluster of mis-attributed failures, silent legs, and false
comments.
**The deadline (critical).** A candidate costs channel open (5s) + stream open
(20s) + — for a peer that opens honestly and then goes SILENT — one full stall
window (20s). The formula budgeted only the first two, so at defaults a stalling
candidate cost 45s against 25s budgeted. `node_pull_stall_timeout_sec` is
operator-tunable and `config/types.rs` invites raising it ("tune it against
upstream responsiveness, not content size"); at 120 a single silent candidate
outlasted the whole 85s deadline and #2/#3 were never dialled — the pre-#859
starvation, reintroduced by the new knob. `stall` is now a term, so the deadline
scales with it and no cross-field check is needed. Worst-case client wait on a
total miss: 85s -> 145s.
Mis-attribution:
- `bind_upstream_ctx` signed with the same buyer key as vouchers, ran before the
stream open on both paths, and `warn!`ed its error away — so a node with a
broken buyer key failed on every candidate while `node_pull_local_fault`, whose
doc calls any sustained rate an emergency, stayed at zero.
- Honest refusals were negative-cached for 5 minutes. `wire_error` collapses seven
reject reasons onto `NotFound` — deliberately, so channel balances cannot be
probed — and three are ours or transient, so an exhausted deposit or the
chain-watcher lag right after we open a channel blackholed a healthy peer.
`RefusalVerdict` now splits durable from transient; the latter gets a 30s TTL.
- A mid-stream `StreamError` was stringified at three sites, fell to the catch-all,
and scored the peer `Unreachable` — the exact bug #1144 fixed, one stage later.
Silent legs: the detached open task's `JoinError` (a panic, with likely no waiter
left to observe it), the sustained store fault on the reuse fast path, and a
poisoned `opens_in_flight` mutex (which wedges every open for the process lifetime)
were unlogged or `debug!`-only — invisible at the default `RUST_LOG=info`.
Cancelled warms now have a counter, so `spawned == succeeded + failed + cancelled`.
Invariants made structural: `ChunkData`'s non-empty floor was advisory — two receive
loops remembered to call `validate()`, neither emitter did, and
`ClientMessage::validate` (the seam the PR added) was called by no receive loop at
all. Now a private field + `new()` + `#[serde(try_from)]`, so an empty frame cannot
be built or decoded; the adversarial test forges it on the wire, which is where an
adversary actually lives. `InFlightOpenGuard::spawn_open` makes a caller-held guard
unrepresentable — `let _guard` -> `let _` was one character from a stranded on-chain
deposit. Background warms now bound bytes, not task count: 8 concurrent x a 1 GiB
blob ceiling was up to 8 GiB resident for an hour each.
Every fix was verified to fail on revert. That check caught one of its own: the
first mid-stream guard asserted against the classifier rather than the receive loop,
and passed with the `bail!`s restored — the same defect that let the first round
ship green.
- `cargo nextest run --workspace` — 2258 passed, 0 skipped
- `cargo nextest run -p decdn-node --features anvil-e2e` — 752 passed
- clippy / fmt / doc / deny / public-api snapshot — clean
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Both were the defect this review round exists to remove — a fix that passes its own test while being unreachable in the case it was written for — so they are worth naming precisely. **The panic report never fired when it mattered.** `spawn_open` reported a dead open task from a combinator on the returned future. A `Shared` only advances when some clone is POLLED, and once the caller's `CHANNEL_OPEN_CALLER_BUDGET` expires the sole remaining clone is the one parked in `opens_in_flight` — which nobody polls. So the report fired *only when a caller was still waiting*, and stayed silent in the no-caller case it exists for. That case is not the rare one: the panic that matters lands during the unbounded receipt wait, minutes long, where by construction no caller is left — and that is exactly when an `openChannel` may already be in the mempool, i.e. a deposit escrowed against no persisted row. Worse, when the panicking task's guard removed the map entry, the last clone dropped and the future was destroyed having never run at all. `a_panicking_open_task_is_reported_and_frees_the_provider` passed throughout, because it keeps a caller waiting the whole time. Now reported from a spawned supervisor, which the runtime drives whether or not anyone awaits it, and guarded by `a_panicking_open_is_reported_even_when_no_caller_is_left_to_see_it` — verified to fail against the previous commit. **The CLI cross-field check used the wrong threshold.** Both call sites build `PullDeadlines` with the OPEN bound also set from `--stall-timeout-ms`, and `--timeout-ms` caps the whole exchange — so up to one stall budget can be spent on the open before the inactivity clock even starts, and `PullStalled` can only fire if the cap outlasts *both*. The check required `timeout > stall`, admitting the entire band up to `2 × stall` where the health signal is still dead. Its own test pinned `5000/5001` as GOOD, which is inside that band. Now `timeout > 2 × stall`. Also: document that the byte budget means TWO concurrent warms at the defaults (1 GiB ceiling, 2 GiB pool), down from the old fixed 8 — bounded at 2 GiB resident rather than 8 GiB. A small-blob node runs far more than 8. - `cargo nextest run --workspace` — 2258 passed, 0 skipped - clippy / fmt — clean Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…review) Two findings from the review, and they are the same bug seen from both ends: one creates a stale nonce, the other makes it permanent and silent. **The acked watermark died with the cancelled frame.** `pull_from_candidate` copied the watermark out of `VoucherProgress` *after* the await, so it ran only on a RETURN. Since #1134 the buffered pull carries `hard_cap: None`, which means nothing inside it ends a slow-but-progressing transfer — everything that ends one is external and DROPS the future: the foreground `outer_pull_deadline`, the background warm's `BACKGROUND_FILL_HARD_CAP`, and `pull_through_bg_shutdown` on restart. `populate` runs `pull_through` inline, so all three cancel it mid-stream. `VoucherProgress`'s own contract claims the copy-back "runs on every return path"; a drop is not a return path. Restart a node mid-warm on a 500 MiB blob and ~448 MiB of paid-for bytes are discarded along with the watermark that recorded them. The ledger is now caller-owned and settled by a `Drop` guard — the one thing that runs on both paths — reading a new sync mirror of the committed cumulative (`Drop` cannot await a `tokio::sync::Mutex`). One persist path, no second copy to forget. **And the voucher arm then swallowed the consequence, forever.** `pull_verdict` matched `UpstreamVoucherRejected` with a bare `.is_some()`, collapsing eleven reasons whose prescribed remedies differ — resend, top up, rotate, stop — into one counter and one `debug!`. `try_reuse_live` gates on expiry ALONE, so the dead channel was handed back on the very next miss: the provider stayed top-ranked, burned a `MAX_PROVIDER_ATTEMPTS` slot every time, and could not serve a byte until the channel expired ~90 days later. At the default `RUST_LOG=info` there was no log line at all. The sentinel had carried the typed reason since #1144 with a comment saying it did so "so a future caller can branch on retry-vs-top-up-vs-abandon"; no caller ever branched. `voucher_verdict` now splits the reasons three ways, exhaustively: - `BadSignature`/`WrongSigner` -> `OurLocalFault`. These mean OUR signer emits vouchers nobody can verify — a defect that hits every candidate. The ladder checked `UpstreamVoucherRejected` *before* `LocalPullFault`, so a broken buyer key reported a `debug!` about payments and left `node_pull_local_fault_total` at zero. - Spent / expired / closed / desynced -> `OurDeadChannel`, which RETIRES the row (compare-and-delete on `channel_id`) so the next pull opens a fresh channel, and warns. - `RetryLater` -> `OurVoucherRetryable`: the upstream's state did not advance (ADR 003), the channel is fine, leave it alone. Also: `record_progress`'s `ChannelMismatch` arm dropped a *paid* voucher's watermark and returned `Ok(())`, so `node_pull_progress_persist_failures` (which fires only on `Err`) never saw it. Its comment asked an operator to watch for a sustained rate in a signal that had no series. Now metered as `node_pull_progress_dropped_total`. New metrics: `node_pull_channel_retired_total`, `node_pull_progress_dropped_total`. Guards, each verified to FAIL against the reverted behavior: - `node_origin_cancelled_pull_still_persists_the_acked_watermark` — a new upstream that is paid for a full interval, acks it, then goes silent; the pull is dropped mid-flight. - `node_origin_a_drained_channel_is_retired_rather_than_reused` - `node_origin_an_unverifiable_voucher_is_a_local_fault_not_a_payment_one` - `cargo nextest run --workspace` — 2261 passed, 0 skipped - clippy / fmt / doc — clean Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…or (#1145 review) The commit that fixed "tests passing on reverted behavior" reintroduced the defect in the code it added. All three of these were verified by reverting the production line and watching the suite stay green. **`LocalPullFault` was entirely unguarded, and its test said so.** Stripping all six `.context(LocalPullFault)` markers left 1080/1080 passing; `node_pull_local_fault_total` had zero assertion sites anywhere in the repo. The test called the real `sign_client_binding`, asserted it was `Ok`, threw the result away, and then hand-built `anyhow!("...").context(LocalPullFault)` before asserting the ladder found `LocalPullFault` in it. Attaching the marker and then finding it is true by construction — and its own doc comment had warned that "a synthetic `anyhow!(...)` would pass this test while production scored the peer". Split in two, honestly: - `the_range_helpers_mark_their_own_faults_as_local` (client-pull) drives the REAL `aligned_wire_len` / `decode_verified_range` into their REAL errors — `align_range` rejects an offset past the end of the blob — and asserts the marker is on them. The test never attaches it. Stripping either marker now fails. - `a_local_fault_outranks_every_arm_that_blames_the_peer` keeps the ladder assertion but says plainly that a pure function over an `anyhow::Error` cannot prove any production site attaches anything, and points at the tests that do. **The refusal-TTL split was unguarded.** Restoring the precise bug `84c09dc` fixed — giving a `Transient` refusal the full 5-minute TTL, which "blackholed a perfectly healthy upstream for five minutes" over one dry deposit — left 1080/1080 green. Deleting `DurableMiss`'s suppression outright passed 38/38. `only_a_durable_refusal_earns_the_full_suppression_ttl` asserts what `classify_refusal` RETURNS, never that the verdict reaches the right `suppress(...)` call. `a_transient_refusal_is_suppressed_briefly_and_a_durable_one_for_the_full_ttl` injects a cache-wide TTL far BELOW `REFUSAL_SUPPRESSION_TTL`, inverting the production order so the two arms have visibly opposite lifetimes, and observes suppression behaviourally (a suppressed peer is filtered out of `probe_and_rank`, so it is never re-probed). Three assertions, each load-bearing: the transient one outlives the cache TTL; the durable one suppresses at all; the durable one expires with the cache TTL. Both mutations now fail. **`OpenSlotReserved` was unguarded.** Deleting its arm passed 749/749, though it fires at every boot — the reconcile scan holds the provider's open slot — and reaching the generic channel-open-FAILURE arm instead turns each restart into a spike of `unclassified` failures. Its sibling `ChannelOpenPending` was guarded; the asymmetry was an oversight. `WedgedOpener` now carries which typed sentinel it raises, and the starvation test runs against both. - `cargo nextest run --workspace` — 2264 passed, 0 skipped - clippy / fmt / doc — clean Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…adlines (#1145 review) Four findings. Each is a bound that looked configured and could not do what it was named for, which is the defect class this review round exists to remove. **`PullStalled` punished honest servers for serving large blobs.** It scores the peer `Unreachable` — a local EWMA hit AND a gossiped observation — and it earns that right from the deadline's reset: a clock that resets on every byte can only fire on a peer that stopped. True for every chunk but the FIRST, where no byte has reset it yet. What it measures there is the server's time-to-first-byte, and that scales with blob size: the serve path writes the `StreamResponse`, then materialises the whole bao wire encoding via `export_bao_range` before it can emit chunk #1. A 1 GiB blob (the default ceiling) off a cold disk can exceed the 20 s default stall budget, and the requester defamed it network-wide for it. Both receive loops now raise `PullTimeout` — exonerating — when the budget elapses at `cumulative == 0`. That is the answer the OPEN stage already gives an identical wait, on identical grounds: a bound of ours elapsing over bounded server work says nothing about the peer. Nothing is given up that the open stage has not already given up. `node_origin_a_silent_first_byte_is_our_deadline_not_the_peers_fault` and its sibling (three chunks, then silence — still scores) pin the boundary at exactly one byte. **`warm_budget_mb(0)` inverted the guard at the one value it named.** `0` is the documented "unlimited" sentinel — every blob-size gate reads it that way (`> 0 &&`, five sites) and config resolution accepts it. So the worst-case blob is UNBOUNDED, and clamping the reserve to a 1 MiB FLOOR admitted 2048 concurrent warms each buffering an arbitrarily large blob into memory for up to an hour. The byte-based pool was strictly worse than the task-count ceiling it replaced. Its test asserted `warm_budget_mb(0).1 == 1` under the comment "a zero ceiling must not make warms free and unbounded" — pinning the mechanism and mistaking it for the property, which was false. An unlimited ceiling now reserves the whole pool: one warm at a time, the same answer a ceiling above the pool already got, because it is the same situation. **The deadline invariant was enforced on the wrong type, in the wrong crate.** `hard_cap > open + stall` is `PullDeadlines`'s invariant, but its fields were `pub`, both production call sites built it with a struct literal, and the check lived in the CLI as a hardcoded `timeout > 2 × stall` — correct only because those sites happen to set `open` from the stall knob. An `--open-timeout-ms` flag would have made it silently wrong, in the direction that reopens the hole. Fields are private, `capped` is fallible and enforces the real relation, and both call sites go through it. `ClientFetchArgs::validate` remains the early, friendly error in the user's own flags; it can now go stale but not WRONG. Also: `--help` still told users `--timeout-ms` "must be larger than --stall-timeout-ms" — the threshold 1096ec5 deleted as unsound. Following it exactly got your command rejected. And `hard_cap()` returned an `Option` that was structurally always `Some`. **`PULL_THROUGH_OUTER_SLACK` was smaller than the overhead it was named for.** A flat 10 s against a probe phase (5 s) plus one slow lookup round (8 s) is 3 s short — and the lookup loop exited on convergence, never on a count, so its worst case was UNBOUNDED and no constant could have covered it. The outer timeout could fire while candidate #3 was still in its stall window: the #859 fallback starvation the formula exists to prevent, at the defaults. The guard test asserted `outer == all_candidates + SLACK`, which proves only that the slack is whatever the slack is. `MAX_LOOKUP_ROUNDS` makes discovery finite; the slack is now DERIVED from it (`PROBE_TIMEOUT + MAX_LOOKUP_ROUNDS × DEFAULT_ROUND_TIMEOUT`). Both halves are needed. Worst-case client wait at defaults: 145 s -> 172 s, updated at all four sites that quote it. - `cargo nextest run --workspace` — 2267 passed, 0 skipped - clippy / fmt / doc — clean Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…view) The doc-correction commit on this branch (e8e8d3c) was followed by three commits that changed the code again, including reverting two fixes as unsound. Several of those corrections went stale in the process. Checked against HEAD, not against intent. **Claims that were false at HEAD:** - `message.rs` said `EmptyChunk` / `ChunkTooLarge` are "Enforced via `ChunkData::validate`". `84c09dc` made the field private and routed decoding through `try_from`, so `validate` is now always-`Ok` and can produce neither. It pointed at the one mechanism that cannot fire, and at the advisory-validator model `client.rs` explains was abandoned as unsafe. Now: enforced by `new` and the decode gate, the only two ways to obtain a frame. (`ChunkData`'s own doc made the same stale claim.) - `client-pull/buyer_channel.rs` claimed "every other tx in this module bounds its receipt wait". There are three txs; `top_up` does not bound its receipt, and correctly so — it ESCROWS, which is the very reason the paragraph gives for `openChannel` not bounding its own. As written it implied the opposite of its own thesis. - `e2e/client.rs` said "the last three reach the closing `true` by fallthrough". The last three are `PullTimeout` / `PullStalled` / `RetryLater`, but `RetryLater` has an explicit arm and `NotFound` does too. It is the MIDDLE three. - `node_origin.rs` said a mid-stream `VoucherRejected` "cannot reach a validated response at all". That covers the OPEN stage only — and this same PR added three mid-stream arms that wrap any `StreamError` into `UpstreamRefused`, with `VoucherRejected` being precisely the mid-stream code. The arm is REACHABLE, and a reader who believed otherwise would delete it as dead, at which point our own payment fault starts blaming the peer. - `UpstreamRefused`'s doc enumerated the codes and omitted `VoucherRejected` — now the one most likely to arrive on the mid-stream path it documents — and called `BlobTooLarge` merely "deterministic" without saying what the consumer does with that. - `PullDeadlines::whole_transfer` said the hard cap "always elapses first, so `PullStalled` can never fire under it". True on the BUFFERED path; the progressive path never consults `hard_cap` at all. **`ChunkData::validate` is now `pub(crate)`.** It is total by construction, and a public function that cannot fail is a check the API advertises and does not have. On a committed public surface that invites a caller to depend on it and makes removing it breaking — for a validator whose only honest answer is `Ok`. The dispatcher is in-crate, so narrowing costs nothing. Public-API snapshot regenerated; the diff is exactly that one symbol. **Review-narration comments removed.** Several comments documented THIS PR's own review rounds ("the first cut of this got that wrong", "the first attempt did", "this doc used to claim…"), describing code states that never existed on `main` and are meaningless after merge. Each stated a constraint worth keeping, so the constraint stays and the defunct draft goes. The one exception is kept and reframed: `spawn_open`'s test doc names a LIVE property of `Shared` (it only advances when a clone is polled) that a maintainer could silently break — a constraint the code cannot show, which is what a comment is for. - `cargo nextest run --workspace` — 2267 passed, 0 skipped - public-api snapshot — regenerated, passes - clippy / fmt / doc — clean Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Three defects, one chain, all reachable at the defaults. Each is verified to
fail on revert.
**Concurrent pulls to one provider collided, and the collision now deleted a
funded channel.** `stream_fetch_shared` documents the contract: N pulls that
each seed voucher state from `ctx.prior_*` all sign `prior_nonce + 1` and
collide, so concurrent pulls on one channel MUST share a ledger. Both node pull
paths built a fresh one per pull (the window path, per *voucher*). Nothing
exotic triggers it: the cache coalesces in-flight pulls BY HASH, so two misses
for different blobs run concurrent `NodeOrigin::fetch` calls and both rank the
same provider first. `BuyerLedgers` now holds one ledger per provider channel,
seeded once and shared; `ctx.prior_*` loses to a live ledger, which is at least
as far along as the row it was read from.
**Retiring a channel deleted the only handle on its deposit.** `reclaimExpired`
refunds the remainder and needs the `channel_id`; both recovery sweeps enumerate
the store. A forgotten row is money nothing in this codebase can ever see again
— the hazard `run_open` already reclaims-before-rotating to avoid, in a comment
that says so. `voucher_verdict` saw the distinction ("the money ran out … or our
accounting drifted") and then gave both the same remedy: drop the row. Neither
group has surrendered its money — a desync spent nothing, `InsufficientDeposit`
means too little for THIS voucher, and an `Expired` channel is exactly what
`reclaimExpired` refunds. Only `CooperativeCloseSigned` is settled on-chain, and
it is now the only reason that may forget a row. The rest keep it and suppress
the provider instead.
**A pull dropped inside the ack wait lost the voucher it had already sent.** The
upstream persists before it acks (ADR 003), so a drop there — the longest await
in the loop, and where a slow peer trips the deadline — left it holding nonce N
while we recorded N-1. `self_pay` already knew ("our persisted watermark can lag
what the node accepted … tracked in #1122"); what changed is that `StaleNonce`
became terminal, turning that lag into a stranded deposit. `ChannelLedger` now
records the voucher in flight and `settlement()` honours it on a drop — it pays
for bytes already delivered, and the serve side tolerates a nonce gap but not a
regression, so this is the survivable direction.
Also: the window path had no drop settlement at all (its serve future is dropped
on shutdown or a downstream reset, so no terminal method runs). Both paths now
settle through the one `SettleOnDrop` guard.
Tests: `two_concurrent_pulls_to_one_provider_share_the_channel_ledger` drives two
real concurrent misses through the real `ClientHandler` — reverting the shared
ledger fails it with the predicted `StaleNonce`. The drained-channel test
asserted the money-losing behaviour and is rewritten, not adapted: it required
the row be deleted, on the false premise that the sweep would still find it.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
**The cheapest griefer in the protocol was unanswered.** A peer that probes honestly (`has_blob: true`, low rate, low RTT → ranks #1), accepts the stream, signs a valid `StreamResponse`, and then sends nothing lands on `OurDeadline` — our budget fired, so it is not scored. It was not suppressed either, so it stayed top-ranked and burned a full budget on every miss, for every hash, forever, at no cost to itself. That is the hole this PR closed for refusals ("a peer that advertises everything and serves nothing burned a candidate slot on every miss forever"), left open one stage over for a peer that does not even answer. Suppression is the instrument that fits, and it is the one this PR already built: scoped to (peer, hash), TTL'd, reputation-neutral. It costs an honest-but-slow peer one TTL and costs a silent one its free lunch, without gossiping a judgement about either — which is what lets it apply to a verdict we cannot attribute. **A mid-stream `VoucherRejected` skipped the channel remedy entirely.** Only `self_pay`'s ack wait turns the code into `UpstreamVoucherRejected`; the three mid-stream receive sites wrap ANY `StreamError` into `UpstreamRefused`. So one arriving outside a voucher round trip was ruled `OurFault` — score nothing, suppress nothing, do nothing — and the wedged channel stayed in the store to be handed back on every subsequent miss, on a `debug!` invisible at the default `RUST_LOG=info`. `pull_verdict` now unwraps it back out and routes it to `voucher_verdict`, the one place that decides what a rejected voucher costs. **`PullDeadlines::new` accepted a zero stall on the path every production pull takes.** It was infallible because a zero bound "fires too EAGERLY — loud, and immediately obvious". It is the opposite of loud: a zero stall trips `PullStalled` on the first poll of every streaming read, and `PullStalled` gossips `Unreachable` — so the failure mode is a node quietly defaming every honest peer it touches, as fast as it can dial them. `config` says exactly this 800 lines away. `capped` refused it from the start; the invariant belongs to the type, not to a resolver in another crate a caller has to remember to run. Both new guards are verified to fail on revert, and the first-byte one fails audibly: with the suppression removed the test takes twice as long, because the second fetch waits on the silent peer all over again. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…1145 review) **A background warm that panicked told no one.** Nothing awaits these tasks — they are spawned and their `JoinHandle` dropped on the spot — so a panic inside `populate`, the tee, or the decoder moved no counter, wrote no log, and left `spawned` permanently one above the sum of its outcomes: a gap that reads like an in-flight warm rather than a crash. The same hole was already closed for the detached channel-open task, which got a supervisor for exactly this reason; the warm has no caller at all, so it was strictly worse off, and it got nothing. `Drop` runs on the unwind, so a guard is the one thing that can still see it. **`..._background_failed_total` could never fire for the emergency it would need to signal.** It counted a clean miss (no provider, no origin — routine) and a store/IO fault (an emergency) on the same series, both at `debug!`, below the project's default `RUST_LOG=info`. No threshold on it could tell them apart, so there was no alert an operator could write. Split: `..._missed_total` is routine, `..._failed_total` is now alertable. **The accounting identity in the comment could never balance.** It claimed `spawned == succeeded + failed + shed + cancelled`, but a shed warm returns *before* `spawned` is incremented, so `shed` is disjoint from all of them. The real identity is `spawned == succeeded + missed + failed + cancelled + panicked`. **A truncated DHT lookup was `debug!`-only.** `MAX_LOOKUP_ROUNDS` shrinks the candidate set feeding `MAX_PROVIDER_ATTEMPTS`, so a node whose network is large enough to hit the ceiling on every lookup is systematically pulling from a worse provider set than the DHT could offer — and had no way to know. **A failed retire borrowed another metric's series.** `node_pull_channel_retire_ failure_total` now exists, so a node whose every retire write fails is no longer indistinguishable from one that never needed to retire. Tests. The three bounds this PR shipped unguarded now fail on revert: - **`MAX_LOOKUP_ROUNDS` had ZERO coverage** — and `PULL_THROUGH_OUTER_SLACK` is now *derived* from it, so the slack is only a valid budget if that loop really honours the ceiling. A chain of six servers, each revealing the next-closer node, with the record placed six hops out: the lookup must be cut off before it reaches it. Remove the ceiling and the walk finds the record. - **The warm memory budget was a bound with no guard.** Deleting the whole `try_acquire_many_owned` block left the suite green. Now driven through the real `maybe_spawn_background_fill` against an origin that never returns, so the first warm genuinely holds the whole pool and the second must shed. - **The slack test was a tautology.** `PULL_THROUGH_OUTER_SLACK` is *defined* as `PROBE_TIMEOUT + DEFAULT_ROUND_TIMEOUT × MAX_LOOKUP_ROUNDS`, and the test recomputed that expression and asserted the slack was at least as big: `A >= A`, passing for any value of any constant. That is precisely the sin its own doc comment accused its predecessor of, restated one level up. Deleted — deriving the constant is what makes it correct, and what can still break is the loop, which is now tested where it lives. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e false (#1145 review) **`spawn_open` did not reserve the slot it documented.** Its doc has always said it "reserves the provider's slot and runs the open under it" — it did the second. The guard was built here; the matching `insert` lived twenty lines away in `join_or_spawn_open`. So the pairing was asymmetric: RELEASE in the type (`Drop`, unconditional), ACQUIRE in the caller. The invariant "a guard exists ⇒ the slot is occupied" was caller-maintained, and a future caller who reached for `spawn_open` without also remembering the insert would get a guard, get no singleflight, and let the next miss open a SECOND `openChannel` — the double-escrowed deposit this whole mechanism exists to prevent. The insert now happens inside `spawn_open`, under the lock the caller already holds, so reservation and guard are one statement. Docs. `c8fd844` was titled "correct the claims the last three commits invalidated" and did not catch them all: - `BACKGROUND_FILL_HARD_CAP` still said `~25×` and `+ 10 s`. The slack became derived (5 s probe + 4 × 8 s lookup = 37 s), so the deadline is 172 s and the ratio ~21×. Now stated against `outer_pull_deadline` rather than restating its arithmetic — restating it is how this went stale. - `MAX_BACKGROUND_FILL_MB` said warms accumulate `~25×` — the same figure, against a different denominator (3600/70 ≈ 51). The two could not both be right; the copy understated the amplification by half. - `record_channel_open_failure` told operators a slow chain lane means raising `node_pull_timeout_sec`. That knob's own doc says outright: "raising this to give a slow L2 more room does nothing: that is the channel open." - `node_pull_timeout_total` described one budget. It fires on two, and for the large-blob case the knob to raise is the one it did not name. - `ClientMessage::validate` claimed to be "the seam a receive loop is told to call" (no receive loop calls it) and that its `ChunkData` arm guards the empty-frame bug (the arm cannot fail — the decode gate does that). - The `NotFound` collapse: four of the seven reasons are ours or transient, not three (`RangeNotSatisfiable` is our own bad range computation). - `outer_pull_deadline` said a fallen-through transfer "continues" in the warm. It does not — the warm calls `populate` and re-pulls from scratch, which also undercuts the "restart from zero" argument in the sentence above it. And one claim this PR made that is still false, now said plainly rather than quietly dropped: the first-byte carve-out fixes the ATTRIBUTION of a slow large blob, not the blob. `export_bao_range` returns an owned `Bytes`, materialising the whole bao encoding before chunk #1, so TTFB scales with blob size by construction — and the warm re-pulls with the same stall budget. #1122/#1132's 708 MB blob is NOT fixed here; the repair is to stream the encoding incrementally on the serve side. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…gs (#1145 review) A fourth multi-agent review found the recurring defect class had reached the money once more, plus a tail of silent legs, hardening gaps, and doc rot. Every fix is guarded by a test verified to FAIL ON REVERT. Blockers (money-losing, confirmed in committed HEAD): - A stalled/lost voucher ack was settled LOW. `ChannelLedger::issue` cleared the in-flight slot on ANY resolved error, but #1134 wrapped the ack read in a stall timeout, so a silent peer now resolves as `Err(PullStalled)` instead of dropping — settling at N-1 while the upstream holds N (ADR 003), then re-signing N on reuse and wedging the channel. Now the slot clears only on a known fate (an ack, or a typed `UpstreamVoucherRejected`); every other error settles high. The next voucher builds on `settlement()`, so a concurrent pull cannot re-sign the armed nonce. - Wedged-channel suppression was (peer,hash)/30s, not provider-until-expiry as three docs claimed. A wedged channel was handed back for any OTHER hash and re-wedged on every miss. Now a provider-wide, expiry-horizon `wedged_providers` map (sourced from the new `ChannelOpener::channel_expiry`) drops the provider from ranking for all hashes until its channel expires. Mediums: - The 4th `{e:?}` site (self_pay's ack-wait catch-all) now carries the typed `UpstreamRefused`, so an honest Overloaded/NotFound is metered, not scored Unreachable. - A `Regressed` watermark from a concurrent settle on the shared ledger is metered benign (`node_pull_progress_superseded`), not a persist failure. - `WarmOutcome::drop` gates on `thread::panicking()`, so a teardown drop-unpolled is `cancelled`, not a false `PANICKED` on every restart. - The prefetch-observer over-count under a shared ledger (M2) and the `is_clean_miss` fault-laundering (M4) are documented as money-safe and deferred: both need cross-crate refactors of delicate money/error paths and are left as follow-ups. Hardening (make the recurring defect unrepresentable): - `InFlightOpenGuard::claim` is reached only through `under_claim`, a closure-runner, so the reconcile guard is never bound at a call site and cannot be dropped early. - `PullDeadlines::whole_transfer` + `stream_fetch` are feature-gated behind `test-util`; production cannot name the zero-stall/uncapped constructor. - `BuyerLedgers` is keyed by (provider, channel) with strong-count pruning, so a stale channel-id can neither collide with nor evict a live ledger. Docs: corrected the `PullTimeout` "not raised by streaming loops" claim, the phantom `retire_dead_channel` references, `stream_fetch_shared`'s snapshot->settlement pointer, the three/four and no-other-constructor miscounts, `MAX_LOOKUP_ROUNDS`'s scale claim, and the `# Errors` gaps on `next_chunk`/`finish`. Verification: `cargo nextest run --workspace` 2289 passed / 0 skipped; anvil-e2e (incl. `e2e_onchain_payment_channel_settlement`) passed; clippy --all-targets, fmt, doc (-D warnings), deny — clean. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-and-classification # Conflicts: # crates/node/src/node_origin.rs
Four open issues that are really four facets of one defect: the client-side fetch loop is neither properly bounded nor able to interpret what a peer tells it. They share the same two files, and the fixes depend on each other — so they ship together.
Closes #1088, closes #1144, closes #1134, closes #1143.
The model, stated once
Every stage of a pull now gets the bound that fits it. This is the through-line of the whole PR:
StreamResponse)deadline × link speed— the #1134 complaint.The commits
b5037d3— #1088: reject zero-lengthChunkData. A peer could send unbounded empty frames; each leftcumulativeuntouched, so the overrun guard never tripped and the loop spun. Low impact alone — but the non-empty floor is what lets the inactivity deadline rest on frame arrival, so a peer can't refresh it with padding. It lands first for that reason.78acd88— #1144: typed refusal sentinel. Both pull paths bailed identically on every refusal, stringifying theStreamErrorand discarding it. So a node that honestly answeredNotFoundwas scoredUnreachable— an EWMA hit and a gossiped observation — exactly as hard as a dead one.UpstreamRefusedcarries the wire code, andclassify_pull_failurenow scores onlyInternalError(a peer reporting its own degradation, #1129);NotFound/EvictedSinceProbe/Overloaded/BlobTooLargeare metered and skipped. Two consumers stop sniffingDisplaystrings and downcast instead.507db1e— #1134: bound each stage by what fits it.--timeout-mswas a whole-blob deadline, which made it a poor health signal: it killed legitimate large or slow-but-healthy transfers while a value small enough to catch a dead node couldn't serve a big blob. The CLI had grown ascaled_timeouthack (a hardcoded 35 MiB/s bandwidth guess) purely to paper over it — deleted.--stall-timeout-ms(30s) is now primary;--timeout-msis an off-by-default cap.560e1fe— #1143: singleflight the channel open.open_or_reuse_channelwas unbounded and runs before the budget #1141/#1142 added, so a wedged open consumed the whole outer deadline. Atokio::timeoutwould drop the future with anopenChannelin the mempool. The open now runs in a detached task that owns the tx and holds the provider's slot; the caller waits only its candidate budget, then getsChannelOpenPendingand moves on.Things found along the way that weren't in the issues
next_chunk/finishread with no bound — only the QUIC idle timeout backstopped a wedged peer.pull_timeoutwrapped the whole buffered fetch, and the background warm that should have rescued it was capped by the same derived deadline. The 708 MB blob in Payment channels aren't resilient to a fetch exiting early: it strands the channel + deposit (durable watermark, resumable fetch, resync, coop-close reconciliation) #1122/Buffered origin pull-through loads the whole blob into memory before serving #1132 is evidence this ceiling was already being hit. The whole-blob deadline is gone — but see the third round below: this does not make that blob fetchable, and the claim that it did was wrong.InFlightOpenGuardis in-memory and was held by the caller, so a dropped future released the provider slot and the next miss opened a second channel. The boot reconcile scan explicitly declines to adopt it (DeferredSecondOpen) — at a 90-day expiry against a ~1–2 day lookback, that deposit is never recovered. Holding the guard in the task removes this by construction.PullTimeoutand aPullStalleddeserve opposite verdicts. The existing no-reputation-hit treatment of a pull timeout was only correct because the whole-blob deadline produced false positives on healthy transfers. A stall bound can only fire on a peer that went silent, so it now scoresUnreachable.Behavior changes to be aware of
--timeout-msis no longer the health signal, but it still exists and still always applies — it now defaults to a generous 1h leak guard rather than a 30s deadline.--stall-timeout-ms(30s) is what catches a dead provider. It cannot simply be removed: inactivity is not liveness, and a peer trickling one byte per stall window would otherwise hangdecdn fetchforever with no error. Both flags now reject0.BACKGROUND_FILL_HARD_CAP), not uncapped. The cap must be far larger than the foreground deadline — that is what makes a large blob acquirable at all — but it cannot be absent, for the same drip-feed reason. Warms are also bounded by a memory budget (MAX_BACKGROUND_FILL_MB, 2 GiB): the hour-long lifetime is ~25× the old one, so an unbounded number of them was a memory and spend amplifier. Each warm reservesmax_blob_size_mb, since a blob's size is not known until it has been fetched.cache.node_pull_stall_timeout_sec(default 20).CHANNEL_OPEN_CALLER_BUDGET, 5s) separate fromnode_pull_timeout_sec. Worst-case client wait on a full miss rises from a claimed 70s to a real 172s — see the review rounds below. The old 70s could not actually reach candidate docs: convert ASCII art schemas to Mermaid diagrams #3, and neither could the 85s or the 145s this PR shipped on the way here.Review round (multi-agent)
A five-agent review of this PR found the engineering sound — the detached-task singleflight survived a deliberate attempt to break it — but found the fix itself was unguarded, and two claims above were previously false. Fixed in
7a28b8f; every fix was verified to fail on revert, which is the bar this PR's own first round missed:BuyerChannelServiceleft the node suite green at 731/731, includinga_wedged_channel_open_does_not_starve_the_candidate_loop— itsWedgedOpenermock re-implements the predicate rather than exercising it. Now guarded at the mechanism (real service, wiremock chain that never answers) plus an anvil section that disables automine so theopenChannelactually sits in the mempool.outer_pull_deadlinebudgeted one stage per candidate, but a candidate now costs two (channel open, then stream open) — so at defaults candidate docs: convert ASCII art schemas to Mermaid diagrams #3 was never dialled.mainconceded this hazard in a comment; this PR had deleted it and asserted the opposite.ClientMessage::validatewas blind to the cdn/client/v1 receive loop: unbounded zero-length ChunkData frames spin without progress #1088 floor — and a test pinned the hole.run_open's 5 error legs were silent (no log, no metric), and they fire precisely when no caller is left listening.NotFoundrefusals left no record at all, so a peer that advertises everything and serves nothing burned a candidate slot on every miss forever.Verification
cargo nextest run --workspace— 2240 passed, 0 skippedcargo nextest run -p decdn-node --features anvil-e2e— 738 passed. The chain-driving test ise2e_onchain_payment_channel_settlement, which exercises the realopen_or_reuse_channelagainst live anvil: the concurrent-open race (asserted on the on-chain nonce delta), expired-channel rotation, and — new — the abandoned-open path with automine disabled.cargo clippy --workspace --all-targets— clean;cargo fmt --check,cargo doc,cargo deny— cleanFixtures, since none of the existing ones could reach these paths (
spawn_a_stalling_serverstalls at the open stage, so it never exercised streaming):a_caller_that_times_out_leaves_the_open_slot_held/a_second_caller_joins_the_in_flight_open_rather_than_opening_again— the singleflight, against the real service. The load-bearing pair: a released slot with a tx in the mempool is a duplicate escrowed deposit.a_wedged_channel_open_does_not_starve_the_candidate_loop— now three candidates (two wedged), so it can tell a loop that reaches docs: Generalize architecture to content-agnostic CDN, refocus slashing on bad edges #2 from one that reaches docs: convert ASCII art schemas to Mermaid diagrams #3.only_internal_error_refusals_are_scored— the heart of client-pull does not distinguish NotFound from InternalError, so the serve path's reason codes are inert #1144, asserted on the real predicate rather than a copy of it.a_store_fault_under_the_open_slot_is_reported_by_the_task,a_reserved_slot_tells_a_joining_pull_to_retry(now driven through the real join path), plusChunkData::validatebounds coverage.Tests fixed rather than adapted: the CLI's unbound-cache-miss hint test built its error with
anyhow!("delivery refused: Some(NotFound)")— a look-alike string, so it would have passed vacuously against a hint that never fired in production. Andouter_pull_deadline_exceeds_all_per_candidate_budgetsasserted the formula against itself; it now asserts against what a candidate can actually cost.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
node_pull_stall_timeout_sec.ChunkData) and typed “channel open pending” signaling.Bug Fixes
Second review round (multi-agent)
A second five-agent review found the first round's defect class had recurred one stage over, plus a cluster of mis-attributed failures, silent legs, and false comments. Fixed in
84c09dc; every fix verified to fail on revert.The deadline was still short a stage (critical)
A candidate costs three sequential stages, not two: channel open (5s) → stream open (20s) → and, for a peer that opens honestly and then goes silent, one full stall window (20s) before failover.
outer_pull_deadlinebudgeted the first two. At defaults a stalling candidate cost 45s against 25s budgeted; and becausenode_pull_stall_timeout_secis operator-tunable — withconfig/types.rsactively inviting a raise ("tune it against upstream responsiveness, not content size") — at120a single silent candidate outlasted the whole 85s deadline and #2/#3 were never dialled. That is the pre-#859 starvation, reintroduced by this PR's own new knob.stallis now a term in the formula, so the deadline scales with the knob automatically and no cross-field config check is needed. Worst-case client wait on a total miss: 85s → 145s (and → 172s after the third round below made the discovery slack a derived term rather than a guess).The guard now sweeps
stallindependently ofper_candidate, because that is the term an operator can raise on its own: a formula that ignores it looks fine at defaults and starves the loop at 120.Mis-attributed failures
node_pull_local_faultcould never fire for the emergency it documents.bind_upstream_ctxsigns with the same buyer key as vouchers and runs before the stream open on both pull paths — itwarn!ed its error away instead of classifying it. A node with a broken buyer key therefore failed at bind on every candidate and never reached the voucher-signingLocalPullFaultdeeper in, so the counter whose doc says "any sustained rate is an emergency" stayed at zero. An operator alerting on it got a false all-clear.wire_errorcollapses seven reject reasons onto the wireNotFound— deliberately, so a probing client cannot map out other clients' channel balances — and three of them are ours or transient (InsufficientDeposit,UnknownChannelduring watcher lag,CooperativeCloseSigned). So a momentarily exhausted deposit, or the pre-observation window right after we open a channel, suppressed a perfectly healthy upstream. The collapse is a privacy property and cannot be undone with new wire codes, so the fix is node-local:RefusalVerdictsplits durable (EvictedSinceProbe,BlobTooLarge→ full TTL) from transient/unattributable (NotFound,Overloaded→REFUSAL_SUPPRESSION_TTL, 30s), preserving the exhaustive match.StreamErrorlost its type. Three receive sitesbail!("stream failed: {e:?}"), so the wire code fell through every downcast to the catch-all and scored the peerUnreachable— the exact mis-attribution client-pull does not distinguish NotFound from InternalError, so the serve path's reason codes are inert #1144 fixed at the open stage, alive one stage downstream.Silent legs
The detached open task's
JoinError— a panic, produced inside aSharedonly a caller polls, so with a 5s caller budget against an unbounded receipt wait the likely case is nobody is left to observe it — had no log, no metric, and noOpenReported. The sustained store fault takes the reuse fast path (which runs before the task spawns), sorun_open's louderror!leg only ever guarded the intermittent blip. A poisonedopens_in_flightmutex, which wedges every open for the process lifetime, wasdebug!— invisible at the project's own defaultRUST_LOG=info. Cancelled warms now have a counter, sospawned == succeeded + failed + cancelledbalances.Invariants made structural
ChunkData's non-empty floor was advisory. Two receive loops remembered to callvalidate(); neither emitter did; andClientMessage::validate— the aggregate seam this PR added — was called by no receive loop at all. The stall detector and, through it, the reputation system bottom out in this invariant. Now: private field,new() -> Result,#[serde(try_from)]. An empty frame cannot be constructed or decoded; the adversarial test forges it on the wire, which is where an adversary actually lives. (ADR 005 now states the rule.)InFlightOpenGuard::spawn_openmakes a caller-held guard unrepresentable.let _guard = guard;→let _ = guard;is one character, reads identical, is a change a linter would encourage — and releases the provider slot with anopenChannelstill in the mempool, sending a second channel and stranding the deposit.The revert check caught one of its own
The first mid-stream-refusal guard asserted against
classify_pull_failure's ladder rather than the receive loop, and passed with thebail!s restored — the classifier was never the thing that broke. It now drives a real upstream that opens honestly and then errors. That is the same defect that let the first round ship green, caught this time because every fix was reverted and re-run.Verification
cargo nextest run --workspace— 2258 passed, 0 skippedcargo nextest run -p decdn-node --features anvil-e2e— 752 passed--all-targets), fmt, doc, deny, public-api snapshot — cleanThird review round (multi-agent)
A third five-agent review found the defect class had recurred twice more, and this time it reached the money. Fixed in
1525e83,9f7e16c,177c810,a15a638; every fix verified to fail on revert.Two ordinary concurrent misses stranded a deposit (critical)
stream_fetch_sharedstates the contract in its own doc: N pulls that each seed voucher state fromctx.prior_*all signprior_nonce + 1and collide, so concurrent pulls on one channel must share a ledger. Both node pull paths built a fresh one per pull (the window path, per voucher). Nothing exotic triggers it — the cache coalesces in-flight pulls by hash, so two misses for different blobs run concurrentNodeOrigin::fetchcalls, and on a tens-of-nodes network both routinely rank the same provider first.On
mainthe loser was a benign skipped candidate. Withafc37b4,StaleNoncebecame terminal — so the losing pull deleted the channel row out from under the winner, which was still streaming on it.BuyerLedgersnow holds one ledger per provider channel.Retiring a channel deleted the only handle on its deposit (critical)
reclaimExpiredrefunds the remainder and needs thechannel_id; both recovery sweeps enumerate the store. A forgotten row is money nothing in this codebase can ever see again — the hazardrun_openalready reclaims-before-rotating to avoid, in a comment that says exactly that.voucher_verdictsaw the distinction — it said in as many words that these arrive "for two different underlying reasons — the money ran out … or our accounting drifted" — and then gave both the same remedy: drop the row. Neither group has surrendered its money.CooperativeCloseSignedis now the only reason that may forget a row; the rest keep it and suppress the provider.A drop inside the ack wait lost a voucher already spent (critical)
The upstream persists before it acks (ADR 003), so a drop there — the longest await in the loop, and exactly where a slow peer trips the deadline — left it holding nonce N while we recorded N-1.
self_payalready knew ("our persisted watermark can lag what the node accepted … tracked in #1122"); what changed is thatStaleNoncebecame terminal, turning a known lag into a stranded deposit.Also
OurDeadline— unscored and unsuppressed, so it stayed top-ranked and burned a budget on every miss forever, free. That is the hole this PR closed for refusals, left open one stage over.VoucherRejectedskipped the channel remedy entirely, landing on adebug!invisible at the defaultRUST_LOG=info.PullDeadlines::newaccepted a zero stall on the path every production pull takes. A zero stall is not "loud" — it gossipsUnreachableabout every honest peer it touches...._background_failed_totalconflated a clean miss with a disk fault, so it could never fire for the emergency it would signal.A >= A, the exact sin its own doc comment accused its predecessor of.MAX_LOOKUP_ROUNDS, which the slack is now derived from, had zero coverage; it is now driven by a six-server chain with the record placed out of reach.spawn_opendid not reserve the slot it documented — release lived in the type, acquire in the caller.Correcting a claim above
The 708 MB blob in #1122/#1132 is not fixed by this PR. The first-byte carve-out fixes the attribution (an honest slow server is no longer gossiped as unreachable); it does not make the blob fetchable.
export_bao_rangereturns an ownedBytes, materialising the whole bao encoding before chunk #1, so TTFB scales with blob size by construction — and the background warm re-pulls with the same stall budget, so it fails identically. The repair is to stream the encoding incrementally on the serve side, and it is not in this PR.Verification
cargo nextest run --workspace— 2282 passed, 0 skippedcargo nextest run -p decdn-node --features anvil-e2e— 771 passed--all-targets), fmt, doc, deny — clean