Skip to content

docs: convert ASCII art schemas to Mermaid diagrams - #3

Merged
thiras merged 3 commits into
mainfrom
docs/mermaid-diagrams
Mar 29, 2026
Merged

thiras merged 3 commits into
mainfrom
docs/mermaid-diagrams

Conversation

@thiras

@thiras thiras commented Mar 29, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Replace all ASCII art diagrams with Mermaid equivalents inline across 8 ADR files
  • Add new visual diagrams for data structures, flows, and relationships that were previously text-only
  • Covers: sequence diagrams (probe, delivery, watchtower, encryption), state machines (payment channel, staking), flowcharts (cache miss, reputation scoring, defense stack), class diagrams (protocol messages, contracts, reputation), pie charts (token distribution, fee allocation), and dependency/relationship graphs

Test plan

  • Verify all Mermaid diagrams render correctly on GitHub PR diff view
  • Spot-check each diagram against its source ADR for accuracy
  • Confirm no prose or technical content was removed or altered

🤖 Generated with Claude Code

Replace inline ASCII art and text-based diagrams with Mermaid equivalents
for better rendering on GitHub and in editors. Adds sequence diagrams for
wire protocols, state machines for payment channels and staking, flowcharts
for cache miss resolution and reputation scoring, class diagrams for data
structures, and pie charts for token/fee allocation.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings March 29, 2026 15:24

@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 replaces text-based diagrams and descriptions with Mermaid diagrams across several Architecture Decision Record (ADR) files to improve visual clarity. The changes cover network routing, payment states, tokenomics, protocol sequences, encryption flows, watchtower interactions, and reputation scoring. A review comment identifies a missing dependency on iroh in the dependency chain diagram within adr/architecture.md and provides a suggestion to restore it for consistency with the original documentation.

Comment thread adr/architecture.md
Comment on lines +287 to +288
protocol --> serde
protocol --> postcard

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The text this diagram replaces mentioned that the protocol crate depends on iroh types. This dependency appears to be missing from the diagram. To ensure consistency, consider adding the dependency on iroh.

Suggested change
protocol --> serde
protocol --> postcard
protocol --> serde
protocol --> postcard
protocol --> iroh

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. Added protocol --> iroh to the dependency diagram.

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

Updates ADR documentation to replace legacy ASCII diagrams with GitHub-renderable Mermaid diagrams, improving readability and enabling richer visualization directly in Markdown.

Changes:

  • Converted multiple ADR ASCII art diagrams into Mermaid (graphs, flowcharts, sequence diagrams, class diagrams, state diagrams, and pie charts).
  • Added new Mermaid diagrams for flows/relationships that were previously only described in prose.
  • Standardized diagram presentation inline across the ADR set.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
adr/architecture.md Replaces the system/dependency ASCII diagrams with Mermaid; adds a cache-miss flowchart.
adr/001-network.md Adds a Mermaid graph describing gossip topics → routing table → DHT fallback.
adr/003-payments.md Adds Mermaid state diagram for channel lifecycle and a class diagram for currency/channel types.
adr/004-tokenomics.md Adds Mermaid pie/state/graph diagrams for distribution, staking/slashing states, fee allocation, and contract relationships.
adr/005-protocol.md Replaces probe/delivery ASCII sequence diagrams with Mermaid sequence diagrams (includes notes).
adr/006-e2e-encryption.md Replaces ASCII sequences/lists with Mermaid diagrams for key delivery, full flow, and offline flows.
adr/007-watchtower.md Replaces ASCII protocol sequence with Mermaid; adds Mermaid defense-stack flowchart.
adr/008-reputation.md Adds Mermaid flowchart for scoring composition and class diagram for reputation report structures.

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

Comment thread adr/006-e2e-encryption.md Outdated
Comment on lines +107 to +114
A->>A: wrapped = XChaCha20(epoch_key, K_blob)
A->>C: sealed envelope {wrapped, epoch_id, hash}

C->>N: StreamRequest {hash}
N->>C: ciphertext (paid per MB via cdn/client/v1)

C->>C: unseal envelope with private key
C->>C: decrypt wrapped with epoch_key to get K_blob

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

This step says wrapped = XChaCha20(epoch_key, K_blob), but earlier in the ADR the wrapping is defined as XChaCha20-Poly1305(epoch_key, K_blob). Align the diagram text with the specified AEAD to avoid implying a non-authenticated cipher.

Suggested change
A->>A: wrapped = XChaCha20(epoch_key, K_blob)
A->>C: sealed envelope {wrapped, epoch_id, hash}
C->>N: StreamRequest {hash}
N->>C: ciphertext (paid per MB via cdn/client/v1)
C->>C: unseal envelope with private key
C->>C: decrypt wrapped with epoch_key to get K_blob
A->>A: wrapped = XChaCha20-Poly1305(epoch_key, K_blob)
A->>C: sealed envelope {wrapped, epoch_id, hash}
C->>N: StreamRequest {hash}
N->>C: ciphertext (paid per MB via cdn/client/v1)
C->>C: unseal envelope with private key
C->>C: decrypt wrapped with epoch_key using XChaCha20-Poly1305 to get K_blob

Copilot uses AI. Check for mistakes.

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. Updated all three references to use the full XChaCha20-Poly1305 AEAD name.

Comment thread adr/006-e2e-encryption.md Outdated
C->>C: unseal envelope with private key
C->>C: decrypt wrapped with epoch_key to get K_blob
C->>C: verify BLAKE3(ciphertext) == hash
C->>C: decrypt XChaCha20(K_blob, ciphertext) and play

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

This line says decrypt XChaCha20(K_blob, ciphertext), but the ADR’s content layer specifies XChaCha20-Poly1305(K_blob, plaintext/ciphertext) (AEAD). The diagram should include -Poly1305 (and keep plaintext/ciphertext direction consistent) to match the written spec.

Suggested change
C->>C: decrypt XChaCha20(K_blob, ciphertext) and play
C->>C: decrypt XChaCha20-Poly1305(K_blob, ciphertext) and play

Copilot uses AI. Check for mistakes.

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 the same change as above.

Comment thread adr/005-protocol.md
Comment on lines +34 to +35
Note over R: RTT = receive_time - timestamp_us
Note over R: Score = rate_per_mb x rtt_ms (lower is better)

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

In Mermaid sequence diagrams, Note over typically requires two participants (Note over A,B:). Using Note over R: may fail to render on GitHub. Consider switching to Note right of R:/Note left of R: or Note over R,C:.

Copilot uses AI. Check for mistakes.

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.

Note over <single participant>: is valid Mermaid syntax. The spec supports Note over Alice: text for single participants, not just Note over Alice,Bob:. GitHub renders it correctly. No change needed.

Comment thread adr/005-protocol.md
end
P->>D: StreamEnd
else redirect
Note over P: Connect to redirect NodeId and retry

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

Note over P: may not be valid Mermaid syntax for a single participant (GitHub Mermaid generally expects Note right/left of or Note over A,B). Adjusting this will help ensure the diagram renders consistently.

Suggested change
Note over P: Connect to redirect NodeId and retry
Note right of P: Connect to redirect NodeId and retry

Copilot uses AI. Check for mistakes.

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.

Same — Note over P: is valid single-participant Mermaid syntax and renders on GitHub.

Comment thread adr/006-e2e-encryption.md
Comment on lines +71 to +76
Note over C: epoch 42 key discarded

Note over A: subscription canceled

A->>C: close connection
Note over C: no epoch 44 key — cannot decrypt new content

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

These notes use Note over <single participant>: which may not parse/render in Mermaid sequence diagrams (GitHub typically supports Note left/right of for a single participant, or Note over A,B: for two). Consider changing to Note right of C: / Note right of A:.

Suggested change
Note over C: epoch 42 key discarded
Note over A: subscription canceled
A->>C: close connection
Note over C: no epoch 44 key — cannot decrypt new content
Note right of C: epoch 42 key discarded
Note right of A: subscription canceled
A->>C: close connection
Note right of C: no epoch 44 key — cannot decrypt new content

Copilot uses AI. Check for mistakes.

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.

Same as the protocol diagram comments — Note over C: is valid Mermaid syntax for a single participant.

Comment thread adr/006-e2e-encryption.md
Comment on lines +71 to +76
Note over C: epoch 42 key discarded

Note over A: subscription canceled

A->>C: close connection
Note over C: no epoch 44 key — cannot decrypt new content

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

Note over C: is used with a single participant here; Mermaid sequence diagrams usually require Note right/left of C: for single-participant notes. This may prevent the diagram from rendering on GitHub.

Suggested change
Note over C: epoch 42 key discarded
Note over A: subscription canceled
A->>C: close connection
Note over C: no epoch 44 key — cannot decrypt new content
Note right of C: epoch 42 key discarded
Note right of A: subscription canceled
A->>C: close connection
Note right of C: no epoch 44 key — cannot decrypt new content

Copilot uses AI. Check for mistakes.

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.

Duplicate of the above.

thiras and others added 2 commits March 29, 2026 18:32
Remove state diagram and class diagram from payments ADR, and remove
staking lifecycle state diagram and contract relationships graph from
tokenomics ADR per review feedback.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add missing protocol --> iroh dependency in architecture diagram.
Use full XChaCha20-Poly1305 AEAD name in encryption flow diagram.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@thiras
thiras merged commit 7a1e86c into main Mar 29, 2026
@thiras
thiras deleted the docs/mermaid-diagrams branch March 29, 2026 15:35
alpergundogdu added a commit that referenced this pull request Apr 30, 2026
Six review comments. All valid; the em-dash anchor question reframed
the original #339 fix.

Em-dash anchor standardization (Gemini #1, #2, #3 — also rolls back
part of this PR's own #339 fix)

Issue #339's premise was wrong. GitHub's slugger
(github-slugger) replaces *each* whitespace character with a hyphen
— it does NOT collapse runs. So a heading like `Foo — Bar` becomes:

  1. Lowercase: `foo — bar`
  2. Strip `—`: `foo  bar` (two consecutive spaces remain)
  3. Each space → hyphen: `foo--bar` (double hyphen)

The double-hyphen anchors in main were therefore CORRECT, not broken.
This PR's earlier "fix" (single-hyphen) introduced the broken anchors.
Reverted, and standardized on the actual GFM-generated form (`--`)
across the ADR set:

- `cdnprobev1--latency-probe` (heading: `cdn/probe/v1 — latency probe`)
- `gossip--rate-change-announcements` (heading: `Gossip — rate change
  announcements`)
- `tier-1--minor-no-coordination` (heading: `Tier 1 — Minor (no
  coordination)`)
- `content-discovery-dht--probe` (heading: `Content Discovery (DHT +
  Probe)` — `+` removal also leaves two spaces)
- `3-session-keys--deferred-to-production-via-erc-7579-smartsessions`
  (heading: `3. Session Keys — Deferred to Production via ERC-7579
  smartsessions`)

Also fixed two pre-existing single-hyphen refs that were never
correct on main: `001-network.md:154` and `014-on-chain-verification.md:278`.

ADR 002:34 (Copilot) — challenge bond ref repointed to ADR 014

Cross-ref pointed at ADR 026 §8 for "challenge bond requirements", but
ADR 026 §8 only lists the bond as part of slashing distribution; the
canonical home for bond mechanics (amount, transfer, forfeit rules) is
ADR 014's `#### Bond Handling` section. Repointed.

ADR 011:128 (Copilot) — keep single stake value (no PoC/Prod split)

Copilot suggested adding "1,000 TOKEN PoC / 50,000 TOKEN production" to
match other places. Per direction "PoC and Prod should follow the same
structure, we'll just modify the fee router," the stake minimum is
unified. Kept the single 50,000 TOKEN value here, and aligned ADR
016:143 (constructor deps row for StakingRegistry) to drop its own
`PoC 1,000 TOKEN; production: 50,000 TOKEN` split. Also dropped the
adjacent "discount-threshold parameters removed" framing since it was
historical-iteration narrative left over from the ADR 004 deletion
sweep — now reads as a definitive statement.

ADR 016:28 (Copilot) — Phase column typo

`FeeRouter` / `VotingEscrow` / `SafetyReserve` rows had Phase column
"Production (production)" — duplicated/typoed. Normalized all three
to "Production only" matching the other rows in the table.
alpergundogdu added a commit that referenced this pull request Apr 30, 2026
* docs(adr): pre-launch cleanup — anchors, framing, superseded ADR

Lands #339, #341, and #342 together since they overlap on several
files and share the same definitive-framing rationale (the protocol
has one design pre-launch; ADRs read as the canonical design, not as
an iteration log).

#339 — cross-reference hygiene (13 broken anchors)

Em-dash collapse fixes (`--` → `-` in anchors): GFM strips em-dashes
from headings and collapses surrounding whitespace into a single
hyphen. Touched: ADR 002, ADR 005 (3 instances), ADR 013 (2
self-anchors), ADR 015 (3 instances).

Renamed/missing target fixes:
- ADR 011 → ADR 005 phantom-announcement: target heading didn't exist;
  repointed to the parent `cdn/probe/v1 — latency probe` heading where
  the mechanism is described inline.
- ADR 012 → ADR 024 session-keys: heading was renamed; repointed to
  the actual `#3-session-keys-deferred-to-production-via-erc-7579-smartsessions`.
- ADR 022 → ADR 013 schema-evolution-strategy: target didn't exist;
  repointed to `#protocol-enums` (the relevant section for the
  per-ALPN protocol enum pattern).

Programmatic check post-fix: zero broken `*--*` anchors across the
ADR tree.

#341 — v3-iteration framing sweep (ADRs 009, 021)

The PR #338 reframe pass missed several pockets. Cleaned up:

- ADR 009 §Bootstrap consideration: "drops the auto-ve-lock-on-vest
  pattern from earlier v2 interim designs" → "Under ADR 026, vesting
  contracts release TOKEN unlocked... (no auto-ve-lock-on-vest)".
- ADR 021 §Tokenomics Validation Requirements: dropped 8 instances of
  "v3 Tokenomics" / "deployment of v3 contracts" / "in v3" / "under v3"
  / "v3 deployment" / "during v3 contract integration testing". Section
  now reads as a definitive validation gate against ADR 026, not as a
  migration narrative.

Programmatic check post-fix: zero `\bv3\b` hits in production ADR
corpus excluding legitimate Balancer V3 / Uniswap V3 references.

#342 — drop superseded ADR 004 + 'ADRs to update on acceptance' sections

ADR 004 deletion. Pre-launch there's no v1 deployment to preserve
historical record for. Audited every inbound cross-ref (54 hits across
13 files) and either:
- repointed to ADR 026's canonical home (ADR 026 §1 supply, §7 staking
  parameters, §8 slashing/auto-ejection/challenge-bond, §11
  governable parameters);
- repointed to ADR 003's Deposit Economics for the gas-cost numbers
  (which ADR 003 already carries verbatim); or
- dropped iteration-narrative phrasing entirely ("under ADR 004",
  "earlier drafts", "supersedes ADR 004", "ADR 004's X mechanic" etc.).

Notable repoint targets:
- ADR 005 / 011 / 014 challenge-bond + slash-schedule refs → ADR 026 §8
- ADR 001 staking refs → ADR 026 §7
- ADR 014 §Integration with Existing Contracts: dropped the
  `submitFraudProof()` historical-replacement note entirely.
- ADR 016 §Contract Inventory table: removed [004] cells from TOKEN /
  StakingRegistry / BuybackBurner rows.
- ADR 018 §Context: collapsed two paragraphs of "ADR 004 says X but
  ADR 026 changes it to Y" iteration narrative into one definitive
  block.
- ADR 021 §Context + §Updates: reframed from "resolves ADR 004
  deferral" to "selects production L2"; renamed §Updates to Prior
  ADRs → §Cross-ADR alignment.
- architecture.md: dropped the standalone ADR 004 entry; updated
  ADR 026 summary to drop "Supersedes ADR 004 in full".
- ADR 026 frontmatter: dropped "Supersedes: [ADR 004] in full".
- ADR 026 / ADR 030 Alternatives Considered: dropped [ADR 004] links
  but kept the rejected-alternatives prose intact.

"ADRs to update on acceptance" section deletions. Once #338 landed and
the touched ADRs were updated, these sections became stale inventory
of past work. Removed from:
- ADR 026 (touched-list pointer)
- ADR 027 (touched: 003, 007, 008, 014, 017, 026)
- ADR 030 (touched: 008, 016, 019, 026 — minus the dropped 009 entry)
- ADR 032 (deferred — touched on adoption: 003, 018, 026, 030)

Final state: ADR tree contains 26 ADRs (001–003, 005–020, 022–032);
ADR 004 slot retired (numbering doesn't reuse). No broken anchors. No
v1/v2/v3 iteration framing in the canonical corpus.

* docs(contributing): repoint ADR 004 ref → ADR 026

Side effect of deleting ADR 004 in this PR — the consistency-checks
section pointed at `004-tokenomics.md` for token names / contract
references / fee parameters. ADR 026 is now the canonical home for
that surface.

* docs(adr): address Copilot + Gemini review pass

Six review comments. All valid; the em-dash anchor question reframed
the original #339 fix.

Em-dash anchor standardization (Gemini #1, #2, #3 — also rolls back
part of this PR's own #339 fix)

Issue #339's premise was wrong. GitHub's slugger
(github-slugger) replaces *each* whitespace character with a hyphen
— it does NOT collapse runs. So a heading like `Foo — Bar` becomes:

  1. Lowercase: `foo — bar`
  2. Strip `—`: `foo  bar` (two consecutive spaces remain)
  3. Each space → hyphen: `foo--bar` (double hyphen)

The double-hyphen anchors in main were therefore CORRECT, not broken.
This PR's earlier "fix" (single-hyphen) introduced the broken anchors.
Reverted, and standardized on the actual GFM-generated form (`--`)
across the ADR set:

- `cdnprobev1--latency-probe` (heading: `cdn/probe/v1 — latency probe`)
- `gossip--rate-change-announcements` (heading: `Gossip — rate change
  announcements`)
- `tier-1--minor-no-coordination` (heading: `Tier 1 — Minor (no
  coordination)`)
- `content-discovery-dht--probe` (heading: `Content Discovery (DHT +
  Probe)` — `+` removal also leaves two spaces)
- `3-session-keys--deferred-to-production-via-erc-7579-smartsessions`
  (heading: `3. Session Keys — Deferred to Production via ERC-7579
  smartsessions`)

Also fixed two pre-existing single-hyphen refs that were never
correct on main: `001-network.md:154` and `014-on-chain-verification.md:278`.

ADR 002:34 (Copilot) — challenge bond ref repointed to ADR 014

Cross-ref pointed at ADR 026 §8 for "challenge bond requirements", but
ADR 026 §8 only lists the bond as part of slashing distribution; the
canonical home for bond mechanics (amount, transfer, forfeit rules) is
ADR 014's `#### Bond Handling` section. Repointed.

ADR 011:128 (Copilot) — keep single stake value (no PoC/Prod split)

Copilot suggested adding "1,000 TOKEN PoC / 50,000 TOKEN production" to
match other places. Per direction "PoC and Prod should follow the same
structure, we'll just modify the fee router," the stake minimum is
unified. Kept the single 50,000 TOKEN value here, and aligned ADR
016:143 (constructor deps row for StakingRegistry) to drop its own
`PoC 1,000 TOKEN; production: 50,000 TOKEN` split. Also dropped the
adjacent "discount-threshold parameters removed" framing since it was
historical-iteration narrative left over from the ADR 004 deletion
sweep — now reads as a definitive statement.

ADR 016:28 (Copilot) — Phase column typo

`FeeRouter` / `VotingEscrow` / `SafetyReserve` rows had Phase column
"Production (production)" — duplicated/typoed. Normalized all three
to "Production only" matching the other rows in the table.
alpergundogdu added a commit that referenced this pull request May 1, 2026
…tions

- appendix-observability.md: #health-endpoint -> #3-health-endpoint
- architecture.md: #future-work-search-discovery -> #future-work-search--discovery
  (GitHub-slugger collapses "& " into double-hyphen)
- README.md: document one-shot pandoc + typst build for printable PDF
- .gitignore: exclude /adr/adrs.pdf build artifact
alpergundogdu added a commit that referenced this pull request May 4, 2026
…vernor

Drop the hand-rolled `TokenBucket` + `BoundedRateMap<K>` and the parallel
per-NodeID layer; replace both with a single `governor::DefaultKeyedRateLimiter`
keyed on `IpAddr`. Two of the four asks on PR #386's review collapse into
this commit because they're entangled: the keyed limiter no longer needs
to know about NodeID, and adopting `governor` (0.10) is the maintained-
crate replacement for the bespoke token-bucket code.

Surface changes:
- Config: `per_ip_*`/`per_node_*` → single `per_source_*` pair.
  `per_source_rate_per_sec = 0` disables the layer; per-NodeID is gone.
- Metrics: `dispatch_rejected_per_ip` + `dispatch_rejected_per_node`
  fold into `dispatch_rejected_per_source`. The skip counter for relay-
  only connections is renamed to `dispatch_per_source_skipped_no_addr`.
- `RejectReason::PerIp`/`PerNodeId` → `RejectReason::PerSource`. Reason
  string `"per-source"`. ADR 013's close-code description trimmed to
  match.
- `ConnectionLimiter::acquire_for_test` no longer takes a node key —
  `peer_ip: Option<IpAddr>` is the only argument.

Naming: "per-source" is intentional. Today the source axis is the
remote `IpAddr` (`/64`-grouped for IPv6, as before). Future keying
axes (NodeID, ASN, etc.) can land without renaming the operator-
visible config and metrics surface.

Implementation:
- `governor::DefaultKeyedRateLimiter<IpAddr>` behind an `RwLock<Option<Arc<...>>>`.
  `None` = layer disabled.
- Cap enforcement: when `limiter.len() > cfg.max_tracked_sources`,
  call `retain_recent()` lazily under the read guard so the keyspace
  stays bounded without a background task.
- `reload()` rebuilds the keyed limiter from the new quota and swaps
  it under the write lock. Token-bucket state is *not* preserved
  across the rebuild — operators tuning a live quota should expect
  the next acquire from each source to start with a fresh burst
  budget. (This was PR #386 review ask #4; falls out for free with
  the rebuild-and-swap approach.)
- Semaphore resize logic untouched (PR #386 ask #2 lands in a follow-up).

Tests: dispatch.rs test module rewritten end-to-end. Dropped tests
covered TokenBucket internals (refill, burst-cap, clock-skew) and
BoundedRateMap mutators (eviction, set_cap, set_rate_burst, disable→
re-enable resume) — governor owns those now. Kept tests cover
ConnectionLimiter behaviour: rejection on global/per-source exhaustion,
relay bypass, IPv6 /64 grouping, hot-reload grow/shrink/disable→re-enable,
concurrent-reload convergence, acquire-storm-vs-reload-storm. All 218
unit tests + 7 probe_loopback + 18 admin_peers + 14 config_validate +
2 sighup_signal pass; clippy and rustdoc clean.

Out of scope (tracked for follow-up commits on the same PR):
- swap-not-resize the global `Arc<Semaphore>` on reload (PR #386 ask #2)
- factor a `Reloadable` trait and migrate sections (PR #386 ask #3)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request May 4, 2026
…tions

Extract the inline per-section glue in `RuntimeReloadState::reload` into
a small `ReloadableSection` trait so adding the next reloadable knob no
longer means touching the central reload body. Addresses ask #3 from the
review on PR #386.

## Trait shape

```rust
trait ReloadableSection: Send + Sync {
    fn name(&self) -> &'static str;
    fn clear_buffer(&self);
    fn resolve(&self, file: &FileConfig) -> anyhow::Result<()>;
    fn fallible_commit(&self) -> anyhow::Result<()> { Ok(()) }
    fn infallible_swap(&self);
}
```

The associated `Resolved` type is erased via a per-section
`Mutex<Option<Resolved>>` buffer cell (option (a) from the brief). This
keeps the trait `dyn`-safe — `RuntimeReloadState` holds
`Vec<Arc<dyn ReloadableSection>>` and iterates it three times per
reload — without forcing a single uniform `Resolved` type across
sections. The buffer's lifecycle: emptied at the start of every
`reload()` (via `clear_buffer`), filled by `resolve`, read by
`fallible_commit`, drained by `infallible_swap`.

## What moved

Each of the four current sections becomes a concrete impl that owns
the state it mutates:

- `PaymentSection` — holds the `Arc<AtomicU64>` for `rate_per_mb` and
  the `PaymentArgs` CLI override.
- `LogLevelSection` — holds the `LogLevelSetter` closure, the
  `current` cache (Mutex<Option<LogLevel>>) for first-reload-applies,
  and the `ObservabilityArgs` CLI override. This is the only section
  with a non-trivial `fallible_commit` (the tracing-filter swap).
- `PinnedHashesSection` — holds the optional `CacheEngine` (attached
  via `attach_cache`).
- `SecuritySection` — holds the optional `Arc<ConnectionLimiter>`
  (attached via `attach_limiter`).

`RuntimeReloadState::reload` becomes a fixed three-phase iteration:

1. Resolve every section. Any failure → return early, previous values
   retained for every section (existing all-or-nothing contract).
2. Run every `fallible_commit`. Documented as the rollback boundary:
   commits already applied stay applied if a later section fails.
3. Run every `infallible_swap`. Atomic stores, `Arc` swaps, and
   `ConnectionLimiter::reload` (the semaphore swap from 46235af is
   infallible, so it lives here, not in phase 2).

## What stayed

- Public API of `RuntimeReloadState`: `new`, `attach_cache`,
  `attach_limiter`, `seed_initial_file_snapshot`, `reload`,
  `rate_per_mb`, `current`, `for_test_with_setter`. Unchanged.
- The all-or-nothing contract: previous values retained for every
  section on any resolve failure.
- The `last_file_sections: Mutex<FileSectionSnapshot>` snapshot/diff
  machinery and the "log changes to non-reloadable sections once"
  plumbing — driven inline in `reload()`, not through the trait, since
  it's cross-cutting rather than per-section.
- Section ordering (`payment`, `log_level`, `pinned_hashes`,
  `security`) — preserved verbatim so operator-visible commit
  ordering doesn't shift behind the refactor.
- Every existing test passes unchanged in behaviour. The poisoned-
  mutex tests adapt to the new field paths
  (`state.cache` → `state.pinned.engine`, `state.limiter` →
  `state.security.limiter`, `state.current_log_level` →
  `state.log_level.current`) but the contracts they enforce — setter
  not called when log-level mutex is poisoned, rate atomic not moved
  on snapshot-mutex poison, etc. — are identical.

## Tracing

Each section emits its own `config reload section applied` info
event keyed by `section = name()`, instead of the prior monolithic
"config reload applied" line carrying every field at once. The
aggregated "config reload applied" line is retained as an
end-of-reload marker for any operators / log scrapers that grep for
it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request May 4, 2026
* feat(dispatch): per-IP / per-NodeID connection rate limit (#235)

Adds a `ConnectionLimiter` shared across all deCDN QUIC protocol handlers
to prevent connection-flood exhaustion. Three enforcement layers are applied
at the top of every `ProtocolHandler::accept` call:

1. Global semaphore — hard cap on total in-flight handler tasks (default 256).
2. Per-NodeID lazy-refill token bucket (default 20 tok/s, burst 20).
3. Per-IP lazy-refill token bucket (default 100 tok/s, burst 200).

Connections that fail any check are closed immediately with the new
`APP_ERR_RATE_LIMITED = 0x10` QUIC application error code (peers SHOULD
back off; they MUST NOT treat it as a protocol error). Using `Ok(())` on
rejection avoids polluting iroh's task logs with spurious failures.

New `[security]` TOML section with safe defaults so a stock node is
protected out of the box. Hot-reload is intentionally excluded — semaphore
rebuild or token-bucket reset mid-run would transiently allow/deny traffic
in unpredictable ways.

New Prometheus metrics: `decdn_dispatch_rejected_{global,per_node,per_ip}_total`
counters and `decdn_dispatch_in_flight` gauge, all following ADR 020 naming.

ADR 013 §Application Error Codes updated with the new `0x10 RATE_LIMITED`
row and its semantic contract.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(dispatch): address code review feedback

- deny.toml: ignore RUSTSEC-2026-0118/0119 (hickory-proto transitive,
  no patch available — same pattern as existing ignores)
- reload: add [security] to FileSectionSnapshot + log_ignored_other_sections
  so SIGHUP edits to security.* emit the standard "requires restart" warning
- config: add is_finite() guard on per_node_rate_per_sec and
  per_ip_rate_per_sec so inf/NaN fail fast at load time
- dispatch: replace double-lookup (contains_key + get_mut) with
  get_mut-then-entry in try_consume, eliminating one hash on the hot path

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(dispatch): observability, type-tightening, and validation gaps

Second round of review feedback on the connection rate limiter.

Observability: dispatch::acquire now emits tracing::debug! per rejection
with reason/node_id/ip, and the QUIC close-frame reason bytes carry a
short layer label (global-full / per-ip / per-node-id) so peers can pick
an appropriate backoff. probe.rs gained a comment explaining why the
rate-limited path returns Ok(()) — returning Err would have iroh
amplify rejection logs as AcceptError under flood.

Correctness: per-IP is now checked before per-NodeID so a per-IP
rejection never charges a per-NodeID token. DEFAULT_PER_NODE_BURST goes
from 20 to 40 (2× the rate, matching per-IP defaults) so well-behaved
peers don't trip the limit on naturally-clumped requests.
BoundedRateMap::cap is now NonZeroUsize, ruling out the cap=0 silent
overflow at the type level. peer_ip filters is_closed paths.

Validation: SIGHUP-driven reload now pre-validates a changed [security]
section and emits a tracing::warn! if the next restart would fail to
start, instead of letting the operator discover it later under
pressure.

Tests: new integration test exercises APP_ERR_RATE_LIMITED on the wire
end-to-end (the rejection path was previously dead code under tests).
New unit tests cover global semaphore exhaustion, Permit drop releasing
the slot, per-IP/per-NodeID rejection, asymmetric-token-charge
invariant, relay-skip, concurrent contention, mutex poisoning recovery,
backward clock skew, and 8 invariants of resolve_security.

Cleanup: removed (issue #235) tags from 8 sites, dropped section
dividers, updated ADR 013 row to explain CONNECTION_CLOSE choice.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(security): hot-reload all [security] knobs on SIGHUP

ConnectionLimiter now resizes in place: token-bucket maps mutate under
their existing Mutex (preserving last_refill and accumulated tokens
clamped to the new burst), and Arc<Semaphore> identity stays stable
across cap changes via add_permits / acquire_many_owned(...).forget().
RuntimeReloadState gains a limiter slot wired into the reload pipeline
with the same fallible-then-commit contract as cache.pinned_hashes.

`0` in any security.* field disables that layer (no global cap, layer
short-circuit, or unbounded source map); rate>0 paired with burst=0
remains rejected as a deny-all corner. Invalid security values now
reject the entire reload (all-or-nothing), replacing the
"requires-restart" warning that became a lie once values applied live.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): cargo doc, doc/code drift, and O(N²) set_cap shrink

- ConnectionLimiter::reload's public doc no longer links to private
  BoundedRateMap::{set_rate_burst,set_cap}; rustdoc -D warnings rejects
  intra-doc links from public to private items.
- SecurityConfig per-field docs now match resolve_security: rate=0 alone
  disables the layer; the paired burst is ignored (the limiter's
  try_consume short-circuits before the bucket is touched). Previously
  the docs claimed "both rate=0 AND burst=0 to disable" while validation
  only checked the rate.
- BoundedRateMap::set_cap: replace the O(N²) shrink loop (evict_oldest
  in a loop) with a single O(N) select_nth_unstable_by_key partition +
  bulk remove. Worst case at the default 4096 cap drops from ~16M
  comparisons under the held mutex to a linear scan plus a partial sort.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): address review feedback on hot-reload work

Doc/comment fixes:
- Replace stale (#issue) placeholder in BoundedRateMap::set_rate_burst
- Drop acquire_for_test's invented rustdoc-discoverability claim
- Correct set_cap complexity: select_nth_unstable_by_key is average O(n)
  via introselect, not "linear with a log factor"
- Point Permit doc at acquire_inner (the actual gauge-increment site)
- Trim acquire_inner's stale doc that predates acquire_for_test
- Replace "now fully reloadable" / "no longer get a warning" wording
  with steady-state phrasing in log_ignored_other_sections trailing comment
- Document the .min(burst) clamp's role in safe set_rate_burst across
  dramatic rate drops with stale last_refill
- Clarify attach_cache/attach_limiter poison handling: recovery stores the
  new value but does NOT clear the poison flag; subsequent reloads
  fail-stop with "<slot> attach mutex poisoned"

Operator-visibility fixes:
- Bind err in shrink-task Err arm (was throwing it away). Bound %err
  surfaces if a future tokio AcquireError variant appears.
- Spell out all-or-nothing semantics in every reload reject warn line:
  payment+security typo no longer leaves operators wondering whether
  their unrelated payment edit applied.
- Add walkable example trace (cap=4 → 0 → 3 → 5) to ConnectionLimiter
  ::reload doc + ties-on-last_refill caveat to set_cap doc

New tests (5):
- concurrent_reloads_converge: 8 concurrent reloads racing for the same
  limiter; pins target_lock serialization.
- bounded_map_disable_then_reenable_preserves_existing_buckets: rate=0
  → rate>0 round-trip preserves bucket fairness state.
- reload_disabled_to_disabled_preserves_live_baseline: (0,0) reload
  must not reset live_semaphore_size.
- bounded_map_set_cap_zero_makes_unbounded_and_retains_entries: set_cap(0)
  transitions to unbounded mode without clearing entries.
- reload_preserves_metrics_handle_for_post_reload_rejects: Arc<Metrics>
  handle survives reload; reject counters still increment.

Make Metrics::encode pub(crate) so dispatch tests can verify post-reload
counter increments.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(metrics): drop redundant _total suffix from dispatch counter fields

The OpenMetrics encoder appends `_total` to counter fields per the
spec; field names that already end in `_total` get rendered as
`*_total_total`, which is awkward and inconsistent with `probe_requests`
(no `_total` in the field, exposed as `decdn_probe_requests_total`).

Rename the three dispatch counter fields:
  dispatch_rejected_global_total → dispatch_rejected_global
  dispatch_rejected_per_node_total → dispatch_rejected_per_node
  dispatch_rejected_per_ip_total → dispatch_rejected_per_ip

Operator-visible metric names are unchanged from what they will be
once this PR merges; only the internal Rust field names move. The
gossip_*_total fields are pre-existing on main and out of scope here.

Update the metrics-after-reload test assertion to match the corrected
exposition name.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): address review feedback on dispatch limiter

Critical:
- resolve_security clamps max_concurrent_handlers at
  Semaphore::MAX_PERMITS so a too-large value fails config rather than
  panicking inside Semaphore::new / add_permits during SIGHUP reload.
- Permit/acquire_inner doc-comments now describe the real gauge
  bookkeeping site (dispatch_permit_acquired runs on success before
  Permit construction; Drop decrements unconditionally).
- lock_recover takes a per-mutex AtomicBool gate so poison-error logs
  fire once per process, not once per acquire.

Important:
- Shrink-task forget() failure logs at error! and bumps a new
  dispatch_shrink_skipped counter so live_semaphore_size drift is
  observable rather than silent.
- IPv6 addresses bucket by /64 prefix in the per-IP layer so a
  customer-grade allocation can't be churned to defeat the limit.
- New dispatch_per_ip_skipped_no_addr counter (gated on a per_ip_enabled
  AtomicBool mirror) records relay-only acceptances under an enabled
  per-IP layer.
- Rate-limit rejection in probe handler awaits conn.closed() with a
  bounded 250 ms timeout so peers reliably observe the 0x10 reason byte
  and its layer label.

Polish:
- Permit is #[must_use] so let _ = limiter.acquire(...) is a compile
  error.
- frame_err_code matches every FrameError variant explicitly.
- pin_diff log emits Option<count> + pinned_skipped_no_cache_attached
  rather than misleading zeros.
- Stale issue-number references and speculative future-state comments
  trimmed; set_cap O(n²) doc corrected to introselect O(n).

Tests:
- Encoded-scrape assertions for the global and per-IP reject counters.
- Relay-only-with-layer-enabled skip counter test.
- IPv6 /64 bucket-collapse + cross-/64 separation test.
- Multi-thread acquire-storm vs reload-storm convergence test.
- 278/278 nextest pass; cargo clippy --workspace -- -D warnings clean;
  cargo doc with -D warnings clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(security): collapse per-IP/per-NodeID into per-source via governor

Drop the hand-rolled `TokenBucket` + `BoundedRateMap<K>` and the parallel
per-NodeID layer; replace both with a single `governor::DefaultKeyedRateLimiter`
keyed on `IpAddr`. Two of the four asks on PR #386's review collapse into
this commit because they're entangled: the keyed limiter no longer needs
to know about NodeID, and adopting `governor` (0.10) is the maintained-
crate replacement for the bespoke token-bucket code.

Surface changes:
- Config: `per_ip_*`/`per_node_*` → single `per_source_*` pair.
  `per_source_rate_per_sec = 0` disables the layer; per-NodeID is gone.
- Metrics: `dispatch_rejected_per_ip` + `dispatch_rejected_per_node`
  fold into `dispatch_rejected_per_source`. The skip counter for relay-
  only connections is renamed to `dispatch_per_source_skipped_no_addr`.
- `RejectReason::PerIp`/`PerNodeId` → `RejectReason::PerSource`. Reason
  string `"per-source"`. ADR 013's close-code description trimmed to
  match.
- `ConnectionLimiter::acquire_for_test` no longer takes a node key —
  `peer_ip: Option<IpAddr>` is the only argument.

Naming: "per-source" is intentional. Today the source axis is the
remote `IpAddr` (`/64`-grouped for IPv6, as before). Future keying
axes (NodeID, ASN, etc.) can land without renaming the operator-
visible config and metrics surface.

Implementation:
- `governor::DefaultKeyedRateLimiter<IpAddr>` behind an `RwLock<Option<Arc<...>>>`.
  `None` = layer disabled.
- Cap enforcement: when `limiter.len() > cfg.max_tracked_sources`,
  call `retain_recent()` lazily under the read guard so the keyspace
  stays bounded without a background task.
- `reload()` rebuilds the keyed limiter from the new quota and swaps
  it under the write lock. Token-bucket state is *not* preserved
  across the rebuild — operators tuning a live quota should expect
  the next acquire from each source to start with a fresh burst
  budget. (This was PR #386 review ask #4; falls out for free with
  the rebuild-and-swap approach.)
- Semaphore resize logic untouched (PR #386 ask #2 lands in a follow-up).

Tests: dispatch.rs test module rewritten end-to-end. Dropped tests
covered TokenBucket internals (refill, burst-cap, clock-skew) and
BoundedRateMap mutators (eviction, set_cap, set_rate_burst, disable→
re-enable resume) — governor owns those now. Kept tests cover
ConnectionLimiter behaviour: rejection on global/per-source exhaustion,
relay bypass, IPv6 /64 grouping, hot-reload grow/shrink/disable→re-enable,
concurrent-reload convergence, acquire-storm-vs-reload-storm. All 218
unit tests + 7 probe_loopback + 18 admin_peers + 14 config_validate +
2 sighup_signal pass; clippy and rustdoc clean.

Out of scope (tracked for follow-up commits on the same PR):
- swap-not-resize the global `Arc<Semaphore>` on reload (PR #386 ask #2)
- factor a `Reloadable` trait and migrate sections (PR #386 ask #3)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(security): swap-not-resize the dispatch semaphore on reload

Replace the add-permits / acquire_many_owned(...).forget() resize
pattern in `ConnectionLimiter` with a whole-`Arc<Semaphore>` swap via
`arc_swap::ArcSwapOption`. On reload the limiter builds a fresh
`Arc<Semaphore>` (or `None` when `max_concurrent_handlers == 0`) and
atomically stores it; new acquires hit the new cell while
already-acquired `OwnedSemaphorePermit`s hold a clone of the previous
`Arc` and drop it harmlessly when released.

Drops the drift-accounting machinery (`target_max_concurrent`,
`live_semaphore_size`, `target_lock`) and the parked-shrink task that
reconciled them, plus the `dispatch_shrink_skipped` metric (no shrink
task left to fail). Drops tests that exercised those invariants
(`concurrent_reloads_converge`, `reload_disabled_to_disabled_preserves_
live_baseline`, `connection_limiter_reload_target_tracking_handles_
repeated_grow`, `acquire_storm_during_reload_storm_does_not_panic`)
and rewrites the grow/shrink/disable+re-enable tests around the new
"new acquires hit the new cap immediately" semantics.

The operator-visible difference is sub-second permit-count freshness
on a small mesh in exchange for materially simpler reload reasoning:
no parked task, no racing N->N+1->N drift, no recorded-vs-actual
divergence on shrink failure. Addresses review-comment #2 on PR #386.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(reload): factor a ReloadableSection trait + migrate four sections

Extract the inline per-section glue in `RuntimeReloadState::reload` into
a small `ReloadableSection` trait so adding the next reloadable knob no
longer means touching the central reload body. Addresses ask #3 from the
review on PR #386.

## Trait shape

```rust
trait ReloadableSection: Send + Sync {
    fn name(&self) -> &'static str;
    fn clear_buffer(&self);
    fn resolve(&self, file: &FileConfig) -> anyhow::Result<()>;
    fn fallible_commit(&self) -> anyhow::Result<()> { Ok(()) }
    fn infallible_swap(&self);
}
```

The associated `Resolved` type is erased via a per-section
`Mutex<Option<Resolved>>` buffer cell (option (a) from the brief). This
keeps the trait `dyn`-safe — `RuntimeReloadState` holds
`Vec<Arc<dyn ReloadableSection>>` and iterates it three times per
reload — without forcing a single uniform `Resolved` type across
sections. The buffer's lifecycle: emptied at the start of every
`reload()` (via `clear_buffer`), filled by `resolve`, read by
`fallible_commit`, drained by `infallible_swap`.

## What moved

Each of the four current sections becomes a concrete impl that owns
the state it mutates:

- `PaymentSection` — holds the `Arc<AtomicU64>` for `rate_per_mb` and
  the `PaymentArgs` CLI override.
- `LogLevelSection` — holds the `LogLevelSetter` closure, the
  `current` cache (Mutex<Option<LogLevel>>) for first-reload-applies,
  and the `ObservabilityArgs` CLI override. This is the only section
  with a non-trivial `fallible_commit` (the tracing-filter swap).
- `PinnedHashesSection` — holds the optional `CacheEngine` (attached
  via `attach_cache`).
- `SecuritySection` — holds the optional `Arc<ConnectionLimiter>`
  (attached via `attach_limiter`).

`RuntimeReloadState::reload` becomes a fixed three-phase iteration:

1. Resolve every section. Any failure → return early, previous values
   retained for every section (existing all-or-nothing contract).
2. Run every `fallible_commit`. Documented as the rollback boundary:
   commits already applied stay applied if a later section fails.
3. Run every `infallible_swap`. Atomic stores, `Arc` swaps, and
   `ConnectionLimiter::reload` (the semaphore swap from 46235af is
   infallible, so it lives here, not in phase 2).

## What stayed

- Public API of `RuntimeReloadState`: `new`, `attach_cache`,
  `attach_limiter`, `seed_initial_file_snapshot`, `reload`,
  `rate_per_mb`, `current`, `for_test_with_setter`. Unchanged.
- The all-or-nothing contract: previous values retained for every
  section on any resolve failure.
- The `last_file_sections: Mutex<FileSectionSnapshot>` snapshot/diff
  machinery and the "log changes to non-reloadable sections once"
  plumbing — driven inline in `reload()`, not through the trait, since
  it's cross-cutting rather than per-section.
- Section ordering (`payment`, `log_level`, `pinned_hashes`,
  `security`) — preserved verbatim so operator-visible commit
  ordering doesn't shift behind the refactor.
- Every existing test passes unchanged in behaviour. The poisoned-
  mutex tests adapt to the new field paths
  (`state.cache` → `state.pinned.engine`, `state.limiter` →
  `state.security.limiter`, `state.current_log_level` →
  `state.log_level.current`) but the contracts they enforce — setter
  not called when log-level mutex is poisoned, rate atomic not moved
  on snapshot-mutex poison, etc. — are identical.

## Tracing

Each section emits its own `config reload section applied` info
event keyed by `section = name()`, instead of the prior monolithic
"config reload applied" line carrying every field at once. The
aggregated "config reload applied" line is retained as an
end-of-reload marker for any operators / log scrapers that grep for
it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(reload): satisfy clippy::map_unwrap_or on Rust 1.95+

CI clippy on Rust 1.95 caught a map(...).unwrap_or(false) on the swap_applied poison-recoverable lock; rewrite as is_ok_and(...). Local clippy on a slightly older toolchain didn't flag it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): release per_source read guard before retain_recent; skip close-flush on GlobalFull

Two review fixes from gemini-code-assist on the post-reshape branch:

1. dispatch.rs: snapshot the limiter Arc and cap under the per_source read guard, drop the guard, then run check_key + retain_recent. Holding the read guard across an O(n) walk would block reload writers under flood. The Arc clone keeps the observed KeyedRateLimiter alive across a concurrent reload swap — operating on the prior generation is operationally indistinguishable.

2. probe.rs: skip the post-rejection conn.closed() flush wait on RejectReason::GlobalFull. Under a global-cap flood every rejection would otherwise park a task for up to REJECTION_CLOSE_TIMEOUT (250ms); at thousands of rejections per second that is the exact memory-pressure path the limiter exists to prevent. Layer label is least useful for GlobalFull anyway (operators pivot on the metric counter). Per-source rejections still wait — the bucket itself rate-limits the parking cost.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): add 10% slack to retain_recent prune threshold

Gemini flagged that calling retain_recent every acquire when over cap could be a sustained-flood bottleneck. Add a 10% margin so the O(n) walk only fires when the keyspace is materially over (cap + cap/10), not on 1-key-over-cap fluctuations. Worst-case overhead is one prune per cap/10 newly-tracked sources rather than one prune per accept.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): single-flight retain_recent under flood

Gemini flagged that even with the 10% slack from 3fd1288, N threads observing over-cap simultaneously would each spawn an O(n) retain_recent walk. Add a pruning_in_progress AtomicBool guard: at most one thread prunes at a time; concurrent over-cap observers skip; the next observer after the prune completes picks up any remaining work. Bounds the worst-case prune throughput to one O(n) walk in flight regardless of accept-thread count.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Alper Gundogdu <[email protected]>
thiras added a commit that referenced this pull request May 14, 2026
Acts on inline review comments from Copilot + Gemini Code Assist:

- **Drop "known ISO code set" overclaim** in the gossip-layer-validation
  paragraph. `crates/gossip/src/validation.rs:127-130` is shape-only
  (length-2 ASCII uppercase). ADR 001 § Gossip validation describes the
  stricter check; tightening `validation.rs` to enforce it is orthogonal
  to this ADR and not a precondition for the self-attestation posture.

- **Clarify migration semantics** for `regionLastChanged`. No storage
  migration required — Solidity zero-initializes the field for pre-upgrade
  records, and the standing-eligibility check reads it with a read-time
  fallback to `firstRegisteredAt`:
  `effective = regionLastChanged != 0 ? regionLastChanged : firstRegisteredAt`.
  Previous "defaults to firstRegisteredAt" wording was ambiguous between
  migration sweep and read-time fallback.

- **`regionLastChanged: uint256`** (was `uint64`) to match
  `firstRegisteredAt`, `registeredAt`, and `lastMultiaddrUpdate` in
  ADR 001 § Data Structure.

- **`RegionUpdated` event signature corrected.** Index `nodeId` to match
  every other `StakingRegistry` event in ADR 001; drop the redundant
  `timestamp` parameter (block timestamp is implicit in the event log
  header).

- **Note ADR 011 § Contract: ContentBlacklist's `bytes2` recommendation**
  for the region field, and explain why ADR 030 retains `string` here
  (consistency with the existing `StakingRegistry.NodeInfo.regionHint`
  shape per ADR 001 § Data Structure; `bytes2` migration is a separate
  `StakingRegistry` storage-shape change orthogonal to this ADR).

- **Rename §3 heading** from "Appeals-standing hardening: regionLastChanged
  + 7-day window" to "Appeals-standing hardening" so the GFM slug is
  predictable and short. Update cross-references in ADR 011:197 and
  ADR 019:259 to use the `#3-appeals-standing-hardening` anchor.

Refs #400 #565

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request May 15, 2026
Resolves the six findings from the PR #565 security/compliance review:

- #1 §4: replace the inverted "misdeclaration expands slashing
  surface" argument with the honest reactive-vs-pre-positioned
  decomposition; reconcile Negative bullet 1 and the same claim
  mirrored in ADR 011 § Regional Scope.
- #2: gate blacklist scope/slash eligibility on the stability window,
  not just appeals standing. Add `regionPrev`, make `updateRegion`
  revert within `REGION_STABILITY_WINDOW` (cooldown = window), and
  amend the ADR 011 § Regional Scope / § Slashing predicate so the
  previous region's entries and slash exposure persist until a change
  ripens — closing the reactive blacklist-evasion flip.
- #3: migration fallback `max(firstRegisteredAt, regionGateActivatedAt)`
  instead of bare `firstRegisteredAt`; add migration-cohort Risks bullet.
- #4: §2 states the residual control is consciously accepted
  unparameterized; log the `validation.rs` vs ADR 001 spec divergence
  as a Forward reference.
- #5: raise `REGION_STABILITY_WINDOW` floor [1d,30d] -> [3d,30d]
  (default 7d unchanged) across §3, threshold rationale, Risks,
  and ADR 011 § Standing.
- #6: this PR keeps ADR 030 (no change here; #566 renumber requested
  separately).

§3 renamed "Appeals-standing hardening" -> "Region-stability window";
anchor references updated in ADR 011, ADR 019, architecture.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request May 15, 2026
* docs(adr): add ADR 030 — node region self-attestation

Closes #400 with a self-claim production posture: regions in NodeAnnounce
and StakingRegistry are accepted at face value; the IP-geolocation oracle
/ third-party attestation path is considered and rejected. Misdeclaration
is the operator's legal exposure under the declared jurisdiction and
*expands* the operator's slashing surface under ADR 011 § Regional Scope
(the operator opts into the declared region's blacklist while remaining
legally reachable through their physical operations). The latency-vs.-
claim reputation penalty from ADR 001 § Risks is the canonical soft
mitigation; this ADR does not respecify it.

The only gaming surface the soft loop does not close is appeals-standing
flipping (ADR 011 § Standing path 2). ADR 030 § 3 closes it: adds a
`regionLastChanged: uint64` field on the StakingRegistry operator record
and a new operator-facing `updateRegion(string)` mutator alongside the
existing `updateMultiaddrs`. Operator standing under path 2 requires
`block.timestamp - regionLastChanged >= REGION_STABILITY_WINDOW` (default
7 days; governable [1d, 30d] per the ADR 009 safety-bound pattern).
Sub-window filings are not auto-rejected — they remain admissible at
multisig discretion, preserving heightened-scrutiny intake as the
soft-norm fallback for legitimate post-relocation filers.

Supersedes the "production mitigation: oracle/attestation" passages in
ADRs 001, 011, and 019. Cross-refs updated in ADRs 001 (§ Risks), 008
(§ Regional coverage caveat), 011 (§ Standing + § Regional Scope), 019
(Phase 1 step 5 + Future Work), architecture.md (Chapter 5 Verification
& Enforcement + numeric ADR index). CLAUDE.md next-ADR counter bumped
030 → 032 (031 already used by 031-content-blacklist-appeals-contract).

Closes #400

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(adr): address review findings on ADR 030 (#400)

Cross-ADR consistency cleanup raised by the comprehensive review on the
ADR 030 branch:

- **Broken anchors fixed.** ADR 030 referenced `[ADR 019 § Step 5.2]`
  and `[ADR 019 § Re-registration]` — neither section exists. The real
  `updateMultiaddrs` precedent lives in [ADR 019 § NAT and Multiaddr
  Handling]; `firstRegisteredAt` is defined under [ADR 019 § Re-Onboarding
  after Deregistration or Auto-Ejection]. Cross-refs in § 3 (Decision —
  StakingRegistry interface delta) and § Consequences/Positive updated.

- **`firstRegisteredAt` precedent overclaim corrected.** The Positive
  bullet had claimed `regionLastChanged` "mirrors the precedent."
  `firstRegisteredAt` is write-once-on-first-registration; `regionLastChanged`
  updates on every successful `updateRegion`. Bullet now: parallel storage
  shape with opposite mutability, called out explicitly.

- **`updateMultiaddrs` "no governance gate" wording corrected.**
  `updateMultiaddrs` has a governable cooldown ([ADR 001 § Multiaddr
  Update Policy], default 0). Reframed as: operator-callable, no-bond;
  no analogous per-call cooldown specified for `updateRegion`; the 7-day
  `REGION_STABILITY_WINDOW` is the only timing gate.

- **`[ADR 001 § Risks]` references corrected to `§ Consequences`.**
  ADR 001 has no `### Risks` section — the regional-attestation
  consequence lives in `## Consequences`. Five references updated (ADR
  030 lines 16/28/72/98, architecture.md line 160, ADR 011 line 548).

- **Self-referential anchor in ADR 011 § Regional Scope edit fixed.**
  Was `[§ Regional Scope](#regional-scope)` — a self-loop. Now
  `[§ Slashing](#slashing)` (the actual target of the "expands slashing
  surface" claim).

- **Section order aligned with ADR 028 / 026 / 031 precedent.**
  Consequences now precedes Alternatives Considered.

- **`Touches:` front-matter expanded.** Added ADRs 008 (regional-coverage
  caveat), 009 (governable-parameter bounds pattern), 026 (minimum-stake
  cost bullet) — all referenced in the body.

- **Terminology mix-up fixed.** Context paragraph had conflated the
  StakingRegistry `regionHint` field with the `NodeAnnounce` `region`
  field. Reworded to name both surfaces explicitly.

- **ADR 030 added to the book-PDF reading-order build list** at
  `adr/README.md:150` (Chapter 5 — Verification & Enforcement).

- **Tightened ADR 028 § 5 alignment claim** (the 30d upper bound) and
  added a sentence on the 7d-stability-window-vs.-3d-filing-window-lower-bound
  interaction in the threshold-rationale paragraph.

Refs #400

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(adr): address PR #565 review feedback on ADR 030 (#400)

Acts on inline review comments from Copilot + Gemini Code Assist:

- **Drop "known ISO code set" overclaim** in the gossip-layer-validation
  paragraph. `crates/gossip/src/validation.rs:127-130` is shape-only
  (length-2 ASCII uppercase). ADR 001 § Gossip validation describes the
  stricter check; tightening `validation.rs` to enforce it is orthogonal
  to this ADR and not a precondition for the self-attestation posture.

- **Clarify migration semantics** for `regionLastChanged`. No storage
  migration required — Solidity zero-initializes the field for pre-upgrade
  records, and the standing-eligibility check reads it with a read-time
  fallback to `firstRegisteredAt`:
  `effective = regionLastChanged != 0 ? regionLastChanged : firstRegisteredAt`.
  Previous "defaults to firstRegisteredAt" wording was ambiguous between
  migration sweep and read-time fallback.

- **`regionLastChanged: uint256`** (was `uint64`) to match
  `firstRegisteredAt`, `registeredAt`, and `lastMultiaddrUpdate` in
  ADR 001 § Data Structure.

- **`RegionUpdated` event signature corrected.** Index `nodeId` to match
  every other `StakingRegistry` event in ADR 001; drop the redundant
  `timestamp` parameter (block timestamp is implicit in the event log
  header).

- **Note ADR 011 § Contract: ContentBlacklist's `bytes2` recommendation**
  for the region field, and explain why ADR 030 retains `string` here
  (consistency with the existing `StakingRegistry.NodeInfo.regionHint`
  shape per ADR 001 § Data Structure; `bytes2` migration is a separate
  `StakingRegistry` storage-shape change orthogonal to this ADR).

- **Rename §3 heading** from "Appeals-standing hardening: regionLastChanged
  + 7-day window" to "Appeals-standing hardening" so the GFM slug is
  predictable and short. Update cross-references in ADR 011:197 and
  ADR 019:259 to use the `#3-appeals-standing-hardening` anchor.

Refs #400 #565

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(adr): address third-pass review on PR #565 (#400)

Two findings from the post-fce0fc2 internal review pass:

- **ADR 030 §3 strict-rule fenced block now uses the read-time fallback.**
  Bullet 1 of §3 introduced
  `effective = regionLastChanged != 0 ? regionLastChanged : firstRegisteredAt`
  to avoid a storage migration, but the canonical fenced rule still read
  `block.timestamp - operator.regionLastChanged >= REGION_STABILITY_WINDOW`,
  which a contract-impl reader could copy verbatim and silently skip the
  fallback for legacy records. The fenced block is now self-contained:

      effective = operator.regionLastChanged != 0 ? operator.regionLastChanged : operator.firstRegisteredAt
      block.timestamp - effective >= REGION_STABILITY_WINDOW

  Runtime semantics unchanged (legacy records with `regionLastChanged == 0`
  already trivially passed `block.timestamp - 0`), but the spec is now
  unambiguous to a code-generation reader.

- **Stale "(ADR 030)" cross-references in ADR 031 corrected.** ADR 031
  was written when "ADR 030" was the informal placeholder for the
  SafetyReserve slash-appeal contract-implementation ADR (the blacklist-
  side analogue of which is ADR 031). With #400 now claiming the 030
  slot for Node Region Self-Attestation, ADR 031's three "(ADR 030)"
  pointers (lines 14, 291, 314) became factually wrong on merge.
  Reworded to refer to #524 alone (the GitHub issue tracking the
  SafetyReserve slash-appeal contract ADR), with parenthetical pointers
  to ADR 030's new occupant for cross-reference. The natural claimant
  of the next-free 032 slot is now #524.

Refs #400 #565

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(adr): address security/compliance review on ADR 030 (#400)

Resolves the six findings from the PR #565 security/compliance review:

- #1 §4: replace the inverted "misdeclaration expands slashing
  surface" argument with the honest reactive-vs-pre-positioned
  decomposition; reconcile Negative bullet 1 and the same claim
  mirrored in ADR 011 § Regional Scope.
- #2: gate blacklist scope/slash eligibility on the stability window,
  not just appeals standing. Add `regionPrev`, make `updateRegion`
  revert within `REGION_STABILITY_WINDOW` (cooldown = window), and
  amend the ADR 011 § Regional Scope / § Slashing predicate so the
  previous region's entries and slash exposure persist until a change
  ripens — closing the reactive blacklist-evasion flip.
- #3: migration fallback `max(firstRegisteredAt, regionGateActivatedAt)`
  instead of bare `firstRegisteredAt`; add migration-cohort Risks bullet.
- #4: §2 states the residual control is consciously accepted
  unparameterized; log the `validation.rs` vs ADR 001 spec divergence
  as a Forward reference.
- #5: raise `REGION_STABILITY_WINDOW` floor [1d,30d] -> [3d,30d]
  (default 7d unchanged) across §3, threshold rationale, Risks,
  and ADR 011 § Standing.
- #6: this PR keeps ADR 030 (no change here; #566 renumber requested
  separately).

§3 renamed "Appeals-standing hardening" -> "Region-stability window";
anchor references updated in ADR 011, ADR 019, architecture.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(adr): exempt first region change from cooldown (#400)

Follow-up to the security/compliance review fixes. The cooldown =
window rule, combined with regionLastChanged being stamped at
registerNode, locked a freshly registered operator out of correcting
a mis-entered region for a full window.

Fix uses regionLastChanged itself as the "has changed region yet"
discriminator rather than overloading regionPrev emptiness (which is
only a clean sentinel if registration forbids an empty region):

- registerNode no longer stamps regionLastChanged (stays 0 until the
  first updateRegion); the effective fallback already covers fresh
  nodes for appeals-standing / blacklist-scope.
- Cooldown reverts iff regionLastChanged != 0 AND
  block.timestamp - regionLastChanged < REGION_STABILITY_WINDOW, so
  the first change is exempt and every subsequent change is gated.

Safe: reactive evasion is foreclosed by the scope predicate (prev
region keeps applying via regionPrev for the window) regardless of
the cooldown; the cooldown only blocks a second flip, still gated
once regionLastChanged != 0. Migration-cohort Risks bullet updated
to note the first post-activation change is cooldown-exempt but
still does not ripen / grant standing until the window passes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Alper Gundogdu <[email protected]>
alpergundogdu added a commit that referenced this pull request May 19, 2026
…tor; 026 → Tokenomics umbrella (#590)

Second and final extraction of the per-bucket split (part 1 was #595,
SafetyReserve → ADR 033).

- New ADR 034 (Gauge Boost and Voting Escrow): §3 gauge-boost formula
  (degenerate-input fallbacks, per-operator gauge-share cap) + §4
  VotingEscrow (checkpointing, lock ownership, contract) moved verbatim.
- New ADR 035 (Delegator Pool): §6 USDC→TOKEN pipeline + DelegatorBuyer
  moved verbatim.
- ADR 026 retitled "# ADR 026: Tokenomics" — it is now the canonical
  economic-model umbrella (Context, §1 supply, §2 FeeRouter six-bucket
  split, §7 operator economics, §8 slashing-burn, §9 governance-weight,
  §10 bootstrap, §11 governable params, Consequences). §3/§4/§5/§6 are
  one-paragraph umbrella pointers; the numbered headings are kept so
  #3/#4/#5/#6 top anchors and their inbound refs stay valid. 026:
  659 (pre-split) → 254 lines. Filename unchanged
  (026-gauge-boost-tokenomics.md) — renaming would break ~100 inbound
  links; an optional filename-rename can be a separate PR.

Anchor-safe technique (same as #595): subsection headings moved with
text unchanged so slugs are identical (only the file changes).
13 inbound subsection refs repointed (11 #per-operator-gauge-share-cap
→ 034, 2 #contract-delegatorbuyer → 035); 3 026-internal dangles fixed;
link text/prose that now points to 034/035 updated from "ADR 026 §N"
to "ADR 034/035 §" (the text/href consistency class flagged by review
on #595). architecture.md Chapter 4 desc/list/numeric index, Makefile
BOOK_SRCS, and CLAUDE.md ADR note updated.

Verified with the github-slugger-accurate corpus link checker: total
broken links unchanged at 10 (all pre-existing, none on any split
anchor); 0 new breaks. make check-book-list green (26 ADRs + 12
appendices); MD001 headings clean; adr/ self-contained; pre-commit
green.

Closes #590. Grouping note: §1/§7/§8/§9/§10/§11 kept in the 026
umbrella (the recommended grouping) — confirmable in review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 21, 2026
…eview

Round 2 of PR #643 review (after the prior poisoning/recursion/comment
round). Addresses findings from five specialized review agents
(code-reviewer, pr-test-analyzer, silent-failure-hunter,
type-design-analyzer, comment-analyzer).

CRITICAL

- **BatchStore now closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE`
  instead of replying with an all-`false` `BatchStoreAck`.** ADR 022
  §STORE Flow line 138 + §Schema Evolution specify that the unsupported
  signal MUST be stream-close-without-ack — an all-`false` ack reads to
  a conformant publisher as "your batch was processed, every hash
  rejected" and triggers NO fallback to per-hash `Store`. The fix is
  structural: `read_dht_request` now narrows the wire `DhtMessage` to a
  new `DhtServerRequest` enum (`FindNode` / `FindValue` / `Store`),
  rejecting `BatchStore` and response-on-server-stream variants up
  front. `dispatch` is then exhaustive over the active set without a
  panic / echo fallback for impossible cases. Loopback test
  `batch_store_returns_unsupported_code_not_ack` guards the contract.

- **`dht.*` wired into the SIGHUP reload pipeline.** `FileSectionSnapshot`
  gains a `dht` field and `log_ignored_other_sections` emits the
  "requires restart" warning when `[dht]` changes. Previously an
  operator who edited `dht.rate_limit.trusted_ips` and SIGHUPed got no
  feedback that the change wasn't applied.

- **`[dht.rate_limit]` is now nested under `[dht]` per ADR 022 §Trusted-IP
  exemption.** Operator key path is `dht.rate_limit.trusted_ips` (matching
  the ADR), not the flat `dht.trusted_ips` from the prior commit. All
  six rate/burst knobs moved with it.

IMPORTANT

- **`DhtServerRequest` narrowing enum replaces `dispatch`'s
  match-all-fallback** (code-reviewer #5, silent-failure-hunter
  Critical #2). The previous arm echoed an empty `FindNodeResponse` if
  reached — dead code that masked a real protocol violation if the
  filter ever drifted. Removed entirely.

- **`decdn_dht_requests_failed_total` counter added.** Bumps when
  `handle_one` returns Err after rate-limit admission (frame decode,
  encode, write, finish, read timeout, etc). Operator running at
  default `RUST_LOG=info` no longer needs to enable debug logs to see
  "DHT requests are failing" (silent-failure-hunter Critical #1).

- **ADR 013 error-code roundtrip loopback tests** for
  `APP_ERR_MALFORMED_MESSAGE`, `APP_ERR_UNSUPPORTED_MESSAGE` (response
  on server stream + `BatchStore`), and `APP_ERR_RATE_LIMITED`
  (pr-test-analyzer Critical #1, #3). `APP_ERR_MESSAGE_TOO_LARGE`
  needs a low-level varint writer to exercise; noted in a comment.

- **`closest_returns_distance_sorted_results` strengthened** to assert
  the full vector is monotonically non-decreasing by XOR distance,
  not just endpoints — catches "first and last correct, middle
  scrambled" regressions (pr-test-analyzer #4).

- **Stale / misleading comments fixed** (comment-analyzer #2, #6, #7):
  routing.rs no longer claims a non-existent "follow-up PR" lands
  ping-then-evict; handler module docs now correctly describe the
  BatchStore stream-close behavior; the dispatch comment reflects the
  new narrowing-enum shape.

DEFERRED (genuine but out of scope for this PR slice)

- `NodeId` newtype (type-design-analyzer single biggest recommendation,
  touches the wire format + multiple crates — file as standalone
  follow-up).
- Per-IP / per-peer keyspace bound (already issue #645).
- Read-timeout app code, `FrameError::Io` mapping nuances (silent-failure-hunter
  MEDIUM, match existing probe handler precedent).

Refs #320, addresses PR #643 multi-agent review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu pushed a commit that referenced this pull request May 22, 2026
… (PR 2/4 of #320) (#643)

* feat(protocol): add cdn/dht/v1 wire types (ADR 022)

Introduces `DhtMessage` and the six request/response structs for the
Kademlia content DHT specified in ADR 022 §Message Types:
`FindValue{Request,Response}`, `Store{Request,Ack}`,
`FindNode{Request,Response}`. The variant order is frozen per
ADR 013 §Protocol Enums and pinned by per-variant discriminant tests so
a reorder fails CI loudly rather than breaking wire compatibility
silently.

Authentication on `StoreRequest` is by QUIC-bound NodeId equality, not
a per-record signature — this depends on records being pushed directly
by the holder and never relayed peer-to-peer. The module docs flag the
invariant so a future relay scheme reintroduces the signature plus
in-scope sender timestamp together (ADR 015 §Replay Safety Analysis).

`BatchStoreRequest` / `BatchStoreAck` are deferred to a follow-up
issue. ADR 022 specifies them as a bandwidth optimization with a
per-hash fallback only useful at C ≥ 10k cached blobs; when added they
append after `FindNodeResponse` so existing discriminants are
preserved.

Wire-cap constants (`MAX_PROVIDERS_PER_HASH = 50`,
`MAX_CLOSER_NODES = 20`) bound the max-size `FindValueResponse` under
the ~2.3 KB ceiling from ADR 022 §DHT Bandwidth Analysis; the upper
bound is asserted by a test so future field additions can't drift past
it unnoticed.

Refs #320.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(protocol): bound Vec wire fields and reorder DhtMessage to ADR-canonical

Addresses PR #642 review feedback (gemini-code-assist + Copilot):

- Add `#[serde(deserialize_with = ...)]` field-level hooks enforcing
  `MAX_PROVIDERS_PER_HASH`, `MAX_CLOSER_NODES`, and `MAX_BATCH_STORE_HASHES`
  at the wire boundary. Pattern mirrors `ProbeResponseBody::rate_per_mb`:
  postcard's positional layout stays derive-driven (no mirror struct, no
  manual `Deserialize` impl), and oversize Vec fields now fail decode
  rather than allocating an attacker-chosen size up to the 16 MiB framing
  ceiling.
- Reorder `DhtMessage` variants to match ADR 022 §Message Types: the ADR
  lists `BatchStore`/`BatchStoreAck` at positions 4/5 and
  `FindNode`/`FindNodeResponse` at 6/7. The original PR put `FindNode` at
  4/5; with postcard's sequential discriminant indexing this would have
  forced a future wire-breaking shuffle once `BatchStore` lands. Define
  the `BatchStore` wire types now (no handler) so the production ordering
  matches the ADR and the future BatchStore PR is a pure handler addition.
- Replace the inner-struct-only size guard with a framed-size assertion
  that includes the `DhtMessage` enum discriminant byte AND the
  `write_frame` length-prefix varint, so the ~2.3 KB ADR 022 wire ceiling
  can't drift via discriminant or framing-layer changes.
- New tests: discriminant pinning for `BatchStore` (4) / `BatchStoreAck`
  (5) / `FindNode` (6) / `FindNodeResponse` (7); decode-time rejection
  for oversize `providers`, `closer_nodes`, `BatchStore.hashes`, and
  `BatchStoreAck.results`; exact-MAX boundary acceptance.

Refs #320, addresses #642 review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(protocol): add lower bound + align BatchStore module doc

Round 2 of PR #642 review (pr-test-analyzer + comment-analyzer).

- `find_value_response_max_framed_size_under_ceiling` previously had
  only `framed_len <= 2_300`. A regression that dropped `providers` or
  `closer_nodes` from the wire shape would shrink the encoded size
  well below the ADR's modeled payload (~2.27 KB) and the test would
  silently pass. Add `framed_len > 2_000` so an accidental field
  removal fails the test loudly.

- Module-level doc for `BatchStore` previously said the runtime "treats
  inbound BatchStore frames as unsupported until then." After the
  PR-#643 fix the handler explicitly closes the stream with
  `APP_ERR_UNSUPPORTED_MESSAGE` (the stream-close-without-ack signal
  ADR 022 §Schema Evolution requires); the doc now reflects the
  precise wire behaviour and cites the matching ADR section.

Refs #320, addresses PR #642 multi-agent review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(node): add cdn/dht/v1 handler, routing table, rate limiter (ADR 022)

PR 2 of 4 for #320 (Kademlia content discovery). Wires the
`cdn/dht/v1` handler skeleton into the runtime and lands the routing
table + rate limiter the rest of the DHT machinery will build on.

What's in:

- `crates/node/src/dht/routing.rs` — k-bucket routing table at K=20,
  256 buckets keyed by XOR distance to the node's own NodeId (ADR 022
  §Routing Table). LRU eviction on bucket overflow; the
  ping-then-evict variant is deferred until the FindNode driver lands
  in PR 4 of #320. Self-id inserts are no-ops so iterative lookup
  never terminates on the local table.
- `crates/node/src/dht/rate_limit.rs` — three-layer token-bucket
  limiter (per-peer NodeId, per-IP, global) with cheapest-first
  short-circuit per ADR 022 §DHT Rate Limiting. Trusted-IP exemption
  bypasses the per-IP layer only; per-peer and global still apply.
  Each layer can be independently disabled (rate == 0 with burst ==
  0). Backed by `governor` like `ConnectionLimiter`.
- `crates/node/src/handlers/dht.rs` — `ProtocolHandler` implementing
  the full ADR 013 error-code mapping and the ADR 022 admission
  order: dispatch limiter → per-stream rate limit → routing-table
  refresh → dispatch. `FindNode` is fully implemented; `Store` and
  `FindValue` return safe placeholders (StoreAck{accepted: false},
  empty providers) so the wire surface is reachable from upgraded
  peers. Real handling for those variants lands in PR 3 of #320.
- `crates/common/src/config/{types,resolved}.rs` and resolver —
  `DhtConfig` / `ResolvedDht` with per-layer rate/burst pairs and a
  parsed trusted-IPs set. Defaults match ADR 022 (20/100/1000 req/s,
  40/200/2000 burst). Pairing rules mirror the existing
  `security.per_source_*` resolver: rate>0 with burst=0 is rejected
  at config time.
- `decdn_dht_rate_limit_rejected_{per_peer,per_ip,global}_total`
  metrics. ADR 022 §Observability specifies a single labeled counter,
  but `iroh_metrics::MetricsGroup` doesn't support per-field labels;
  we follow the existing convention (cf. `dispatch_rejected_*`) and
  surface one counter per layer. Operators with the ADR-022 alert
  form do a Prometheus `sum()` to recover the rolled-up rate.
- Runtime registers `cdn/dht/v1` on the iroh router alongside
  `cdn/probe/v1` and `iroh-gossip`.
- Loopback integration test (`tests/dht_loopback.rs`) covering a
  seeded routing table responding to FindNode plus the FindValue
  placeholder shape (pinned now so a future regression while the
  record store lands can't pass under the same loopback name).

What's deferred (per the issue-320 plan):

- Record store + Store/FindValue admission, per-publisher quota,
  receiver-anchored TTL, iterative lookup — PR 3.
- Republish scheduler, bootstrap, on-chain origin fallback — PR 4.
- BatchStore variants and prefetch — follow-up issues.

Refs #320.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(node): address PR #643 review — routing-table poisoning, recursion, docs

Addresses PR #643 review feedback (gemini-code-assist + Copilot):

- **HIGH: drop attacker-controlled routing-table refresh.**
  `handle_find_node` was calling `note_peer_seen(req.requester)` on the
  unauthenticated wire field, letting an authenticated peer A send
  `FindNode { requester: B }` to inject any NodeId B into the routing
  table without owning the matching key (routing-table poisoning). The
  authenticated peer NodeId from the QUIC handshake is already
  refreshed once per admitted request in `serve()`, which is the only
  honest signal we have. Removed the second `note_peer_seen` call;
  added a regression test that confirms the attacker-supplied
  `req.requester` is NOT inserted while the authenticated client IS.
- **Replace `unreachable_size_mismatch` with `std::array::from_fn`.**
  The previous helper recursed indefinitely on its own error path —
  the recursion is unreachable by construction but a future
  regression would stack-overflow instead of producing a clear
  diagnostic. `std::array::from_fn` builds the fixed-size array in
  place so the validation step (and the recursion) go away entirely.
- **Fix inverted bucket-index comment.** The code returns bucket 255
  for max distance and bucket 0 for the closest peers; the comment
  said the opposite. Rewrote it (and renamed the two related tests
  `bucket_index_max_distance_is_top_bucket` /
  `bucket_index_min_nonzero_is_bucket_zero`) to match the
  implementation.
- **Re-evaluate `peer_ip` per stream.** Iroh paths can switch over a
  connection's lifetime (relay-only initially, then a direct UDP path
  becomes selected). Capturing the IP once at accept would permanently
  disable the per-IP rate-limit layer for any connection that started
  relay-only. Moved the `peer_ip(&conn)` call inside the per-stream
  loop so a relay→direct switch engages the layer for subsequent
  streams.
- **Align `rate_limit.rs` doc references with the actual emitted
  metric names** (`decdn_dht_rate_limit_rejected_{per_peer,per_ip,
  global}_total` — one Counter per layer, since the metrics backend
  doesn't support per-field labels).
- **`sort_unstable_by_key` in `RoutingTable::closest`.** Computes
  `xor_distance` once per element instead of twice per pairwise
  comparison; lower asymptotic XOR cost on fully-populated tables.
- **`BatchStore`/`BatchStoreAck` dispatch arms.** PR-1 fix
  re-introduced these enum variants at their ADR-canonical
  discriminants; the handler now answers `BatchStore` with a
  per-hash `accepted: false` ack so publishers fall back to per-hash
  `Store` per ADR 022 §Schema Evolution. Handler-side admission
  (two-stage rate limit, holder check, per-hash quota) is the
  follow-up issue tracking `BatchStore` proper.

Deferred to a follow-up issue (raised in PR #643 review):

- Per-IP / per-peer keyed-rate-limiter keyspace cap + periodic GC
  (mirror of `dispatch::ConnectionLimiter::max_tracked_sources` +
  `retain_recent`). Same DoS shape as the dispatch limiter; meaningful
  fix but a self-contained chunk of work with its own runtime wiring.

Refs #320, addresses #643 review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(node): apply consolidated review fixes from PR #643 multi-agent review

Round 2 of PR #643 review (after the prior poisoning/recursion/comment
round). Addresses findings from five specialized review agents
(code-reviewer, pr-test-analyzer, silent-failure-hunter,
type-design-analyzer, comment-analyzer).

CRITICAL

- **BatchStore now closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE`
  instead of replying with an all-`false` `BatchStoreAck`.** ADR 022
  §STORE Flow line 138 + §Schema Evolution specify that the unsupported
  signal MUST be stream-close-without-ack — an all-`false` ack reads to
  a conformant publisher as "your batch was processed, every hash
  rejected" and triggers NO fallback to per-hash `Store`. The fix is
  structural: `read_dht_request` now narrows the wire `DhtMessage` to a
  new `DhtServerRequest` enum (`FindNode` / `FindValue` / `Store`),
  rejecting `BatchStore` and response-on-server-stream variants up
  front. `dispatch` is then exhaustive over the active set without a
  panic / echo fallback for impossible cases. Loopback test
  `batch_store_returns_unsupported_code_not_ack` guards the contract.

- **`dht.*` wired into the SIGHUP reload pipeline.** `FileSectionSnapshot`
  gains a `dht` field and `log_ignored_other_sections` emits the
  "requires restart" warning when `[dht]` changes. Previously an
  operator who edited `dht.rate_limit.trusted_ips` and SIGHUPed got no
  feedback that the change wasn't applied.

- **`[dht.rate_limit]` is now nested under `[dht]` per ADR 022 §Trusted-IP
  exemption.** Operator key path is `dht.rate_limit.trusted_ips` (matching
  the ADR), not the flat `dht.trusted_ips` from the prior commit. All
  six rate/burst knobs moved with it.

IMPORTANT

- **`DhtServerRequest` narrowing enum replaces `dispatch`'s
  match-all-fallback** (code-reviewer #5, silent-failure-hunter
  Critical #2). The previous arm echoed an empty `FindNodeResponse` if
  reached — dead code that masked a real protocol violation if the
  filter ever drifted. Removed entirely.

- **`decdn_dht_requests_failed_total` counter added.** Bumps when
  `handle_one` returns Err after rate-limit admission (frame decode,
  encode, write, finish, read timeout, etc). Operator running at
  default `RUST_LOG=info` no longer needs to enable debug logs to see
  "DHT requests are failing" (silent-failure-hunter Critical #1).

- **ADR 013 error-code roundtrip loopback tests** for
  `APP_ERR_MALFORMED_MESSAGE`, `APP_ERR_UNSUPPORTED_MESSAGE` (response
  on server stream + `BatchStore`), and `APP_ERR_RATE_LIMITED`
  (pr-test-analyzer Critical #1, #3). `APP_ERR_MESSAGE_TOO_LARGE`
  needs a low-level varint writer to exercise; noted in a comment.

- **`closest_returns_distance_sorted_results` strengthened** to assert
  the full vector is monotonically non-decreasing by XOR distance,
  not just endpoints — catches "first and last correct, middle
  scrambled" regressions (pr-test-analyzer #4).

- **Stale / misleading comments fixed** (comment-analyzer #2, #6, #7):
  routing.rs no longer claims a non-existent "follow-up PR" lands
  ping-then-evict; handler module docs now correctly describe the
  BatchStore stream-close behavior; the dispatch comment reflects the
  new narrowing-enum shape.

DEFERRED (genuine but out of scope for this PR slice)

- `NodeId` newtype (type-design-analyzer single biggest recommendation,
  touches the wire format + multiple crates — file as standalone
  follow-up).
- Per-IP / per-peer keyspace bound (already issue #645).
- Read-timeout app code, `FrameError::Io` mapping nuances (silent-failure-hunter
  MEDIUM, match existing probe handler precedent).

Refs #320, addresses PR #643 multi-agent review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 22, 2026
… of #320) (#646)

* feat(protocol): add cdn/dht/v1 wire types (ADR 022)

Introduces `DhtMessage` and the six request/response structs for the
Kademlia content DHT specified in ADR 022 §Message Types:
`FindValue{Request,Response}`, `Store{Request,Ack}`,
`FindNode{Request,Response}`. The variant order is frozen per
ADR 013 §Protocol Enums and pinned by per-variant discriminant tests so
a reorder fails CI loudly rather than breaking wire compatibility
silently.

Authentication on `StoreRequest` is by QUIC-bound NodeId equality, not
a per-record signature — this depends on records being pushed directly
by the holder and never relayed peer-to-peer. The module docs flag the
invariant so a future relay scheme reintroduces the signature plus
in-scope sender timestamp together (ADR 015 §Replay Safety Analysis).

`BatchStoreRequest` / `BatchStoreAck` are deferred to a follow-up
issue. ADR 022 specifies them as a bandwidth optimization with a
per-hash fallback only useful at C ≥ 10k cached blobs; when added they
append after `FindNodeResponse` so existing discriminants are
preserved.

Wire-cap constants (`MAX_PROVIDERS_PER_HASH = 50`,
`MAX_CLOSER_NODES = 20`) bound the max-size `FindValueResponse` under
the ~2.3 KB ceiling from ADR 022 §DHT Bandwidth Analysis; the upper
bound is asserted by a test so future field additions can't drift past
it unnoticed.

Refs #320.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(protocol): bound Vec wire fields and reorder DhtMessage to ADR-canonical

Addresses PR #642 review feedback (gemini-code-assist + Copilot):

- Add `#[serde(deserialize_with = ...)]` field-level hooks enforcing
  `MAX_PROVIDERS_PER_HASH`, `MAX_CLOSER_NODES`, and `MAX_BATCH_STORE_HASHES`
  at the wire boundary. Pattern mirrors `ProbeResponseBody::rate_per_mb`:
  postcard's positional layout stays derive-driven (no mirror struct, no
  manual `Deserialize` impl), and oversize Vec fields now fail decode
  rather than allocating an attacker-chosen size up to the 16 MiB framing
  ceiling.
- Reorder `DhtMessage` variants to match ADR 022 §Message Types: the ADR
  lists `BatchStore`/`BatchStoreAck` at positions 4/5 and
  `FindNode`/`FindNodeResponse` at 6/7. The original PR put `FindNode` at
  4/5; with postcard's sequential discriminant indexing this would have
  forced a future wire-breaking shuffle once `BatchStore` lands. Define
  the `BatchStore` wire types now (no handler) so the production ordering
  matches the ADR and the future BatchStore PR is a pure handler addition.
- Replace the inner-struct-only size guard with a framed-size assertion
  that includes the `DhtMessage` enum discriminant byte AND the
  `write_frame` length-prefix varint, so the ~2.3 KB ADR 022 wire ceiling
  can't drift via discriminant or framing-layer changes.
- New tests: discriminant pinning for `BatchStore` (4) / `BatchStoreAck`
  (5) / `FindNode` (6) / `FindNodeResponse` (7); decode-time rejection
  for oversize `providers`, `closer_nodes`, `BatchStore.hashes`, and
  `BatchStoreAck.results`; exact-MAX boundary acceptance.

Refs #320, addresses #642 review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(protocol): add lower bound + align BatchStore module doc

Round 2 of PR #642 review (pr-test-analyzer + comment-analyzer).

- `find_value_response_max_framed_size_under_ceiling` previously had
  only `framed_len <= 2_300`. A regression that dropped `providers` or
  `closer_nodes` from the wire shape would shrink the encoded size
  well below the ADR's modeled payload (~2.27 KB) and the test would
  silently pass. Add `framed_len > 2_000` so an accidental field
  removal fails the test loudly.

- Module-level doc for `BatchStore` previously said the runtime "treats
  inbound BatchStore frames as unsupported until then." After the
  PR-#643 fix the handler explicitly closes the stream with
  `APP_ERR_UNSUPPORTED_MESSAGE` (the stream-close-without-ack signal
  ADR 022 §Schema Evolution requires); the doc now reflects the
  precise wire behaviour and cites the matching ADR section.

Refs #320, addresses PR #642 multi-agent review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(node): add cdn/dht/v1 handler, routing table, rate limiter (ADR 022)

PR 2 of 4 for #320 (Kademlia content discovery). Wires the
`cdn/dht/v1` handler skeleton into the runtime and lands the routing
table + rate limiter the rest of the DHT machinery will build on.

What's in:

- `crates/node/src/dht/routing.rs` — k-bucket routing table at K=20,
  256 buckets keyed by XOR distance to the node's own NodeId (ADR 022
  §Routing Table). LRU eviction on bucket overflow; the
  ping-then-evict variant is deferred until the FindNode driver lands
  in PR 4 of #320. Self-id inserts are no-ops so iterative lookup
  never terminates on the local table.
- `crates/node/src/dht/rate_limit.rs` — three-layer token-bucket
  limiter (per-peer NodeId, per-IP, global) with cheapest-first
  short-circuit per ADR 022 §DHT Rate Limiting. Trusted-IP exemption
  bypasses the per-IP layer only; per-peer and global still apply.
  Each layer can be independently disabled (rate == 0 with burst ==
  0). Backed by `governor` like `ConnectionLimiter`.
- `crates/node/src/handlers/dht.rs` — `ProtocolHandler` implementing
  the full ADR 013 error-code mapping and the ADR 022 admission
  order: dispatch limiter → per-stream rate limit → routing-table
  refresh → dispatch. `FindNode` is fully implemented; `Store` and
  `FindValue` return safe placeholders (StoreAck{accepted: false},
  empty providers) so the wire surface is reachable from upgraded
  peers. Real handling for those variants lands in PR 3 of #320.
- `crates/common/src/config/{types,resolved}.rs` and resolver —
  `DhtConfig` / `ResolvedDht` with per-layer rate/burst pairs and a
  parsed trusted-IPs set. Defaults match ADR 022 (20/100/1000 req/s,
  40/200/2000 burst). Pairing rules mirror the existing
  `security.per_source_*` resolver: rate>0 with burst=0 is rejected
  at config time.
- `decdn_dht_rate_limit_rejected_{per_peer,per_ip,global}_total`
  metrics. ADR 022 §Observability specifies a single labeled counter,
  but `iroh_metrics::MetricsGroup` doesn't support per-field labels;
  we follow the existing convention (cf. `dispatch_rejected_*`) and
  surface one counter per layer. Operators with the ADR-022 alert
  form do a Prometheus `sum()` to recover the rolled-up rate.
- Runtime registers `cdn/dht/v1` on the iroh router alongside
  `cdn/probe/v1` and `iroh-gossip`.
- Loopback integration test (`tests/dht_loopback.rs`) covering a
  seeded routing table responding to FindNode plus the FindValue
  placeholder shape (pinned now so a future regression while the
  record store lands can't pass under the same loopback name).

What's deferred (per the issue-320 plan):

- Record store + Store/FindValue admission, per-publisher quota,
  receiver-anchored TTL, iterative lookup — PR 3.
- Republish scheduler, bootstrap, on-chain origin fallback — PR 4.
- BatchStore variants and prefetch — follow-up issues.

Refs #320.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(node): address PR #643 review — routing-table poisoning, recursion, docs

Addresses PR #643 review feedback (gemini-code-assist + Copilot):

- **HIGH: drop attacker-controlled routing-table refresh.**
  `handle_find_node` was calling `note_peer_seen(req.requester)` on the
  unauthenticated wire field, letting an authenticated peer A send
  `FindNode { requester: B }` to inject any NodeId B into the routing
  table without owning the matching key (routing-table poisoning). The
  authenticated peer NodeId from the QUIC handshake is already
  refreshed once per admitted request in `serve()`, which is the only
  honest signal we have. Removed the second `note_peer_seen` call;
  added a regression test that confirms the attacker-supplied
  `req.requester` is NOT inserted while the authenticated client IS.
- **Replace `unreachable_size_mismatch` with `std::array::from_fn`.**
  The previous helper recursed indefinitely on its own error path —
  the recursion is unreachable by construction but a future
  regression would stack-overflow instead of producing a clear
  diagnostic. `std::array::from_fn` builds the fixed-size array in
  place so the validation step (and the recursion) go away entirely.
- **Fix inverted bucket-index comment.** The code returns bucket 255
  for max distance and bucket 0 for the closest peers; the comment
  said the opposite. Rewrote it (and renamed the two related tests
  `bucket_index_max_distance_is_top_bucket` /
  `bucket_index_min_nonzero_is_bucket_zero`) to match the
  implementation.
- **Re-evaluate `peer_ip` per stream.** Iroh paths can switch over a
  connection's lifetime (relay-only initially, then a direct UDP path
  becomes selected). Capturing the IP once at accept would permanently
  disable the per-IP rate-limit layer for any connection that started
  relay-only. Moved the `peer_ip(&conn)` call inside the per-stream
  loop so a relay→direct switch engages the layer for subsequent
  streams.
- **Align `rate_limit.rs` doc references with the actual emitted
  metric names** (`decdn_dht_rate_limit_rejected_{per_peer,per_ip,
  global}_total` — one Counter per layer, since the metrics backend
  doesn't support per-field labels).
- **`sort_unstable_by_key` in `RoutingTable::closest`.** Computes
  `xor_distance` once per element instead of twice per pairwise
  comparison; lower asymptotic XOR cost on fully-populated tables.
- **`BatchStore`/`BatchStoreAck` dispatch arms.** PR-1 fix
  re-introduced these enum variants at their ADR-canonical
  discriminants; the handler now answers `BatchStore` with a
  per-hash `accepted: false` ack so publishers fall back to per-hash
  `Store` per ADR 022 §Schema Evolution. Handler-side admission
  (two-stage rate limit, holder check, per-hash quota) is the
  follow-up issue tracking `BatchStore` proper.

Deferred to a follow-up issue (raised in PR #643 review):

- Per-IP / per-peer keyed-rate-limiter keyspace cap + periodic GC
  (mirror of `dispatch::ConnectionLimiter::max_tracked_sources` +
  `retain_recent`). Same DoS shape as the dispatch limiter; meaningful
  fix but a self-contained chunk of work with its own runtime wiring.

Refs #320, addresses #643 review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(node): apply consolidated review fixes from PR #643 multi-agent review

Round 2 of PR #643 review (after the prior poisoning/recursion/comment
round). Addresses findings from five specialized review agents
(code-reviewer, pr-test-analyzer, silent-failure-hunter,
type-design-analyzer, comment-analyzer).

CRITICAL

- **BatchStore now closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE`
  instead of replying with an all-`false` `BatchStoreAck`.** ADR 022
  §STORE Flow line 138 + §Schema Evolution specify that the unsupported
  signal MUST be stream-close-without-ack — an all-`false` ack reads to
  a conformant publisher as "your batch was processed, every hash
  rejected" and triggers NO fallback to per-hash `Store`. The fix is
  structural: `read_dht_request` now narrows the wire `DhtMessage` to a
  new `DhtServerRequest` enum (`FindNode` / `FindValue` / `Store`),
  rejecting `BatchStore` and response-on-server-stream variants up
  front. `dispatch` is then exhaustive over the active set without a
  panic / echo fallback for impossible cases. Loopback test
  `batch_store_returns_unsupported_code_not_ack` guards the contract.

- **`dht.*` wired into the SIGHUP reload pipeline.** `FileSectionSnapshot`
  gains a `dht` field and `log_ignored_other_sections` emits the
  "requires restart" warning when `[dht]` changes. Previously an
  operator who edited `dht.rate_limit.trusted_ips` and SIGHUPed got no
  feedback that the change wasn't applied.

- **`[dht.rate_limit]` is now nested under `[dht]` per ADR 022 §Trusted-IP
  exemption.** Operator key path is `dht.rate_limit.trusted_ips` (matching
  the ADR), not the flat `dht.trusted_ips` from the prior commit. All
  six rate/burst knobs moved with it.

IMPORTANT

- **`DhtServerRequest` narrowing enum replaces `dispatch`'s
  match-all-fallback** (code-reviewer #5, silent-failure-hunter
  Critical #2). The previous arm echoed an empty `FindNodeResponse` if
  reached — dead code that masked a real protocol violation if the
  filter ever drifted. Removed entirely.

- **`decdn_dht_requests_failed_total` counter added.** Bumps when
  `handle_one` returns Err after rate-limit admission (frame decode,
  encode, write, finish, read timeout, etc). Operator running at
  default `RUST_LOG=info` no longer needs to enable debug logs to see
  "DHT requests are failing" (silent-failure-hunter Critical #1).

- **ADR 013 error-code roundtrip loopback tests** for
  `APP_ERR_MALFORMED_MESSAGE`, `APP_ERR_UNSUPPORTED_MESSAGE` (response
  on server stream + `BatchStore`), and `APP_ERR_RATE_LIMITED`
  (pr-test-analyzer Critical #1, #3). `APP_ERR_MESSAGE_TOO_LARGE`
  needs a low-level varint writer to exercise; noted in a comment.

- **`closest_returns_distance_sorted_results` strengthened** to assert
  the full vector is monotonically non-decreasing by XOR distance,
  not just endpoints — catches "first and last correct, middle
  scrambled" regressions (pr-test-analyzer #4).

- **Stale / misleading comments fixed** (comment-analyzer #2, #6, #7):
  routing.rs no longer claims a non-existent "follow-up PR" lands
  ping-then-evict; handler module docs now correctly describe the
  BatchStore stream-close behavior; the dispatch comment reflects the
  new narrowing-enum shape.

DEFERRED (genuine but out of scope for this PR slice)

- `NodeId` newtype (type-design-analyzer single biggest recommendation,
  touches the wire format + multiple crates — file as standalone
  follow-up).
- Per-IP / per-peer keyspace bound (already issue #645).
- Read-timeout app code, `FrameError::Io` mapping nuances (silent-failure-hunter
  MEDIUM, match existing probe handler precedent).

Refs #320, addresses PR #643 multi-agent review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(node,cache): record store + Store/FindValue + cache hook (ADR 022)

PR 3 of 4 for #320 (Kademlia content discovery). Replaces the
PR-2 placeholder responses with the spec-conformant admission pipeline
and exposes the cache → DHT republish hook that PR 4 will consume.

What's in:

- `crates/node/src/dht/records.rs` — receiver-side `RecordStore`
  enforcing the ADR 022 §Content Records and TTL admission rules:
  * Per-publisher cap of 200 records — hard reject above cap.
  * Global cap of 100k records — global LRU eviction when over cap
    and the inserting publisher is below their per-publisher cap.
  * Per-hash provider cap of 50 — evict oldest holder for that hash.
  * Receiver-anchored TTL of 1 hour; refresh-in-place on re-publish
    (no double-count against the publisher quota).
  * Periodic GC sweep + on-demand expiry scrub on every providers
    lookup.
- `crates/node/src/dht/staker_set.rs` — `StakerSet` trait + file-
  config-driven `ConfigStakerSet`. The chain-backed `ChainStakerSet`
  that reads `StakingRegistry.getActiveNodes()` lives in the on-chain
  origin-directory follow-up issue; same trait, drop-in swap.
- `handlers/dht.rs` — real `Store` admission (holder == authenticated
  NodeId → active-staker filter → record-store insert) and real
  `FindValue` (record-store providers + routing-table closer_nodes).
  Per ADR 022 §Lookup integrity the requester-side filters (XOR-
  distance check, active-staker filter, negative-probe-cache,
  randomisation) belong on the iterative-lookup side and land with
  PR 4 of #320 — the responder is intentionally minimal here.
- `crates/cache/src/engine.rs` — `CacheEngine::subscribe_inserts()`
  broadcast hook. Emits the committed hash from the `pull_through`
  success arm (the single convergence point for streaming + buffered
  commits); the local-store-hit short-circuit deliberately does NOT
  emit (a hit doesn't start a new TTL cycle).
- `dht.static_active_nodes` config field — operator-supplied 64-char
  hex `NodeId` list parsed via the existing `parse_node_id_hex`
  helper; malformed entries fail config resolution.

What's deferred (per the issue-320 plan):

- Iterative requester-side `FindValue` lookup (α=3 parallelism, three
  requester-side filters from ADR 022 §Lookup integrity, provider-set
  randomisation) — PR 4 of #320, where it pairs naturally with the
  bootstrap and republish-scheduler call sites.
- Republish scheduler that consumes `subscribe_inserts` and pushes
  `Store` to the K+3 closest peers with jittered (30–50 min) cadence —
  PR 4 of #320.
- Subscribe-to-staker-changes (broadcast channel on `StakerSet`) — the
  current `ConfigStakerSet` set is immutable post-startup, so the
  subscriber surface doesn't pay rent yet.

Tests:

- 11 new `RecordStore` unit tests covering insert / refresh / quota /
  global LRU / per-hash cap / TTL / GC.
- 4 new `ConfigStakerSet` tests.
- 2 new `CacheEngine::subscribe_inserts` tests: emit on pull-through
  success, NO emit on cache hit.
- 3 new DHT loopback tests under `store_admission`: round-trip for a
  staked publisher; rejection for a non-staked publisher; rejection
  when `holder != authenticated NodeId` (lying-`holder` attack).

Refs #320.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(node,common): address PR #646 multi-bot review (TTL drift, eviction, GC)

Addresses PR #646 review (Copilot + gemini-code-assist):

Correctness:

- **TTL no longer drifts with insert volume.** Previously
  `monotonic_tail` was added directly into `receive_us` and propagated
  into `expiry_us`, so 1M unrelated inserts shifted a record's expiry
  forward by ~1s; 1B inserts ~17 min — material against the 1-hour
  TTL. Per ADR 022 §Content Records and TTL line 122,
  `expiry_us = receive_us + ttl_us` is the contract. Replaced with a
  separate `sequence` field that's used only as the second component
  of the `global_lru` key, never mixed into time-domain values.
  Regression test: a record inserted at wall-clock 500 with
  `ttl_us = 1_000` has `expiry_us == 1_500` exact after 10k unrelated
  prior inserts.
- **No more "two evictions for one insert".** The prior order was
  "global LRU first, then per-hash cap" — when both were full this
  evicted an unrelated record AND a per-hash holder for one insert,
  leaving the store under-full by one and dropping an unrelated hash's
  oldest holder. Per-hash cap now fires first; the global LRU is
  skipped when the per-hash eviction already nets the store out at
  the same global count. Regression test pins both invariants.
- **Periodic record-store GC task added.** Without it, expired records
  accumulated against the per-publisher and global caps until any
  query for the specific hash forced a scrub. A publisher who put
  one record and stopped requesting it would eventually fill its
  200-record quota with stale entries and have every future `Store`
  rejected. The task runs on the existing `DISPATCH_GC_INTERVAL` (60s)
  and shuts down via the same `oneshot` shape as `run_dispatch_gc`.
- **`RecordStore::gc` now `O(expired × log N)` instead of `O(N)`.**
  Since `ttl_us` is constant, `global_lru` (ordered by `receive_us`)
  is also ordered by `expiry_us` — pop the front until non-expired
  and stop. gemini-code-assist's exact suggestion.

Cleanup:

- `parse_node_id_hex`'s error message is now field-agnostic ("must be
  64 hex chars, got X"). Callers (`gossip.allowlist[idx]` and
  `dht.static_active_nodes`) already wrap with the field path; the
  helper no longer hardcodes "gossip.allowlist".
- `AllStaked` test stub: `len()` now returns 0 to stay consistent
  with the empty `active_nodes()` (was `usize::MAX`, an inconsistency
  the bot flagged). Doc on the helper now spells out that it's not
  enumerable — tests that need a concrete set use `ConfigStakerSet`.

Tests:

- 2 new `RecordStore` unit tests pinning the TTL-no-drift and
  no-double-eviction contracts.
- Existing 12 record-store + 4 staker-set + 2 cache subscribe + 10
  DHT loopback tests still green (998/998 workspace).

Refs #320, addresses PR #646 review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(node,cache): apply PR #646 round-3 review (correctness + comments + tests)

Five-agent review on PR #646 surfaced 4 correctness issues, 6 comment
factual errors, and several test gaps.

Correctness:

- **Empty staker-set startup warning** — `dht.static_active_nodes` missing
  silently rejects every `Store` (ADR 022 line 140). Runtime now logs
  `warn!` at startup when the set is empty so the failure mode is one
  high-signal line, not silent per-request debug rejections.
- **`now_us()` clock-broken log** — `SystemTime` before-UNIX-EPOCH used
  to silently fall back to `receive_us=0`, collapsing every record to
  the same `expiry_us` and triggering mass eviction at the 1-hour
  mark when the clock recovered. Now logs `error!` once per affected
  insert so the operator sees the host-clock fault. Fallback keeps
  the store functional in the degraded state.
- **Refresh corruption-path** — `entries.get_mut(idx)` returning `None`
  after `position()` returned `Some(idx)` used to surface as
  `InsertOutcome::Refreshed` → `accepted: true` on the wire,
  confirming a write that never happened. Now returns
  `RejectedQuotaExceeded` and logs `error!` with full context.
- **Store-rejection metrics** — three new counters
  (`decdn_dht_store_rejected_holder_mismatch_total`,
  `decdn_dht_store_rejected_non_staked_total`,
  `decdn_dht_store_rejected_quota_total`) plus
  `decdn_dht_store_accepted_total`. Lying-holder + non-staked +
  quota-exhaustion are operator-actionable security/abuse signals
  that previously needed `RUST_LOG=debug` to see.

Comment factual errors:

- `cache/engine.rs:765` line citation 124 → 126 (the quoted "When a
  node caches blob H" sits at line 126, not the section header at 124).
- `handlers/dht.rs:527` "PR-2-of-#320 slice" → "this slice" (the file
  is now PR 3).
- `handlers/dht.rs:530` "§Schema Evolution line 138" was misattributed;
  line 138 is in §STORE Flow. Now reads "§STORE Flow line 138 +
  §Schema Evolution".
- `handlers/dht.rs:301` dispatch by-value comment referenced
  `FindValueResponse` (the response shape); the function takes
  request variants. Now says "request variants whose payloads include
  Vec fields (e.g. a `BatchStoreRequest::hashes` once the handler-side
  admission lands)".
- `records.rs:451` test comment claimed "receive_us is monotonic-
  counter-mixed"; that was the pre-fix behaviour. Now asserts exact
  equality with `receive_us = 200` + `expiry_us = 200 + ttl_us`.
- `records.rs:587/600` test internally cited 10k AND 100k AND 1M
  unrelated inserts; only 10k is real. All references now match.

Tests:

- `default_config_matches_adr_022` pins the four `RecordStoreConfig`
  defaults (200 / 100k / 50 / 1h) against the ADR 022 §Content Records
  and TTL table. Without it, a regression that halved any value would
  pass the entire existing test suite (all use `small_cfg()`).
- `publisher_quota_beats_global_lru` regression-pins the rule that a
  publisher at their per-publisher cap hard-rejects WITHOUT touching
  the global LRU — a future refactor that swapped check order would
  let quota-exceeded publishers displace other publishers' records.
- `run_record_store_gc_exits_promptly_on_shutdown` mirrors the
  `run_dispatch_gc_exits_promptly_on_shutdown` precedent: a regression
  that reorders the `tokio::select!` arms or drops `biased` would
  silently extend `SHUTDOWN_DEADLINE` by up to 60s.

Pushed back / filed for follow-up:

- Extracting `add_entry`/`remove_entry` helpers to make the tri-index
  `RecordStore` invariant structural rather than convention. Real
  recommendation; non-trivial refactor that's well-covered by the
  existing regression tests today. Worth doing but not in this PR.
- Stripping unused `StakerSet::{active_nodes, len, is_empty}` (YAGNI).
  `active_nodes` is the bootstrap surface PR 4 needs, and trait
  methods are harder to add once an external impl exists. Keep.
- `Hash` type alias same fate as `NodeId` (already a filed follow-up).

1001/1001 workspace tests pass. Clippy + fmt + cargo doc + cargo deny
+ ADR-hygiene hooks all clean.

Refs #320, addresses PR #646 round-3 review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(node): drop dht.static_active_nodes; wire empty StakerSet pending PR 4

Per review discussion: maintaining a TOML-file mirror of
StakingRegistry.getActiveNodes() invites drift (operators omitting
stakers, censoring, forgetting to update). Drop the config surface
now — the chain-backed StakerSet is what ADR 022 §STORE Flow line 140
specifies, and PR 4 of #320 already needs the same on-chain read for
bootstrap, so it's the natural home for ChainStakerSet too.

Until PR 4 lands, the runtime wires ConfigStakerSet::empty() with a
loud startup warn. The cache → DHT republish hook exposed in this PR
has no producer yet (PR 4 brings the scheduler), so no publisher-side
traffic is gated either.

Tests build StakerSet programmatically via ConfigStakerSet::{new,
empty} and are unaffected. The StakerSet trait and ConfigStakerSet
remain exported (tests still use them; runtime swap is one line when
ChainStakerSet lands).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 25, 2026
Both PR review bots flagged 14 items on PR #679. 13 are valid; 2
(Copilot 8 + 9 on firstBondedAt vs firstRegisteredAt) are resolved
by accepting Gemini #3's rename.

Fixed:

1. ADR 009:139 — `unbondingWindow` / `setUnbondingWindow` → `unbondingPeriod`
   / `setUnbondingPeriod` to match the actual contract surface in
   ADR 014 (Gemini #1).

2. ADR 014:167+170 — unbonding bounds `[3 days, 30 days]` → `[7 days,
   60 days]` matching ADRs 009/026; PoC default "unbonding 7 days" →
   "unbonding 14 days" matching v2.1 default (Gemini #2).

3. Rename `firstRegisteredAt` → `firstBondedAt` (and `getFirstRegisteredAt`
   → `getFirstBondedAt`) across ADRs 003, 008, 016, 019, 030, and the
   operator-key-rotation appendix. Under v2.1 the single
   `CapacityBond.register(declaredMbps)` call is both registration and
   bonding, so one field serves both the cold-start bootstrap bonus
   (ADR 008) and the governance `age_ramp` (ADR 026 § Governance).
   This resolves Gemini #3 and the Copilot 8/9 "mixes two concepts"
   thread — under v2.1 the two timestamps coincide.

4. ADR 030:43 — anchor `#interface-additions-to-stakingregistry` →
   `#interface-additions-to-capacitybond` matching the renamed
   heading in ADR 003 (Gemini #4).

5. appendix-operator-key-rotation:55 — row content rewritten from
   "Cleared only by `deregisterNode`" (contradicted ADR 003's
   write-once invariant) → "Write-once; never cleared by
   `deregisterNode` or auto-ejection" (Copilot #5).

6. appendix-operator-key-rotation:109-111 — `CapacityBond.deregisterNode()`
   no longer claimed to start unbonding (it only deactivates per
   ADR 003 § Node Registry). Added explicit `CapacityBond.unbond()`
   step with the v2.1 14-day default. The withdraw step now follows
   the unbonding window (Copilot #6).

7. appendix-operator-key-rotation:114 — re-bond flow rewritten:
   `TOKEN.approve` → `CapacityBond.register(declaredMbps)` →
   `CapacityBond.registerNode(...)` matching ADR 019 Phase 2 sequence
   (Copilot #7). The prior `CapacityBond.stake` was a pre-v2.1
   carryover.

8. ADR 024:80 — Bond-management bullet rewritten from
   `CapacityBond.stake()` / `deregister()` to
   `CapacityBond.register(declaredMbps)` / `deregisterNode()` /
   `unbond()` matching the v2.1 surface in ADR 003 / 016 (Copilot #10).

9. appendix-l2-deployment:181-186 — bytesPerEpoch ownership corrected:
   "CapacityBond.recordSettlement SSTORE that also increments
   bytesPerEpoch" → "FeeRouter-internal `bytesPerEpoch` write +
   single CapacityBond.recordSettlement SSTORE updating
   lastSettlementAt". Matches ADR 016's interface and the prior
   commit-8 fix to 016 (Copilot #11).

10. appendix-peer-table-eviction:45-47 — "active staked node set" /
    "staking gate" → "active bonded operator set" / "CapacityBond
    registry gate" (Copilot #12).

11. ADR 001:204 — "All staked nodes register in CapacityBond" → "All
    bonded nodes register in CapacityBond" (Copilot #13).

12. appendix-observability:187 — metric source
    `CapacityBond.activeOperatorCount()` (function didn't exist) →
    `CapacityBond.getActiveNodeCount()` matching the documented
    Off-Chain Read API in ADR 016 line 482. Added a sentence noting
    that 1:1 NodeId↔Ethereum binding makes node-count and
    operator-count equivalent (Copilot #14).

Hygiene guards all pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 27, 2026
Addresses 7 inline comments on commit 5c643ad:

- spec: drop /home/thiras/... workstation path from
  2026-05-27-served-bytes-voting-design.md §Design Decisions
  (not reproducible for repo readers — copilot)
- ADR 036 §Behaviors: reword quorum/proposalThreshold bullet — the
  Governor reads FeeRouter.totalBytesInWindow as an UPPER-BOUND PROXY
  for Σ_op vote_weight, not the exact sum. Per-operator cap + age_ramp
  multipliers make actual Σ ≤ totalBytesInWindow, so calibrating quorum
  against the proxy is intentionally conservative and avoids per-castVote
  summation gas. Proxy is exact in the no-cap, all-tenured steady state.
  (copilot)
- appendix-observability:194 decdn_capacity_bond_amount_token: drop
  "service-emission grants"; reframe as voluntary bond + vested portion
  of any Genesis Bond Credit; PendingCredit tracked separately (copilot)
- appendix-observability:346 deferred dashboards: drop "operator-emissions
  tracking"; replace with served-bytes voting + Genesis Bond Credit
  vesting (copilot)
- appendix-operator-key-rotation:53,134: "service-emission grant history"
  → "Genesis Bond Credit PendingCredit position" (copilot ×2)
- ADR 008 §Regional-Coverage: "Sections 3–4" replaced with
  [§ Local Score Calculation] and [§ Network Score Aggregation] named
  links; "Section 12" replaced with [§ Capacity-Shortfall and Wash-Trading:
  Reputation as Off-Chain Signal] named link. (gemini — note: literal
  suggestion of [§ 3](#3) was rejected because (a) #3/#4 are not valid
  GFM-slugified anchors of those headings and (b) the §N pattern would
  trigger the check-no-section-numbers pre-commit hook; implemented the
  underlying intent properly.)

Pre-commit hooks pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 29, 2026
…+ 6 more

7 findings from the max-effort escrow-on-slash review on #708.

#1 (blocker) — appeal-slot griefing. `openSlashAppeal` was permissionless;
the one-shot-per-slashId guard let anyone (notably the recorded challenger,
who earns 50% of an upheld slash) front-run a junk appeal and permanently
burn the operator's only recourse. Now operator-only: `msg.sender` must equal
the operator recorded in the slash. New `CallerNotOperator` error + tests.

#6 (must-fix) — clip the credit-slash leg. `_slashPendingCreditAtTier` now
caps `slashed` at `atRisk` (symmetric with `_reduceStakeAtTier`'s C2 clip), so
`escrowedTotal` can never book more than the tokens removed if a tier constant
is ever set >100%. Invariant comment added.

#7 (must-fix) — granted appeal restores credit vesting, not liquid TOKEN.
`SlashRecord` gains `creditPortion` (set in `_mintSlashRecord`). On
`settleAppealGranted` the credit portion is added back to
`_pendingCredit.originalGrant` (grantedAt untouched → vest resumes) and only
the stake portion is refunded liquid — exactly whole, no accelerated-credit
windfall. New credit-restore test.

#2 — conditional `slashedAtEpoch` clear. `settleAppealGranted` clears the
per-operator stamp only when it belongs to the reversed slash; a later
still-standing slash keeps its zero-out. Two-slash regression test. (Closes
the deferral in #709.)

#3 — `upholdAppeal` graceful degrade. Drops the `ChallengerPoolNotWired`
revert; burns 100% of the bond when the pool is unset (matching
`rejectAppeal`) so a misconfig can't block an uphold and let cleanup flip it
to an operator-favorable grant. Pool-unset test.

#4 — pause covers the whole settlement path. `whenNotPaused` added to the
CapacityBond settle hooks and all SlashAppeal resolution functions.

#5 — appeal windows extended by paused duration. Each contract tracks
`pausedTotal` (override `_pause`/`_unpause`); filing/review/ratification
deadline checks add the offset so a pause never silently consumes a window.
Pause-spans-window test.

ADR 028 updated for operator-only filing. Verification: build --deny warnings
(both contracts <24,576), fmt, 262/262 tests, aderyn 0 high, slither no
medium+, gas snapshot regenerated.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 29, 2026
…t to burn (#708)

* refactor(contracts): remove SafetyReserve; escrow-on-slash + 5% bucket to burn

Removes the SafetyReserve contract and its standing USDC insurance pool.
Slash restitution is now handled by escrow-on-slash in CapacityBond, and the
slash-appeal state machine lives in a new standalone SlashAppeal contract.

Contracts:
- Delete SafetyReserve.sol / ISafetyReserve.sol (+ test + mock).
- FeeRouter: drop the 4th "safety" bucket; fold its 5% into buyback
  (25%->30%). Split is now 60/30/10, uint256[4]->uint256[3].
- CapacityBond: escrow-on-slash. slash() escrows the slashed TOKEN
  (escrowedTotal) instead of distributing it; add permissionless
  finalizeUnappealedSlash (50/50 challenger/burn after the 30-day window)
  and the SLASH_APPEAL_ROLE settle hooks markAppealOpen / settleAppealUpheld
  / settleAppealGranted (refund operator + internal _clearSlashedAtEpoch).
  Remove the 30% safety redirect, recordSlashInflow try/catch, and the
  SafetyReserveNotWired guard.
- New SlashAppeal.sol + ISlashAppeal.sol + ICapacityBondSlashEscrow.sol:
  open/fastTrack/reject/grant/uphold/cleanup; TOKEN appeal bonds only,
  no USDC/pool/swap/queue. grant/uphold replace the old ratify/reverse.
- CapacityBond drops to 23,167 B (was 23,912) despite gaining escrow logic.

Verification: forge build --sizes --deny warnings (all <24KB), forge fmt,
257/257 tests pass (new SlashAppeal + escrow-lifecycle coverage), aderyn 0
high, slither no medium+, gas snapshot regenerated.

ADRs (single source of truth):
- Retire 032 + 033 to _history/.
- Rewrite 026 (split 60/30/10, escrow-on-slash 50/50, recourse-gap note)
  and 028 (escrow-refund-in-TOKEN, SlashAppeal surface).
- Structural updates to 016 + 009; cross-ref fixes in 003/008/014/018/031/
  036/architecture/glossary/appendices; update decdn/CLAUDE.md ADR note.

Accepted scope reduction: downtime / bad-data user recourse is no longer a
protocol contract surface (DAO Treasury governance only); reputation
(ADR 008) is the standing deterrent.

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

* fix(contracts): address PR review — restrict rejectAppeal, add UnknownSlash guards

Code-review feedback from gemini-code-assist + Copilot on #708:

- SlashAppeal.rejectAppeal: restrict to AppealStatus.Open only. A FastTracked
  appeal must be resolved by the Governor (grantAppeal/upholdAppeal), so the
  multisig can no longer overturn its own interim relief and burn the full
  bond — preserves the two-stage governance process and the 50/50 bond split
  on the fast-tracked-failure path. (matches ADR 028 "rejects at intake")
- CapacityBond: add explicit `slashId >= slashCounter -> UnknownSlash` guards
  to finalizeUnappealedSlash / markAppealOpen / settleAppealUpheld /
  settleAppealGranted, matching getSlashRecord's clearer error reporting.
- Tests: replace bare vm.expectRevert() with specific selectors in
  SlashAppeal.t.sol (access-control) and FeeRouter.t.sol (SharesDoNotSum /
  NonZeroShareNeedsDestination).

ADR consistency (stale-reference cleanups the reviewers flagged):
- 018: remaining 25% buyback/inflow refs -> 30% (liquidity-cap + risk sections).
- glossary: BuybackBurner 25%->30%; Slashing entry -> escrow-on-slash 50/50;
  slashedAtEpoch cleared via settleAppealGranted (not clearSlashedAtEpoch).
- 009: "four FeeRouter shares" -> three; drop "safety" from the 0%-floor prose.
- 026 + 028: correct the credit-slash scope to match the contract — the full
  at-risk pool (originalGrant - claimed, incl. vested-but-unclaimed) is
  slashable (closes the delay-to-shield loophole); claimed credit is slashed
  via the stake path. (Pre-existing ADR/contract mismatch.)

Verification: build --deny warnings (all <24KB), fmt, 257/257 tests, aderyn 0
high, slither no medium+, gas snapshot regenerated.

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

* fix(contracts): address @alpergundogdu review — appeal-slot griefing + 6 more

7 findings from the max-effort escrow-on-slash review on #708.

#1 (blocker) — appeal-slot griefing. `openSlashAppeal` was permissionless;
the one-shot-per-slashId guard let anyone (notably the recorded challenger,
who earns 50% of an upheld slash) front-run a junk appeal and permanently
burn the operator's only recourse. Now operator-only: `msg.sender` must equal
the operator recorded in the slash. New `CallerNotOperator` error + tests.

#6 (must-fix) — clip the credit-slash leg. `_slashPendingCreditAtTier` now
caps `slashed` at `atRisk` (symmetric with `_reduceStakeAtTier`'s C2 clip), so
`escrowedTotal` can never book more than the tokens removed if a tier constant
is ever set >100%. Invariant comment added.

#7 (must-fix) — granted appeal restores credit vesting, not liquid TOKEN.
`SlashRecord` gains `creditPortion` (set in `_mintSlashRecord`). On
`settleAppealGranted` the credit portion is added back to
`_pendingCredit.originalGrant` (grantedAt untouched → vest resumes) and only
the stake portion is refunded liquid — exactly whole, no accelerated-credit
windfall. New credit-restore test.

#2 — conditional `slashedAtEpoch` clear. `settleAppealGranted` clears the
per-operator stamp only when it belongs to the reversed slash; a later
still-standing slash keeps its zero-out. Two-slash regression test. (Closes
the deferral in #709.)

#3 — `upholdAppeal` graceful degrade. Drops the `ChallengerPoolNotWired`
revert; burns 100% of the bond when the pool is unset (matching
`rejectAppeal`) so a misconfig can't block an uphold and let cleanup flip it
to an operator-favorable grant. Pool-unset test.

#4 — pause covers the whole settlement path. `whenNotPaused` added to the
CapacityBond settle hooks and all SlashAppeal resolution functions.

#5 — appeal windows extended by paused duration. Each contract tracks
`pausedTotal` (override `_pause`/`_unpause`); filing/review/ratification
deadline checks add the offset so a pause never silently consumes a window.
Pause-spans-window test.

ADR 028 updated for operator-only filing. Verification: build --deny warnings
(both contracts <24,576), fmt, 262/262 tests, aderyn 0 high, slither no
medium+, gas snapshot regenerated.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 29, 2026
…ck map

Address alpergundogdu's PR #713 review (the two actionable observations;
#1 and the design note verified correct, no change).

#2 per_hash_fallback aggregate timeout: a receiver that accepts the
connection but never answers could pin one publish task for up to
MAX_BATCH_STORE_HASHES x DHT_CLIENT_TIMEOUT (~34 min). Bail after
MAX_CONSECUTIVE_FALLBACK_TIMEOUTS (3) back-to-back read timeouts; any
answering outcome resets the run so a slow-but-responsive peer is not cut
off. Thread the per-hash timeout as a parameter (prod passes
DHT_CLIENT_TIMEOUT) and expose per_hash_fallback as a reusable building
block for the #630 republish scheduler. New loopback test asserts exactly
K streams open against a non-answering stub.

#3 BatchStoreFallback size cap: DEFAULT_BATCH_FALLBACK_MAX_ENTRIES = 4096
(mirrors rate_limit max_tracked_per_peer); a new mark at capacity evicts
the soonest-to-expire entry. No periodic GC -- unlike rate_limit's
keyspace maps (keyed by attacker-supplied inbound IP/peer, hence #676's
sweep) this map is keyed only by receivers the local node chose to publish
to that returned a 0x01 close, so it is not externally inflatable and a
static cap suffices. Unit tests cover cap eviction, no-evict-on-re-mark,
and zero-cap clamp.

fmt + clippy clean; node suite 318 pass (dht_loopback 21/21).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 29, 2026
) (#713)

* feat(node): DHT BatchStore handler-side admission (closes #648)

Implements ACs 17-20 of ADR 022 §Batch token accounting: publishers can
now send a single BatchStoreRequest covering many hashes destined for one
receiver instead of N separate Store RPCs (~80% wire-bytes reduction at
C ≥ 10k cached blobs), with a per-hash Store fallback for receivers that
don't implement batching.

Handler admission (handlers/dht.rs, ACs 17/19):
- Route BatchStore through handle_batch_store: batch-level holder ==
  authenticated NodeId check once (mismatch -> MALFORMED_MESSAGE
  stream-close per ADR 022 step 2), then per-hash admission identical to
  N separate Stores (active-staker filter + RecordStore::insert_at)
  sharing one receiver-anchored receive_us. One bool per hash in request
  order. Oversize (>256) rejected at wire decode -> MALFORMED_MESSAGE.
- Thread peer_ip into handle_one/dispatch; dispatch returns
  Result<_, app_code> for the stream-close case.

Two-stage rate-limit accounting (rate_limit.rs, AC 18):
- Refactor check() to share a metric-free try_admit_one; add
  admit_batch_extra() consuming up to n-1 more units cheapest-first with
  short-circuit, byte-for-byte equivalent to N separate Store admissions.
  Stage 1 (the frame token) is already charged in serve(). No rejection
  counter bump on the partial-admit boundary.

Publisher fallback (batch_fallback.rs new, client.rs, AC 20):
- BatchStoreFallback: bounded per-receiver unsupported_until cache
  (default 15 min), lazy expiry, clock-injected for tests.
- client::batch_store primitive + batch_store_with_fallback: skips batch
  when cached unsupported; on an UNSUPPORTED (0x01) close caches the
  negative result + retries per-hash; malformed/too-large/rate-limited/
  transport errors hard-fail (no per-hash storm).
- Fix exchange_on: a peer stream-reset was collapsed by iroh's AsyncRead
  into an io::Error with no typed source, so extract_app_error_code lost
  the code and fallback never fired. Now probe recv.received_reset() and
  re-surface ReadError::Reset(code) typed.

Metrics: dht_batch_store_received, dht_batch_store_hashes_deferred_rate_limit;
per-hash outcomes reuse the existing dht_store_* counters.

Tests: 13 unit (rate-limit, fallback cache, classifier) + 8 loopback
(roundtrip, holder-mismatch MALFORMED, >256 MALFORMED, partial rate-limit
admit, single-hash boundary, primitive roundtrip, batch-vs-fallback path
selection, and end-to-end UNSUPPORTED-close -> cache -> per-hash fallback).

Scope: the republish scheduler is not rewired to group hashes by receiver
(that consumes these building blocks and belongs to #630); AC 20's
publisher-MUST is satisfied by the tested batch_store_with_fallback helper.

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

* refactor(node): address PR #713 review feedback on BatchStore

Apply automated-reviewer (gemini, copilot) findings; all behaviour-
preserving except the metric-counting fix, which is covered by a new
regression test.

- client::per_hash_fallback: reuse a single QUIC connection across the
  fallback set via exchange_on instead of opening one connection per hash
  (up to 256 sequential handshakes). Each per-hash exchange keeps its own
  DHT_CLIENT_TIMEOUT.
- handle_batch_store: lock the record store once before the loop (no
  .await inside) instead of per-hash; only lock on the active path. Fixes
  the inaccurate "rejecting remaining hashes" log spamming once per hash
  on a poisoned mutex (now logged once, "rejecting all hashes").
- handle_one: a dispatch Err(app_code) is a deliberate protocol rejection
  (holder-mismatch -> MALFORMED stream-close) already counted by
  dht_store_rejected_holder_mismatch; reset the stream and return Ok(())
  so it no longer inflates dht_requests_failed (reserved for post-
  admission internal failures). New test asserts the counter split.
- rate_limit::try_admit_one: add a `prune` flag; admit_batch_extra passes
  false. Stage-2 units key on the same (peer, ip) stage-1 already
  inserted, so they can't grow the keyed maps -> the per-unit prune check
  is redundant (bound upheld by stage-1 + periodic GC).
- batch_store_with_fallback: guard an over-cap (>256) batch up front with
  a clear error log + per-hash fallback, instead of burning a doomed
  batch round-trip that looked like a normal all-false rejection.

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

* refactor(node): bound per-hash fallback wall-clock + cap batch-fallback map

Address alpergundogdu's PR #713 review (the two actionable observations;
#1 and the design note verified correct, no change).

#2 per_hash_fallback aggregate timeout: a receiver that accepts the
connection but never answers could pin one publish task for up to
MAX_BATCH_STORE_HASHES x DHT_CLIENT_TIMEOUT (~34 min). Bail after
MAX_CONSECUTIVE_FALLBACK_TIMEOUTS (3) back-to-back read timeouts; any
answering outcome resets the run so a slow-but-responsive peer is not cut
off. Thread the per-hash timeout as a parameter (prod passes
DHT_CLIENT_TIMEOUT) and expose per_hash_fallback as a reusable building
block for the #630 republish scheduler. New loopback test asserts exactly
K streams open against a non-answering stub.

#3 BatchStoreFallback size cap: DEFAULT_BATCH_FALLBACK_MAX_ENTRIES = 4096
(mirrors rate_limit max_tracked_per_peer); a new mark at capacity evicts
the soonest-to-expire entry. No periodic GC -- unlike rate_limit's
keyspace maps (keyed by attacker-supplied inbound IP/peer, hence #676's
sweep) this map is keyed only by receivers the local node chose to publish
to that returned a 0x01 close, so it is not externally inflatable and a
static cap suffices. Unit tests cover cap eviction, no-evict-on-re-mark,
and zero-cap clamp.

fmt + clippy clean; node suite 318 pass (dht_loopback 21/21).

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jun 2, 2026
…ck wiring (#791 review)

Multi-agent review of #791 found the new VoucherActivity clock CLEAN on
correctness but surfaced one type-design leak and one test gap.

LOAD-BEARING: VoucherActivity.touch inserted per ChannelId with no eviction.
On-chain channel close removes the channel from the live map but left its
Instant lingering for the process lifetime -- a slow leak on a long-running,
high-churn node. Add panic-free, idempotent VoucherActivity::forget (poisoned
lock = no-op, same safe degradation as touch/seconds_since) and call it from
ClientHandler::forget_channel, the single site that drops a closed channel
from the live map (both ChannelSettled callers funnel through it).

TEST GAP: the two one-liners wiring the clock (attach_voucher_activity + the
touch in the accept path) had zero test callers, so a dropped/mis-placed stamp
or the writer and reader holding different Arcs would silently report
seconds_since_last_voucher: None forever. Add:
  - client_loopback: a real signed-voucher accept through the live handler
    advances the shared Arc<VoucherActivity> (crit 7);
  - admin: a touch on the SAME Arc the channels() reader holds surfaces as
    Some(age) and sorts the active channel first (crit 6).
Plus VoucherActivity::forget unit tests (removes a stamped channel; unknown
channel no-op).

MicroUsdc newtype (optional #3): declined-for-scope -- the *_micro_usdc unit
suffix already disambiguates the three amount fields from last_nonce, and a
newtype on the DTO fields alone would force .0/MicroUsdc(..) conversions across
~99 references in 8 files (config types, resolved config, runtime, reload,
CLI) where micro-USDC flows as u64. Not low-churn.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jun 3, 2026
…791)

* feat(cli): add decdn node channels payment-channel snapshot (#749)

Add a `decdn node channels` subcommand and the backing `admin_v1_channels`
RPC that print a live snapshot of every open payment channel: per channel
the last-accepted nonce, outstanding accrued claim (micro-USDC), escrowed
deposit, time since the last voucher, and settlement eligibility.

- common: `ChannelSnapshot` / `ChannelsResponse` wire DTOs + `channels()`
  RPC method on the `AdminRpc` trait, `CHANNEL_STORE_ERROR_CODE`, and serde
  round-trip / legacy-default tests.
- node admin: `ChannelStatusHandles` (channel store + voucher-activity clock
  + redeem threshold) attached via `with_dht`-style `with_channels`; the
  handler loads the store off the blocking pool, builds snapshots, and
  computes `settlement_eligible` as `outstanding >= redeem_threshold`
  (upper bound — the admin surface has no on-chain `withdrawnAmount`).
- incentive: new in-memory `VoucherActivity` clock (non-durable, resets on
  restart) shared between the `cdn/client/v1` handler (stamps on each
  accepted voucher) and the admin snapshot (reports seconds-since).
- cli: `Channels(ChannelsArgs)` subcommand + handler with a grep-friendly
  plain-text table and `--json`, mirroring `node status` / `node peers`.

Settlement eligibility uses `>=` to match the redeemer's `< threshold`
short-circuit. Time-since-voucher is `None` after a restart until the next
voucher, since `ChannelState` persists no last-voucher wall-clock.

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

* fix(node): evict VoucherActivity on channel close + cover accept->clock wiring (#791 review)

Multi-agent review of #791 found the new VoucherActivity clock CLEAN on
correctness but surfaced one type-design leak and one test gap.

LOAD-BEARING: VoucherActivity.touch inserted per ChannelId with no eviction.
On-chain channel close removes the channel from the live map but left its
Instant lingering for the process lifetime -- a slow leak on a long-running,
high-churn node. Add panic-free, idempotent VoucherActivity::forget (poisoned
lock = no-op, same safe degradation as touch/seconds_since) and call it from
ClientHandler::forget_channel, the single site that drops a closed channel
from the live map (both ChannelSettled callers funnel through it).

TEST GAP: the two one-liners wiring the clock (attach_voucher_activity + the
touch in the accept path) had zero test callers, so a dropped/mis-placed stamp
or the writer and reader holding different Arcs would silently report
seconds_since_last_voucher: None forever. Add:
  - client_loopback: a real signed-voucher accept through the live handler
    advances the shared Arc<VoucherActivity> (crit 7);
  - admin: a touch on the SAME Arc the channels() reader holds surfaces as
    Some(age) and sorts the active channel first (crit 6).
Plus VoucherActivity::forget unit tests (removes a stamped channel; unknown
channel no-op).

MicroUsdc newtype (optional #3): declined-for-scope -- the *_micro_usdc unit
suffix already disambiguates the three amount fields from last_nonce, and a
newtype on the DTO fields alone would force .0/MicroUsdc(..) conversions across
~99 references in 8 files (config types, resolved config, runtime, reload,
CLI) where micro-USDC flows as u64. Not low-churn.

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

* refactor(cli,node): address PR #791 review — dedupe age formatter, simplify sort, accurate JoinError log

- crates/cli: drop `format_age_secs`; the channels path now scales the
  whole-second wire value and reuses `format_age` (microsecond input) via
  `saturating_mul(1_000_000)`. Boundary buckets are identical and covered by
  `format_age_units`; the now-redundant `format_age_secs_units` test is removed.
- crates/node: `build_channel_snapshots` uses `sort_unstable_by_key` with the
  same total-order key tuple (no closure, no allocation), preserving ordering.
- crates/node: the channel-store `JoinError` log distinguishes cancellation
  from panic (`is_cancelled`) so a shutdown-time cancel isn't logged as a panic.

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

* test(cli): cover node channels --json output + EIP-55 counterparty rendering (#791, Alper review)

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@thiras thiras mentioned this pull request Jun 6, 2026
10 tasks done
thiras added a commit that referenced this pull request Jul 13, 2026
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]>
thiras added a commit that referenced this pull request Jul 14, 2026
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]>
thiras added a commit that referenced this pull request Jul 14, 2026
…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]>
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]>
alpergundogdu added a commit that referenced this pull request Sep 12, 2026
…ress

Address PR #1982 review (money-band correctness on the bundle chunk-hint
range-dedup path). All in crates/cli/src/commands/bundle_pull.rs.

- #1 (resume): after the FIRST complement drive, check staging.try_exists() and
  return success when the drive finalized the blob (a resumed run whose .partial
  already held the donor-overlap ranges) instead of opening a now-renamed
  .partial and failing the entry. Same guard shape already used after the refetch
  and whole-blob re-drives; now covers all three. The dedup reassembly is
  extracted into reassemble_dedup over a RangeDriver trait so this seam is
  unit-testable without a live endpoint or pool.
- #2 (bad hint = re-download, never fail): plan_dedup skips a donor whose
  registered length disagrees with the recipient's claimed length (leaves the
  range in the paid, bao-verified complement); splice_donors treats a per-donor
  seek/copy error (a mismatched span or truncated donor that would EOF) as
  untrusted -> refetch rather than a fatal error.
- #3 (never re-pay a paid blob): a donor group whose blob is fetched and
  registered but whose materialize failed is mark_retained on the ChunkIndex, and
  the run-end sweep skips retained sources, so a rerun resumes from the finalized
  <hex> instead of re-driving and re-paying the whole blob.
- #4 (progress): on any dedup-path success, true the file + total bars up to 100%
  (spliced donor bytes never flow through drive's progress callback). Monotonic,
  so paths already at 100% are unaffected; the plain-entry path is untouched.
- #5 (one probe per entry): resolve the range-drive provider order once per dedup
  entry and thread it into every sub-drive, so a self-heal entry no longer
  re-probes up to 3x. Happy path still probes once.
- #7: inline should_remove_staging (now just !any_failed), reconciled with #3.

Regression tests (each shown to bite pre-fix): reassemble_dedup succeeds when the
first drive finalizes (#1); plan_dedup skips a length-mismatched donor and
splice_donors refetches an EOF-ing copy (#2); the run-end sweep keeps a retained
donor and removes a normal one (#3). cli unit suite green; the anvil e2e
(cli_bundle_pull_range_dedup, incl. self-heal) passes, confirming the extraction
is behavior-preserving.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
alpergundogdu added a commit that referenced this pull request Sep 14, 2026
…parallelism (#1982)

* feat(client-pull): add run-scoped LaneLedgers registry

* feat(client-pull): pool-wide spent/credit from LaneLedgers in multi_source_fetch

multi_source_fetch takes an optional run-wide LaneLedgers registry. When
present, the deposit gate's spent/credit span every lane the bundle-pull
run has registered, not just this fetch's own lanes, so concurrent fetches
sharing a deposit gate correctly. When absent, behavior is unchanged: the
gate folds over only this fetch's lanes, as a solo `decdn fetch` always did.

* feat(cli): source per-lane ledger from LaneLedgers on both fetch paths

* refactor(cli): replace pool_serial + LaneLocks with shared LaneLedgers

* feat(cli): global bundle-pull concurrency gate (semaphore) over all blob fetches

* feat(cli): fetch a chunked file's chunks concurrently under the global gate

* feat(cli): default bundle-pull --jobs to 16, redocumented as global blob-fetch cap

* docs(cli): bundle-pull + ledgers comments describe concurrent shared-ledger delivery

* test(e2e): concurrent chunked-file bundle pull from one node pays once

* fix(cli): bound bundle-pull live bar fan-out at --jobs and reconcile lane deposit on reuse

Code-review fixes for bundle-pull-parallel-shared-ledger:

- bundle_pull.rs: pull_plain/pull_chunked's outer streams were widened to
  buffer_unordered(len), instantiating one live progress bar per manifest
  entry/group before it ever acquires PullCtx.gate — a terminal-flooding
  regression on large bundles. Re-bound both outer streams at --jobs (new
  PullCtx.jobs field) while leaving the inner per-chunk stream and the
  global gate untouched, so a many-chunk file still saturates --jobs.

- fetch.rs: lane_ledger discarded a freshly-built PoolContext on a
  registry-reuse touch, even when open_or_reuse_pool had just performed a
  low-water top-up raising the on-chain deposit above the registry's
  stored value. The pool-wide spent/credit gate reads that stale value and
  could refuse (PoolExhausted) prematurely. Reconcile the shared handle's
  ctx.deposit upward to the fresher reading on every touch (a no-op when
  the touch's own build won the registry race).

- bundle_pull.rs: drop stray changelog-voice "now" from two comments.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(cli): thread ledgers arg into merged caller; bound chunk fan-out at --jobs

Merging main brought in a new multi_source_fetch test caller (PR #1978) that
predates the ledgers parameter; pass None there. Also bound the per-file chunk
stream at --jobs (buffer_unordered) so a file with very many chunks no longer
buffers one future per chunk — the global gate is the real in-flight-fetch cap
(addresses the Copilot review note).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* chore(cli): retire per-chunk-fanout jobs default + e2e ahead of range-dedup

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* feat(cli): origin import --optimize stores whole-file blobs + chunk hints

Flip --optimize to store each file as one whole-file blob + its .obao4
outboard, exactly like a plain import, and emit the chunk list only as
manifest dedup hints. Previously --optimize stored per-chunk blobs and
left the whole-file blob unstored; nodes serving whole files (already
supported) is what makes client-side range dedup possible later.

import_optimized_file streams the file twice: import_one_file writes
the whole-file blob once, then a no-op-sink chunk_file pass computes
the hint list, with its whole_hash/total_size cross-checked against
the written blob to catch a concurrent-modification read race.

Drops the chunks_written status counter (there is no longer a
dedup-storage count to report); chunks_total is now the chunk-hint
count. Updates the existing optimize integration tests to assert
whole-file storage instead of per-chunk storage.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* feat(cli): drive_ranges fetches a set of blob ranges into an unfinalized partial

Adds the two client-side primitives the range-dedup hints work needs:
complement_runs (pure range math, unit-tested) turns a donor's covered
byte ranges into the gaps still worth a paid pull, and drive_ranges
opens a blob's pool + ranged store once and drives a set of ranges
into its .partial without finalizing, so a later assembly step can
promote it once donor bytes fill the rest.

Factors drive_fetch's handshake/store-open/source-build prelude into
open_fetch_prelude so both functions share it instead of duplicating
it; drive_fetch's own tests continue to pass unchanged, confirming the
refactor is behavior-preserving.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* feat(cli): bundle pull dedups chunk-hint ranges against an in-run index

Treat a bundle entry's chunk list as a range-dedup hint rather than a
per-chunk fetch plan. Every entry is fetched and verified by its
authoritative whole-file BLAKE3; when a chunk it names is already
materialized on disk by a sibling entry this run, the fetch pays only for
the complement (the group-aligned bytes no donor covers) and splices the
rest from the sibling's finalized blob.

- `pull_entry` replaces the per-chunk `pull_chunked`/`pull_chunked_file`
  path: plan the dedup against a run-wide `ChunkIndex`, drive only the
  complement into the entry's `.partial`, splice each donor range after
  re-hashing the whole donor chunk against its hint hash (a lying donor
  hint or short read falls back to a paid re-fetch), then verify the
  reassembled `.partial` against the whole-file hash. A lying recipient
  hint (wrong placement) is caught by that check and recovered by
  re-driving the full blob.
- `drive_ranges` now persists the lane's voucher watermark once its
  ranges are driven, exactly as `drive_fetch` does (committed on success,
  settlement HIGH on ambiguous failure), so a failed or resumed chunked
  pull never re-pays a byte already bought.
- Delete the per-chunk path (`ChunkCell`, `ChunkedPlan`, `plan_chunked`,
  `assemble_plan`, `parse_chunk_hashes`, `assemble_chunks`, the chunked
  progress-bar API) and unify `pull_all` on one by-hash grouping through
  `pull_entry`. A donor's finalized staging blob is kept until the run
  ends, then swept.
- Remove the per-chunk-blob shared-chunk e2e; its premise (chunk as
  standalone blob) is gone. A range-dedup e2e lands in a later task.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(cli): unit-test the range-dedup splice byte path

Add pure unit tests for splice_donors/chunk_verified/copy_exact/
hash_partial: a happy-path subset copy that lands the correct bytes
at the recipient offset with an empty refetch list, a corrupted-donor
case that is pushed to refetch with no bytes written, plus direct
chunk_verified/copy_exact/hash_partial coverage. Verified the
corrupted-donor test genuinely bites by temporarily short-circuiting
chunk_verified to always return true (test failed as expected), then
reverted.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* docs: bundles use chunks as range-dedup hints, not stored blobs

An optimized bundle stores each file as one whole-file blob; its
manifest chunks list is an advisory range-dedup hint, never a
separately stored or fetched blob. Rewrite appendix-bundles.md's
Chunked files/Generation/Pull sections in present-tense ASD-STE100 to
match, and sweep stale comments in manifest.rs, chunker.rs, and
bundle_pull.rs that still described chunks as stored/served/
concatenated blobs.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* test(e2e): optimized bundle pull dedups an overlapping range instead of re-downloading

Two files sharing a 4 MiB chunk-group-aligned run are pulled from one node
in a single `decdn bundle pull` invocation. Asserts byte/BLAKE3-exact
output, that the shared lane bills exactly the first file's whole-file
wire size plus the second file's complement wire size (strictly less than
re-downloading both whole files), and that a lone non-overlapping file
bills exactly its whole-file wire size (dedup parity).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(cli): bundle self-heal must not hash a promoted .partial

On the range-dedup self-heal paths, re-driving ranges that complete the
blob lets `drive` finalize and rename `<hex>.partial` -> `<hex>`, after
which `hash_partial`/`promote_partial` operate on a `.partial` that no
longer exists and the entry fails spuriously even though `drive` already
bao-verified the whole blob against the manifest hash.

Guard both self-heal re-drives (the all-donors-corrupt refetch and the
whole-file-mismatch `[(0,total)]` re-drive): if the finalized `staging`
now exists, the blob is verified and promoted, so register the donor
chunks and return `Ok` instead of hashing an absent `.partial`. The
happy dedup path (complement-only drive) never completes the blob, so
`staging` does not exist there and the splice+hash+promote flow is
unchanged.

Add an anvil e2e that arms the self-heal with a lying recipient hint (a
real donor chunk placed where the recipient's bytes differ, so the
donor splice verifies but the whole-file BLAKE3 mismatches). It runs the
measured pull single-shot so the serve-race retry loop cannot mask the
bug; without the guard it fails with `open <hex>.partial: No such file`.

Also soften the `downloaded` metric docs (range-dedup does not lower it
below `reconstructed` on a single-path blob) and note the ~2x staging
disk retention until the run-end sweep.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(e2e): drive bundle range-dedup from a real origin import --optimize

Add cli_bundle_pull_from_optimize_import_dedups: runs the real `decdn
origin import --optimize` over an on-disk source tree (pinning
--chunk-avg/--chunk-min/--chunk-max to fastcdc's MINIMUM_MAX so the
chunker degenerates to fixed-size cuts landing on the shared/tail
seam), asserts the import wrote whole-file blobs + outboards (and no
separately-stored chunk-hash objects), serves the import store's
actual bytes (manifest + both whole files) from a NodeFixture, and
`bundle pull --hash`es the import-emitted bundle hash. Closes the gap
where the existing range-dedup e2e seeds whole-file blobs directly and
hand-builds the manifest, never exercising the import -> hint -> pull
seam.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* docs(cli): correct bundle pull --jobs help for range-dedup entries

A chunk is no longer a fetch unit; each distinct blob is one unit of work
holding one --jobs slot across its complement drive, donor splice, and any
re-fetch. Rewrite the stale help text (present tense) to match (PR #1982 review
item 6).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(cli): harden bundle range-dedup resume, planning, sweep, and progress

Address PR #1982 review (money-band correctness on the bundle chunk-hint
range-dedup path). All in crates/cli/src/commands/bundle_pull.rs.

- #1 (resume): after the FIRST complement drive, check staging.try_exists() and
  return success when the drive finalized the blob (a resumed run whose .partial
  already held the donor-overlap ranges) instead of opening a now-renamed
  .partial and failing the entry. Same guard shape already used after the refetch
  and whole-blob re-drives; now covers all three. The dedup reassembly is
  extracted into reassemble_dedup over a RangeDriver trait so this seam is
  unit-testable without a live endpoint or pool.
- #2 (bad hint = re-download, never fail): plan_dedup skips a donor whose
  registered length disagrees with the recipient's claimed length (leaves the
  range in the paid, bao-verified complement); splice_donors treats a per-donor
  seek/copy error (a mismatched span or truncated donor that would EOF) as
  untrusted -> refetch rather than a fatal error.
- #3 (never re-pay a paid blob): a donor group whose blob is fetched and
  registered but whose materialize failed is mark_retained on the ChunkIndex, and
  the run-end sweep skips retained sources, so a rerun resumes from the finalized
  <hex> instead of re-driving and re-paying the whole blob.
- #4 (progress): on any dedup-path success, true the file + total bars up to 100%
  (spliced donor bytes never flow through drive's progress callback). Monotonic,
  so paths already at 100% are unaffected; the plain-entry path is untouched.
- #5 (one probe per entry): resolve the range-drive provider order once per dedup
  entry and thread it into every sub-drive, so a self-heal entry no longer
  re-probes up to 3x. Happy path still probes once.
- #7: inline should_remove_staging (now just !any_failed), reconciled with #3.

Regression tests (each shown to bite pre-fix): reassemble_dedup succeeds when the
first drive finalizes (#1); plan_dedup skips a length-mismatched donor and
splice_donors refetches an EOF-ing copy (#2); the run-end sweep keeps a retained
donor and removes a normal one (#3). cli unit suite green; the anvil e2e
(cli_bundle_pull_range_dedup, incl. self-heal) passes, confirming the extraction
is behavior-preserving.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(cli): report range-dedup outcomes, fix credit_all lock order, harden self-heal test

Address the still-live code findings from the second review of the bundle
chunk-hint range-dedup path (money-band).

Critical-4: the self-heal e2e asserted a cumulative `paid >= wire_min` that
the warm-up already satisfied, so it could not tell the self-heal path from a
plain fetch. Snapshot the lane watermark after the warm-up and assert the
measured run's EXACT delta: a's whole file plus b's complement plus b's
re-driven head. Harden `run_bundle_pull_until_ready` to bail on a
non-transient reconstruction fault instead of absorbing (and re-paying for)
it via the serve-race retry.

Important-5: an already-finalized `<hex>` staging blob has no `.ranges`
sidecar (promotion deletes it), so re-driving it would `open_or_create` ->
`create` -> truncate and re-pay for the whole blob. `pull_entry` now hash-
verifies an existing staging once and materializes from it, never re-driving.
The misleading "no-op" comment is corrected to the real invariant.

Important-6: `LaneLedgers::credit_all` locked each lane `ctx` while holding
the map lock — the inverse of the driver's ctx-then-map order, a latent
deadlock. It now clones the ctx handles under the map lock, releases it, then
writes each deposit, and recovers a poisoned ctx with `into_inner` like the
other methods (making it infallible).

Important-12: the CLI installs no tracing subscriber, so ignored-hint and
self-heal `warn!`/`debug!` lines were no-ops and a bundle whose hints all lie
paid an unhinted price with an identical summary. `PullReport` now carries
`spliced_bytes` (bytes served from a local donor splice) and `hints_ignored`
(hints dropped by a fault), surfaced in both the human summary and `--json`.
Reporting only; payment is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(cli): --max-lane-streams caps concurrent same-lane bundle pulls (default 1)

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs: correct bundle range-dedup docs, ADRs, and comments to the shipped model

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(cli): box the top-level run() future to satisfy clippy::large_futures

CI runs `clippy --workspace --all-targets` (no --all-features); the range-dedup
+ --max-lane-streams locals pushed main's aggregated future 48 bytes over the
16 KiB large_futures threshold. Boxing run() keeps main's future off the stack.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[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

Development

Successfully merging this pull request may close these issues.

2 participants