Repository navigation
feat(node): reactive mid-pull deposit top-up on the node-to-node buyer leg (#1530) - #1600
Conversation
…r leg (#1530) The daemon's cache-miss buyer leg reached the wire through `stream_fetch_shared` at a fixed `byte_offset == 0`: it buffered the whole blob and had no resume point. That made the reactive half of the two-tier deposit impossible here — a genuine `InsufficientDeposit` could only be answered by retrying from zero, re-paying for every delivered byte, and then re-exhausting at the same offset on the fresh deposit. So a single node-to-node pull larger than the initial deposit (0.5 USDC, ~50 MB at the stock rate) simply failed, and the node shipped with the proactive low-water refill only. `node_origin/resume.rs` now drives the loop the CLI streaming fetch already drives: `open_progressive_pull` at a live offset, `pull_to_sink` into an in-memory sink, and on a ceiling hit an on-chain top-up followed by a resume at the PAID frontier (`content_paid_frontier`) — so `[frontier, delivered)` is re-fetched and paid exactly once, a bounded over-pay of under one chunk group, and nothing is skipped unbilled. The wallet-less reseed retry that used to live inside `fetch_inner` moves up into the same loop. Differences from the CLI leg, all deliberate: - The `topUp` runs on a detached task awaited through a oneshot. `top_up` waits on `get_receipt()` with no timeout — correctly, since abandoning an escrowing tx does not cancel it — but this runs inside the miss-pull future, which the foreground serve path DROPS at `outer_pull_deadline`. Inline, that cancellation would leave the deposit escrowed and untracked on the client-facing path. - One top-up per pull, not three: the node graduates initial -> working in one 20x step, so a second exhaustion is a pricing problem, not a funding one. - No stale-partial restart branch. The CLI's prefix is an unverified on-disk artifact of another process; ours was chunk-group-verified in this frame, so that branch could only throw away paid bytes. Also: peak memory on this path drops from ~2x the blob to ~1x (the buffered requester held the bao wire form and the decoded content); `ResumeOffsetPastEnd` gets a `pull_verdict` arm so our own frontier arithmetic cannot score an honest peer `Unreachable`; the settle wait and the receipt are excluded from the elapsed time feeding the delivery-speed reputation signal; and the proactive and reactive legs now share one `fund_channel` kernel so their allowance posture and escrowed-but-untracked grading cannot drift. Test fixtures that went silent or errored mid-stream were serving filler bytes. The incremental decoder verifies each chunk group as it lands, so filler is now CORRUPTION detected before the silence or the error those tests are about. They serve honest bao prefixes instead, which is what their doc comments already claimed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (8)
🚧 Files skipped from review as they are similar to previous changes (4)
WalkthroughThe node-to-node buffered pull path now supports bounded reactive channel top-ups. It waits for settlement confirmation, resumes from the paid frontier, and tracks payment wait time separately. Shared funding logic and integration tests cover successful, refused, disabled, and invalid exhaustion scenarios. ChangesReactive pull funding
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant NodePull
participant Upstream
participant BuyerChannelService
participant ChainWatcher
NodePull->>Upstream: Pull progressive leg
Upstream-->>NodePull: Return bytes or deposit exhaustion
NodePull->>BuyerChannelService: Request reactive top-up
BuyerChannelService-->>NodePull: Return credited deposit
NodePull->>ChainWatcher: Wait for ChannelToppedUp
ChainWatcher-->>NodePull: Return settlement observation
NodePull->>Upstream: Resume from paid frontier
Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
Coverage reportTotal: 80.48% (was 80.21%, ▲ +0.27%) — 57977/72043 lines
History
|
…t, refusal metering Five review passes over the #1530 reactive top-up. Two findings were real defects, one of them silent corruption. **The resume frontier could overshoot the bytes the leg decoded.** It is derived from `ledger.committed().bytes`, which is the CHANNEL's watermark — shared with every concurrent pull on it (`BuyerLedgers`), and that concurrency is routine: the cache engine coalesces by hash, so two misses for different blobs run concurrent fetches that both rank the same provider. A concurrent pull's acked vouchers inflated the delta past this leg's delivery, and the consequence was not an accounting rounding error: `buf.truncate(frontier)` on a shorter buffer is a no-op (truncate never grows), so the resumed leg spliced its bytes at the wrong position and the blob failed the cache engine's hash check — after the upstream had already been scored `Delivered`. The frontier is now capped at the chunk-group floor of what the leg holds, so any inflation degrades to a bounded re-fetch of already-paid content instead. Pinned twice: a deterministic unit test on `resume_frontier`, and a two-concurrent-pulls wire test that fails on three of three runs without the clamp. **A proactive refill in flight wedged the provider for ~90 days.** `topups_in_flight` was a bare dedup `HashSet`, so a reactive top-up arriving while the low-water refill held the slot could only return the STALE deposit; the caller correctly read that as "no headroom added" and ended the pull on the original `InsufficientDeposit`, which classifies `OurDeadChannel` and suppresses the provider for all hashes until channel expiry — while the refill's funds landed seconds later, with nothing clearing the wedge. And that race is the common case, not a corner: the reuse that starts a miss pull fires the refill precisely when the deposit is nearly spent. The set becomes a map of joinable shared futures (the `opens_in_flight` shape), so the reactive caller joins the in-flight refill and gets its credited deposit. The spawned funding work is now supervised too, so a panic during the unbounded receipt wait — with the caller long dropped at `outer_pull_deadline` — still reports the possibly-escrowed deposit instead of vanishing with the task. Also from the review: - `node_pull_reactive_topup_refused` never counted the case its own doc called "the interesting cause": an uncorroborated `InsufficientDeposit` returned `Terminal`, and the counter is only ticked on the funding path. A distinct `ResumeAction::RefuseFunding` carries it to the metric, and the doc now states the causes it actually has. - The settle-wait budget derived from `event_poll_interval_ms`, which has a config floor but no ceiling — a 60 s chain lane bought 120 s of foreground sleep. Capped at 30 s, and the re-open each step implies is now charged to `paid_wait` too, so none of our funding latency reaches the peer's delivery-speed score. - `top_up_channel`'s trait doc said a channel at the target is a no-op; the real impl targets spendable HEADROOM (a spent-to-target channel gets the full amount — the state this leg exists to rescue). The doc was wrong and the test double had implemented the wrong reading; both fixed, with unit tests on the real impl. - The reseed arm moved out of `client-pull` in #1530 with no coverage of its own, while a still-green test claimed to pin it. Added `decide` tests (advancing bundle reseeds; outranks funding even on `InsufficientDeposit`; bounded) and corrected that test's doc. - `ResumeBudgets` gained transition methods, so the `awaiting_topup_settle` / `settle_waits` pairing cannot be half-updated across the three places that touched it. - Stale cross-references invalidated by #1530: `fetch_inner` and `MAX_TOPUP_ATTEMPTS` in `client-pull` still named `stream_fetch_shared` as the daemon's miss leg; `bind_upstream_ctx` pointed at `stream_fetch_tracked`; ADR 003 described the node's settle bound as the client's. Follow-up filed: #1601 (a wedge whose cause is "cannot pay" outlives the channel becoming able to pay — pre-existing, shared with the proactive refill). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review round applied (667f4e6)Ran five review passes (code, tests, silent-failures, comments, types). Two findings were real defects; both are fixed with regression tests that I verified fail against the unfixed code. The two that mattered1. The resume frontier could overshoot the bytes the leg decoded — silent corruption.
The consequence isn't a rounding error. Fixed by clamping the frontier to the chunk-group floor of what the leg actually holds, so any inflation degrades to a bounded re-fetch of already-paid content. Pinned by 2. A proactive refill in flight wedged the provider until channel expiry (~90 days).
And it's the common case: the reuse that starts a miss pull fires Fixed by converting the set into a map of joinable shared futures (the existing Also applied
Deliberately not done
GateStill worth a rebase before merge — the branch is based on |
Code reviewFound 1 issue:
decdn/crates/node/src/node_origin/resume.rs Lines 373 to 388 in 667f4e6 The subtraction it feeds: decdn/crates/node/src/node_origin/mod.rs Lines 1801 to 1816 in 667f4e6 🤖 Generated with Claude Code - If this code review was useful, please react with 👍. Otherwise, react with 👎. |
…1605) * feat(node): don't reactively top up a near-expiry channel mid-pull The reactive mid-pull top-up (#1530/#1600) funds an exhausted channel and resumes at the paid frontier, but `decide` only checked spendable headroom via `genuine_exhaustion` — never the channel's remaining time to `expires_at`. `topUp` deliberately does NOT extend expiry (the contract forbids it), so a reactive top-up on a near-expiry channel escrowed a fresh working-deposit into a channel that could expire before the resumed leg spent it — stranding capital until `reclaimExpired` and risking the pull failing anyway. The proactive refill runs behind the `try_reuse_live` non-expired gate; the reactive leg had no equivalent expiry posture. Add a governance-tunable near-expiry margin, in seconds, alongside the other blockchain config fields: - `blockchain.buyer_reactive_topup_min_ttl_secs` (default ~1 day, 86_400). Seconds so operators can tune it per chain lane; `0` disables the guard (pre-guard always-top-up behaviour). Wired through `ResolvedBlockchain` and `NodeOriginConfig.reactive_topup_min_ttl` exactly like `working_deposit` / `event_poll_interval`. Before a reactive top-up, if the channel has less than that margin to its on-chain `expires_at`, `decide` returns a new `ResumeAction::NearExpiry` instead of `TopUp`: the pull ends cleanly on the original exhaustion (the same error shape the existing "top-up added no headroom" path returns, so classification — retire the channel, no peer blame — is unchanged), the candidate loop falls through to the next provider, and the next miss opens a fresh, full-lifetime channel. The near-expiry channel's residual deposit is freed by the reclaim sweep at its imminent expiry. Metered via a distinct `decdn_node_pull_reactive_topup_near_expiry_total` counter, apart from `_refused` (a lying peer / funding failure) and a healthy `_topup`. The channel's `expires_at` is read once per pull from `channel_expiry` (`topUp` cannot move it) and carried in `ResumeBudgets`; `NEVER_EXPIRES` (0) and a zero margin both read as "never near expiry". Tests cover the near-expiry skip, the still-fund-when-healthy case with the guard armed, an already-past expiry, the zero-margin disable, and the `NEVER_EXPIRES` carve-out. The mid-flight "open a fresh channel and continue streaming the remainder through it" the issue floats as an optional extension is intentionally left as a follow-up; this PR is the immediate correctness piece (don't fund a doomed channel). Refs #1603. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(node): correct near-expiry remedy wording — wedged, not retired Copilot review (#1605): an `InsufficientDeposit` rejection classifies as `OurDeadChannel` → `wedged_channel`, which KEEPS the channel row (the reclaim sweep needs it to `reclaimExpired` the escrowed deposit) and suppresses the provider until expiry — it deliberately does NOT `retire_channel`/delete the row. Fix the three comments (the `NearExpiry` variant doc, the loop arm, and the metric doc) that mis-described this as "retires the channel". Comment-only. Refs #1603. Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Closes #1530.
The problem
The daemon's cache-miss buyer leg reached the wire through
stream_fetch_sharedat a fixedbyte_offset == 0: it buffered the whole blob and had no resume point. That made the reactive half of the two-tier deposit (ADR 003 § Two-tier deposit) impossible here — a genuineInsufficientDepositcould only be answered by retrying from zero, re-paying for every delivered byte, and then re-exhausting at the same offset on the fresh deposit. So a single node-to-node pull larger than the initial deposit (0.5 USDC, ~50 MB at the stock rate) simply failed, and the node shipped with the proactive low-water refill only.The change
crates/node/src/node_origin/resume.rs(new) drives the loop the CLI streaming fetch already drives:open_progressive_pullat a live offset,pull_to_sinkinto an in-memory sink, and on a corroborated ceiling hit an on-chain top-up followed by a resume at the paid frontier (content_paid_frontier).[frontier, delivered)is re-fetched and paid exactly once — a bounded over-pay of under one chunk group — and nothing is skipped unbilled. The wallet-less reseed retry that used to live insidefetch_innermoves up into the same loop, so nothing regresses.node_origin.rsbecomesnode_origin/mod.rs(a plain module move; the diff of the loop is separate from it).Three deliberate departures from the CLI template
topUpruns on a detached task, awaited through a oneshot.top_upwaits onget_receipt()with no timeout — correctly, since abandoning an escrowing tx does not cancel it (buyer_channel.rs:133-140records the same reasoning foropenChannel). But this runs inside the miss-pull future, which the foreground serve path drops atouter_pull_deadline. Inline, that cancellation would mine the transaction and never runstore.add_deposit— escrowed-and-untracked USDC, silently, on the client-facing path.MAX_TOPUP_ATTEMPTS = 3. The node graduates initial → working in one 20× step at the shipped defaults, so one top-up covers any blob insidecache.max_blob_size_mb. A second exhaustion is a pricing problem no amount of funding fixes, and each attempt costs a transaction plus a settle wait that a client waits through.NotFound.Also in scope
ResumeOffsetPastEndgets apull_verdictarm (OurLocalFault). It was unreachable whilebyte_offsetwas always 0; now it can fire, and without an arm it fell through toUnreachable— gossiping an honest peer as dead on the strength of our own frontier arithmetic.elapsed, the same exclusion the code already applies to the watermark fsync. Otherwise every top-up defames the upstream's delivery-speed score for time we spent on a chain.fund_channelkernel behind both the proactive low-water refill and the reactive top-up, so their allowance posture and escrowed-but-untracked grading cannot drift.BytesMutand the decoded content in aVec.decdn_node_pull_reactive_topup_total/_refused_total. The refused one is what makes 'an upstream lied about our deposit' visible.Settle-wait sizing
After a top-up the upstream refuses to serve until its chain watcher observes
ChannelToppedUp. Waiting that out is money-safe (no voucher sent, offset unmoved). Budgeted at twoblockchain.event_poll_interval_msintervals — 14 s at the 7 s default — rather than a hard-coded constant: one interval leaves no room for the watcher's head TTL, and anything derived from our own timeouts would drift when an operator retunes the chain lane. With top-ups capped at 1 it is spent at most once per candidate, comfortably inside the per-candidate share ofouter_pull_deadline(45 s at defaults), so it cannot starve the fallback walk.Test-fixture change worth reviewing
Five existing tests needed fixing, and the reason is a real behavioural finding. Their fixtures served filler bytes before going silent or sending a mid-stream error. The buffered path accumulated everything and decoded at the end, so the stall or the error fired first. The incremental decoder verifies each chunk group as it lands, so filler is now classified as CORRUPTION before the silence or the error those tests are actually about.
They now serve honest bao prefixes via a new
wire_frameshelper — which is what their own doc comments already claimed ('Three 1 KiB frames: real progress'). The tests still pin exactly what they pinned before.New tests
crates/node/tests/node_origin_pull.rs, on a newserve_with_deposit_ceilingfixture (the only one in the file that can produce a mid-blobInsufficientDeposit) plus aFundingOpenerdouble whose buyer view and upstream ceiling can be driven apart:a_pull_larger_than_the_initial_deposit_tops_up_once_and_completes— the headline case.the_resumed_leg_does_not_re_pay_for_delivered_bytes— the money assertion. Asymmetric bounds on the persisted wire watermark: the floor is one whole-blob bao encoding (falling under it means content was delivered that no voucher covered — computed in wire bytes, since a content-sized floor would pass while the proof overhead went unbilled); the ceiling allows the resumed leg's re-sent root→offset proof path plus under one chunk group, but not a second copy. Verified as a real guard by temporarily forcing the resume offset to 0 — it fails withDOUBLE-PAY: billed 5255945 wire bytes … one encoding costs 3158793.a_node_crying_poverty_while_our_ledger_has_headroom_is_not_funded— an upstream that refuses vouchers it could accept must not be able to make us escrow on demand.a_topup_that_adds_no_headroom_ends_the_pull— a reverted tx or a concurrent refill holding the slot is terminal, not a spin.a_zero_working_deposit_never_funds_a_pull— the documented0-disables sentinel.decideunit tests inresume.rs(no network, no chain) covering everyResumeAction.Docs
ADR 003 § Two-tier deposit and the
buyer_working_deposit_micro_usdcconfig doc both said the reactive leg wasdecdn fetchonly and deferred here — updated (ASD-STE100 for the ADR). TheNodeProgressivePulldoc now records why the window/serve path deliberately gets no reactive top-up: it forwards to a client already holding a signedStreamResponse, and a re-open produces a new bao range encoding that cannot be spliced into a stream in flight.Verification
Follow-ups filed
crates/e2ehas no node-to-node paid-pull test at all today (the threelaunch_pull_through_cachecall sites all passdiscovery_peers = &[]). It is the only thing that can exercise a realtopUpreceipt, the upstream's real watcher lag, and the pre-serve deposit gate.decdn bundle pull#1599 —decdn bundle pull, the last fetch path with the proactive leg only.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes