Skip to content

fix(node): don't sign an authoritative NotFound for a backend fault or a wedged candidate (#1129, #1141) - #1142

Merged
thiras merged 3 commits into
mainfrom
fix/serve-path-miss-semantics
Jul 13, 2026
Merged

thiras merged 3 commits into
mainfrom
fix/serve-path-miss-semantics

Conversation

@thiras

@thiras thiras commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1129. Closes #1141.

Two fixes on the cdn/client/v1 serve path, plus a correction to the reasoning I originally shipped them with (see the last section — it matters).

1. A degraded node reported itself as merely empty (#1129)

The reactive fill helpers returned a bare bool, so a transient CacheError::OriginError / CacheError::Store — an S3 5xx surviving retry exhaustion, an open circuit breaker, an fs I/O error — collapsed to false, indistinguishable from "no origin had it", and refused with CacheMiss (wire NotFound): the code a healthy but empty node returns. The cache engine already draws this distinction (it deliberately prefers OriginError over NotFound when an origin faulted); the handler threw it away.

Introduces FillOutcome { Filled, CleanMiss, HardFault }, threaded through the fill helpers, with the fault latched across tiers (fault_seen) — falling through to a further tier after a fault is legitimate, since another source may still serve, but a later clean miss must not overwrite the fault. When no tier fills, the refusal is InternalError.

What this actually buys, stated precisely:

  • Client routing. InternalError = "do not retry this node"; the client goes elsewhere instead of treating a broken node as an empty one.
  • Operator observability. Seven distinct reject reasons collapse to the single NotFound wire code, so the per-reason reject counter is the only server-side place the true cause is visible. An operator whose origin is 5xx-ing must not see that reported as a cache miss.

Deliberately narrow: BlobTooLarge / HashMismatch / VerifyFailed are not faults. They are deterministic and recur on every request for that hash, so reporting them as "this node is broken" would steer clients off a healthy node permanently over one bad blob — and for BlobTooLarge it would contradict the size gate, which refuses the identical condition with the dedicated BlobTooLarge code.

A deadline expiry is also not a fault: we do not know that anything is broken, the blob may well exist upstream, and reporting a slow upstream as "do not retry this node" would penalise a healthy node for someone else being slow.

2. A wedged candidate starved the fallback loop (#1141)

The buffered path bounds each candidate with pull_timeout inside stream_fetch_tracked. The window path's open_from_candidate called open_progressive_upstream with no timeout at all. Its only bound was the outer deadline — which is sized at MAX_PROVIDER_ATTEMPTS × pull_timeout + slack precisely so candidates #2..N stay reachable (#859).

So a candidate that accepted the QUIC connection and then went quiet consumed the entire budget for all three candidates, and the node refused a blob honest peers held. A peer quoting a low rate ranks first, so a cheap-and-wedged provider preferentially starves the loop.

The typed PullTimeout flows into the existing classify_pull_failure, which meters the timeout and — per #857 — does not blame the peer, since our own deadline is not evidence the provider is bad.

Scope honestly: this bounds the progressive-open stage. open_or_reuse_channel runs before it and remains unbounded on both paths, because wrapping it would drop an in-flight on-chain openChannel tx mid-flight. Filed as #1143.

Correction: the justification I first shipped was wrong

The initial commits, comments and CHANGELOG argued that a misclassified refusal was a false EIP-712-signed attestation. That is not true, and a multi-agent review caught it by reading the protocol rather than my PR text:

  • StreamResponse.error is explicitly "unsigned and informational". The slash_sig covers only StreamResponseBody (ok: false) — not the reason code. A misclassification is a correctness and observability bug, not a false attestation.
  • InternalError is documented as "do not retry this node", not "retryable", which is how I framed it throughout.
  • NotFound is not reputation-benign: classify_pull_failure folds any refusal — both codes alike — into Outcome::Unreachable.

Every comment resting on those three claims has been rewritten. The fix is still right; the story was wrong. (The third point is itself a latent bug — an honest, empty upstream currently takes an Unreachable reputation hit for saying so. Filed as #1144.)

That review also found four real defects in my own first cut, all fixed here: the HardFault catch-all swept in BlobTooLarge; the leech-admission exit dropped the latched fault; the latch started after the range tier, silently dropping a CacheError::Store there; and on_pull_through_timeout counted a store fault as both an error and a timeout, contaminating the metric whose whole job is to separate "slow upstream" from "broken store".

Verification

Every behavioural claim is pinned by a test that fails without the fix (verified by reverting each fix and re-running):

  • node_origin_window_open_falls_through_a_stalled_candidate — two stallers, not one: with a single staller, a regression that budgeted the whole loop instead of each candidate still passes. Asserts both stallers are exonerated (node_pull_timeout_total == 2, unreachable == 0, neutral EWMA, nothing gossiped) and that the abandoned opens leaked no voucher spend or region bytes.
  • local_origin_hard_fault_is_internal_error_not_signed_not_found — cache-only operator, origin fault ⇒ InternalError.
  • local_hard_fault_survives_fallthrough_to_the_window_tier — the arm most likely to regress: local tier faults, window tier cleanly misses, refusal must still be InternalError.
  • buffered_pull_through_hard_fault_is_internal_error — new: before it, reverting try_pull_through's HardFault broke zero tests.
  • local_populate_miss_is_clean_cache_miss — strengthened to pin NotFound and the inverse metric assertion, so over-promoting clean misses to InternalError (which would steer clients off a healthy node) fails as loudly as under-reporting a fault.

The metric flip (internal_error vs cache_miss) was asserted nowhere before this round; it now is, in both directions.

cargo clippy --all-targets   # clean
cargo fmt -- --check         # clean
cargo nextest run            # 2223 passed, 0 skipped

No contract surface touched.

🤖 Generated with Claude Code

…r a wedged candidate (#1129, #1141)

A `cdn/client/v1` refusal is EIP-712 signed, so `ServeRejectReason::CacheMiss`
(wire `NotFound`) is an attributable claim that the node does not hold the blob.
Two paths signed that claim when it wasn't true.

#1129 — the reactive fill helpers returned a bare `bool`, so a hard
`CacheError::OriginError` / `CacheError::Store` (an S3 5xx surviving retry
exhaustion, an open circuit breaker, an fs I/O error) collapsed to `false`,
indistinguishable from "no origin had it", and terminated as a signed `NotFound`
— telling paying clients a blob is gone when the node will serve it fine once its
origin recovers. The cache engine already draws this distinction (it prefers
`OriginError` over `NotFound` when an origin faulted); the handler discarded it,
even though the same file honors the invariant for its top-level `has` gate.

Introduce `FillOutcome { Filled, CleanMiss, HardFault }` and thread it through the
five fill helpers. A fault on one tier is remembered (`fault_seen`) across a
legitimate fall-through to a later tier, so a subsequent clean miss cannot launder
it back into a `NotFound`; the terminal refusal is then `InternalError`. A deadline
expiry stays a clean miss on purpose: the blob may well exist upstream, and
`InternalError` is reputation-bearing for this node while `NotFound` is benign.

#1141 — the window-paced node→node open applied no per-candidate timeout, while
the buffered path bounds each candidate with `pull_timeout` inside
`stream_fetch_tracked`. A candidate that accepted the connection and then went
quiet consumed the whole outer deadline — which is sized at
`MAX_PROVIDER_ATTEMPTS × pull_timeout + slack` precisely so candidates #2..N stay
reachable (#859) — so the serve path refused a blob honest peers held. Bound the
open on the same per-candidate budget; the typed `PullTimeout` flows into the
existing `classify_pull_failure`, which meters the timeout and exonerates the peer
(#857), exactly as on the buffered path.

Tests: a window-path counterpart of `node_origin_pull_falls_through_a_stalled_candidate`
(hangs to the outer budget without the fix); a `FailingOrigin` mock and two
hard-fault serve tests, incl. the fall-through arm where the local tier faults and
the node→node tier cleanly misses; and the clean-miss regression is strengthened to
pin `NotFound` rather than "some refusal".

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 13, 2026 15:22
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@thiras, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 25 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 944c0f2b-e3d0-433a-91a5-ff3827597878

📥 Commits

Reviewing files that changed from the base of the PR and between d667c0d and 9725cac.

📒 Files selected for processing (6)
  • CHANGELOG.md
  • crates/client-pull/src/lib.rs
  • crates/node/src/handlers/client.rs
  • crates/node/src/node_origin.rs
  • crates/node/tests/client_loopback.rs
  • crates/node/tests/node_origin_pull.rs

Walkthrough

The pull-through serving path now distinguishes clean absence from backend faults, preserves faults across tier fallthrough, and reports retryable internal errors when appropriate. Progressive upstream candidates are bounded by pull_timeout, with tests covering stalled-candidate fallback and fault classification.

Changes

Pull-through reliability

Layer / File(s) Summary
Explicit fill outcomes
crates/node/src/handlers/client.rs
Fill helpers now return explicit filled, clean-miss, or hard-fault outcomes, including store errors observed during timeout and coalesced-fill handling.
Multi-tier refusal classification
crates/node/src/handlers/client.rs, crates/node/tests/client_loopback.rs, CHANGELOG.md
Serve fallthrough preserves earlier hard faults and maps terminal refusals to retryable InternalError; loopback tests cover local faults, tier fallthrough, and genuine signed NotFound misses.
Progressive candidate timeout
crates/node/src/node_origin.rs, crates/node/tests/node_origin_pull.rs
Window-paced upstream opening applies pull_timeout per candidate and falls through from a stalled provider to an honest candidate.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant serve_stream
  participant LocalOrigin
  participant NodeOrigin
  participant Cache
  Client->>serve_stream: request blob
  serve_stream->>Cache: check local cache
  Cache-->>serve_stream: miss
  serve_stream->>LocalOrigin: populate from origin
  LocalOrigin-->>serve_stream: clean miss or hard fault
  serve_stream->>NodeOrigin: try window pull-through
  NodeOrigin-->>serve_stream: fallback result
  serve_stream-->>Client: NotFound or InternalError refusal
Loading

Note

🎁 Summarized by CodeRabbit Free

Your 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 @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 88.71% (2452/2764 lines)
▲ +0.00pp vs base (88.71% → 88.71%)
Run: 29264371359

Copilot AI 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.

Pull request overview

This PR tightens cdn/client/v1 serve-miss semantics so nodes don’t EIP-712 sign an authoritative NotFound when the underlying cause is a backend/store fault or a wedged upstream candidate, improving correctness of attributable refusals and making operator metrics reflect reality.

Changes:

  • Introduces a tri-state FillOutcome and threads it through reactive fill helpers so hard origin/store faults terminate as InternalError (retryable) instead of being mis-signed as NotFound.
  • Adds a per-candidate timeout to the window-path open_progressive_pull open stage so a stalled #1 candidate can’t consume the whole outer deadline and starve fallback candidates.
  • Extends/strengthens tests to pin the new refusal classifications and the window-path fallback behavior.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/node/src/handlers/client.rs Adds FillOutcome and uses fault_seen to prevent backend faults being laundered into signed NotFound on terminal misses.
crates/node/src/node_origin.rs Wraps window-path candidate open with pull_timeout so the multi-candidate fallback loop remains reachable under stalls.
crates/node/tests/node_origin_pull.rs Adds a regression test ensuring window-path open falls through after a stalled candidate without reputationally blaming it.
crates/node/tests/client_loopback.rs Adds failing-origin fixtures + tests to ensure hard local faults become InternalError and clean misses remain signed NotFound.
CHANGELOG.md Documents both user/operator-visible bug fixes in release notes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +306 to +325
match tokio::time::timeout(
deps.config.pull_timeout,
open_progressive_upstream(
&deps.endpoint,
EndpointAddr::new(pk),
&ctx,
&deps.slash_domain,
provider_addr,
hash_bytes,
0,
now_micros(),
deps.config.max_blob_size_bytes,
),
)
.await
{
.unwrap_or_else(|_| {
Err(anyhow::Error::new(PullTimeout {
after: deps.config.pull_timeout,
}))
}) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 574dc5d, and the root cause was slightly wider than the comment suggests.

PullTimeout's Display hardcodes the stage: write!(f, "stream_fetch timed out after {:?}", ...). That was accurate when stream_fetch_tracked was its only construction site; #1141 added a second one on the progressive-open stage, so the message became a falsehood there — not just under-specified. Adding context at my site alone would have masked it in %err (anyhow renders only the outermost layer) while leaving the lie in any {:?} chain dump.

So, two changes:

  • PullTimeout::Display is now stage-neutral: "upstream pull timed out after {:?}". This preserves the "timed out" substring that the !contains("timed out") negative assertion in node_to_node_pull_through's deadline test pins (called out in the type's own doc).
  • The open site adds .context("progressive upstream open") so logs name the stage.

Classification is unaffected, as you note — and that is already pinned rather than assumed: buyer_side_sentinels_survive_anyhow_downcast has a case proving downcast_ref recovers the sentinel through a .context() layer (anyhow walks the chain). Full suite green.

Comment on lines +252 to +260
enum FillOutcome {
/// The blob is now present locally; fall through to the size gate + delivery.
Filled,
/// No source had it. Terminal (when no further tier fills): signed `NotFound`.
CleanMiss,
/// A backend/store fault, not an absence. Terminal: `InternalError`, so the
/// client retries rather than treating the blob as gone.
HardFault,
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 574dc5d — the doc, not the behavior.

You are right that the variant is overloaded, and the inconsistency was mine: the buffered arm returns _ => FillOutcome::CleanMiss under a comment that literally says "nothing was attempted", while the enum doc said "No source had it".

I did not split it into a fourth NotAttempted variant, because the two cases behave identically at every use site and would for any plausible future one: neither is evidence of a fault, so both correctly defer the terminal classification to whatever the other tiers found (fault_seen is what actually carries the signal). A variant that is never distinguished would be a distinction the type claims to make but does not — worse than the honest union. If a future change ever needs to tell them apart, that is the moment to split it.

The doc now states what the variant actually means:

/// The tier produced no blob and no evidence of a fault. Covers BOTH a genuine
/// clean miss (a source was asked and did not have it) and a tier that was
/// never attempted at all (pull-through unconfigured, or the request not
/// authorized to make this node spend). The two are deliberately one variant:
/// neither is evidence of a fault, so both leave the terminal classification to
/// whatever the other tiers found. Terminal (when no tier fills and none
/// faulted): a signed `NotFound`.
CleanMiss,

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request addresses two main issues in the node serve path. First, it introduces a FillOutcome enum to distinguish between genuine cache misses and hard backend/origin faults, ensuring that transient errors are reported as retryable InternalErrors rather than signed NotFound responses. Second, it bounds progressive pull attempts with a per-candidate timeout to prevent a stalled upstream provider from starving the fallback loop. Comprehensive integration tests have been added to verify these behaviors. I have no feedback to provide as there are no review comments.

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.

@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.28% (was 80.25%, ▲ +0.04%) — 45238/56347 lines

File Coverage Lines Δ
crates/client-pull/src/lib.rs 88.77% 759/855 ● 0.00%
crates/node/src/handlers/client.rs 78.80% 1037/1316 ▲ +0.81%
crates/node/src/node_origin.rs 89.55% 523/584 ▲ +0.92%
History
Commit Total Δ vs base
d667c0d 80.31% ▲ +0.06%
574dc5d 80.29% ▲ +0.04%
9725cac (HEAD) 80.28% ▲ +0.04%

thiras and others added 2 commits July 13, 2026 18:31
…Miss doc

Review follow-ups on #1142.

`PullTimeout`'s `Display` hardcoded "stream_fetch timed out …", which was accurate
when the buffered delivery was its only construction site. #1141 added a second one
on the progressive-open stage, making the message a falsehood there — an operator
debugging a window-path stall would see a log line naming the buffered path. Make
the message stage-neutral ("upstream pull timed out …", preserving the "timed out"
substring the deadline test's negative assertion pins) and add a `.context` layer at
the open site so logs name the stage. Classification is unaffected: `downcast_ref`
walks the anyhow chain through `.context`, which `buyer_side_sentinels_survive_anyhow_downcast`
already pins.

`FillOutcome::CleanMiss`'s doc claimed "No source had it", but the variant is also
returned when a tier is never attempted (pull-through unconfigured, or the request
unauthorized to make this node spend). Behavior is right — neither case is evidence
of a fault, so both correctly defer the terminal classification to the other tiers —
but the doc was not. Say what the variant actually means.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…it (#1129)

Multi-agent review of #1142 found real defects in the #1129 half, and — reading
the protocol docs rather than my own PR text — that the justification I wrote for
the whole change was wrong. Both are fixed here.

The premise, corrected. `StreamResponse.error` is explicitly "unsigned and
informational"; the EIP-712 `slash_sig` covers only `StreamResponseBody`
(`ok: false`), NOT the reason code. So a misclassified refusal is a correctness
and observability bug, not the "false signed attestation" the earlier commits,
comments and CHANGELOG claimed. Two further corrections: `InternalError` is
documented as "do not retry this node" (not "retryable"), and `NotFound` is NOT
reputation-benign — `classify_pull_failure` folds ANY refusal, both codes alike,
into `Outcome::Unreachable`. Every comment resting on those three claims is
rewritten to say what the codes actually mean: `NotFound` is what a healthy-but-
empty node returns, `InternalError` says this node is degraded, and the value of
the split is honest client routing plus the per-reason reject metric — the only
server-side place the true cause survives, since seven reasons collapse to one
wire code.

Defects fixed:

- The `HardFault` catch-all was too wide: `populate` also returns
  `CacheError::BlobTooLarge` / `HashMismatch` / `VerifyFailed`, which are
  deterministic and recur on every request for that hash. Classifying them as
  "this node is broken" would steer clients off a healthy node permanently over
  one oversized blob, and for `BlobTooLarge` it contradicted the size gate, which
  refuses the identical condition with the dedicated `BlobTooLarge` code. Narrow
  `HardFault` to `OriginError | Store`.
- The leech-admission exit refused with a bare `CacheMiss`, dropping a latched
  fault. `NotFound`'s doc does sanction a pull-through decline, so this is
  defensible in isolation — but it is the wrong code once the local origin has
  faulted, since that fault is the only reason the request reached the paid peer
  path at all. Route it through `miss_reason`. The channel-class refusals
  (`UnknownChannel`, `InsufficientDeposit`) keep their own reasons: they are
  client-attributable and collapse to `NotFound` deliberately, so a prober cannot
  map other clients' channel balances.
- The fault latch started AFTER the range tier, so a `CacheError::Store` there
  was dropped (and unmetered). The local tier happened to re-detect it, but that
  is a coincidence of tier ordering, not an invariant. Latch and meter it.
- `on_pull_through_timeout` counted a store fault as BOTH an error and a timeout,
  contaminating the metric whose job is to separate "slow upstream" from "broken
  store" — while its sibling states that exact rule as law. Aligned.

Tests. The metric flip was asserted nowhere, and reverting `try_pull_through`'s
`HardFault` failed zero tests. Adds a metrics-returning fixture and pins both
directions (fault ⇒ internal_error=1/cache_miss=0; clean miss ⇒ the inverse, so
over-promotion fails as loudly as under-reporting), plus a buffered-tier fault
test. The window staller test now uses TWO stallers — with one, a regression that
budgeted the whole loop instead of each candidate still passed — and a 3s
per-candidate budget, since that budget now also bounds the honest candidate's
open and 1s was a CI flake risk.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras
thiras merged commit 6b10e7a into main Jul 13, 2026
23 checks passed
@thiras
thiras deleted the fix/serve-path-miss-semantics branch July 13, 2026 16:07
thiras added a commit that referenced this pull request Jul 15, 2026
…1088, #1144, #1134, #1143) (#1145)

* fix(protocol): reject zero-length ChunkData frames (#1088)

`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]>

* fix(client-pull): carry the refusal StreamError as a typed sentinel (#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]>

* fix(client-pull): bound each stage by what actually fits it (#1134)

`--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]>

* fix(node): singleflight the buyer channel open on a candidate budget (#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]>

* review: address bot review on #1145

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]>

* fix(node): the openChannel receipt must NOT be bounded (#1143 review)

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]>

* fix(node): reject a zero pull budget; give the background warm a real 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]>

* test(node): guard the fixes — 3 of 4 were passing on reverted behavior

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]>

* docs: correct claims that no longer match the code (#1145 review)

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]>

* fix: address the multi-agent review of #1145

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]>

* fix: address the second multi-agent review of #1145

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]>

* fix: two of the previous commit's own fixes were unsound (#1145)

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]>

* fix(node): a cancelled pull lost the money it had already spent (#1145 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]>

* test(node): guard the three arms that were passing on reverted behavior (#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]>

* fix: bounds that could not do their job — first-byte, warm budget, deadlines (#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]>

* docs: correct the claims the last three commits invalidated (#1145 review)

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]>

* fix: the money the last round's fixes could still lose (#1145 review)

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]>

* fix: exonerating a peer is not the same as ignoring it (#1145 review)

**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]>

* fix: the legs nobody was watching, and the bounds nobody was testing (#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]>

* fix: make the reservation structural, and correct the claims that were 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]>

* fix: the fourth review's two money bugs, and the round's remaining legs (#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]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants