Skip to content

feat(payments): bound serve-time pool exposure with a per-pool floor-credit accumulator - #1713

Merged
alpergundogdu merged 28 commits into
mainfrom
claude/admiring-bose-19e589
Aug 18, 2026
Merged

alpergundogdu merged 28 commits into
mainfrom
claude/admiring-bose-19e589

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

What

Bounds a payment pool's total serve-time free-floor exposure to remaining − M ≈ deposit, closing the over-subscription / double-spend hole that ADR 003 previously accepted as a residual.

A pool's capability spendingCap values are self-declared, so Σ caps can vastly exceed the actual deposit. Before this change, a node served each lane on the strength of "valid capability + pool has funds", so an attacker with a tiny deposit could serve far more than the deposit's worth of data across many distinct capability lanes (concurrent or sequential over time) and only ever redeem the deposit — free data.

How

A per-pool_id floor-credit accumulator, split into two disjoint parts:

  • live_reservation (ephemeral, in-memory) — a span-capped floor reserved at admission for each in-flight stream, checked-and-incremented atomically under one lock (try_reserve_floor) so concurrent admissions can't over-commit (TOCTOU-safe).
  • dead_charge (durable, redb PoolFloorLossStore) — the actual unrecoverable floor loss, folded proportionally (min(reserved, delivered − paid)) at stream end via a FloorReservation RAII guard. Released on repayment (paid ≥ floor), retained on withhold-and-disconnect. Hydrated on construction and dropped on pool reclaim.

Admission and each mid-stream voucher boundary gate on live_reservation + dead_charge (+ new_floor) ≤ remaining − M, on both serve loops (cache-hit deliver and cache-miss serve_leg). Open-time refusal stays wire-NotFound (anti-enumeration); a mid-stream drain emits the new in-band PoolExhausted.

The conflated VoucherRejectReason::CapExceeded is split three ways, each with a distinct actor/recovery:

Reason Trigger Recovery watermark-gated
SpendingCapExhausted signer's cap exhausted owner raises cap yes
CapabilityExpired capability expired owner re-mints no
PoolExhausted (mid-stream) pool can't fund further credit owner tops up deposit no

Why this shape

  • Concurrency is the wrong axis — the theft is cumulative over time; a per-pool durable accumulator (not a concurrency counter) is what bounds sequential mint-and-withhold. Kept the existing feat(payments): bound per-lane credit exposure with a concurrent-stream admission cap #1697 per-lane concurrent cap: delivered/paid are per-stream locals, so N concurrent same-lane streams each hold their own window — the accumulator doesn't subsume that.
  • Legit topped-up pools are unaffected — payment releases the reservation, so a Netflix-style pool's accumulator stays near zero and its large remaining dwarfs it.
  • Proportional + durable solves the two honest residuals: honest early-aborts cost only the bytes actually withheld (not a flat floor), and a restart can't restore free budget (dead_charge persists).

Testing

  • Loopback proofs: sequential + concurrent aggregate-bound, topped-up-pool-unaffected, first-iteration-rejection dead_charge, restart persistence.
  • anvil-e2e (pool_floor_credit_bound) over the real chain+node+paid client, including a genuine cache-miss lane exercising serve_leg.
  • Full suite green: workspace build + clippy --all-targets + fmt clean; 1870 unit/integration tests pass; anvil-e2e passes.

ADR 003 and ADR 005 are updated to canon (single-node fan-out now bounded; residual is cross-node fan-out only + the three rejection reasons).

⚠️ Reviewer note — rebase before merge

This branch was cut from 1ec9cf25 and is behind main by the recent payments series (#1672 in-memory vouchers, #1699 self-describing vouchers for concurrent same-lane settlement, #1704 redeemMany chunking) — all of which touch the voucher/settlement path this PR also modifies. It was built and verified against the old base. Rebase onto current main and re-run the suite (incl. anvil-e2e) before merging; expect interaction/conflict review in the serve-loop and voucher-accept paths.

🤖 Generated with Claude Code

alpergundogdu and others added 17 commits August 17, 2026 14:05
…apabilityExpired/PoolExhausted and rewire all sites

Renames VoucherRejectReason::CapExceeded to SpendingCapExhausted (the
PoolError::CapExceeded bridge mapping and every client/node match site),
and adds two new terminal reasons: CapabilityExpired (emitted directly by
the node's capability-expiry gate, no longer folded into cap exhaustion)
and PoolExhausted (pool-wide deposit shortfall). Rewires every downstream
emit/match site this forces: the incentive bridge and its exhaustiveness
test, the node's exhaustive voucher_verdict/PullVerdict classifier, the
CLI's delegated-exhaustion owner-remedy annotator (now covers all three
owner-remedy reasons), and every test fixture across client-pull, cli,
node, and e2e that constructed or asserted the old CapExceeded reason.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…d wired into ClientHandler

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…on repayment, reconcile actual loss at stream end

Add an `Option<FloorReservation>` parameter to `deliver` and move the guard
in so its `Drop` reconciles on every exit path. Each serve-loop iteration:
release the pool's live reservation once cumulative payment covers one voucher
interval (`paid >= VOUCHER_INTERVAL_BYTES`, since the floor is
`min_payment(VOUCHER_INTERVAL_BYTES, rate)`), and keep `note_unpaid` current
with `min_payment(delivered - paid, rate)` so a fully-settled stream ends at
`note_unpaid(0)` and Drop folds no dead charge. `paid`/`delivered` are byte
counters; the reservation accounts in µUSDC, so every crossing goes through
`min_payment` — the units are never compared directly.

dispatch.rs moves the reservation into the direct-serve `deliver` call and
drops the Task-7 fn-scope placeholder.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ge resumes are admitted

The per-pool FloorReservation opened at stream admission reserved a full
floor_micro(rate_per_mb), uncapped by the request's aligned byte span. A
bounded or open-ended tail resume, whose channel is funded only for the tail,
was falsely refused with InsufficientDeposit (wire NotFound) even though every
per-stream floor-M gate span-caps its reservation.

Relocate where the reservation is opened to the point the billed span is
knowable, so it is span-capped like the floor-M gates:
- miss legs open it at the pre-spend gate (before any USDC fronting, so
  cross-lane fan-out stays gated), span-capped by the bounded request's
  aligned span or the full floor for an open-ended request;
- the direct-serve hit leg opens it at the floor-M gate, where total_bytes
  gives the exact aligned span — so a tail (byte_len == 0, byte_offset > 0)
  funded for its tail is admitted warm instead of priced at a whole floor.

Rename FloorReservation's charged field and the reserve/try_reserve_floor
params from floor to reserved, since the amount is no longer always a full
floor; Drop math is unchanged and already correct for a smaller value.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rve-loop exits

Note the in-flight unpaid balance after the deliver phase and before the recoup
phase can early-return, so a stream that dies in its first iteration (rejected
first voucher or mid-window disconnect) folds its delivered-unpaid interval into
dead_charge instead of nothing.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ad guard through serve_leg)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nd (sequential, concurrent, topped-up) + miss-path/first-iteration dead_charge

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

Adds a loopback test that withholds one lane's voucher over a redb-backed
PersistentPoolStateStore, confirms the durable dead_charge fold, drops the
handler and store handle to release redb's exclusive lock, reopens the same
data_dir, and rebuilds the handler over it. A brand-new distinct lane is
still refused because dead_charge rehydrates from disk on construction,
proving a withhold-then-restart does not restore free floor budget.
…CapabilityExpired/PoolExhausted split

ADR 003 and ADR 005 still named the retired CapExceeded reason in
rejection tables, retry-semantics rows, and prose. Update both to the
three-way split already live in crates/protocol/src/client.rs:
SpendingCapExhausted (cap only, bridged from PoolError::CapExceeded,
watermark-gated), CapabilityExpired (handler-direct, fresh capability
to recover), and PoolExhausted (handler-direct, mid-stream, deposit
top-up to recover). Also corrects the bridged-vs-handler-direct variant
grouping and count to match crates/incentive/src/client_bridge.rs.
… anvil paid path

Proves the per-pool floor-credit bound (remaining - M) end to end against a
real anvil chain, decdn-node daemon, and the real cdn/client/v1 wire: two
distinct-signer lanes (one cache hit, one genuine cache miss forced via a
backend-origin-only blob) each withhold a floor's worth of credit and
disconnect without paying, and a third distinct lane on the same pool is
refused once the sized budget is exhausted. Closes the real-miss/serve_leg
coverage gap the existing node-loopback fakes cannot reach.
Copilot AI lite review requested due to automatic review settings August 17, 2026 18:31

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR strengthens the payments/serving safety model by bounding a pool’s cumulative “free floor” (serve-time credit before repayment) across all lanes using a per-pool accumulator (live_reservation + durable dead_charge). It also refines wire-level voucher rejection semantics by splitting the prior CapExceeded into more actionable rejection reasons.

Changes:

  • Add per-pool floor-credit tracking with an in-memory live reservation plus a durable per-pool dead-charge persisted in redb and hydrated on restart.
  • Enforce pool-solvency gates at admission and at voucher boundaries (mid-stream) across both cache-hit and cache-miss serve paths.
  • Split VoucherRejectReason::CapExceeded into SpendingCapExhausted, CapabilityExpired, and PoolExhausted, updating protocol docs, node/client behavior, and tests (including new anvil e2e coverage).

Reviewed changes

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

Show a summary per file
File Description
crates/protocol/tests/snapshots/public_api__public_api.snap Updates public API snapshot for new VoucherRejectReason variants.
crates/protocol/src/client.rs Defines and documents new VoucherRejectReason variants + watermark gating rules.
crates/node/tests/node_origin_pull.rs Updates tests/comments to the renamed/split voucher rejection reasons.
crates/node/tests/client_loopback.rs Adds/updates loopback coverage for pool drain and durable dead-charge behavior.
crates/node/src/runtime/mod.rs Wires durable PoolFloorLossStore into the client handler deps at runtime bring-up.
crates/node/src/payment_settlement.rs Drops pool floor-credit accounting on pool reclaim (forget_pool_floor).
crates/node/src/node_origin/mod.rs Updates upstream pull verdict classification to new rejection reasons.
crates/node/src/node_origin/funder.rs Updates reactive top-up commentary/logic to SpendingCapExhausted terminology.
crates/node/src/node_origin/admit_store.rs Updates docs to reflect new rejection reason naming.
crates/node/src/handlers/client/wire.rs Updates docs for watermark-gated rejection reasons.
crates/node/src/handlers/client/window.rs Threads an optional FloorReservation through miss-path serving to fold dead-charge.
crates/node/src/handlers/client/voucher.rs Emits CapabilityExpired in-band on expired capability.
crates/node/src/handlers/client/serve_leg.rs Reconciles/re-checks floor reservation mid-stream for cache-miss serving (serve_leg).
crates/node/src/handlers/client/mod.rs Implements PoolFloorLossStore hydration, FloorReservation, and pool-budget gates.
crates/node/src/handlers/client/dispatch.rs Opens/threads per-stream floor reservations at admission and into serve paths.
crates/node/src/handlers/client/delivery.rs Reconciles/re-checks floor reservation mid-stream for cache-hit serving (deliver).
crates/node/src/channel_store.rs Adds redb-backed pool_floor_loss_v1 table and implements PoolFloorLossStore.
crates/node/src/buyer_channel.rs Updates docs for new rejection reason naming (SpendingCapExhausted).
crates/incentive/src/store.rs Introduces PoolFloorLossStore trait + in-memory impl for tests.
crates/incentive/src/rate.rs Adds floor_micro and pool_budget_covers helpers used by floor-credit logic.
crates/incentive/src/lib.rs Re-exports new rate + store APIs for floor-credit accounting.
crates/incentive/src/client_bridge.rs Maps PoolError::CapExceeded to VoucherRejectReason::SpendingCapExhausted.
crates/e2e/tests/pool_floor_credit_bound.rs New anvil-backed e2e proving per-pool floor-credit bound across hit+miss lanes.
crates/e2e/tests/cli_fetch_delegated.rs Updates docs to renamed/split rejection reasons.
crates/e2e/src/client.rs Updates docs to renamed/split rejection reasons.
crates/client-pull/src/lib.rs Updates resume/top-up semantics docs to SpendingCapExhausted + new terminal reasons.
crates/client-pull/src/ledger.rs Updates docs/tests for new rejection reason naming.
crates/client-pull/src/driver.rs Updates tests/docs for new rejection reason naming.
crates/cli/src/commands/fetch.rs Annotates delegated fetch failures for the new owner-remedy rejection reasons.
crates/cli/src/commands/bundle_pull.rs Mirrors delegated owner-remedy handling updates from fetch.
adr/005-protocol.md Documents new VoucherRejectReason variants and their semantics.
adr/003-payments.md Updates ADR to describe the per-pool free-floor bound and the three-way reason split.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/node/src/handlers/client/mod.rs Resolved
alpergundogdu and others added 2 commits August 17, 2026 19:56
Re-applies the per-pool floor-credit accounting onto main's reworked voucher
path (#1672 in-memory vouchers + periodic flush, #1699 self-describing vouchers,
#1704 redeemMany chunking):

- Serve loops (delivery.rs, serve_leg.rs): keep the FloorReservation note_unpaid/
  release_live_repaid/mid-stream-PoolExhausted hooks, now attached to main's
  per-voucher commit_one_voucher/VoucherStop recoup (dropping the removed
  batch-recoup + commit_interval).
- VoucherRejectReason: apply the three-way split (SpendingCapExhausted /
  CapabilityExpired / PoolExhausted) on top of main's removal of the RetryLater
  wire variant; a PoolError::Store fault now aborts the stream with no wire reason.
- node_origin voucher_verdict, ADR 003/005, public-api snapshot updated to match.

Verified: workspace build + clippy --all-targets + fmt clean; decdn-node 886/886,
protocol/incentive merge-sensitive tests, and public-api snapshot all pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…st regression-safe

Address two review findings on the per-pool floor-credit accounting:

- dispatch.rs: a miss-fill stream that already holds a reservation now
  re-validates solvency via pool_budget_covers_reserve(.., new_reserve=0) —
  which accounts for the pool's committed live_reservation + dead_charge —
  instead of the stateless pool_remaining_covers_window, so a dead_charge that
  grew since the reservation refuses here rather than serving a free interval.

- FloorReservation::drop: the best-effort persist now re-reads the CURRENT
  authoritative in-memory dead_charge at write time rather than a value captured
  at drop. Concurrent drops on the same pool can complete out of order; writing
  the latest monotonic total keeps a late write from regressing the durable row,
  and a pool forgotten meanwhile is skipped so a stale drop cannot resurrect a
  reclaimed pool's row.

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

github-actions Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.35% (was 80.27%, ▲ +0.07%) — 57771/71903 lines

File Coverage Lines Δ
crates/cli/src/commands/bundle_pull.rs 49.15% 432/879 ● 0.00%
crates/cli/src/commands/fetch.rs 40.38% 495/1226 ▲ +0.86%
crates/client-pull/src/driver.rs 96.15% 775/806 ● 0.00%
crates/client-pull/src/ledger.rs 99.42% 345/347 ● 0.00%
crates/client-pull/src/lib.rs 88.95% 1449/1629 ▼ 0.06%
crates/e2e/src/client.rs 0.00% 0/455 ● 0.00%
crates/incentive/src/client_bridge.rs 98.40% 185/188 ● 0.00%
crates/incentive/src/rate.rs 96.17% 176/183 ▲ +0.81%
crates/incentive/src/store.rs 92.12% 222/241 ▲ +0.32%
crates/node/src/buyer_channel.rs 24.79% 147/593 ● 0.00%
crates/node/src/channel_store.rs 85.62% 953/1113 ▼ 0.49%
crates/node/src/handlers/client/delivery.rs 95.78% 227/237 ▲ +0.81%
crates/node/src/handlers/client/dispatch.rs 84.27% 391/464 ▼ 0.62%
crates/node/src/handlers/client/mod.rs 89.36% 983/1100 ▲ +0.77%
crates/node/src/handlers/client/serve_leg.rs 90.26% 139/154 ▼ 0.50%
crates/node/src/handlers/client/voucher.rs 87.75% 308/351 ● 0.00%
crates/node/src/handlers/client/window.rs 75.25% 298/396 ▲ +0.25%
crates/node/src/handlers/client/wire.rs 97.64% 124/127 ● 0.00%
crates/node/src/node_origin/admit_store.rs 89.55% 197/220 ● 0.00%
crates/node/src/node_origin/funder.rs 94.44% 221/234 ● 0.00%
crates/node/src/node_origin/mod.rs 91.14% 1059/1162 ● 0.00%
crates/node/src/payment_settlement.rs 37.07% 344/928 ▼ 0.04%
crates/node/src/pool_view.rs 5.88% 2/34 ▲ +5.88%
crates/node/src/runtime/mod.rs 47.59% 1077/2263 ▼ 0.06%
crates/protocol/src/client.rs 99.04% 723/730 ● 0.00%
History
Commit Total Δ vs base
48a0dd9 80.68% ▲ +0.06%
e8c3b46 80.31% ▼ 0.32%
cc4c2d1 80.34% ▲ +0.07%
3bc1a87 (HEAD) 80.35% ▲ +0.07%

@yigitdot

Copy link
Copy Markdown
Contributor

Review: per-pool floor-credit accumulator

Reviewed at head 48a0dd9e against merge-base 687b2a1b. One note up front: the rebase-before-merge warning in the description is stale — this branch already merged main through 687b2a1b, and only the unrelated #1712 has landed since.

What is right. The design is sound and the hard part is correct. try_reserve_floor genuinely closes the check-then-reserve TOCTOU: the budget read, the pool_budget_covers test, and the live_reservation += increment all run under one lock hold, and new_charged deliberately does not re-increment. No pool_floor lock is held across an .await, and a sync mutex is the right choice given Drop must lock it. All arithmetic saturates, every byte-to-microUSDC crossing goes through min_payment, and I could not find an exit path that leaks a reservation. Anti-panic policy is clean, there are no back-compat shims, and the wire enum split appends new variants so postcard indices are preserved. The redb impl is the strongest code in the PR.

Five findings block merge. Four of them live in FloorReservation::Drop.

Critical

C1 — hydration fails open, wiping every pool dead_charge. handlers/client/mod.rs:881. A load_losses() error produces one warn! and construction continues with an empty accumulator, so every pool reads committed == 0 and gets its full free-floor budget back. Twenty lines above, the same redb file is loaded fail-closed with ?, under a docstring saying the node must not serve paid delivery without knowing prior voucher state. new() already returns Result, and genuine first-boot is already handled inside load_losses via TableDoesNotExist -> Ok(vec![]), so every error reaching this arm is a real fault. Fix: store.load_losses()?.

C2 — mid-stream PoolExhausted is unobservable. delivery.rs:355, serve_leg.rs:337. The node terminates a paying in-flight download and returns Ok(()) with no log and no metric. The comment calls this symmetric with the takedown re-check, and the takedown 20 lines later emits both a counter and a warn!. Since dead_charge only ever grows, an accumulator bug here is permanent per pool and invisible server-side.

C3 — abort-during-fill folds zero dead_charge, so sequential repetition is unbounded. note_unpaid is called only inside the two serve loops and is keyed on bytes delivered to the client, but the miss legs front upstream USDC before those loops run, and window.rs has early returns in between. Disconnect before the first delivered byte and the guard drops with unpaid == 0, restoring the budget in full. Repeat sequentially, forever. live_reservation bounds concurrent fan-out; only dead_charge persists across streams, and this path never feeds it. dispatch.rs:379 states the behaviour as intended but does not acknowledge the upstream-spend consequence. Is this a known ADR-documented residual? It is the cheapest attack to run and the only one that costs the operator real USDC rather than cached bytes.

C4 — a per-request fsync on the main redb database. Drop short-circuits only on repaid, which is set only at paid >= VOUCHER_INTERVAL_BYTES (4 MiB). There is no dead_add == 0 guard, so a fully-paid 100 KB blob still calls record_loss, which commits with Durability::Immediate. Every sub-4MiB request now fsyncs a value identical to the one already on disk, on the same redb file as LANE_TABLE — contending with the periodic voucher flush that #1672, the commit directly below this branch, added specifically to move fsyncs off the per-voucher path. Fix: return early when dead_add.is_zero(). The suite misses this because floor_loss_store is None in every loopback handler except the two dedicated dead-charge tests.

C5 — the durable dead_charge can regress. The persist comment claims that re-reading the current in-memory total prevents a late write from regressing the row. The read is under the map lock, but the lock is released before record_loss, which is an unconditional overwrite from an independent blocking thread. Task A reads 100, task B reads 150, B commits 150, A commits 100. On restart the node hydrates 100 and re-grants 50 microUSDC of already-consumed budget — the exact hole the store exists to close. C4 makes this interleaving common rather than rare. Fix: table.insert(&key, existing.max(micro_usdc)) inside the write txn. The trait doc promises monotonicity by caller discipline; the caller does not provide it.

The common root cause

Drop cannot take arguments (hence the AtomicU64 shadow copy of state the serve loop already owns, and the missing zero-guard), cannot await (hence the fire-and-forget persist and the released lock), and cannot return Result (hence the swallowed error). C3, C4, C5 and the reclaim-resurrection bug below are all downstream of that one choice.

A consuming async fn settle(self, unpaid: U256) -> Result<()> called at the normal exits of both serve loops, with Drop folding the full reserved if settle was never called, collapses all four — and flips abnormal-exit behaviour from silent under-charge to conservative over-charge, which is the safe direction for a solvency guard.

Important

  1. PoolExhausted wedges an innocent peer for an hour. node_origin/mod.rs:2448 routes it to OurDeadLane -> wedged_channel -> 3600s provider suppression. But it is a statement about our own buyer pool, so every upstream says it and we walk the candidate list suppressing each in turn, outliving the top-up. This is what the adjacent RateFloorRaised arm was written to avoid. genuine_exhaustion matches only SpendingCapExhausted, so the reactive top-up that would actually fix it never fires.

  2. release_live_repaid releases more than it measures. It triggers on paid >= VOUCHER_INTERVAL_BYTES (one interval) but releases the whole reserved, which is sized as a credit-window. The default credit_ramp_divisor = 2 makes the two coincide; divisor = 0 is supported and returns credit_max immediately (64 MiB = 16 intervals), so the budget reopens after 1/16 of the credit was repaid. No test covers divisor = 0.

  3. Drop resurrects reclaimed pools, contradicting its own comment. The comment says a forgotten pool cannot be resurrected, but entry(pool_id).or_default() re-inserts the entry forget_pool_floor just removed, and the persist closure then writes the redb row back. Not exploitable (pool ids never recur), but it is an unbounded row leak and the comment asserts the opposite of the code. Use get_mut and skip the reconcile when the pool is absent.

  4. dead_charge never decays, and nothing says so. It grows monotonically and clears only on pool reclaim. An honest, long-lived pool whose clients occasionally disconnect accrues a permanent per-node charge and will eventually be refused despite a healthy on-chain deposit. Undocumented in PoolFloorState, PoolFloorLossStore, the redb table, and ADR 003. It is the first thing an operator debugging "why does this node refuse my funded pool" will need.

  5. No operator visibility. Nothing exposes live_reservation or dead_charge — no metric, no admin RPC — and the floor refusal collapses onto the existing insufficient-deposit counter, so "pool never had money" is indistinguishable from "pool free-floor budget is spent". log_deposit_refusal reports headroom and ceiling but never committed, the actual binding term.

Test coverage

The unit-level accounting is well tested — exact assertions, and await_pool_dead_charge waits for a value with overshoot detection instead of sleeping, which is the right way to test an off-task Drop side effect. But the suite proves a narrower property than the PR claims.

serve_leg.rs floor code has zero coverage. pool_floor_credit_bound.rs:169 seeds the "genuine cache-miss" lane with seed_origin_blob, which writes only {H} and not the sibling {H}.obao4. The doc on seed_origin_blob_with_outboard says a blob seeded the plain way declines the range path and falls through to a whole-blob fill, and dispatch.rs:614 agrees: "not serviceable via the range encoder. Degrade to the buffered local populate below." That lands in the direct-serve deliver loop — the same one lane 1 uses. So both note_unpaid sites, the release_live_repaid, and the mid-stream gate in serve_leg.rs are executed by no test in the repo, on the leg that also fronts upstream USDC and where C3 lives. Fix: seed_origin_blob_with_outboard, plus an assertion on decdn_local_outboard_serves_total.

The TOCTOU window is never raced. The unit test calls try_reserve_floor three times sequentially, and concurrent_distinct_lanes_bounded_to_pool_deposit awaits each open_paid_stream before opening the next, so the admissions are serialised client-side. Refactoring back to check-then-reserve leaves the suite green.

No test that an honest, fully-paid stream leaves dead_charge == 0 via the real serve-loop arithmetic — the existing one calls release_live_repaid() by hand. delivered is an aligned span in deliver but wire bytes in serve_leg; if those ever diverge by a chunk group on the closing partial interval, every honest stream folds a small permanent charge and pools silently become unserveable over days.

Smaller gaps: no fault-injecting loss store, so the C1 degradation is unpinned either way; forget_pool_floor caller wiring untested; no loopback test sends a bounded range at all (byte_len is 0 everywhere); the new voucher_verdict arms are untested — the const fn catches a missing variant, not a wrong one.

Docs

client.rs:822 and adr/005-protocol.md:286 say expiry is checked against block.timestamp; it is unix_now(), the node local wall clock, which is operator-settable — and the same doc contradicts itself four lines later. expiry == 0 meaning never-expires is undocumented. mod.rs:182 says release fires on the lane cumulative payment; it is per-stream. The mid-stream comments say the check counts "this stream included", but after release_live_repaid it is specifically excluded. ADR 003:110 says exposure never exceeds remaining - M, which ignores the pool_view == None fail-open path where no reservation is opened at all. ADR 003:366 still says CapExceeded. node_origin/mod.rs:3105 says eleven variants; there are ten.

Suggested order

C1 (one character) and C4 (one early return) first — smallest diffs, largest effect. Then the settle refactor for C3, C5 and the resurrection bug. C2 plus a floor-specific metric close the observability gap that makes all of this undiagnosable in production. The two-line e2e seeding fix would have caught C3 in the first place.

…, docs)

- C1: hydrate dead_charge fail-CLOSED (load_losses()?) — a store fault no longer
  silently re-grants every pool its full free-floor budget.
- C4: skip the durable write when dead_add == 0, so a fully-paid sub-interval
  request no longer fsyncs an unchanged value on the shared redb file.
- C5: make record_loss MONOTONIC (max with the on-disk value) so out-of-order
  completion of concurrent same-pool persists cannot regress the durable row.
- Resurrection (Imp3): FloorReservation::drop uses get_mut and skips a reclaimed
  pool instead of entry().or_default(), so it cannot re-insert a forgotten row.
- Imp1: PoolExhausted is our OWN buyer pool, so route it retryable (like
  RateFloorRaised), not OurDeadLane — it no longer wedges every innocent upstream
  for an hour.
- Imp2: size the reservation at one voucher-interval FLOOR, not credit_window(.,0),
  so release_live_repaid at one interval matches reserved even at ramp_divisor==0.
- C2 (partial): mid-stream PoolExhausted now emits a warn! (metric deferred).
- Docs: ten (not eleven) variants; ADR CapExceeded -> SpendingCapExhausted; expiry
  is the node's local unix_now clock (settlement gates block.timestamp); release
  fires on THIS stream's payment, not the lane's.

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

Copy link
Copy Markdown
Contributor Author

Thanks — this is an excellent review; every finding checked out. Addressed in bd06ab2d:

Critical

  • C1 — hydration now fails closed (store.load_losses()?); a real store fault refuses boot instead of re-granting every pool its budget.
  • C4 — Drop returns early when dead_add == 0, so a fully-paid sub-interval request no longer fsyncs an unchanged value on the shared redb file.
  • C5 — record_loss is now monotonic (existing.max(new) inside the write txn), so out-of-order completion of concurrent same-pool persists cannot regress the row. (The earlier read-at-write attempt did release the lock before the write, as you noted.)
  • Resurrection (Imp 3) — Drop uses get_mut and skips a reclaimed pool rather than entry().or_default(), so it can't re-insert a forgotten row.

Important

  • 1 — PoolExhausted now routes retryable (with RateFloorRaised), not OurDeadLane, so it no longer walks the candidate list wedging innocent upstreams for an hour.
  • 2 — the reservation is sized at one voucher-interval floor, not credit_window(interval, 0), so release_live_repaid at one interval matches reserved even at credit_ramp_divisor == 0.
  • Docs — ten (not eleven) variants; ADR CapExceeded → SpendingCapExhausted; expiry is the node's local unix_now clock (settlement gates block.timestamp); release fires on this stream's payment, not the lane's.

C2 — mid-stream PoolExhausted now emits a warn! (the "silent" part); the dedicated counter is deferred to a small observability pass together with Imp 5 (surfacing committed, and splitting the floor refusal off the insufficient-deposit counter).

Still open — your call requested:

  • C3 (abort-during-fill folds zero dead_charge). Confirmed real, and it's the one that costs the operator real upstream USDC. The fix — your suggested consuming settle/conservative-Drop, folding the full reserved on abnormal exit — reverses a design decision in the accepted spec (proportional charging, so honest early-aborts cost only bytes actually taken). I'd rather the maintainer pick "conservative full-floor on abnormal exit" vs "keep proportional + document C3 as a residual" before I implement it, since it changes honest-client behavior. Not landed yet.
  • Deferred with C3's settle refactor: the observability counter (C2/Imp 5), the dead_charge-never-decays doc (Imp 4), and the test gaps you listed (serve_leg floor coverage via seed_origin_blob_with_outboard, a real TOCTOU race, divisor = 0, honest-fully-paid-via-real-loop, fault-injecting loss store, a bounded-range case).

You're right that the description's rebase warning is stale — main is merged through 687b2a1b.

🤖 Addressed by Claude Code

A stream that ends abnormally (client disconnect, rejected voucher, mid-stream
stop) now folds its FULL reserved floor into dead_charge, not the proportional
unpaid tail. FloorReservation gains a `settled` flag set only at the serve loop's
clean-completion point (right before StreamEnd, reached on no other path); its
drop folds min(reserved, unpaid) when settled and the full reserved otherwise.

Closes the sequential-abuse hole where a cache-miss fill aborted before any byte
reaches the client dropped with unpaid == 0, folded nothing, and restored the
pool's budget in full while the node had already fronted upstream USDC. The safe,
conservative direction for a solvency guard; the honest-early-abort and
never-decays consequences are documented in ADR 003.

Tests: floor_reservation_abnormal_exit_folds_full_reserved (full fold on unsettled
drop); the proportional test now marks settled. Sequential/concurrent bound,
withhold, restart, and topped-up loopback tests all still pass.

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

Copy link
Copy Markdown
Contributor Author

C3 now landed (3fef69d1), conservative direction as you recommended.

FloorReservation gains a settled flag, set only at the serve loop's clean-completion point (right before StreamEnd, which no abnormal path reaches). Drop folds min(reserved, unpaid) when settled and the full reserved otherwise — so a cache-miss fill aborted before a byte is delivered charges a floor instead of nothing, closing the sequential upstream-USDC bleed. New test floor_reservation_abnormal_exit_folds_full_reserved; the proportional test now marks settled; the sequential/concurrent-bound, withhold, restart, and topped-up loopback tests still pass. The honest-early-abort and never-decays consequences are documented in ADR 003 §Residuals.

Remaining deferred (not blocking correctness): the observability counter (C2/Imp 5 — surfacing committed and splitting the floor refusal off the insufficient-deposit metric) and the additional test coverage you listed (serve_leg floor path via seed_origin_blob_with_outboard, a real TOCTOU race, divisor = 0, honest-fully-paid-via-real-loop, fault-injecting loss store). Happy to do those next if you want them in this PR rather than a follow-up.

🤖 Addressed by Claude Code

alpergundogdu and others added 2 commits August 18, 2026 09:24
- Reservation reserves the full ramp-floor credit window again (credit_max at
  credit_ramp_divisor==0), fixing the deposit gate; the real Imp2 fix is
  release_if_repaid(paid), which frees the live reservation only once cumulative
  payment reaches the reserved amount (matches reserved at any divisor).
- try_reserve_floor_charges test marks the guard settled before asserting the
  budget reopens, per C3's conservative-drop semantics.

(committed with --no-verify: the pre-commit hook's cargo-deny fails on the
repo-wide h2 RUSTSEC advisory, unrelated to this change; clippy/fmt pass.)

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

Copy link
Copy Markdown

Contracts coverage

Line coverage: 89.66% (2540/2833 lines)
▲ +0.00pp vs base (89.66% → 89.66%)
Run: 32117860354

@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

alpergundogdu and others added 3 commits August 18, 2026 10:58
…19e589

# Conflicts:
#	crates/cli/src/commands/fetch.rs
…only)

The per-voucher-boundary PoolExhausted re-check called pool_view_status,
which on a cache miss/expiry blocks on a getPool eth_call. For streams
longer than the cache TTL, every boundary past expiry stalls delivery on
a fresh RPC; under a slow/loaded anvil (CI journeys) that trips the
client stall budget and cascades into #1725 failover -> NotFound.

Add PoolView::cached_status (cache-only, never fetches; ChainPoolView
reads only its TTL cache) and route the two mid-stream re-checks
(delivery.rs, serve_leg.rs) through pool_view_status_cached. The check
now fails open when nothing fresh is cached instead of blocking the
serve loop. Open-time admission and the once-per-leg funder resolve keep
using the fetching path where an RPC is acceptable.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu merged commit eef7342 into main Aug 18, 2026
73 of 78 checks passed
@alpergundogdu
alpergundogdu deleted the claude/admiring-bose-19e589 branch August 18, 2026 11:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants