Skip to content

docs: Generalize architecture to content-agnostic CDN, refocus slashing on bad edges - #2

Merged
thiras merged 8 commits into
mainfrom
docs/generalize-architecture-and-slash-bad-edges
Mar 29, 2026
Merged

thiras merged 8 commits into
mainfrom
docs/generalize-architecture-and-slash-bad-edges

Conversation

@thiras

@thiras thiras commented Mar 28, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Content-agnostic protocol: Removed audio-specific manifest format (track_id, artist, album, bitrate). Protocol now handles arbitrary BLAKE3-hashed blobs with no metadata assumptions — applications define their own layers on top.
  • Token rename: Replaced all "AUDIO" token references with "TOKEN" placeholder across all ADRs and spec docs (real name TBD before launch).
  • Slashing refocused on bad edges: Added phantom blob announcement and rate manipulation as slashable offenses with cryptographic proof mechanisms (signed ProbeResponse/StreamResponse). Removed vault storage withholding slash (now reputation-only). Added signature fields to wire protocol messages (ADR 005).

Test plan

  • Grep for AUDIO, audio, track_id, manifest_hash, artist, album, bitrate, opus — should return zero hits
  • Verify all four slash offenses (corrupted delivery, phantom announcements, rate manipulation, double settlement) are consistently described across ADR 003, 004, 005, CDN spec, and tokenomics spec
  • Verify withholding only appears in non-slashable/rejected context
  • Verify ProbeResponse and StreamResponse signature fields are defined in ADR 005

🤖 Generated with Claude Code

…refocus slashing on bad edges

Make the protocol public-facing and content-agnostic by removing audio-specific
manifest format, renaming AUDIO token to TOKEN placeholder, and replacing all
audio/track/artist terminology with generic content delivery language. Refocus
slashing on edge node misbehavior: add phantom blob announcement and rate
manipulation as slashable offenses, remove vault storage withholding slash
(now reputation-only), and add cryptographic signature fields to ProbeResponse
and StreamResponse to enable on-chain fraud proofs.

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

@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 transitions the decentralized CDN from an audio-specific service to a general-purpose content delivery network. It updates terminology across ADRs and specifications, replacing "audio" and "tracks" with "content" and "blobs," and renames the native token to TOKEN. Key protocol enhancements include cryptographic signatures for probe and stream responses to enable slashing for rate manipulation and phantom announcements. Feedback focuses on resolving inconsistencies between documents regarding the implementation scope of slashable offenses and updating attack descriptions to align with the new architecture.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR updates the Superpowers docs/ADRs to describe a content-agnostic, BLAKE3-addressed CDN/storage network (instead of an audio-specific protocol), renames the native token placeholder to TOKEN, and refocuses slashing on provable “bad edge” behaviors (phantom announcements + rate manipulation) with signed wire messages.

Changes:

  • Generalize specs/ADRs from audio-specific concepts (tracks/manifests) to arbitrary blobs and application-defined metadata layers.
  • Replace AUDIO token references with a TOKEN placeholder across protocol/tokenomics/stablecoin docs.
  • Add/clarify slashable edge offenses (phantom blob announcements, rate manipulation) and introduce protocol signatures in ADR 005 to support proofs.

Reviewed changes

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

Show a summary per file
File Description
docs/superpowers/specs/2026-03-24-tokenomics.md Updates tokenomics narrative/examples for blob delivery and adds new slashable offenses/proof descriptions.
docs/superpowers/specs/2026-03-24-stablecoin-payments.md Renames token references to TOKEN and updates stablecoin-based buyback/burn narrative.
docs/superpowers/specs/2026-03-24-decentralized-storage-design.md Generalizes the storage design to arbitrary blobs and reframes client/provider flows accordingly.
docs/superpowers/specs/2026-03-24-decentralized-cdn.md Removes audio manifest format, makes the CDN content-agnostic, and updates slashing/offense descriptions.
adr/architecture.md Replaces AUDIO with TOKEN in the high-level architecture summary.
adr/005-protocol.md Adds signature fields to ProbeResponse/StreamResponse and documents their intended slashing use.
adr/004-tokenomics.md Renames AUDIO→TOKEN and refocuses edge slashing (removes vault withholding slashing).
adr/003-payments.md Aligns payment ADR with TOKEN placeholder and marks phantom/rate manipulation as slashable via signed messages.
adr/002-content-addressing.md Removes manifest-as-canonical-ID and states blob hash is the canonical identifier; adds content-agnostic framing.
Comments suppressed due to low confidence (1)

docs/superpowers/specs/2026-03-24-decentralized-cdn.md:468

  • Section 11.1 lists phantom announcements and rate manipulation as slashable, but Section 11.2 “Slash Evidence” only defines an on-chain claim flow for hash mismatch. Add the concrete evidence formats/verification steps for phantom announcements and rate manipulation here (e.g., signed ProbeResponse/StreamResponse and/or signed CacheAnnounce, time-window rules, and what’s verified on-chain vs off-chain) so the slashing design is complete and consistent with ADR 003/005.
### 11.2 Slash Evidence

A client that receives data failing the BLAKE3 hash check can submit a slash claim:


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

Comment thread adr/004-tokenomics.md Resolved
Comment thread adr/005-protocol.md Resolved
thiras and others added 7 commits March 29, 2026 00:57
…s config

Merge the three-role model (vault node, edge node, client) into two roles
(node, client). Origin backend (S3/R2) is now a deployment configuration
option, not a protocol-level distinction. All staked nodes share a single
staking tier, slashing ruleset, and registry entry type. Peer pulls via
cdn/peer/v1 are available between any staked nodes that opt in. Origin-backed
nodes may decline free peer pulls to avoid absorbing egress costs.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…/client/v1

Drop cdn/peer/v1 entirely. The protocol simplifies from 4 ALPNs to 3.
Every byte delivered in the network — whether client→node or node→node —
is paid via cdn/client/v1 with USDC payment channels. This eliminates
the free-rider problem, accepts_peer_pull complexity, and separate
PeerPullRequest/PeerPullResponse message types.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Defines envelope encryption (XChaCha20-Poly1305 per blob) with epoch key
rotation for subscription-gated access. Preserves global content-addressing
while enabling server-enforced revocation within 5-minute epochs. CDN
protocol remains unchanged — nodes only ever see ciphertext.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Defines device-bound offline leases that bundle K_blob values sealed to
platform keystore keys, with bounded TTL (30 days) and track limits (500).
Documents the explicit tradeoff: revocation speed degrades from 5 minutes
to lease TTL in exchange for offline availability. Covers device compromise
mitigations (attestation, watermarking, behavioral detection).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ng channel disputes

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… expand StreamResponse signature

- Rename minAudioOut → minTokenOut across stablecoin-payments spec and ADR 004
- Fix minimum stake from "100 USDC equivalent" to "1,000 TOKEN" in CDN spec (matches ADR 004)
- Align "verified delivery" → "verified streaming" to match iroh terminology
- Update storage withholding attack to CDN-model content withholding
- Promote rate manipulation slashing to PoC + Production (matches ADR 003/005)
- Expand StreamResponse signature to bind all security-relevant fields (ok, redirect, total_bytes)
- Align phantom announcement proof text with ADR 005 ok field

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Fold missing content from the four original spec files (2026-03-24) into
the existing ADRs, add a new ADR 008 for the reputation system, and
delete the now-redundant docs/superpowers/ directory.

- Add ADR 008 for reputation system (EWMA scoring, decay, clamping,
  cold-start, rate limiting, gossip protocol)
- Expand ADR 004 with token distribution, slash schedule, fee allocation,
  BuybackBurner, node unit economics, governance model, multi-chain bridging
- Expand ADR 003 with contract interfaces, client priority staking,
  decimal handling, stablecoin migration path
- Expand architecture.md with origin integration, cache behavior, crate
  structure, observability, glossary, non-goals, considered alternatives,
  and future work (federated indexers)
- Remove docs/superpowers/specs/ (all content consolidated into ADRs)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@thiras
thiras merged commit 4b9f10c into main Mar 29, 2026
@thiras
thiras deleted the docs/generalize-architecture-and-slash-bad-edges branch March 29, 2026 01:12
@altanoruc

Copy link
Copy Markdown
Contributor

hololo

Comment thread adr/000-language.md
## Context

We are building a decentralized CDN with three node roles: **vault nodes** that hold canonical content behind a hidden backend and seed it into the network, **edge nodes** that cache and deliver content close to clients, and **clients** that consume content. The network requires:
We are building a decentralized CDN with two participant roles: **nodes** (providers) that cache and deliver content to clients — some configured with an origin backend (S3/R2) as the canonical source for specific content — and **clients** that consume content. The network requires:

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.

@blecterov

thiras added a commit that referenced this pull request Apr 4, 2026
From the gemini-code-assist + Copilot review pass on commit 1ee0f75.
All 6 findings verified as valid; no pushback.

- ADR 018 Parameter Table: move the subSwapCount footnote definition
  below the table body. A footnote block between table rows breaks
  markdown table rendering — the "Execution activation" row was
  orphaned from the rest of the table. (gemini)
- ADR 018 Buyback execution: disambiguate "Router v2" naming. The
  Arbitrum mainnet router 0xEAedc32a51c510d35ebC11088fD5fF2b47aACF2E
  is labelled "Router v2" in Balancer's deployment registry, which
  is a contract versioning *within* Balancer V3 (second iteration
  of the V3 Router artifact), not a reference to Balancer V2. The
  ADR now calls this out explicitly to prevent operators from
  assuming "Router v2" means V2. (Copilot)
- ADR 016 MEV protection note: fix stale anchor link
  #buyback-execution-via-balancer → #buyback-execution-via-balancer-v3
  (the ADR 018 section heading was renamed in the V3 migration).
  (Copilot)
- ADR 016 MEV protection note: reconcile wording with ADR 018. The
  previous text said "recommended production path is to route
  buybacks through CoW Swap", which contradicted ADR 018's V3
  downgrade of CoW routing to a conditional add-on. Now says direct
  Router + TWAP is the primary production path and required
  fallback; CoW is a conditional add-on that requires operator
  verification of V3 solver routing. (Copilot)
- ADR 016 constructor deps row: clarify that the pool address is
  an initial convenience parameter (may be zero-address at deploy)
  and remains governance-mutable post-deploy via setPool(address).
  The previous wording implied the pool was a hard constructor
  requirement, which contradicted ADR 003's setPool setter. (Copilot)

PR description drift (Copilot finding #2) is addressed separately
via gh pr edit, not in this commit.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Apr 4, 2026
* docs: add ADR 018 liquidity strategy (Balancer 80/20 POL)

Reverses the implicit Uniswap V3 venue choice in prior ADRs in favour
of a Balancer V2 80/20 TOKEN/USDC weighted pool seeded as
Protocol-Owned Liquidity. Motivated by a USDC-poor treasury, the
small team's inability to operate concentrated-liquidity keeper
infrastructure, and an IL profile better aligned with the
TOKEN-upside thesis. Sweeps all Uniswap references in ADRs 004 and
016 to Balancer; adds setPoolId(bytes32) to IBuybackBurner in ADR 003
to keep the interface symmetric across venues.

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

* docs: fix ADR 018 review findings (IL math, TWAP semantics, interface dedup)

Corrections from PR #188 review:

- IL math: 80/20 at 2x price move is ~3.3%, not 1.3%; reduction vs
  50/50 is ~1.75x, not 4x. Added the derivation formula in ADR 018
  and propagated the corrected figures to the architecture.md summary.
- Removed the duplicated IBuybackBurner interface snippet from ADR 018;
  reference the canonical block in ADR 003 as the single source of
  truth, eliminating drift (the snippet had omitted setPoolId,
  setKeeper, keeper, and getAccumulatedFees).
- Rephrased the "requires no changes" claim so it no longer
  contradicts adding setPoolId(bytes32) in the same section. The core
  executeBuyback call pattern is unchanged; the interface is extended
  with one venue-symmetric setter.
- TWAP policy: minTokenOut is now the aggregate minimum across the
  full split request, with per-sub-swap guards derived from remaining
  required output / remaining sub-swaps (ceil-division). Eliminates
  the integer-truncation bug where naive minTokenOut / subSwapCount
  could allow aggregate output to fall below the caller's minimum.
- TWAP policy: removed the maxBuybackAmount / subSwapCount cap.
  ADR 016 defines maxBuybackAmount as a per-transaction MEV limit, so
  each sub-swap (being its own transaction) may be as large as
  maxBuybackAmount; dividing the cap would unnecessarily restrict fee
  throughput.
- Minor: "pool id" -> "poolId" in ADR 016 constructor deps row for
  naming consistency with ADR 018 and ADR 004.

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

* docs: address comprehensive review findings on ADR 018

From the pr-review-toolkit comment-analyzer pass on #188 (no critical
issues, 5 important, 6 suggestions). Applied:

Important:
- architecture.md ADR 018 index entry: scope the "1/4 USDC" claim
  with "for small trades" to match the qualifier already in ADR 018's
  body. A future reader skimming the index should not walk away
  thinking total pool depth is 4x cheaper.
- ADR 018 comparison table: add a footnote on the V3 $1M figure
  noting it is an order-of-magnitude comparison against a
  roughly-equivalent near-spot range, not an exact requirement (V3
  USDC-side requirements depend entirely on range width).
- ADR 018 Consequences: tighten the Balancer-incidents phrasing by
  pinning it to the ADR date (2026-04-04) and naming the affected
  pool families (ComposableStable, Boosted, linear wrappers) so the
  claim is auditable against future advisories.
- ADR 018 comparison table + Consequences: replace "Balancer is a
  primary CoW venue" with "a supported CoW Swap settlement venue"
  (structural property, not market-share claim) to avoid time-decay.

Suggestions:
- ADR 018 PoC seed sizing: document why the $5K-$20K range is wide
  and who picks the point estimate (governance at deployment, based
  on observed PoC traffic).
- ADR 018 "No withdraw path to an EOA" invariant: add the
  enforcement parenthetical (BPT custody at Timelock; Balancer has
  no protocol-level lockup).
- ADR 018 setPoolId future-V3 note: soften the forward commitment
  so a future V3-supplement ADR is free to reuse or introduce a
  distinct setter.
- ADR 018 subSwapCount=4: add rationale footnote (balance MEV vs
  keeper gas and ceilDiv rounding).
- ADR 018 "When to revisit": add quantitative placeholder triggers
  (USDC runway, LP fee / protocol fee ratio, execution failures,
  aggregator regression) so governance voters have concrete bars.
- ADR 018 IL-exposure consequence: cross-reference ADR 004 Token
  Distribution so worst-case IL can be sized quickly.

Skipped finding #5 (ADR 003 PoC note pointer chain) because ADR 004's
activation criteria paragraph is not changed by this PR, so there is
no redirect chain for a reader to follow.

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

* docs: migrate ADR 018 from Balancer V2 to Balancer V3

Triggered by the 2025-11-03 Balancer V2 Composable Stable Pool
exploit (~$125M across multiple chains). Root cause per Certora,
Trail of Bits, and OpenZeppelin post-mortems: a rounding-direction
bug in _upscale/_downscale latent since 2021, exploited via
EXACT_OUT + batchSwap to manipulate BPT pricing. V3's new Vault
architecture (transient accounting via unlock/settle, unified
scaling) is explicitly cited by Certora as mitigating this bug
class.

Standard V3 Weighted Pools are first-class, undeprecated, and
deployed on Arbitrum, so the core 80/20 POL decision (USDC
efficiency, IL alignment, zero-keeper posture) is preserved — those
are properties of weighted pools in general, not V2-specific. Only
the execution path, pool identifier, interface setter name, and
security framing change.

Mechanical changes:

- Swap entry point: Vault.swap(SingleSwap, FundManagement, limit,
  deadline) becomes Router.swapSingleTokenExactIn(pool, tokenIn,
  tokenOut, exactAmountIn, minAmountOut, deadline, wethIsEth,
  userData). The contract called is the V3 Router, not the Vault.

- Pool identifier: bytes32 poolId becomes address pool. V3 pools
  are identified by their contract address directly.

- IBuybackBurner setter rename: setPoolId(bytes32) becomes
  setPool(address). This PR is not merged, so this is a rename, not
  a breaking change.

- Approvals footgun: V3 contracts approve the Vault address for
  input-token pulls while calling the Router to execute the swap.
  Documented explicitly in ADR 018 deployment config, ADR 016
  constructor-deps row, and ADR 016 call table.

- Security disclaimer: rewritten to (a) cite the Nov 2025 V2
  exploit as realized history, (b) use it as affirmative
  justification for V3, (c) name the V3 pool taxonomy (Weighted,
  Stable, Stable Surge, Boosted, LBP, ReClamm, QuantAMM, Gyro,
  hooks-based) rather than the V2 families, (d) acknowledge V3's
  shorter track record as residual risk.

- CoW Swap claim downgrade: CoW routing is now described as a
  conditional add-on pending verification that CoW solvers route
  through the deployed V3 weighted pool. Balancer's V2-only
  aggregator fee-discount program was explicitly not extended to
  V3, and CoW's V3 coverage is still maturing. TWAP + minTokenOut
  guards are the primary MEV defense.

Arbitrum mainnet V3 addresses are referenced in ADR 018 for the
Vault (0xbA1333333333a1BA1108E8412f11850A5C319bA9) and Router v2
(0xEAedc32a51c510d35ebC11088fD5fF2b47aACF2E). Sepolia and other
testnet addresses MUST be pulled from
balancer-deployments/addresses/arbitrum-sepolia.json at deployment
time and are not hardcoded.

Things unchanged: IL math (~1.75x at 2x price move), USDC
efficiency (~1/4 vs 50/50), TWAP ceilDiv semantics,
maxBuybackAmount per-transaction cap, parameter numerics
(subSwapCount=4, subSwapMinBlockGap=10, slippageBps=200,
minBuybackAmount=100 USDC), activation criteria depth
requirements. These are all venue-version-agnostic properties of
weighted-pool curves or of the BuybackBurner MEV policy.

Files touched:
- adr/018-liquidity-strategy.md: primary rewrite
- adr/003-payments.md: IBuybackBurner interface (setPool rename)
- adr/004-tokenomics.md: 3 V2->V3 references
- adr/016-contract-interactions.md: 7 edits (constructor deps, 2
  mermaid diagrams, call table, reentrancy row)
- adr/architecture.md: ADR 018 index summary updated

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

* docs: address review findings on ADR 018 V3 migration

From the gemini-code-assist + Copilot review pass on commit 1ee0f75.
All 6 findings verified as valid; no pushback.

- ADR 018 Parameter Table: move the subSwapCount footnote definition
  below the table body. A footnote block between table rows breaks
  markdown table rendering — the "Execution activation" row was
  orphaned from the rest of the table. (gemini)
- ADR 018 Buyback execution: disambiguate "Router v2" naming. The
  Arbitrum mainnet router 0xEAedc32a51c510d35ebC11088fD5fF2b47aACF2E
  is labelled "Router v2" in Balancer's deployment registry, which
  is a contract versioning *within* Balancer V3 (second iteration
  of the V3 Router artifact), not a reference to Balancer V2. The
  ADR now calls this out explicitly to prevent operators from
  assuming "Router v2" means V2. (Copilot)
- ADR 016 MEV protection note: fix stale anchor link
  #buyback-execution-via-balancer → #buyback-execution-via-balancer-v3
  (the ADR 018 section heading was renamed in the V3 migration).
  (Copilot)
- ADR 016 MEV protection note: reconcile wording with ADR 018. The
  previous text said "recommended production path is to route
  buybacks through CoW Swap", which contradicted ADR 018's V3
  downgrade of CoW routing to a conditional add-on. Now says direct
  Router + TWAP is the primary production path and required
  fallback; CoW is a conditional add-on that requires operator
  verification of V3 solver routing. (Copilot)
- ADR 016 constructor deps row: clarify that the pool address is
  an initial convenience parameter (may be zero-address at deploy)
  and remains governance-mutable post-deploy via setPool(address).
  The previous wording implied the pool was a hard constructor
  requirement, which contradicted ADR 003's setPool setter. (Copilot)

PR description drift (Copilot finding #2) is addressed separately
via gh pr edit, not in this commit.

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

* docs: address pre-merge review findings on ADR 018 V3 integration

From the pr-review-toolkit review pass on 2946989. Zero critical
issues; 5 Important items applied as a single commit before merge.

1. Pool taxonomy accuracy (ADR 018 Consequences).
   "Boosted" is a composition pattern (weighted/stable pools with
   ERC-4626 wrapped tokens via BufferRouter), not a peer pool family
   — there is no BoostedPoolFactory. "QuantAMM" is a V3 hook-based
   partner family but is not deployed on Arbitrum per the
   balancer-deployments registry. Rewrote the taxonomy list to
   reflect the live Arbitrum registry and to caveat QuantAMM as
   "on other chains".

2. "Router v2" disambiguation cross-link (ADR 016).
   The disambiguation text in ADR 018 line 65 was not cross-linked
   from ADR 016. A deployment engineer landing in ADR 016 first and
   then searching the Balancer registry for 20250307-v3-router-v2
   could momentarily wonder whether "v2" means V2 protocol. Added a
   "Router naming note" to the BuybackBurner constructor deps row
   that both explains and cross-links to ADR 018.

3. Constructor vs setPool semantics in ADR 018.
   ADR 016 permits zero-address at deploy; ADR 018 did not mention
   this and did not state whether executeBuyback reverts on
   zero-address. Added one sentence stating constructor-time and
   setter-time semantics are equivalent, and that executeBuyback
   MUST revert if the configured pool is the zero address regardless
   of how it got there.

4. Actor clarification for Vault approval (ADR 018).
   Previous wording said "USDC approval is made to the V3 Vault
   address" in passive voice, leaving the actor ambiguous. The only
   workable interpretation is BuybackBurner self-approves the Vault
   during initialization — because the Vault pulls from the
   msg.sender of the Router call, which is BuybackBurner itself. A
   deployment script that approves the Vault from a multisig
   operator address would ship a broken contract. Rewrote the
   footgun bullet to explicitly name BuybackBurner as the actor,
   clarify that the approval is issued by contract code (not a
   runbook step), and explain why (Vault pulls from Router
   msg.sender).

5. Actor clarification cascade (ADR 003, ADR 016 call table).
   The same passive-voice "must be approved to the Vault" wording
   lived in ADR 003:516 and ADR 016:145. Updated both to name
   BuybackBurner as the self-approving actor, consistent with
   ADR 018.

Suggestions 6-11 (time-sensitive address framing, registry task-ID
citations, revisit trigger addition, post-mortem URLs, Vault/Router
glossary, WeightedPoolFactory task-ID pin) are deferred as
Suggestions-grade polish; none affect technical correctness or
merge-readiness.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request Apr 29, 2026
Audit flagged these as out-of-scope (pre-existing on origin/main), but
several land in files this PR already modifies — easier to fix here
than file a separate "ADR cross-ref hygiene" issue.

ADR 001 (gets new headings + anchor fixes):
- Promote three bolded paragraph leads to h5 headings so they generate
  GFM anchors that callers reference: `##### Registry cache`,
  `##### Gossip validation`, `##### Clock synchronization`.
- Fix em-dash anchor `005#gossip--rate-change-announcements` →
  `#gossip-rate-change-announcements` (line 154).
- Fix em-dash anchor `014#1-ed25519-signature-verification--dual-key-slash-signatures`
  → `#1-ed25519-signature-verification-dual-key-slash-signatures` (405).
- Fix self-anchor `#future-work-scaling-content-discovery` →
  `#future-work-scaling-content-discovery-resolved-by-adr-022` (187)
  to match the actual heading "Future Work: Scaling Content Discovery
  (Resolved by ADR 022)".

ADR 004:
- Two refs to `003#fee-calculation-on-disputed-closes` →
  `#fee-routing-on-disputed-closes` (the heading was renamed in this
  PR; ADR 004's cross-refs needed the same rename).

ADR 014:
- `005#gossip--rate-change-announcements` → `#gossip-rate-change-announcements`
  (em-dash collapse).

ADR 018:
- `016#2-deployment-order-and-initialization` →
  `#2-deployment-order-and-initialization-dependencies` (heading is
  "Deployment Order and Initialization Dependencies").

ADR 019 (5 anchors):
- `001#clock-synchronization` → `001#clock-synchronization` (now
  resolves via the new h5 heading in ADR 001).
- `001#registry-cache` / `001#gossip-validation` → resolve via the new
  h5 headings in ADR 001.
- `003#startup` → `003#rate-bounds-refresh` (the parent section that
  contains the startup-rate-bounds-check content).
- `011#startup-sync` → `011#polling` (the section that contains the
  initial-sync-on-startup content).
- `003#nodeid-binding-and-rebinding` → `003#nodeid-to-ethereum-binding`
  (the parent h2 covering both binding and rebinding).

ADR 020:
- `001#gossip-validation` → resolves via the new h5 heading in ADR 001.
- `019#phase-5--accepting-paid-delivery` →
  `#phase-5-accepting-paid-delivery` (em-dash collapse).

architecture.md:
- `#future-work-search--discovery` → `#future-work-search-discovery`
  (em-dash collapse for the "Future Work: Search & Discovery" heading).

Programmatic anchor check: 0 broken anchors remain in PR-touched files.
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 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
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]>
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]>
alpergundogdu added a commit that referenced this pull request May 5, 2026
Three medium-priority readability comments from the post-link-fix Gemini
review. All address the same shape — a single sentence stacking two or
three clauses joined by em-dashes or semicolons — and split into shorter
sentences without changing technical content:

- ADR 001 §Consequences (positive #2): the origin-role description ran
  three concepts together (DAO-governance / registered vs default-open /
  bootstrap window). Now three sentences plus a See: line.
- ADR 003 §Withholding (minimum-redundancy bullet): replace the
  semicolon-joined "owners propose; governance ratifies" with two
  sentences.
- ADR 011 §Decision (positive-authority bullet): same propose/ratify
  pair, same split.

No semantic change. All anchor links preserved.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request May 5, 2026
Three medium-priority readability comments from the post-link-fix Gemini
review. All address the same shape — a single sentence stacking two or
three clauses joined by em-dashes or semicolons — and split into shorter
sentences without changing technical content:

- ADR 001 §Consequences (positive #2): the origin-role description ran
  three concepts together (DAO-governance / registered vs default-open /
  bootstrap window). Now three sentences plus a See: line.
- ADR 003 §Withholding (minimum-redundancy bullet): replace the
  semicolon-joined "owners propose; governance ratifies" with two
  sentences.
- ADR 011 §Decision (positive-authority bullet): same propose/ratify
  pair, same split.

No semantic change. All anchor links preserved.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request May 5, 2026
* docs(adr): add DAO-governed origin assignment authority

Resolves #189. Distributes the design across 9 existing draft ADRs (no
new ADR) per planning direction:

- ADR 002: publisher/namespace identity primitive + IPublisherRegistry
- ADR 011: Origin Assignment Authority section + IOriginAssignment;
  DAO ratifies publisher-proposed operator sets via the standard
  timelock path
- ADR 005: ProbeResponse extended with is_origin field; phantom-origin
  slashing for false origin claims in registered namespaces
- ADR 016: PublisherRegistry and OriginAssignment added to inventory,
  deployment order, call graph, role matrix, and reentrancy analysis
- ADR 009: new governable parameters with safety bounds
  (min-redundancy, assignment timelock, namespace caps, transfer
  timelock) and rationale
- ADR 022: resolves "publisher" terminology collision; documents
  origin-only discovery via OriginAssignment.getOrigins
- ADR 001: rewrites the unconditional permissionless-origin claim;
  cache role permissionless, origin role DAO-gated for registered
  namespaces
- ADR 003: rewrites multi-origin redundancy as DAO-supervised via the
  OriginAssignment min-redundancy invariant
- architecture.md: high-level overview reflects the role split

The default-open namespace (namespaceId == 0) preserves the
permissionless / long-tail story for unregistered content.

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

* docs(adr): address PR #390 review feedback

- Phantom-origin slashing: add namespaceOfAt and isAuthorizedOriginAt
  historical views with checkpoint storage; SlashJudge evaluates against
  on-chain state at the response timestamp, not current state. Bounded
  by Max evidence age (ADR 009).
- Replace cross-contract removeAllAssignments (unbounded gas) with
  runtime-check pattern: blacklisted operators are treated as
  unauthorized at probe / peer-table / slashing time regardless of
  stale OriginAssignment state. Permissionless pruneBlacklistedAssignment
  for lazy storage cleanup.
- Reorder ADR 016 deployment: PublisherRegistry → OriginAssignment →
  ContentBlacklist (resolves circular dependency on construction).
- Origin-only discovery in ADR 022: DHT remains primary; on-chain
  OriginAssignment.getOrigins is fallback with operator → NodeId
  mapping via StakingRegistry.getActiveNodes.
- Add operator-uniqueness validation to proposeAssignment (prevents
  bypassing minRedundancy via duplicates).
- Add cross-parameter invariant 1 ≤ minRedundancy ≤ maxOriginsPerNamespace
  to ADR 009.
- Add StakingRegistry.isActive to ADR 016 proposeAssignment guards
  (table now matches the prose and ADR 011).
- Update ADR 011 ADRs Affected re: ADR 022 — DHT STORE remains
  permissionless; origin authorization enforced at probe time.
- Update ADR 013 v1 baseline to include is_origin in ProbeResponse
  signed-fields table.

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

* docs(adr): extend DAO origin authority to namespace 0

The default-open namespace was carved out of OriginAssignment as a
permissionless escape hatch for unclaimed content, leaving phantom-origin
claims for default-open hashes non-slashable, no DAO-accountable party
for takedown, and no redundancy floor for long-tail availability.

Extends OriginAssignment with a single global DAO-maintained allow-list
keyed by namespaceId == 0, reusing the existing per-namespace storage and
checkpoint history. Lifecycle is single-step governance under the
standard 48h Governor timelock — no propose/ratify split, no second
timelock parameter. Bootstrap rule: permissive (any active staker
authorized) until the first non-empty activation flips
defaultOpenAllowlistActive permanently and emits
DefaultOpenAllowlistActivated. New parameters defaultOpenMinRedundancy
(5–500, default 10) and defaultOpenMaxOrigins (20–500, default 100) with
cross-parameter invariants enforced at the contract layer. Probe-time
and slashing rules collapse to a uniform branch — no namespaceId == 0
special case downstream; isAuthorizedOriginAt(0, op, t) returns true for
t < defaultOpenActivatedAt so pre-activation probes are not retroactively
slashable.

Updates ADRs 001, 002, 005, 009, 011, 016, 022, architecture.md, and the
PoC/production seams appendix to remove the carve-out language and point
at the new ADR 011 §Default-open allow-list.

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

* docs(adr): address PR #390 review feedback (round 2)

Resolves Copilot inline comments on commit 52119cc:

- ADR 011 §Decision and §Lifecycle, ADR 011 Consequences: replace
  "atomically removes" / "atomically evicted" / "no stale entries"
  language with the actual model (runtime check is the security primitive;
  storage cleanup via pruneBlacklistedAssignment is lazy and permissionless).
- ADR 011 §Hash Evasion: fix pruneBlacklistedAssignments → singular
  pruneBlacklistedAssignment to match the interface.
- ADR 011 IOriginAssignment + ADR 016 GOVERNANCE_ROLE row + reentrancy
  table: add the missing setMaxOriginsPerNamespace setter (ADR 009 already
  documents the parameter as governable).
- ADR 003 §Withholding mitigations: scope the "any staked operator may
  serve" line to the default-open bootstrap window; post-activation,
  withholding mitigation is the allow-list's redundancy floor.
- ADR 016 deployment dependency graph: drop stale CB → OA edge
  (ContentBlacklist no longer cross-calls OriginAssignment).
- ADR 016 OriginAssignment construction notes: pruneBlacklistedAssignment
  reverts (not no-op) until the ContentBlacklist address is bound,
  matching the post-deploy initialization section.

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

* docs(adr-011): tighten default-open allow-list section

Three reviewer agents flagged the same redundancies after round 2:
- bootstrap rule restated 4× with subtle wording variations
- runtime-check + lazy-prune pattern explained in 4 places
- Solidity comment block re-stated the prose Lifecycle below it
- "Unassigned" subsection was nested under "Default-open allow-list"
- "Permissionless property" paragraph hedged twice over

Compress to a single canonical Bootstrap subsection; replace later
restatements with cross-references. Trim the setDefaultOpenAllowlist
interface comment to a one-line pointer. Promote the unassigned-namespaces
paragraph to its own §Unassigned namespaces section. Tighten the Decision
bullet, Lifecycle step 4, the Permissionless property paragraph, and the
Consequences bullet to point at §Interaction with ContentBlacklist and
§Default-open allow-list rather than re-explain.

No semantic change — same model, fewer words.

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

* docs(adr): link cross-ADR references in 002 and 011

Closes the link-hygiene gaps surfaced by the issue #189 reconstructability
audit. Two starting ADRs (002 and 011) named other ADRs in plain text where
the convention elsewhere in the same files uses [ADR NNN](NNN-name.md):

- ADR 002 §"Why this lives in ADR 002": the four ADRs named as referrers
  (011, 016, 005, 022) are now anchored links, with 011 and 005 pointing
  at the specific subsections (#origin-assignment-authority and the
  cdn/probe/v1 anchor) that justify ADR 002's role.
- ADR 011 §"ADRs Affected": the seven plain-bold entries (001, 002, 003,
  005, 009, 016, 022) now match the format already used for the ADR 026
  entry in the same list. ADR 002 deep-links to
  #publisher-identity-and-namespaces; ADR 005 deep-links to
  #cdnprobev1--latency-probe (matching the existing intra-document
  reference at the §Interaction with ContentBlacklist bullet).

No semantic change.

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

* docs(adr): split dense sentences flagged by Gemini review

Three medium-priority readability comments from the post-link-fix Gemini
review. All address the same shape — a single sentence stacking two or
three clauses joined by em-dashes or semicolons — and split into shorter
sentences without changing technical content:

- ADR 001 §Consequences (positive #2): the origin-role description ran
  three concepts together (DAO-governance / registered vs default-open /
  bootstrap window). Now three sentences plus a See: line.
- ADR 003 §Withholding (minimum-redundancy bullet): replace the
  semicolon-joined "owners propose; governance ratifies" with two
  sentences.
- ADR 011 §Decision (positive-authority bullet): same propose/ratify
  pair, same split.

No semantic change. All anchor links preserved.

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

* docs(adr): flip from single-claim to multi-claim content registration

The previous one-namespace-per-hash + first-write-wins rule created two
failure modes the PR did not address:

- Stranded hashes: a namespace owner who lost keys, abandoned, or refused
  cooperation stranded every hash they had claimed, with no escape valve
  for another publisher or the DAO. The lifecycle (revocation, transfer)
  all required the current owner.
- Squatting: any party could pre-claim popular hashes (e.g. a future
  release ISO's BLAKE3) and block the legitimate publisher.

ADR 002 forward-referenced "ADR 016 for the dispute resolution rules and
the consequences if a second claim is rejected"; ADR 016 only said
revert(). The cross-reference promised more than it delivered.

Drop the one-claim rule. Allow any non-zero namespace to claim any hash
independently; reverts only on duplicate by the same namespace
(idempotency). The set of operators authorized to serve the hash as
origin is the union across claiming namespaces, plus the default-open
allow-list when the claim set is empty.

Mechanical changes:

- ADR 002 § Default-open namespace + new § Multi-claim semantics:
  reframe claim from "authorial ownership" (never load-bearing) to
  "registration as a responsible origin authority". `namespaceOf` and
  `namespaceOfAt` return `uint256[]` instead of scalar; `claimContent`
  no longer reverts on cross-namespace duplicates. Storage becomes a
  per-hash append-only `(namespaceId, claimedAt)` array.
- ADR 011 § Historical state and slashing evidence: `SlashJudge`
  predicate becomes an OR-search over the claiming-namespace set at
  the response timestamp. The `ProbeResponse` schema is unchanged —
  the signer asserts authorization as a property of the world; the
  protocol verifies it holds against any one claiming authority. No
  `claimed_namespace` field added.
- ADR 016 § PublisherRegistry: drop "first-write-wins across non-zero
  namespaces" guard from `claimContent` row.

Untouched: ContentBlacklist (hash-keyed, namespace-agnostic),
OriginAssignment.proposeAssignment / activateAssignment / revokeAssignment
(per-namespace, agnostic to how many namespaces claim a given hash),
min-redundancy floor (per-namespace at activation; effective network-wide
redundancy is now the sum across claiming namespaces — strictly better),
default-open allow-list, ADR 005 ProbeResponse schema, ADR 003 § Content
withholding, ADR 009 governance parameters.

What we lose: the framing of an on-chain claim as "the official publisher
of this content." That framing was never load-bearing on any protocol
primitive — slashing, takedown, and probe verification are hash-keyed and
operator-keyed, never publisher-keyed.

What we gain:

- Squatting becomes pointless: claiming a hash you do not intend to serve
  gates nothing.
- Stranded hashes recover automatically: another publisher just claims
  independently and starts serving.
- Per-namespace effective redundancy floors sum network-wide.
- Design matches reality: Microsoft, Cloudflare, GitHub Releases, and
  mirrors all legitimately serve the same bytes with no need for the
  protocol to pretend one of them is the sole author.

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

* docs(adr): address Gemini review on multi-claim amendment

Five medium-priority Gemini comments on the multi-claim flip — two were
direct fallout from the type change (`namespaceOf` now returns an array),
three were pre-existing nits worth fixing in the same pass.

- ADR 005 § cdn/probe/v1 (`is_origin` rules and SlashJudge clause): the
  pseudo-code calls `OriginAssignment.isAuthorizedOrigin(namespaceOf(hash),
  operator)` and `…isAuthorizedOriginAt(namespaceOfAt(hash, t), operator,
  t)` — both type-mismatch after the array return. Replaced with the
  ∃-quantifier over the claiming set, with default-open as the
  empty-set fallback. Pointed the SlashJudge clause at ADR 011 §
  Historical state and slashing evidence rather than restate the
  predicate inline.
- ADR 011 § Contract: OriginAssignment: added the missing
  `setContentBlacklist(address)` interface method. ADR 016 already
  references it as a post-deploy initialization step; the interface
  block was the orphan.
- ADR 011 § Historical state and slashing evidence (pruning paragraph):
  spell out the two invariants pruning must respect — never prune the
  currently-active checkpoint (`revokedAt == type(uint64).max`); always
  retain the most recent checkpoint whose `activatedAt` precedes the
  start of the current evidence window so binary-search lookups at the
  window's lower edge stay valid.
- ADR 016 § Off-Chain Read API: `namespaceOf` row updated to
  `returns (uint256[])` with a one-line pointer to ADR 002 § Multi-claim
  semantics.
- ADR 016 § Role matrix (Governor → OriginAssignment row):
  `activateAssignment` takes only `namespaceId` (operators come from the
  pending proposal); add the new `setContentBlacklist(address)` setter.

No semantic change beyond the pruning invariants (which were implied by
the threat model but not explicitly stated).

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

* docs(adr): drop is_origin and phantom-origin slashing

Folding the unwind described in #399 (closed) directly into this PR per
team direction — clean up at introduction time rather than land then
remove. Confirmed during this work that no Rust code or Solidity
contracts reference these symbols on main, so the change is ADR-only.

Origin status was being signaled in two redundant places: on the wire
via `ProbeResponse.is_origin`, and on chain via `OriginAssignment`. The
on-chain view is authoritative; the wire bit is just a cached
restatement. Phantom-origin slashing is the offense category that exists
to deter lying about that wire bit — i.e., it only exists *because*
is_origin exists. Remove the wire bit and the attack surface and the
slashing category disappear together.

What origin status was actually controlling at the protocol layer:

- Routing / discovery: handled by `OriginAssignment.getOrigins(ns)`,
  which clients and watchtowers query off-chain.
- Payment economics: same `rate_per_mb` for origins and caches; nothing
  to differentiate.
- Takedown compliance: `ContentBlacklist` is hash-keyed; serving a
  blacklisted hash is slashable for any node, origin or cache.
- Min-redundancy: enforced contract-side at activation; probe-time
  signaling is unrelated.
- BLAKE3 verification: bytes are bytes; clients verify the hash
  regardless of who served them.

So the wire bit was load-bearing on nothing except itself.

Mechanical changes:

- ADR 005 § cdn/probe/v1: drop `is_origin` from `ProbeResponse`, drop
  the `is_origin` rules paragraph, drop `is_origin` from the signature
  field set, drop the phantom-origin entry from the slashing-categories
  enumeration (now 2 categories: phantom-announcement, rate-manipulation).
- ADR 011 § Origin Assignment Authority: drop `isAuthorizedOriginAt`
  from `IOriginAssignment`. Drop § Historical state and slashing
  evidence in full — the OR-search predicate, checkpoint storage,
  pruning invariants, and re-authorization handling were all in service
  of phantom-origin SlashJudge; none has another consumer.
- ADR 011 § Interaction with ContentBlacklist: drop probe-time /
  requester-side / SlashJudge bullets. Replace with off-chain
  cross-reference pattern: callers of `getOrigins(ns)` filter against
  `ContentBlacklist.isOriginBlacklisted` themselves.
- ADR 011 lifecycle step 3 + Default-open intro + ADRs Affected (ADR 005):
  reframe to drop probe-time signaling.
- ADR 002 § Multi-claim semantics: drop SlashJudge OR-search reference;
  trim to the routing/discovery framing.
- ADR 002 IPublisherRegistry: drop `namespaceOfAt(hash, t)` historical
  view (only consumer was SlashJudge). Storage simplifies from
  per-hash append-only `(namespaceId, claimedAt)` array to per-hash
  `uint256[]` set; ordering / timestamps no longer load-bearing.
- ADR 002 "Why this lives in ADR 002": drop ADR 005 link (no probe-time
  enforcement to cross-reference).
- ADR 016 § Off-Chain Read API + § Reentrancy table + storage notes:
  drop `isAuthorizedOriginAt` rows; simplify storage to current-state
  `EnumerableSet` only (no checkpoint history, no GC pruning).
- ADR 013 § Signed-fields table: drop `is_origin` from `ProbeResponse`
  signed-field set (this matches the new ADR 005 baseline; the v1 ALPN
  is unchanged because the field never shipped on a deployed network).
- ADR 022 § Origin discovery + ADRs Affected (ADR 011): reframe — no
  probe-time `is_origin` validation; clients intersect probed peers
  against the off-chain `getOrigins(ns)` set.
- ADR architecture.md § Origin Integration: drop "advertise itself as
  origin" framing; origin status surfaces via `getOrigins(ns)` only.
- ADR appendix-poc-production-seams.md § Default-open allow-list row:
  drop "rejects is_origin: true claims (slashable phantom-origin)";
  reframe to "off-chain consumers consult getOrigins(0) to filter
  unauthorized origins".

What stays untouched: ContentBlacklist (hash-keyed, never cared about
origin status), OriginAssignment.proposeAssignment / activateAssignment
/ revokeAssignment (per-namespace, namespace-agnostic to claims),
min-redundancy invariant (per-namespace at activation), default-open
allow-list, governable parameters, all publisher and DAO workflows.
PublisherRegistry registration and namespace lifecycle are unchanged.

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

* docs(adr): address Gemini readability nits on the unwind

Two medium-priority comments on the is_origin unwind, both stylistic:

- ADR 011 § Hash Evasion (origin-blacklisting bullet): the blacklisted-
  origin runtime-removal description still listed "probes, peer-table
  validation, slashing evaluation" — a stale enumeration after the
  unwind (probe-time origin check no longer exists; phantom-origin
  slashing no longer exists). Trim to "Effectively removed at runtime;
  storage cleanup is lazy and permissionless via
  pruneBlacklistedAssignment", with the cross-reference to § Interaction
  with ContentBlacklist preserved.
- ADR 016 § Contract Inventory: row 10 (OriginAssignment) had a single
  table cell carrying constructor args + default-open bootstrap +
  governance entry points + ContentBlacklist binding rationale.
  Trimmed the cell to constructor args plus a one-line pointer; moved
  the bootstrap / governance / binding detail into a new
  § OriginAssignment construction notes subsection between the table
  and § Post-Deployment Initialization. Same content, restructured for
  table readability.

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

* docs(adr-012, adr-019): align with new on-chain origin authority

Two ADRs not previously touched by this PR were left inconsistent with
the new OriginAssignment surface introduced in ADR 011:

- ADR 012 § Eclipse Attack Mitigation: the rejection of "Option A —
  Origin-backed nodes as fallback" was framed as a flat refusal to
  expose origin status on-chain, which now reads as a contradiction
  with `OriginAssignment.getOrigins(ns)`. Reframe to reject origin
  status as a *trust* mechanism (still true) while acknowledging the
  new on-chain primitive as an *availability commitment* (publisher's
  min-redundancy commitment, not a node-quality ranking). The original
  design invariant — "no external origin URL is ever exposed" — is
  preserved: `OriginAssignment` records only operator Ethereum
  addresses, never backend URLs. Clients still verify content via
  BLAKE3 and score peers via reputation / probes regardless of
  authorized-origin status.
- ADR 019 § Phase 1 Step 6: the existing wording said "the protocol
  treats all staked nodes identically." Post-PR-390 false — recognised
  origin status for registered namespaces requires
  `OriginAssignment.proposeAssignment` (publisher) and DAO ratification
  via timelock; for default-open content it requires the DAO-maintained
  allow-list (subject to the bootstrap rule). Reword Step 6 to keep the
  cache-only-is-permissionless framing and add a paragraph spelling
  out the on-chain authorisation flow for operators who want origin
  status, with the explicit note that it runs on the publisher's /
  governance's timeline rather than the operator's onboarding flow.

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

* docs(adr): add StakingRegistry.nodeIdOf view for origin discovery

Surfaced during a walkthrough of the on-chain "given a hash, find an
authorized origin NodeId" path. The operator-address → NodeId step was
the only one in the chain that required paginating getActiveNodes;
every other lookup (namespaceOf, getOrigins, isOriginBlacklisted) is
already O(1) per call. Adding a typed per-operator view collapses that
step to a single read.

Storage already exists — addressToNodeId is a public mapping populated
atomically inside registerNode (ADR 001 § Constraints, ADR 003 § NodeId-
to-Ethereum Binding) — so this is purely a typed-view addition that
also bundles the active flag to save a second read against
nodes[nodeId].active.

- adr/003-payments.md: declare nodeIdOf alongside the existing
  StakingRegistry storage block, with a comment pointing at the two
  consumers (ADR 016 read API, ADR 022 origin discovery).
- adr/016-contract-interactions.md: row added to § Off-Chain Read API
  table noting the per-operator binding+activity lookup as the
  canonical step in the on-chain origin-discovery fallback.
- adr/022-content-discovery.md: § Origin discovery fallback now points
  at nodeIdOf for per-operator NodeId resolution, replacing the bulk
  paginated getActiveNodes path. Notes that the chain of reads
  (namespaceOf → getOrigins → nodeIdOf → isOriginBlacklisted) is
  batchable via the standard Multicall3 aggregator on Arbitrum without
  prescribing the implementation, since batching is a client-library
  concern that does not affect protocol semantics.

Strict 1:1 binding (ADR 001 § Constraints line 340) means a single-
valued return is correct as-is; if the design ever loosens to N:1
(multiple NodeIds per stake — currently rejected), this view would
need to widen to bytes32[] memory and the OriginAssignment min-
redundancy story would need rework.

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

* docs(adr): resolve remaining PR 390 review items

Co-authored-by: Copilot <[email protected]>

* docs(adr): drop PublisherRegistry PoC note from ADR 002

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Alper Gundogdu <[email protected]>
Co-authored-by: Copilot <[email protected]>
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 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]>
yigitdot added a commit that referenced this pull request Sep 27, 2026
…s, fixture hardening

- The leg-2 lane pays SEEDER #2, not SEEDER #1, so it cannot show a #1
  cumulative carried over; say what it proves (the repointed node buys and
  settles on #2 at the leg-2 price) and let the store assertions carry the
  guard.
- Wait for the buyer bootstrap (decdn_buyer_wallet_usdc) after every
  restart before reading boot state, so the negative checks cannot pass on
  a bootstrap that has not run.
- Propagate admin RPC and address-parse errors from polls; wait on metered
  bytes / watermark >= expected before asserting the exact figure; price
  with rate::min_payment.
- redeploy_payment_pool copies the snapshot pool's and router's parameters
  at runtime and reads the new pool's wiring back.
- NodeFixture: stop() propagates a failed kill; the log tee records a
  capture failure and ends a cut-off line; strip_ansi drops a lone ESC
  alone; wait_for_log_line timeouts carry the log tail.
- Doc fixes: timelock role, HEAVY tier list, client approval.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thiras pushed a commit that referenced this pull request Sep 27, 2026
…deployments (#2182)

* test(e2e): cover the PaymentPool redeploy collision against two live deployments (#2088)

Pool ids carry no contract address, so a node's first pool on a
redeployed PaymentPool has the same id as its first pool on the old
one. Pin the buyer-side guard against two real deployments: a node
repointed at an empty redeploy drops its stale row (logged naming the
old deployment as foreign_payment_pool), opens nothing at boot, and
opens fresh on its first miss; a node whose key already owns the
reissued id on the redeploy adopts it with the new deposit and no
lanes, and pays the redeploy only for the bytes it delivers.

Fixture support: ChainFixture::redeploy_payment_pool deploys a second
PaymentPool behind a fresh FeeRouter (the snapshot router's role table
is frozen); NodeFixture gains a PaymentPool override at launch,
repoint_payment_pool, stop, and a daemon log tee with log_line /
wait_for_log_line; ClientFixture can pay through a chosen PaymentPool.

The redeploy leg is served by a fresh seeder: the seller-side lane store
has the same collision, tracked in #2181.

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

* test(e2e): address #2182 review — bootstrap barrier, honest assertions, fixture hardening

- The leg-2 lane pays SEEDER #2, not SEEDER #1, so it cannot show a #1
  cumulative carried over; say what it proves (the repointed node buys and
  settles on #2 at the leg-2 price) and let the store assertions carry the
  guard.
- Wait for the buyer bootstrap (decdn_buyer_wallet_usdc) after every
  restart before reading boot state, so the negative checks cannot pass on
  a bootstrap that has not run.
- Propagate admin RPC and address-parse errors from polls; wait on metered
  bytes / watermark >= expected before asserting the exact figure; price
  with rate::min_payment.
- redeploy_payment_pool copies the snapshot pool's and router's parameters
  at runtime and reads the new pool's wiring back.
- NodeFixture: stop() propagates a failed kill; the log tee records a
  capture failure and ends a cut-off line; strip_ansi drops a lone ESC
  alone; wait_for_log_line timeouts carry the log tail.
- Doc fixes: timelock role, HEAVY tier list, client approval.

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

---------

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

3 participants