Skip to content

Add devcontainer for secure Claude Code sessions - #1

Merged
thiras merged 3 commits into
mainfrom
feat/devcontainer-setup
Mar 26, 2026
Merged

thiras merged 3 commits into
mainfrom
feat/devcontainer-setup

Conversation

@thiras

@thiras thiras commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Adds .devcontainer/ setup (Dockerfile, devcontainer.json, init-firewall.sh) based on the Claude Code reference implementation, customized for this Rust/iroh project
  • Includes Rust stable toolchain, Claude Code CLI, default-deny firewall whitelisting GitHub, crates.io, Anthropic APIs, and Arbitrum Sepolia RPCs
  • Adds README with setup instructions for Windows, macOS, and Linux, covering prerequisites, authentication, firewall, unattended mode, and troubleshooting

Test plan

  • Run docker build -f .devcontainer/Dockerfile .devcontainer/ to verify image builds
  • Open in VS Code and "Reopen in Container" — verify container starts
  • Verify claude --version, rustc --version, cargo --version work inside container
  • Verify ANTHROPIC_API_KEY is forwarded from host
  • Verify firewall blocks curl https://example.com and allows curl https://api.github.com/zen
  • Test on Windows (WSL2), macOS, and Linux if possible

🤖 Generated with Claude Code

Adds a devcontainer setup based on the Claude Code reference implementation,
customized for this Rust/iroh project. Includes Rust stable toolchain,
Claude Code CLI, default-deny firewall with whitelisted domains (GitHub,
crates.io, Anthropic, Arbitrum Sepolia RPCs), and persistent volumes for
shell history, Claude config, and cargo registry. README documents setup
for Windows, macOS, and Linux.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings March 25, 2026 22:02
@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request establishes a robust and secure development environment using VS Code Dev Containers. The primary goal is to provide a consistent, isolated, and secure workspace for all contributors, particularly for integrating and safely utilizing the Claude Code AI assistant. By encapsulating the development setup within a container and implementing a strict firewall, it ensures that external interactions are controlled, fostering a more reliable and secure coding workflow.

Highlights

  • Devcontainer Setup: Introduced a comprehensive .devcontainer/ configuration, including a Dockerfile, devcontainer.json, and a firewall initialization script, to standardize the development environment.
  • Secure Environment: Implemented a default-deny iptables firewall (init-firewall.sh) within the devcontainer, whitelisting only essential domains like GitHub, crates.io, Anthropic APIs, and Arbitrum Sepolia RPCs, enhancing security for Claude Code sessions.
  • Development Tooling: Configured the devcontainer with a Rust stable toolchain (including rust-analyzer, cargo-watch, cargo-nextest), Claude Code CLI, git-delta, zsh with Powerlevel10k, and other essential development utilities.
  • Comprehensive Documentation: Added a detailed README.md that covers prerequisites, quick start instructions, authentication, unattended Claude Code usage, firewall details, persistent volumes, customization, and troubleshooting for the devcontainer.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@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 introduces a new Dev Container setup for the "Storage Layer Dev" environment, including a Dockerfile, devcontainer.json, and a firewall initialization script. The Dockerfile sets up various development tools, the Rust toolchain, git-delta, and the Claude Code CLI. The devcontainer.json configures VS Code extensions, environment variables, and persistent volumes, with a postStartCommand to activate the firewall. The init-firewall.sh script establishes a default-deny iptables firewall, whitelisting specific domains and services. The README.md is updated to reflect these changes, providing comprehensive documentation for the new setup.

Feedback includes critical issues such as incorrect Zsh history persistence configuration in the Dockerfile and the use of a deprecated waitFor property in devcontainer.json, which should be replaced with postCreateCommand for firewall setup to ensure immediate security. High-severity concerns were raised regarding the firewall script's assumption of a /24 host network subnet, which could lead to security vulnerabilities or functional issues, and its reliance on a hardcoded Docker DNS IP. Additionally, there are suggestions to remove redundant sudo commands and unnecessary $HOME/.cargo/env sourcing in the Dockerfile, and to consider tightening the default outbound SSH firewall rule for enhanced security.

Comment thread .devcontainer/Dockerfile Resolved
Comment thread .devcontainer/devcontainer.json Resolved
Comment thread .devcontainer/init-firewall.sh Resolved
Comment thread .devcontainer/Dockerfile Resolved
Comment thread .devcontainer/Dockerfile Resolved
Comment thread .devcontainer/init-firewall.sh Resolved
Comment thread .devcontainer/init-firewall.sh Resolved

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

Adds a VS Code devcontainer environment intended to enable “secure Claude Code sessions” for this Rust/iroh project, including a default-deny container firewall and setup documentation.

Changes:

  • Added .devcontainer/ with a Dockerfile, devcontainer configuration, and firewall initialization script.
  • Added repository README.md documenting setup, authentication forwarding, and firewall behavior.
  • Added .gitignore entries to prevent committing local .env files.

Reviewed changes

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

Show a summary per file
File Description
README.md New setup + security/firewall documentation for the devcontainer workflow
.gitignore Ignore .env and .env.* files
.devcontainer/init-firewall.sh Firewall bootstrap: iptables/ipset allowlist + verification curls
.devcontainer/devcontainer.json Devcontainer definition (build args, capabilities, mounts, postStartCommand)
.devcontainer/Dockerfile Builds the devcontainer image (tools, Rust, Claude Code CLI, firewall script)

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

Comment thread .devcontainer/devcontainer.json Resolved
Comment thread .devcontainer/Dockerfile Resolved
Comment thread .devcontainer/init-firewall.sh Resolved
Comment thread .devcontainer/init-firewall.sh Resolved
Comment thread .devcontainer/init-firewall.sh Resolved
Comment thread .devcontainer/init-firewall.sh Resolved
Comment thread README.md Resolved
Comment thread .devcontainer/init-firewall.sh Resolved
Comment thread .devcontainer/devcontainer.json Resolved
thiras and others added 2 commits March 26, 2026 01:29
Firewall hardening:
- Reset iptables policies to ACCEPT before network operations so re-runs
  don't deadlock when previous DROP policies block curl/dig
- Restrict DNS to Docker's embedded resolver (127.0.0.11) to prevent
  DNS tunneling via arbitrary DNS servers
- Restrict SSH (port 22) to whitelisted IPs only (GitHub git ranges)
  instead of allowing SSH to any destination
- Filter IPv6 CIDRs from GitHub Meta API to prevent aggregate/regex errors
- Use exact host gateway IP instead of hardcoded /24 subnet

Other fixes:
- Fix zsh history persistence: use HISTFILE with .zsh_history and
  zsh-native APPEND_HISTORY/SHARE_HISTORY instead of bash PROMPT_COMMAND
- Remove unused SNIPPET variable from Dockerfile template
- Remove redundant sudo in dpkg RUN step (already running as root)
- Drop NET_RAW capability (only NET_ADMIN needed for iptables/ipset)
- Update README firewall section to accurately document DNS, SSH, and
  host gateway exceptions

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Critical fixes in init-firewall.sh:
- Add EXIT/ERR trap to set DROP policies if script fails mid-execution,
  preventing the container from being left with fully open ACCEPT policies
- Split domains into CRITICAL (fail-hard with 3 retries) and OPTIONAL
  (warn-and-skip) categories so core services like api.anthropic.com
  always resolve or the script aborts
- Move DROP policies to the very end, after all ACCEPT rules are in place,
  so a late iptables failure cannot brick networking
- Replace blanket ipset add error suppression with targeted duplicate-only
  handling so real errors (ipset full, permissions) are caught
- Add --fail flag to curl for GitHub API to catch HTTP errors (rate limits)
- Validate GitHub CIDR output is non-empty before proceeding
- Filter NAT rule restoration to only -A lines to avoid passing garbage
- Expand verification to check ipset entry count and api.anthropic.com
  in addition to GitHub

README fixes:
- Remove misleading DNS tunneling claim (Docker resolver still forwards)
- Replace raw API key echo with safe existence check in verification step
- Fix Rosetta advice (native arm64 images work, Rosetta not needed)
- Update firewall docs to reflect critical/optional domain split
- Clarify that image rebuild (not just restart) is needed for script changes
- Fix Apple Silicon build note (downloads binaries, compiles dev tools)

Dockerfile fix:
- Move USER root before COPY init-firewall.sh to make ownership intent
  explicit and prevent future --chown mistakes

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@thiras
thiras merged commit a23c23e into main Mar 26, 2026
@thiras
thiras deleted the feat/devcontainer-setup branch March 26, 2026 23:37
thiras added a commit that referenced this pull request Apr 29, 2026
…pecs

Aligns the v2 tokenomics specs with the convention introduced in #335:
ADR 021 is the source of truth for L2 selection, so other docs cite it
rather than naming the chain incidentally.

- Acceptance criteria #1 (both specs): "local Arbitrum fork" →
  "local fork of the canonical L2 (per ADR 021)".
- Gauge-boost spec open question #7: "$8–$1500/yr in gas on Arbitrum" →
  "$8–$1500/yr at typical L2 gas prices" — the claim is about cost, not
  the chain.

No semantic changes.

Co-Authored-By: Claude Opus 4.7 (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 1, 2026
The history file's ADR 014 entry pointed at
`#1-poc-approach-eip-712-secp256k1-on-existing-fields`, an anchor
that doesn't exist in the source ADR. The actual heading is
`### 1. Ed25519 Signature Verification — Dual-Key Slash Signatures`,
which under GFM slug generation produces
`#1-ed25519-signature-verification--dual-key-slash-signatures` (the
em-dash drops, the surrounding spaces become a `--` pair).

Update the link text and anchor to match. Spotted in PR review.

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

* docs(adr): move pre-launch Alternatives Considered to _history/ (#346)

The README has long carried a TODO that moving rejected-alternatives
content out of ADR bodies into a dedicated `adr/_history/` audit trail
is tracked in #346 ("Tier 3 of the book-readiness program"). This
delivers it.

Each of the eight `## Alternatives Considered` sections is moved into
`adr/_history/alternatives-pre-launch.md` (single audit-trail file,
anchored by source ADR) and replaced in the source ADR with a one-
paragraph stub naming the alternatives evaluated and pointing at the
history entry. Sources moved:

- ADR 014 § 1 (slash signature scheme: RIP-7212 / Solidity ed25519 /
  ZK / optimistic vs. dual-key chosen)
- ADR 018 (Uniswap V3 + revisit triggers)
- ADR 022 (six discovery alternatives: probe fan-out, gossip
  announcements, hash-prefix hints, iroh mainline DHT, indexer
  nodes, full libp2p Kademlia)
- ADR 026 (five tokenomics shapes: original 3% flat, auto-ve-lock-on-
  vest, USDC ve-pool, pure-deflationary slashing, TOKEN bootstrap
  fund)
- architecture.md (decentralised-storage model)
- appendix-encrypted-content-publishing (client expiry, decryption
  proxy, proxy re-encryption, per-client ECIES)
- appendix-local-admin-http (REST hyper, OpenRPC, Unix socket, iroh
  ALPN, /metrics extension)
- appendix-poc-production-seams (cfg!() branch, two features,
  runtime enum, Option fields, two repos, scattered cfg)

Neither `adrs.pdf` (numeric) nor `adrs-book.pdf` (reading-order)
includes the history file — the audit trail lives in the source repo
only, matching the README's "the protocol has one design" framing.
PDF readers approaching the protocol top-to-bottom get the canonical
spec; readers researching a specific decision can follow the
breadcrumb at the end of each source ADR back to the history.

The strip filter in the book PDF build still drops the now-stub
`## Alternatives Considered` headings (the patterns are unchanged) so
the book output is unaffected. The numeric PDF includes the stubs
plus their links to `_history/`, which render as plain text URLs in
typst — readable and discoverable on GitHub, where the cross-file
anchor resolves.

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

* docs(adr): trim architecture.md per-ADR summaries to a compact index

The `## Architectural Decisions` section walked every ADR with a
multi-paragraph summary (~8-10 lines per ADR × 22 ADRs = ~180 lines)
that duplicated each ADR's own Context / Decision intro. Readers who
clicked through to the ADR got the same content twice.

Replace the per-ADR sub-sections with a single bullet list, one line
per ADR, keeping each ADR's bold one-line decision summary verbatim
as the bullet body. Heading anchors (e.g. `#adr-001-network-topology-
and-peer-mesh`) were not referenced from any other ADR or the
README/CLAUDE.md/CONTRIBUTING.md (verified by grep), so collapsing
the headings into list items is safe.

Net result: architecture.md drops from 593 → 436 lines (-157),
~6 PDF pages off both numeric and book builds. The Reading Order
chapter index above remains the thematic top-to-bottom navigation;
this section is now the canonical numeric per-ADR index.

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

* docs(adr): also strip per-ADR Date/Status preamble in book PDF

Each ADR opens with two metadata lines between the H1 title and the
first content section:

    # ADR 002: Content Addressing

    **Date:** 2026-03-28
    **Status:** Draft

    ## Context

In a top-to-bottom read of the protocol spec, those lines are noise:
they age poorly (most ADRs were touched on a date no one cares about
months later), and the "Draft" status is correct-but-meaningless once
the protocol ships. They remain useful as audit metadata in the
source `.md` files, but the rendered book PDF should read like a
single canonical design.

Extend `_build/strip-meta-sections.lua` with a `Para` filter inside
the existing `doc:walk` that drops paragraphs whose stringified text
starts with `Date:` or `Status:`. Both the soft-break-joined form
(no blank line between Date and Status) and the two-Para form
(ADR 022 has a blank line, parses as two Paras) are caught — the
leading text matches `Date:` / `Status:` either way.

Source files unchanged; only the reading-order `adrs-book.pdf` build
is affected. Numeric `adrs.pdf` keeps the metadata.

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

* docs(adr): fix broken anchor in _history link to ADR 014 § 1

The history file's ADR 014 entry pointed at
`#1-poc-approach-eip-712-secp256k1-on-existing-fields`, an anchor
that doesn't exist in the source ADR. The actual heading is
`### 1. Ed25519 Signature Verification — Dual-Key Slash Signatures`,
which under GFM slug generation produces
`#1-ed25519-signature-verification--dual-key-slash-signatures` (the
em-dash drops, the surrounding spaces become a `--` pair).

Update the link text and anchor to match. Spotted in PR review.

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

---------

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

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

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

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

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

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

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

Closes #400

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #400

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

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

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

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

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

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

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

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

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

Refs #400 #565

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

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

Two findings from the post-fce0fc2 internal review pass:

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

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

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

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

Refs #400 #565

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Alper Gundogdu <[email protected]>
thiras added a commit that referenced this pull request May 15, 2026
…499) (#572)

* test(node): cover SIGHUP rejection of restart-required config fields (#499)

Add an integration test that drives a real SIGHUP carrying both mutable
(payment.rate_per_mb, observability.log_level) and restart-required
(network/blockchain/cache/identity/gossip) changes, asserting the mutable
ones apply while the restart-required ones are rejected with an
info-level "ignoring change to X (requires restart)" notice.

The existing reload unit tests poke the diff helpers directly and the
other tests in this file only feed reloadable sections, so no test
previously exercised the restart-required rejection arm against an OS
signal -- the silent apply/drop regression #499 calls out.

The test exercises all three branches of log_ignored_other_sections'
section diff: reload #1 hits the absent->present no-baseline
conservative-warn path ([network] vs empty baseline) and asserts absent
sections stay silent; reload #2 keeps [network] byte-identical (the
suppression branch must not re-warn) while newly-changed sections each
emit exactly one notice, alongside mutable changes that must still
apply. Assertions match the stable section prefix + "(requires restart)"
suffix so cosmetic warn_ignored field-list edits don't break the test.

Runs on a current_thread runtime with an inline-awaited reload and a
thread-local buffer-capturing subscriber; tracing-subscriber is repeated
as a dev-dependency since integration tests link only the public API +
dev-deps. Module doc notes these tests require nextest's per-process
isolation (tokio signal registration is process-global).

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

* test(node): drop redundant tracing-subscriber dev-dependency

tracing-subscriber is already a normal [dependencies] entry of
decdn-node. Integration tests have access to the package's normal
dependencies (not only dev-dependencies, as the removed comment
incorrectly claimed), so the duplicate dev-dependency was unnecessary
and risked feature/version drift between the two entries. Verified by
forced recompile of tests/sighup_signal.rs with the dev-dep removed:
3/3 tests still build and pass.

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

---------

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

* docs(adr): remove ADR 024 Cross-ADR Impact residue (verified already-applied)

All 5 amendments (003/012/014/016/019) verified already native in targets:
003 uses SignatureChecker (L54/599/704); 016 OZ table lists it (L819);
019 documents Safe+ERC-7579+smartsessions (L46/L260); 012/014 reflect it.
No decision lost: 024's design lives in its Decision §3; targets canonical.

* docs(adr): remove ADR 014 Cross-ADR Impact residue (verified already-applied)

002 reads canonical (no open on-chain-verif Q); 005 already slash_sig-sole
(L57); 003 has §Corrupted delivery; 011 §Slashing uses ecrecover slash_sig;
028 openSlashAppeal(slashId) canonical in 028. No decision lost.

* docs(adr): remove ADR 012 Cross-ADR Impact residue (verified already-applied)

003 L277 already states eclipse resolved-in-ADR-012 / PoC-registry-only;
001 retains node bootstrap; 005 wire fields + 008 client-local-reputation
decisions canonical in 012 body. No decision lost.

* docs(adr): remove ADR 013 Cross-ADR Impact residue (verified already-applied)

005 L170 already frames voucher_interval_mb as Tier-1 minor evolution;
001 already validates GossipEnvelope-unwrapped payloads; arch index has
ADR 013 entry. Consequences section preserved. No decision lost.

* docs(adr): fold ADR 022 Cross-ADR Impact (DHT metrics -> observability)

Genuine fold: 3 decdn_dht_* metrics moved into appendix-observability
§2.11 (the canonical metric registry) -> decision preserved. Other bullets
verified residue: 022 body L150/L205/L225 canonically state origin-not-at
-probe + false-STORE->reputation; 001 already shows Future Work resolved.
No decision lost.

* docs(adr): remove ADR 011 Cross-ADR Impact residue (verified already-applied)

All 9 bullets are restatement of decisions canonical in 011's own body:
§Slashing (serving-blacklisted slashable, L582+), §Origin Assignment
Authority, §OriginAssignment contract, §Interaction-with-appeals
(028 decoupling). Targets 009/016/022/002 already integrated; 001 has
no permissionless-origin claim; 005 L53 origin-not-at-probe. No decision lost.

* docs(adr): fold ADR 031 Cross-ADR Impact (enumerate appeal sub-modes in ADR 009)

Genuine fold: ADR 009 Emergency Multisig capability (3) now enumerates the
ContentBlacklist blacklist-entry-appeal sub-modes (fastTrackAppeal/
unFastTrackAppeal/rejectAppeal/rejectAppealAsPerjury), mirroring how cap (4)
documents its slash-appeal sub-modes -> decision preserved in 009's
exhaustive list. Residue bullets removed: 011 L312 already points to ADR 031
for ABI; 016 no-op; 032 parallel-pointer obvious. References kept. No decision lost.

* docs(adr): remove ADR 032 Cross-ADR Impact residue (verified already-applied)

Event/storage spec is canonical in 032 §3 (032 is THE impl ADR); 026 stub
is a forward-pointer (no decision there); 028 L178 already 'six new entry
points'; arch index + CLAUDE.md are bookkeeping (CLAUDE.md is not a book
file). References kept. 028#cross-adr-impact anchor still served by A.9.
No decision lost.

* docs(adr): condense ADR 028 Cross-ADR Impact to forward-coupling only

KEEP heading (anchor served to 014/032) + full SafetyReserve-future-split
migration decision (4-item coupling list + escrow-semantics constraint
preserved verbatim in substance). Prose tightened ~222->~160w; 032-pinning
+ 011-decoupling reduced to tight pointers (canonical in 032 §3 / 011
§Interaction-with-appeals). No decision lost.

* docs(adr): tidy ADR 026/030 Cross-ADR sections

026: removed empty Cross-ADR Impact (its '(none — wash-trading defense is
the §3 cap)' note is a pointer to §3, which stays canonical).
030: condensed the deliberate tracked-divergence notes (#400-response)
~121->~90w; every tracked fact (ADR 008 scope, validation.rs spec/impl
divergence, §3-canonical) preserved. No decision lost.

* docs(adr): Lever B — architecture.md dedup + taxonomy normalize

B.1 dedup (~1,210w): removed Origin Integration prose (kept the unique
Supported-Origins table/OriginStore trait + Hash-to-Object-Key catalog as
'## Origin Backends'), Cache Behavior, Crate Structure, Binaries,
Dependency Chain, Observability — each duplicated an authoritative ADR/
appendix. Decision-loss guard: cache/incentive-independence + binary-split
preserved as a new Key Invariant citing appendix-poc-production-seams /
appendix-binaries (canonical there + CLAUDE.md).
B.2 taxonomy: merged 'Future Work: *' + 'What Is Not Decided Yet' into one
'## Deferred & Open' (canonical -> lua-stripped from book; preserved in
numeric+source). Repointed 4 inbound links (005x2, 011, blob-cache-eviction)
to appendix-observability / ADR 005. Zero dangling anchors. No decision lost.

* docs(adr): Lever C — condense ADR 016 IFeeRouter NatSpec essays

Premise correction (Phase 1): IFeeRouter is the corpus-canonical FeeRouter
definition (not a restatement) — NOT pointer-ized. Instead: tightened the
verbose multi-line NatSpec comment essays that restate ADR 026 mechanics,
and the **Notes** block. PRESERVED verbatim: every function signature,
every event, the ShareDestinations struct, and every invariant/security
line (cross-validation, 26-epoch claim window, msg.sender==delegatorBuyer
sole-auth, epoch-immutability, 'no operator-asserted summary/identity-gate
/fraud-challenge', what-is-paused). §1 table/classDiagram/Tunable-Economics
/No-proxy/Shared-swap-helper and §2-§8 (deploy order, call table, role
grants, fund-flow, reentrancy) left structurally intact. No decision lost.

* docs(adr): condense appendix-bundles.md (~1151->1110w, prose only)

All headings + link targets identical; every schema field, 6 path-safety
rules, 5 determinism axes, hash-format rule, non-goal preserved (agent
decision-preservation report verified). No decision lost.

* docs(adr): condense appendix-operator-key-rotation.md (~2588->2215w, prose only)

All headings + link targets identical; every rotation step/command/
contract-call/parameter/failure-mode preserved; collapsed one redundant
dual cast-code example (both outcomes kept in prose). No decision lost.

* docs(adr): condense appendix-operator-upgrade-path.md (~2045->1807w, prose only)

All headings + 15 link targets identical; every tier def, Tier-1/2/3 step,
ordering constraint, MUST/SHOULD, failure mode preserved. No decision lost.

* docs(adr): condense appendix-binaries.md (~772->710w, dedupe 3x binary-size restatement)

All 6 headings + the one link target identical; binary-split decision +
all 4 rationale points preserved (binary-size mechanics stated once in
Cross-ADR Impact, cross-referenced). No decision lost.

* docs(adr): condense appendix-l2-deployment.md (2180->1723w, ~21%)

Arbitrum-One decision + all criteria + every ADR-dependent number + the
chain-comparison table byte-identical; headings + 6 link targets unchanged
(fixed one non-descriptive link text to satisfy MD059, target preserved).
Cut only post-table prose re-narrating table cells. No decision lost.

* docs(adr): condense appendix-local-admin-http.md (1424->1174w, ~18%)

Every endpoint/route/error-code/security decision + both links preserved;
headings identical. Collapsed Rationale Q&A restating the Decision. No decision lost.

* docs(adr): condense appendix-fraud-detection.md (774->676w, ~13%)

Heavily-referenced (10 inbound); 8 headings + all link targets identical;
every detection mechanism/parameter/cross-ref preserved. No decision lost.

* docs(adr): condense appendix-encrypted-content-publishing.md prose (3569->3435w)

ADR-017-cited section names: 13 headings TEXT+ORDER identical; every ALPN/
message/key-rule/lease-mechanic/threat + all links preserved (code, crypto,
2 mermaid, tables untouched). Prose-only. No decision lost.

* docs(adr): condense appendix-observability.md prose (3785->3547w)

LOAD-BEARING anchor #### 2.6 Gossip Metrics byte-identical; all headings +
numbers unchanged; 64 metric names == 64 (every row/Type/Tier/Label/
threshold/health-key preserved); §2.11 DHT block intact. Description-cell
+ §5/§6 narrative prose tightened only. No decision lost.

* docs(adr): condense appendix-blob-cache-eviction.md (2460->2358w)

§2/§3 anchor headings byte-identical; 5 resolved questions + every
invariant (LRU key, pinning-overrides, evict-orthogonal, probe-hold,
reputation-not-a-factor) + all params/metrics/links preserved. Collapsed
2 structural duplications. No decision lost.

* docs(adr): condense appendix-peer-table-eviction.md (2108->2001w)

§1/§3/§4 anchor headings byte-identical; TTL 600s/last_seen_us, active-
eviction triggers, no-hard-cap rationale, reputation-not-a-factor, all
metrics/links preserved. No decision lost.

* docs(adr): condense appendix-poc-production-seams.md (2908->2857w)

LOAD-BEARING seam-1 heading byte-identical (em-dash xxd-confirmed); all 9
seam headings text+number unchanged; every trait/PoC/prod/decision + leaf-
crate principle + single-poc-feature + mechanical-deletion rule preserved.
Seam-preamble prose only. No decision lost.

* docs(adr): Lever F — condense ADR 003 prose (12826->12255w)

Collapsed 3x zero-voucher-close restatement to canonical home + back-refs;
deduped 3x 10-USDC-minimum; cut Attack-Vectors ceremony; tightened NatSpec
essays. All 3 settlement invariants, Channel struct, function/reject tables,
NodeId-binding security props, decimal invariants, headings, links preserved.
No decision lost.

* docs(adr): Lever F — condense ADR 011 prose (10443->10178w, conservative)

Collapsed 4x appeal-decoupling + 2x 'not-a-new-multisig-power' restatement
to canonical homes + back-refs. Synthetic-standing clawback, half-open
evidence window + µs-invariant, compliance/bond tables, On-Blacklist-Event
steps, §Slashing, interfaces, headings, links all byte-preserved. No decision lost.

* docs(adr): Lever F — condense ADR 026 prose (7438->7010w)

Collapsed §5 payout-ordering / §2 pre-launch / §11 / Risks restatements to
canonical homes + pointers; tightened NatSpec essays. Allocation + 6-bucket
+ ve + §11 safety-bounds tables, working_bytes/share_i formulas, div-by-zero
fallbacks, 3 queue-ordering properties, interfaces, headings, links
preserved. No decision lost.

* docs(adr): Lever F — condense ADR 005 prose (6090->5944w, conservative)

Deduped 5x 'probe data not confidential' + redundant rate-manipulation
explanatory tail to canonical homes. Every ALPN/wire-message/field/error
code/MUST-SHOULD rule/parameter, headings, 33 link targets byte-preserved.
No decision lost.

* docs(adr): Lever F — condense 001-network prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 018-liquidity-strategy prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 008-reputation prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 012-client prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 014-on-chain-verification prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 022-content-discovery prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 010-multi-token prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 013-schema-evolution prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 017-privacy prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 019-node-onboarding prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 030-node-region-self-attestation prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 028-slashing-appeals prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 031-content-blacklist-appeals-contract prose (no-decision-loss; headings+links preserved)

* docs(adr): Lever F — condense 032-safety-reserve-appeals-contract prose (no-decision-loss; headings+links preserved)

* docs(adr): Option 4 — relocate remaining inline Alternatives to _history (#346)

Moved the 6 still-inline '## Alternatives Considered' bodies (028/030/031/
032 + blob-cache-eviction + peer-table-eviction appendices) into the
_history audit trail, leaving the standard one-line breadcrumb stub —
completing the #346 Tier-3 pattern already applied to 014/018/022/026/etc.
Every rejected alternative preserved verbatim in _history (no decision-
record loss). Zero inbound #alternatives-considered links. NOTE: 0 book-page
impact (lua already strips Alternatives from adrs-book.pdf); shrinks the
numeric build + source only.

* docs(adr): add presentational page-density build config (#1, layout-only)

The pandoc/typst defaults (~2.5cm margins, 11pt, slack leading, toc-depth 2)
rendered the reading-order book at ~429pp (no-mermaid). Adding a standard
technical-book geometry — _build/book-margins.yaml (1.6cm/1.8cm) +
_build/book-density.typ (10pt, linestretch 1.0, tighter par/raw/table/
heading) wired into both README build commands — takes it to 258pp
no-mermaid (~230pp mermaid-rendered), numeric 251pp. Section-level TOC
(toc-depth 2) retained. ZERO content/decision change: drop the four flags
to render byte-identical content at the loose default. Both builds exit 0,
zero typst dangling-label errors. No PDFs committed (per task: leave
binary regeneration to the mermaid-fixed CI pipeline).

* docs(adr): add adr/Makefile for both PDF builds; point README at it

Makefile is the single source of truth for the pandoc invocation:
  make            both PDFs (mermaid-rendered, canonical)
  make book/numeric   one PDF
  make MERMAID=0  no mermaid-filter (no mmdc/puppeteer; soundness check)
  make clean / help
  make check-book-list   drift guard — fails if a numbered/appendix .md
                         is missing from the hand-maintained BOOK_SRCS
Recipes mirror the prior README commands exactly (incl. density flags,
npm PATH prefix, lua filter, title/date). README's two copy-paste pandoc
blocks replaced with make usage + a pointer; all explanatory notes
(deps, mermaid, lua-strip, density, hand-maintained-list caveat) kept.
Verified: make MERMAID=0 exit 0, zero dangling, adrs.pdf 251pp /
adrs-book.pdf 258pp, make clean works. No PDFs committed.

* ci: validate ADR book list, scoped to ADR-book changes only

Guards the silent-omission hazard (a numbered ADR/appendix added without
updating adr/Makefile BOOK_SRCS would drop it from adrs-book.pdf).

- ci.yml: new 'adr' dorny/paths-filter (adr/**/*.md, adr/Makefile) + a
  lightweight 'adr-book-list' job (checkout + 'make -C adr
  check-book-list', no pandoc/typst, sub-second) gated
  'if: needs.changes.outputs.adr == true' so it runs ONLY on ADR-book
  changes; wired into ci-success needs + allowed-skips so the skip on
  unrelated PRs is accepted.
- .pre-commit-config.yaml: local 'adr-book-list' hook scoped via
  files: ^adr/(.*\.md|Makefile)$ — instant local feedback, skips on
  non-ADR commits.

Verified: check-yaml passes both files; pre-commit hook fires on
adr/Makefile (Passed) and skips on a Rust file.

* docs(adr): strip resolved-tombstone residue so the spec reads canonical

Zero decision-loss — every removed item's resolution is canonical in the
ADR it points to:
- 001: delete struck '### ~~Future Work: Scaling Content Discovery~~
  (Resolved by ADR 022)' section (no inbound links; canonical in ADR 022)
- 005: delete struck '~~Postcard has no schema evolution~~ — resolved by
  ADR 013' bullet (canonical in ADR 013)
- 019: delete the 2 struck '~~…~~ Resolved —' Deferred&Open bullets
  (Geolocation→ADR 030, Delegated-signer→ADR 024); kept the 2 genuinely
  open items
- 012: drop 'Resolves the open question in ADR 003…' meta-line (section
  already states the Option-B decision); reword the Consequences bullet
  to canonical voice
- architecture.md: collapse '### Open / undecided' to the one real open
  item (Parallel multi-node streaming), dropping 8 struck 'decided —'
  changelog tombstones; reword the ERC-20 Trust-Assumption that called
  ADR 010 vetting 'an open question' -> points at ADR 010's decided
  Token Vetting Checklist

* docs(adr): #346 — relocate inline rejected-alternatives to _history; fix orphaned ref

- 003 § Probe fishing: moved the 3 rejected probe-DoS options (require-
  channel-to-probe / PoW / monitor-only) to _history, leaving the canonical
  mitigation (layered rate limit, ADR 005) + Note inline + a breadcrumb.
- 018: replaced the V2-vs-V3 drafting-history blockquote with a canonical
  V3 statement + breadcrumb; the V2-rejection + 2025-11-03 exploit record
  preserved verbatim in _history (affirmative V3 justification stays in
  ADR 018 § Consequences).
- _history: +2 sections (ADR 003 probe-fishing, ADR 018 Balancer V2) —
  every rejected alternative preserved verbatim; section count 14->16.
- FIX: 001-network.md:176 same-file link '[Future Work](#future-work-
  scaling-...)' orphaned by the Commit-1 tombstone removal -> repointed to
  [ADR 022]. (My pre-removal grep required a filename prefix and missed the
  bare same-file ref — exactly the failure mode the verification protocol
  warns about; caught by the typst build, now fixed.)

Authoritative: both builds exit 0, ZERO typst dangling-label errors,
book 257pp / numeric 250pp (no-mermaid). No decision lost.

* docs: add Phase-1 ADR-book-reduction plan (methodology + findings)

The written plan that drove this branch: per-lever analysis, the measured
'corpus is decision-dense' headline finding, page calibration, and the
verification protocol. Reviewer traceability for a 50-commit reduction;
safe to drop if the repo doesn't want a docs/superpowers/ tree.

* chore: drop docs/superpowers planning artifact from the PR

Per maintainer request — it was the working-process Phase-1 plan, flagged
as droppable. (docs/runbook.md is a pre-existing repo file, untouched.)

* docs(adr): drop _history breadcrumbs from ADRs; spec carries no alternatives pointers

_history/alternatives-pre-launch.md is in neither built PDF, so the 'see
_history' stubs were dead pointers in the artifacts and iteration-log noise
in a canonical spec. Removed:
- 14 '## Alternatives Considered' breadcrumb stub sections (014 #### / 018
  /022/026/028/030/031/032 + architecture.md + 5 appendices) — heading +
  the one _history pointer line; 014's substantive '> Note' kept
- 2 inline _history breadcrumbs (003 § Probe fishing, 018 V2-vs-V3)
- 026: 4 same-file '[Alternatives Considered](#alternatives-considered)'
  refs reworded to '… was considered and rejected' (named alternatives
  kept inline, no dangling link)
Docs synced to the new reality: README (design principle, Decision-record
context, #346 note now 'complete', strip paragraph, taxonomy row),
_history header, _build/preface.md.
The _history archive itself is unchanged (every rejected alternative still
preserved verbatim) — it is simply no longer linked from the spec.
Both builds exit 0, ZERO typst dangling-label errors; book 257pp / numeric
248pp (no-mermaid). No decision lost.
alpergundogdu added a commit that referenced this pull request May 18, 2026
Address PR #582 review: link to a stable section anchor instead of the
bare file. Corrected the anchor — the reviewer suggested
`#contract-inventory`, but ADR 016's heading is `### 1. Contract
Inventory` (slug `#1-contract-inventory`, per 016's own self-link at
line 804); the suggested slug would have dangled. Applied the verified
anchor to both this-PR references (appendix + 009) for consistency, plus
the suggested comma after the introductory link.

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

* docs(adr): reconcile PoC framing to ADR 016 canon; slim seams appendix

Canonical rule (workspace CLAUDE.md): "PoC" is a network-scale
milestone, NOT a reduced contract surface — the on-chain surface ships
at full production shape with governance-tunable economics from day one
([ADR 016 § Contract Inventory / § Tunable Economics]).

Genuine inconsistencies with that canon, fixed:
- 003-payments.md: rate bounds were "governable post-PoC" — contradicts
  ADR 016:18/102 ("governance-tunable from day one"). Now: tunable from
  day one within the hardcoded safety bounds, admin-key-gated in PoC,
  ve-Governor in production.
- 009-governance.md: "governance contracts are additive post-PoC" /
  "implemented post-PoC" — contradicts ADR 016:34/35 (DecdnGovernor +
  TimelockController are in the day-one single-audit-pass inventory;
  Timelock is DEFAULT_ADMIN_ROLE day one). Reframed: the contracts ship
  day one; only the governance *process* (admin key -> ve-Governor)
  differs by phase, not the contract surface.

Deliberately left as-is (investigated per request — these are
consistent, separately-documented scope decisions, not mis-framing):
- Multi-token: ADR 003/010 and the canonical ADR 016:24 inventory all
  model it as a distinct post-PoC PaymentChannel replacing the USDC-only
  StablePaymentChannel ("multi-token PaymentChannel ... is deferred").
- ADR 014 PoC scope (double-settlement, regional, 10%-flat): deliberate
  and internally consistent; parameterization is tunable day-one anyway.

Seams appendix slimmed to the durable principle (option b):
- Dropped the `#[cfg(feature="poc")]` Cargo-feature design and the
  "mechanical-deletion graduation path" thesis (no `poc` feature exists
  in crates/; it framed PoC as a stubbed surface to delete, conflicting
  with "contracts ship production-shaped day one").
- Dropped the stale 5-crate inventory + crates/ tree + 9 per-seam code
  blocks (predated the cli/common two-binary split; crates are early).
  Now defers to CLAUDE.md / appendix-binaries.md as the layout source.
- Reframed the contract surface as NOT a PoC/production seam — the only
  contract-side seam is deployed-contract vs in-process test double.
- Fixed the resulting dangling inbound anchor (003-payments.md ->
  removed appendix §1) and architecture.md's stale one-line descriptor.

Verified: markdownlint + heading checks clean; no dangling anchors;
`make MERMAID=0 book` builds clean.

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

* docs(adr): stable anchor on the ADR 016 Contract Inventory links

Address PR #582 review: link to a stable section anchor instead of the
bare file. Corrected the anchor — the reviewer suggested
`#contract-inventory`, but ADR 016's heading is `### 1. Contract
Inventory` (slug `#1-contract-inventory`, per 016's own self-link at
line 804); the suggested slug would have dangled. Applied the verified
anchor to both this-PR references (appendix + 009) for consistency, plus
the suggested comma after the introductory link.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
yigitdot added a commit that referenced this pull request May 19, 2026
)

Addresses the multi-agent review of PR #606. No production control-flow
change (label constants are value-identical strings).

Tests (pr-test-analyzer Gaps A/B/C):
- resolve_cache_origins_accumulates_every_bad_entry: two malformed
  origins (idx 0, 2) both reported by index, valid idx 1 absent.
- Strengthened resolve_gossip allowlist test → accumulates every
  invalid entry by index (was the stale pre-#222 fail-fast premise).
- resolve_config_missing_rpc_url_emits_no_parse_cascade: missing
  rpc_url is the sole problem, no "is not a valid URL" cascade.
- resolve_config_malformed_slash_judge_emits_no_zero_address_cascade.
- resolve_config_aggregates_cross_and_intra_section_problems: exact
  4-count across cross + intra-section with region cascade suppressed.
- config_validate: lock the fail-fast boundary (file-load errors must
  not be wrapped in the aggregate header).

Hardening (type-design-analyzer #1 + silent-failure-hunter Finding 3):
- IDENTITY_REGION / IDENTITY_DATA_DIR consts used at both the
  producing and has_field guard sites so a rename can't silently
  disable cascade suppression.

Comments (comment-analyzer): qualified the "verbatim" claims (multi-line
messages get indented continuations), corrected the resolve_gossip doc
to the drop-and-record-by-index behaviour, and tightened the keystore
guard comment to state the defaulted-keystore skip is deliberate.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
thiras added a commit that referenced this pull request Jul 14, 2026
…adlines (#1145 review)

Four findings. Each is a bound that looked configured and could not do what it was named
for, which is the defect class this review round exists to remove.

**`PullStalled` punished honest servers for serving large blobs.** It scores the peer
`Unreachable` — a local EWMA hit AND a gossiped observation — and it earns that right from
the deadline's reset: a clock that resets on every byte can only fire on a peer that
stopped. True for every chunk but the FIRST, where no byte has reset it yet. What it
measures there is the server's time-to-first-byte, and that scales with blob size: the
serve path writes the `StreamResponse`, then materialises the whole bao wire encoding via
`export_bao_range` before it can emit chunk #1. A 1 GiB blob (the default ceiling) off a
cold disk can exceed the 20 s default stall budget, and the requester defamed it
network-wide for it.

Both receive loops now raise `PullTimeout` — exonerating — when the budget elapses at
`cumulative == 0`. That is the answer the OPEN stage already gives an identical wait, on
identical grounds: a bound of ours elapsing over bounded server work says nothing about
the peer. Nothing is given up that the open stage has not already given up.
`node_origin_a_silent_first_byte_is_our_deadline_not_the_peers_fault` and its sibling
(three chunks, then silence — still scores) pin the boundary at exactly one byte.

**`warm_budget_mb(0)` inverted the guard at the one value it named.** `0` is the
documented "unlimited" sentinel — every blob-size gate reads it that way (`> 0 &&`, five
sites) and config resolution accepts it. So the worst-case blob is UNBOUNDED, and clamping
the reserve to a 1 MiB FLOOR admitted 2048 concurrent warms each buffering an arbitrarily
large blob into memory for up to an hour. The byte-based pool was strictly worse than the
task-count ceiling it replaced. Its test asserted `warm_budget_mb(0).1 == 1` under the
comment "a zero ceiling must not make warms free and unbounded" — pinning the mechanism
and mistaking it for the property, which was false. An unlimited ceiling now reserves the
whole pool: one warm at a time, the same answer a ceiling above the pool already got,
because it is the same situation.

**The deadline invariant was enforced on the wrong type, in the wrong crate.**
`hard_cap > open + stall` is `PullDeadlines`'s invariant, but its fields were `pub`, both
production call sites built it with a struct literal, and the check lived in the CLI as a
hardcoded `timeout > 2 × stall` — correct only because those sites happen to set `open`
from the stall knob. An `--open-timeout-ms` flag would have made it silently wrong, in the
direction that reopens the hole. Fields are private, `capped` is fallible and enforces the
real relation, and both call sites go through it. `ClientFetchArgs::validate` remains the
early, friendly error in the user's own flags; it can now go stale but not WRONG.

Also: `--help` still told users `--timeout-ms` "must be larger than --stall-timeout-ms" —
the threshold 1096ec5 deleted as unsound. Following it exactly got your command rejected.
And `hard_cap()` returned an `Option` that was structurally always `Some`.

**`PULL_THROUGH_OUTER_SLACK` was smaller than the overhead it was named for.** A flat 10 s
against a probe phase (5 s) plus one slow lookup round (8 s) is 3 s short — and the lookup
loop exited on convergence, never on a count, so its worst case was UNBOUNDED and no
constant could have covered it. The outer timeout could fire while candidate #3 was still
in its stall window: the #859 fallback starvation the formula exists to prevent, at the
defaults. The guard test asserted `outer == all_candidates + SLACK`, which proves only that
the slack is whatever the slack is.

`MAX_LOOKUP_ROUNDS` makes discovery finite; the slack is now DERIVED from it
(`PROBE_TIMEOUT + MAX_LOOKUP_ROUNDS × DEFAULT_ROUND_TIMEOUT`). Both halves are needed.
Worst-case client wait at defaults: 145 s -> 172 s, updated at all four sites that quote it.

- `cargo nextest run --workspace` — 2267 passed, 0 skipped
- clippy / fmt / doc — clean

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jul 14, 2026
**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]>
thiras added a commit that referenced this pull request Jul 14, 2026
…e false (#1145 review)

**`spawn_open` did not reserve the slot it documented.** Its doc has always said
it "reserves the provider's slot and runs the open under it" — it did the second.
The guard was built here; the matching `insert` lived twenty lines away in
`join_or_spawn_open`. So the pairing was asymmetric: RELEASE in the type (`Drop`,
unconditional), ACQUIRE in the caller. The invariant "a guard exists ⇒ the slot is
occupied" was caller-maintained, and a future caller who reached for `spawn_open`
without also remembering the insert would get a guard, get no singleflight, and
let the next miss open a SECOND `openChannel` — the double-escrowed deposit this
whole mechanism exists to prevent. The insert now happens inside `spawn_open`,
under the lock the caller already holds, so reservation and guard are one
statement.

Docs. `c8fd844` was titled "correct the claims the last three commits
invalidated" and did not catch them all:

- `BACKGROUND_FILL_HARD_CAP` still said `~25×` and `+ 10 s`. The slack became
  derived (5 s probe + 4 × 8 s lookup = 37 s), so the deadline is 172 s and the
  ratio ~21×. Now stated against `outer_pull_deadline` rather than restating its
  arithmetic — restating it is how this went stale.
- `MAX_BACKGROUND_FILL_MB` said warms accumulate `~25×` — the same figure, against
  a different denominator (3600/70 ≈ 51). The two could not both be right; the
  copy understated the amplification by half.
- `record_channel_open_failure` told operators a slow chain lane means raising
  `node_pull_timeout_sec`. That knob's own doc says outright: "raising this to
  give a slow L2 more room does nothing: that is the channel open."
- `node_pull_timeout_total` described one budget. It fires on two, and for the
  large-blob case the knob to raise is the one it did not name.
- `ClientMessage::validate` claimed to be "the seam a receive loop is told to
  call" (no receive loop calls it) and that its `ChunkData` arm guards the
  empty-frame bug (the arm cannot fail — the decode gate does that).
- The `NotFound` collapse: four of the seven reasons are ours or transient, not
  three (`RangeNotSatisfiable` is our own bad range computation).
- `outer_pull_deadline` said a fallen-through transfer "continues" in the warm. It
  does not — the warm calls `populate` and re-pulls from scratch, which also
  undercuts the "restart from zero" argument in the sentence above it.

And one claim this PR made that is still false, now said plainly rather than
quietly dropped: the first-byte carve-out fixes the ATTRIBUTION of a slow large
blob, not the blob. `export_bao_range` returns an owned `Bytes`, materialising the
whole bao encoding before chunk #1, so TTFB scales with blob size by construction
— and the warm re-pulls with the same stall budget. #1122/#1132's 708 MB blob is
NOT fixed here; the repair is to stream the encoding incrementally on the serve
side.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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 Jul 30, 2026
PR #1510 bundled five changes; this removes only the `cache.prewarm`
feature (its item #1) and leaves the other four intact — the #1470
`Candidate.stake: u64` change, the #1475 metric sibling-counter
convention docs, and the #1504/#1508 watcher-drift fixes.

Removed:
- `CacheEngine::prewarm` / `prewarm_cancellable` / `prewarm_pinned` and
  the `PrewarmReport` / `PrewarmOutcome` / `FillOwnership` types.
  `populate_inner` reverts to `CacheResult<()>` (the `FillOwnership`
  metering existed only to feed prewarm's coalesced-vs-fetched counts).
- The four `decdn_cache_prewarm_*` counters.
- `cache.prewarm` config field, `DEFAULT_PREWARM`, `prewarm_enabled_for`,
  and the `decdn config validate` / template reporting of the flag.
- Startup prewarm spawn, shutdown cancellation, and the reload-time
  single-flight warm machinery (`warm_in_flight` / `warm_dirty` /
  `warm_wanted` / `prewarm_stop`).
- The prewarm integration-test file and all prewarm unit tests, plus the
  observability-appendix rows and CHANGELOG entry.

Kept (per request): the oversized-pin-set warning
(`warn_if_pins_exceed_cache`), which is independent of prewarm — it runs
unconditionally at startup and on reload. The reload path reverts to a
plain detached `rescan_origins` + budget-warn spawn. The
`fs_rescan_interval_sec` `config validate` reporting (a #1508 drift fix)
is also kept.

Verification: cargo build, clippy --all-targets, fmt --check clean;
cache/common/cli 1096 tests and node 897 tests pass; anvil-e2e compile
gate and RUSTDOCFLAGS=-D warnings doc clean.

Co-authored-by: Claude Opus 4.8 <[email protected]>
alpergundogdu added a commit that referenced this pull request Aug 17, 2026
…tlement (#1699) (#1702)

* feat(payments): put bytes_delivered on the wire voucher for order-independent settlement (#1699)

The node reconstructed a voucher's cumulative bytes from stream-processing
order, so a skip-ahead voucher recovered the wrong signer and was rejected.
Transmit the already-signed bytes_delivered and verify against it directly, so
concurrent same-lane vouchers settle regardless of arrival order.

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

* feat(payments): treat a superseded same-lane voucher as already-satisfied, not a fatal regression (#1699)

Once vouchers carry their own cumulative, a lower voucher processed after a
higher sibling is superseded, not a fault. Stage this stream's own delta
(headroom + receipt) without moving the watermark and keep serving, so an
honest lagging stream is not killed. A divergent voucher at equal amount with
more bytes stays a single-signer fault.

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

* fix(payments): cap paid headroom at the settled watermark so benign vouchers cannot leech (#1699)

The benign already-satisfied branch advanced a stream's paid window by its real
delivered delta even though a benign voucher raises the watermark by nothing, so
a client could deliver a window, pay a (0,0) voucher to reopen it, and repeat to
download an entire blob for zero. Restore design rule #1: track a monotone
lane-level paid_credited bounded by the settled watermark, and advance the serve
loop's paid by the watermark-capped credit. An advance voucher credits its full
delta (no change); a benign voucher a sibling already settled still credits (the
watermark covers it); a benign voucher with no slack credits nothing.

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

* test(protocol): update public-API snapshot for the Voucher bytes_delivered field (#1699)

The feature-gated public-api-test snapshot pins decdn-protocol's exported
surface; adding bytes_delivered to the wire Voucher is the reviewable API diff.

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

* fix(payments): address review — precise Voucher doc + fail-closed credit conversion (#1699)

- Voucher doc: amount is the sole ordering/replay key; bytes_delivered is an
  additional signed monotone field the node verifies against — matching
  stage_voucher, which the prior "together they order" phrasing did not.
- commit_batch: convert the capped credit with a hard error instead of
  saturating to u64::MAX. The value provably fits u64, but a broken invariant
  must fail the batch rather than advance paid catastrophically; paid_credited
  advances only after the conversion holds.

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 Aug 20, 2026
#1030)

Implementation plan for issue #1030. Two halves: enforce the ADR 019 Phase 4 acceptance criterion #1 on the cdn/client/v1 serve path (the daemon never implemented it, so an unregistered and therefore unslashable node earns today), then write the bare-to-serving e2e journey that uses that gate as its hinge.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alpergundogdu pushed a commit that referenced this pull request Aug 20, 2026
…1030) (#1768)

* docs(plan): G-NODE-01 onboarding journey + ADR-019 registry serve gate (#1030)

Implementation plan for issue #1030. Two halves: enforce the ADR 019 Phase 4 acceptance criterion #1 on the cdn/client/v1 serve path (the daemon never implemented it, so an unregistered and therefore unslashable node earns today), then write the bare-to-serving e2e journey that uses that gate as its hinge.

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

* feat(node): refuse paid delivery when not in the on-chain active set (#1030)

ADR 019 Phase 4 lists `CapacityBond.isActiveNode(nodeId)` as acceptance criterion 1 for serving `cdn/client/v1`, but the daemon never enforced it. `serve_stream` read no registry state at all; the only registration awareness was `binding_check`, an advisory bring-up WARN. So a node that was never registered - or whose key was swapped out from under its binding - kept selling bytes while being unslashable, which is the one state the enforcement model cannot price.

The predicate already existed. The DHT registry projection keeps a live `StakerSet` off `getRegisteredNodes` plus the CapacityBond membership events, so the gate is `staker_set.is_active(self_node_id)` against the same Arc DHT admission holds - no new poller route (a second CapacityBond route would collide on (address, topic0) and fail the daemon at boot), no new RPC, and no unconfirmed state to fail closed on.

The gate sits below the two denylist checks so a takedown still answers `HashBlacklisted` rather than degrading to `NotFound`, and above everything that spends money or sends bytes. It signs `NotFound`, deliberately indistinguishable from a miss: a distinct code would be a cheap oracle for which operators cannot currently sell. The cause is operator-local, in `decdn_serve_stream_rejected_not_registered_total` and `registry_active` on `decdn node health`.

Also closes a real gap in the registry route itself: `EjectedByBlacklist` was missing from its topic0 OR-set, so a blacklist ejection only landed at the 15-minute re-enumeration and every consumer of the staker set - DHT admission included - was wrong until then.

Probes stay ungated (unpaid, and the canonical rate-discovery channel), as does the daemon's own buyer leg: the rule is may-not-sell, not may-not-participate.

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

* test(e2e): G-NODE-01 onboarding journey, bare to accepting delivery (#1030)

Starts where an operator starts - a provisioned data dir, a running daemon, nothing on chain - and drives the production `decdn setup` CLI through approve/bond/declareMbps/registerNode until the same process is selling bytes. Every other journey begins already onboarded (`NodeFixture::launch` onboards before the daemon spawns), so nothing observed the bare state and no test drove a SUCCESSFUL setup end to end; `cli_setup_partial` covers only the failure path.

The load-bearing assertion is the hinge, not the CLI: one process, no restart, refusing at step 1 and delivering at step 3. That is what proves the ADR 019 serve gate reads a live projection rather than a boot-time sample. The refusal is pinned by the `not_registered` counter, not by the error - every reject reason collapses to a wire `NotFound`, so asserting on the error alone would pass just as happily for a cache miss.

New fixtures: `NodeFixture::launch_bare` (the only path to an un-onboarded daemon; funds gas but not TOKEN so setup's funding pre-flight has a real step to clear), `ChainFixture::register_node_raw` (the signing half of `onboard_operator`, which is now built on it, so the two cannot disagree), and `fund_and_bond`.

Both negatives were previously untested anywhere in the repo. `register_below_min_bond_reverts` also corrects the issue's wording: `bond()` has no floor - it guards only `ZeroAmount` - so an under-bond succeeds and the TOKEN really moves; the floor is enforced at `registerNode`, which is why an operator can strand capital and still not be registered. The re-registration negative bonds its impostor to minBond FIRST and signs both proofs genuinely, because `_checkRegistrationPreconditions` runs before `_checkBindingOneToOne` - an unfunded impostor would revert on the bond floor and pass for the wrong reason.

The admin_rpc drain stub needed `registry_active`: it hand-builds the health JSON precisely so DTO drift fails a test rather than silently deserializing.

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

* docs(plan): record the three deviations from the #1030 plan as executed

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

* docs: drop the #1030 implementation plan from the repo

The plan was scaffolding for the change, not a design artifact the repo needs to carry: ADR 019 already owns the serve-gate decision, and the PR description carries the rationale. Leaving it in docs/ would have introduced a plans/ convention the repo does not otherwise have.

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

* refactor(node): drop the serve-path registration gate; keep the journey (#1030)

Review call on #1768: the gate was a node checking its OWN registration and choosing to refuse. There is no code we can force a node to run, so an operator who wants to sell unregistered deletes the check and rebuilds - it constrained only the honest, which is not enforcement. Reverts the serve path, the not_registered reject reason and counter, and the ClientHandlerDeps staker-set wiring; crates/node/src/handlers/, metrics.rs and tests/ are now byte-identical to main.

The real constraints are external and already exist. An unregistered operator never called declareMbps, so DecdnGovernor._getVotes caps each epoch at declaredMbpsAtEpoch x epochSeconds x BYTES_PER_MBIT_SECOND = 0 and it accrues no vote weight (contracts/src/DecdnGovernor.sol:265, landed in #1760). And a client should not select an upstream it cannot slash. Neither can be removed by patching the daemon.

ADR 019 Phase 4 now says this outright, including why a serve-side gate should not be re-added, so the acceptance criterion stops reading as a daemon obligation.

Kept: registry_active on admin health, now documented as purely diagnostic. It is the answer to "my node is up and earning nothing" - more necessary without a gate, not less, since nothing on the wire says so and the traffic simply never arrives. It is also what lets the journey assert the daemon observed its own registration live.

Kept: the EjectedByBlacklist topic0 fix, which is a genuine registry-route bug affecting DHT admission - a peer-side decision, not self-policing.

The journey keeps its arc (bare -> real decdn setup -> paid delivery on one process, no restart) and both negatives. Only the refusal assertion is gone; the no-restart poll on registry_active stays, since it proves the registry projection is live rather than sampled at boot.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
thiras pushed a commit that referenced this pull request Aug 23, 2026
…ed pool

Strengthen the multi-source solvency coverage (review finding #1): the existing
observation test only proved the pacer SEES deposit-minus-Σcommitted. Add
shared_gate_refuses_a_second_leg_into_a_drained_pool, which proves the gate
actually BLOCKS. A peer lane's ledger is pre-seeded near the deposit; the healthy
lane fetches its own segment, then is refused the reassigned second segment
because the aggregate remaining is below the next voucher cost. Asserts the fetch
ends incomplete, the healthy lane bills exactly one segment (never the refused
second), and combined committed stays within deposit + one in-flight leg — the
honest leg-boundary bound (on-chain redemption is the hard backstop). RED against
a naive own-committed gate: the fetch completes and the lane bills two segments.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
thiras added a commit that referenced this pull request Aug 24, 2026
…#1164) (#1773)

* docs(adr): rewrite ADR 039 as multi-source scheduler; fix bounded-range claims in 005/038

* docs(adr): state eager fan-out explicitly in ADR 039 decision

* feat(client-pull): single-writer present-record flush; drop per-checkpoint fsync

* feat(client-pull): pure segmentation + tail-steal helpers

* fix(client-pull): canonicalize gap edges to close segment-overlap hole

initial_segments and steal_split each rounded a raw, possibly unaligned
byte-range end up to the next bao chunk-group boundary via align_range,
but compared that ceiling against the raw unaligned end. Two gaps
separated by less than one group of held data (or a range whose true
end fell mid-group) could produce two AlignedRanges whose fetch spans
overlapped by up to one group -- a double-fetch and, once the
multi-source scheduler pays per source, a double-pay.

Canonicalize every input span to its enclosing group boundaries (and
merge touching/overlapping spans) before splitting, so every boundary
handed to align_range is already aligned and its ceiling-up can never
carry a segment past where the caller intended it to stop.

* fix(client-pull): reject out-of-bounds gaps instead of silently dropping them

canonicalize_ranges clamped a span's rounded-up end to total_bytes to
handle the blob's legitimate partial last group, but that same clamp
silently absorbed a genuinely out-of-bounds span too: a gap whose
start was at or past total_bytes was dropped, and one whose raw
(pre-rounding) end exceeded total_bytes was silently truncated. This
contradicted the still-documented RangeVerifyError propagation and the
repo's fail-loudly-on-malformed-input convention.

canonicalize_ranges now checks each span's start and raw end against
total_bytes before any rounding, and returns
RangeVerifyError::RangeOutOfBounds -- the same error align_range
itself raises -- for a span that is genuinely out of bounds. The
legitimate final-partial-group clamp (raw end == total_bytes, rounds
up then clamps back down) is unaffected and still succeeds.

* feat(client-pull): multi-source scheduler core with tail-stealing

Fan a request across several paid sources over one shared store (spec
§5.3): bao-aligned segmentation, one worker per source, and a freed
source steals the aligned second half of the largest in-flight range.
One outstanding unit per source (lane correctness). Node path untouched.

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

* feat(client-pull): deadline-based reassignment + steal-cancellation (no double-pay)

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

* fix(client-pull): present-bytes backstop closes completed-range steal double-pay

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

* feat(client-pull): set-valued candidate admission with operator/region spread

* feat(cli): engagement gate + config flags for multi-source fetch

Adds the CLI-side pieces for ADR 039 multi-source fetch: --multi-source
(default on) / --no-multi-source, --max-sources, --multi-source-min-bytes,
--unit-deadline-ms on ClientFetchArgs, and the pure should_multi_source
engagement gate (enabled && total_bytes > min_bytes && admissible >= 2) in
crates/cli/src/commands/fetch.rs, covered by a TDD unit test.

Wiring the gate into drive_fetch/bundle_pull is deliberately deferred: see
task-7-report.md for why multi_source_fetch's single shared ctx/ledger/funder
cannot yet correctly pay several distinct-provider sources at once.

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

* feat(client-pull,cli): per-provider payment lanes + shared solvency for multi-source; wire scheduler into fetch/bundle

multi_source_fetch now takes a SourceLane set — each source paired with its
OWN PoolContext (provider) + PoolLedger — instead of one shared ctx/ledger, so
a voucher is signed against the source's real on-chain provider and each lane's
cumulative advances independently (ADR 039 § Payment model). fill_gap gains an
optional aggregate-committed reader: multi-source workers gate remaining_deposit
on pool_deposit - Σ committed across every lane, so concurrent lanes cannot each
treat the whole deposit as their own; the single-source drive path passes None
and is unchanged. Wired into `decdn fetch`: when should_multi_source engages,
build one per-provider lane per admitted candidate and call multi_source_fetch,
else the single-source failover loop runs unchanged.

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

* test(client-pull): prove shared gate blocks a second leg into a drained pool

Strengthen the multi-source solvency coverage (review finding #1): the existing
observation test only proved the pacer SEES deposit-minus-Σcommitted. Add
shared_gate_refuses_a_second_leg_into_a_drained_pool, which proves the gate
actually BLOCKS. A peer lane's ledger is pre-seeded near the deposit; the healthy
lane fetches its own segment, then is refused the reassigned second segment
because the aggregate remaining is below the next voucher cost. Asserts the fetch
ends incomplete, the healthy lane bills exactly one segment (never the refused
second), and combined committed stays within deposit + one in-flight leg — the
honest leg-boundary bound (on-chain redemption is the hard backstop). RED against
a naive own-committed gate: the fetch completes and the lane bills two segments.

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

* test(e2e): multi-source parallel fetch across two holders

* fix(client-pull): interval flush of present-record bounds crash-loss to one interval (spec §5.5)

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

* fix(client-pull): propagate terminal fetch errors from the multi-source scheduler instead of masking as "all sources failed"

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

* fix(client-pull): scope shared-pool-exhaustion terminality to the multi-source scheduler; keep single-source failover on budget refusal

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

* fix(client-pull,cli): payment-lane, failure-path and coverage fixes from PR review

Address the review on #1773. Payment accounting first, then what happens when
things go wrong, then the coverage that would have caught either.

Payment accounting across lanes:

- `admit_sources` admits at most ONE node per operator. A voucher lane is keyed
  on `(signer, provider)` and `provider` IS the operator address, so filling
  spare slots with a repeat operator built two concurrent voucher streams on one
  watermark and collided two watermark writes under one `LaneKey`. The admitted
  set now shrinks instead. `multi_source_fetch` re-checks the same precondition
  on the lane set it is handed, so the premise is verified at the boundary
  rather than asserted in prose.
- The deposit, the spend that gates it, and the reactive-top-up budget are facts
  of the POOL, not of a lane. They move behind one shared view: the gate
  subtracts the aggregate committed, the top-up budget is counted once per fetch
  rather than once per lane (4 lanes x 3 = 12 real escrows against a documented
  bound of 3), and a landed top-up credits EVERY lane rather than only the one
  that funded it.
- A multi-source lane persists its ARMED cumulative. A tail steal drops the
  victim's `fill_gap` future inside the voucher exchange on a SUCCESSFUL fetch,
  so settling that lane at `committed` persisted below what the node redeems.

Failure paths:

- Retryable worker errors are kept and reported. A failed fetch names each lane
  by its payee and carries the last real error as its cause, so a caller's
  downcast still reaches it — which is what makes the CLI's two-cause cache-miss
  diagnosis reachable on this path at all.
- A failed fan-out falls back to the single-source failover loop unless the
  failure is terminal. It resumes the same `.partial`, so nothing already paid
  for is re-bought.
- The present record is flushed on the error path too, in both `drive` and the
  scheduler: the bytes a failed fetch delivered are paid for.
- `is_complete`'s error is propagated rather than read as "not complete", which
  reported success with no output file on disk.
- A freed worker with nothing to steal PARKS instead of retiring, so it is still
  there when a peer faults and re-queues moments later.
- `steal_split` returns WHICH range it split, deleting a cross-module argmax
  agreement that had no compiler support; a steal that cannot trim its victim is
  declined rather than handed out untrimmed; `pick`/`clear` refuse an
  out-of-range worker index.
- The engagement gate applies its size floor to the probe's reported size before
  opening a pool and a throwaway header stream, and each decline says which
  condition was unmet.

Coverage:

- The stall watchdog had none, and the test named for it exercised the fault
  path. Renamed it, added a `stall_after` source double (a source that wedges
  WITHOUT erroring — the only shape that reaches the watchdog), and covered all
  four branches deterministically under a paused clock.
- The per-lane watermark rule is a pure function with tests: cross the lanes and
  nothing else in the fetch path would notice.

ADR 039 and the CHANGELOG record the behavior.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JjiDQL7FuB8UHGBBpG1PjH

* test(e2e): gate the multi-source journey on both lanes billing, not on exit status

The journey retried `decdn fetch` until it exited 0, because a holder whose
chain watcher has not yet observed the freshly-opened pool refuses the stream
pre-serve. Exit status stopped being a readiness signal once a retryable
refusal on one lane falls back to single-source failover: the fetch now exits 0
having been served by the OTHER holder alone, the retry loop stops, and the
both-holders-paid assertion fails against a fetch that never fanned out.

Wait for what the journey actually asserts — one invocation that bills BOTH
lanes. Requiring both within a SINGLE invocation is what keeps it honest: a loop
that accumulated payments across attempts would pass on two single-source
fetches that each paid a different holder, which is the non-parallelized case
this journey exists to rule out. Each attempt clears the output and `.partial`
set first, so a resumed fetch cannot bill one lane for the other's remainder.

Reproduced at ~1 run in 4 before, 10/10 green after.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JjiDQL7FuB8UHGBBpG1PjH

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Ant Somers <[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]>
yigitdot added a commit that referenced this pull request Sep 28, 2026
poolId = keccak256(owner, ownerPoolNonce) names neither the chain nor the
contract, so a pool id repeats across PaymentPool redeploys. The seller
lane table, both pending-settle sets and the watcher checkpoint carried no
deployment, so a seller repointed with its data dir intact kept the old
deployment's frontier for a returning buyer's reissued pool: it rejected
the buyer's first voucher as AmountRegression and redeemed the old
signatures against the new contract.

PersistentPoolStateStore::open now takes the configured Deployment
(chain id + PaymentPool) and keeps a stamp in lanes.redb. A matching
stamp is a read-only check; a missing stamp is claimed without dropping
rows; a foreign stamp drops the lanes, pending settles and checkpoints
(lanes in the same commit as the new stamp) and logs the drop at WARN.

The redeploy e2e gains the acceptance journey: SEEDER #1 repointed at
the redeploy with its data dir intact serves the reissued pool from zero.

Closes #2181.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
yigitdot added a commit that referenced this pull request Sep 29, 2026
poolId = keccak256(owner, ownerPoolNonce) names neither the chain nor the
contract, so a pool id repeats across PaymentPool redeploys. The seller
lane table, both pending-settle sets and the watcher checkpoint carried no
deployment, so a seller repointed with its data dir intact kept the old
deployment's frontier for a returning buyer's reissued pool: it rejected
the buyer's first voucher as AmountRegression and redeemed the old
signatures against the new contract.

PersistentPoolStateStore::open now takes the configured Deployment
(chain id + PaymentPool) and keeps a stamp in lanes.redb. A matching
stamp is a read-only check; a missing stamp is claimed without dropping
rows; a foreign stamp drops the lanes, pending settles and checkpoints
(lanes in the same commit as the new stamp) and logs the drop at WARN.

The redeploy e2e gains the acceptance journey: SEEDER #1 repointed at
the redeploy with its data dir intact serves the reissued pool from zero.

Closes #2181.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thiras pushed a commit that referenced this pull request Sep 30, 2026
* fix(node): bind the seller store to its PaymentPool deployment

poolId = keccak256(owner, ownerPoolNonce) names neither the chain nor the
contract, so a pool id repeats across PaymentPool redeploys. The seller
lane table, both pending-settle sets and the watcher checkpoint carried no
deployment, so a seller repointed with its data dir intact kept the old
deployment's frontier for a returning buyer's reissued pool: it rejected
the buyer's first voucher as AmountRegression and redeemed the old
signatures against the new contract.

PersistentPoolStateStore::open now takes the configured Deployment
(chain id + PaymentPool) and keeps a stamp in lanes.redb. A matching
stamp is a read-only check; a missing stamp is claimed without dropping
rows; a foreign stamp drops the lanes, pending settles and checkpoints
(lanes in the same commit as the new stamp) and logs the drop at WARN.

The redeploy e2e gains the acceptance journey: SEEDER #1 repointed at
the redeploy with its data dir intact serves the reissued pool from zero.

Closes #2181.

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

* docs(changelog): note the seller store's PaymentPool deployment binding

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

* fix(node): guard the deployment rebind and make its drop auditable

Review follow-ups on the seller-store deployment binding (#2181):

- Boot verifies the configured deployment against the live chain before
  the lane store opens: eth_chainId must match blockchain.chain_id and
  the PaymentPool address must have code. A config typo aborts bring-up
  instead of triggering the irreversible seller-state drop.
- The voucher EIP-712 domain is derived from the same Deployment the
  store is stamped with (one parse in build_infra, threaded via Infra).
- The rebind logs each dropped lane (pool id, signer, provider,
  unredeemed value) as the last record of its claim, plus a summed
  forfeited_micro_usdc on the summary WARN.
- Deployment::from_bytes decodes without the panicking Address::from_slice.
- New unit tests: a crashed drop is repeated by the next boot, a foreign
  stamp over an absent lane table drops cleanly, buyer.redb survives the
  seller-side drop, the stamp survives record/flush cycles, and the
  unstamped claim keeps every family.
- Docs: the unstamped-store case is a pre-stamp store (not "new"), the
  config-revert crash hazard is documented, ADR 003 sentences are split
  to STE form, the e2e module doc names both watched logs and pins the
  blob-price ordering its mutation detection rests on, and the operator
  runbook gains a "Repointing at a redeployed PaymentPool" section.

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

* docs(runbook): drain sub-floor lanes before repointing at a new PaymentPool

Every redeem path, graceful shutdown included, submits a chunk only when
its unredeemed total clears blockchain.redeem_threshold_micro_usdc (config
enforces > 0), so sub-floor lanes never redeem and decdn_unredeemed_usdc
may never reach 0. Drop the floor to 1 µUSDC on the old deployment first,
drain, stop gracefully, then repoint. Also drop the pending-settle wait:
those tables have no production writer.

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

* docs(node): the shutdown redeem sweep applies the configured floor

The redeem path docs still described a forced close/shutdown path passing
floor == 0. The close-redeem path was the only zero-floor caller and is
gone; every caller, including the graceful-shutdown sweep, passes
blockchain.redeem_threshold_micro_usdc, which config keeps above zero, so
sub-floor dust defers on every path. Correct the redeem_planned_lanes,
chunk_redemptions, flush_store_durable and final_redeem_sweep docs, the
non-strict flush-failure log line, and two test comments.

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

* fix(node): probe PaymentPool identity at boot and report the full forfeited claim

Second review pass on the deployment-binding follow-ups:

- The deployment preflight now also calls PaymentPool.usdc(): a code-
  presence check alone passes a sibling contract pasted from the same
  deploy manifest — the likeliest wrong-address typo — and the rebind
  would still drop the lanes. A non-PaymentPool target surfaces as a
  permanent contract error and aborts at once. The preflight is generic
  over the provider and gains five mocked unit tests (match, chain-id
  mismatch, codeless address, non-PaymentPool target pinned as
  not-retried, transient fault retried). It runs on its own retry
  budget, and the misplaced doc block that had swallowed
  check_rpc_reachability's rustdoc is re-attached.

- The forfeit audit reports the lane's full claim: forfeited_value is
  owed() — the signed cumulative plus the chain-verified frontier —
  minus the paid watermark, the figure the redeemer collects;
  last_amount alone understates a lane by up to one whole chain. The
  summary WARN gains undecodable_lanes so a partial sum announces
  itself, and a table or iterator error during the walk degrades to a
  WARN instead of aborting bring-up: the walk is observational, and the
  delete that follows arbitrates real corruption. New tests pin the
  value math, the corrupt-foreign-row tolerance, the crash-state setup
  deletes, and the absent-lane-table precondition; journey 3 asserts
  undecodable_lanes=0 and the per-lane last-record line.

- Docs: the rpc_url parse error no longer echoes the URL (it can embed
  an API key); two remaining "forced close" passages in receipt_log and
  the watermark-reconcile comment now name the shutdown sweep; the
  redeem floor is described as per-chunk (dust rides alongside larger
  lanes); the runbook drain procedure waits out the gauge's initial
  zero, watches decdn_redemption_skipped_insolvent_total for held
  drained-pool lanes, and tallies from the final boot's summary line;
  the CHANGELOG tells operators to leave buyer.redb in place.

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

* test(node): encode preflight mock faults as None, matching the workspace convention

The preflight test helpers returned Result<Value, ()> so they could sit
beside Err(()) fault entries, which needed three
#[expect(clippy::unnecessary_wraps)]. Follow the Option convention the
other mixed-response mock helpers use (incentive payment_pool.rs mocked,
cli fetch.rs run): the helpers return a bare serde_json::Value, the call
sites wrap in Some, and None faults the call. The list stays JSON rather
than Bytes because eth_chainId answers with a quantity.

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

* test(node): queue preflight mock answers as a local MockAnswer enum

Replace the Option encoding in the preflight test provider with a small
local enum, MockAnswer { Ok(serde_json::Value), TransientError }, so each
queued answer names what it is. The helpers keep returning a bare
serde_json::Value and call sites wrap them. buyer_channel.rs's MockCall is
not reused: it holds Bytes, and eth_chainId answers with a JSON quantity.

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.

2 participants