Skip to content

feat(node): reactive mid-pull deposit top-up on the node-to-node buyer leg (#1530) - #1600

Merged
alpergundogdu merged 2 commits into
mainfrom
feat/1530-node-reactive-topup
Aug 5, 2026
Merged

alpergundogdu merged 2 commits into
mainfrom
feat/1530-node-reactive-topup

Conversation

@yigitdot

@yigitdot yigitdot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1530.

The problem

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 (ADR 003 § 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.

The change

crates/node/src/node_origin/resume.rs (new) 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 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 inside fetch_inner moves up into the same loop, so nothing regresses.

node_origin.rs becomes node_origin/mod.rs (a plain module move; the diff of the loop is separate from it).

Three deliberate departures from the CLI template

  • 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 (buyer_channel.rs:133-140 records the same reasoning for openChannel). But this runs inside the miss-pull future, which the foreground serve path drops at outer_pull_deadline. Inline, that cancellation would mine the transaction and never run store.add_deposit — escrowed-and-untracked USDC, silently, on the client-facing path.
  • One top-up per pull, not MAX_TOPUP_ATTEMPTS = 3. The node graduates initial → working in one 20× step at the shipped defaults, so one top-up covers any blob inside cache.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.
  • No stale-partial restart branch. The CLI's prefix is an unverified on-disk artifact of an earlier process; ours was chunk-group-verified in this frame, so that branch could only throw away paid bytes on the first NotFound.

Also in scope

  • ResumeOffsetPastEnd gets a pull_verdict arm (OurLocalFault). It was unreachable while byte_offset was always 0; now it can fire, and without an arm it fell through to Unreachable — gossiping an honest peer as dead on the strength of our own frontier arithmetic.
  • Settle-wait and receipt time are excluded from the reputation 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.
  • One shared fund_channel kernel behind both the proactive low-water refill and the reactive top-up, so their allowance posture and escrowed-but-untracked grading cannot drift.
  • Peak memory on this path drops from ~2× the blob to ~1× — the buffered requester held the bao wire form in a BytesMut and the decoded content in a Vec.
  • New counters 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 two blockchain.event_poll_interval_ms intervals — 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 of outer_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_frames helper — 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 new serve_with_deposit_ceiling fixture (the only one in the file that can produce a mid-blob InsufficientDeposit) plus a FundingOpener double 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 with DOUBLE-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 documented 0-disables sentinel.
  • Seven pure decide unit tests in resume.rs (no network, no chain) covering every ResumeAction.

Docs

ADR 003 § Two-tier deposit and the buyer_working_deposit_micro_usdc config doc both said the reactive leg was decdn fetch only and deferred here — updated (ASD-STE100 for the ADR). The NodeProgressivePull doc now records why the window/serve path deliberately gets no reactive top-up: it forwards to a client already holding a signed StreamResponse, and a re-open produces a new bao range encoding that cannot be spliced into a stream in flight.

Verification

cargo clippy --workspace --all-targets -- -D warnings   # clean
cargo fmt --all -- --check                              # clean
cargo nextest run --workspace --no-fail-fast            # 2775 passed
cargo deny check                                        # advisories/bans/licenses/sources ok
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --no-deps --document-private-items   # clean

Follow-ups filed

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added reactive deposit top-ups for client fetches and node-to-node cache-miss pulls.
    • Transfers resume from the paid frontier after successful funding.
    • Buyers wait for upstream settlement confirmation before resuming.
    • Added reporting for successful and declined node-to-node top-up attempts.
  • Bug Fixes

    • Improved handling of payment exhaustion, settlement delays, duplicate funding, and invalid resume states.
    • Provider latency measurements now exclude payment-related waiting time.
    • Limited reactive retries to prevent ineffective repeated funding.

…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]>
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: ef31614c-d5a7-4301-a463-ae08ec4a7ca3

📥 Commits

Reviewing files that changed from the base of the PR and between 14355ba and 667f4e6.

📒 Files selected for processing (8)
  • adr/003-payments.md
  • crates/client-pull/src/lib.rs
  • crates/incentive/src/buyer_channel.rs
  • crates/node/src/buyer_channel.rs
  • crates/node/src/metrics.rs
  • crates/node/src/node_origin/mod.rs
  • crates/node/src/node_origin/resume.rs
  • crates/node/tests/node_origin_pull.rs
🚧 Files skipped from review as they are similar to previous changes (4)
  • crates/node/src/metrics.rs
  • adr/003-payments.md
  • crates/node/src/node_origin/mod.rs
  • crates/node/src/node_origin/resume.rs

Walkthrough

The 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.

Changes

Reactive pull funding

Layer / File(s) Summary
Shared channel funding
crates/node/src/buyer_channel.rs, crates/node/src/metrics.rs, crates/incentive/src/buyer_channel.rs
Shared funding handles allowance checks, topUp execution, outcome handling, detached tasks, and reactive-top-up metrics.
Resumable pull engine
crates/node/src/node_origin/resume.rs
pull_blob preserves verified content, classifies failures, waits for settlement, performs bounded top-ups, and resumes from the paid frontier.
Node-origin integration and configuration
crates/node/src/node_origin/mod.rs, crates/node/src/runtime/mod.rs, crates/common/src/config/types.rs, crates/client-pull/src/lib.rs, adr/003-payments.md
Buffered node-origin pulls use the resumable engine and working-deposit and event-poll settings. Documentation describes client and node retry behavior.
Reactive pull validation
crates/node/tests/node_origin_pull.rs
Fixtures and tests cover verified Bao streams, deposit ceilings, successful resume, payment accounting, refusal, invalid exhaustion, concurrency, and disabled or bounded top-ups.

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
Loading

Note

🎁 Summarized by CodeRabbit Free

Your 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 @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.48% (was 80.21%, ▲ +0.27%) — 57977/72043 lines

File Coverage Lines Δ
crates/client-pull/src/lib.rs 90.15% 1428/1584 ▲ +0.38%
crates/incentive/src/buyer_channel.rs 90.05% 380/422 ● 0.00%
crates/node/src/buyer_channel.rs 64.20% 1598/2489 ▲ +3.10%
crates/node/src/metrics.rs 95.67% 1105/1155 ● 0.00%
crates/node/src/node_origin/mod.rs 93.04% 1030/1107 new
crates/node/src/node_origin/resume.rs 93.18% 519/557 new
crates/node/src/runtime/mod.rs 46.47% 1093/2352 ▼ 0.14%
History
Commit Total Δ vs base
14355ba 80.34% ▲ +0.13%
667f4e6 (HEAD) 80.48% ▲ +0.27%

…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]>
@yigitdot

yigitdot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

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 mattered

1. The resume frontier could overshoot the bytes the leg decoded — silent corruption.

resume_frontier derives the frontier from ledger.committed().bytes, which is the channel's watermark, shared with every concurrent pull on it (BuyerLedgers). That concurrency is routine, not exotic: the cache engine coalesces in-flight pulls by hash, so two misses for different blobs run concurrent NodeOrigin::fetch calls that both rank the same provider first. A concurrent pull's acked vouchers inflate committed − anchor past what this leg received.

The consequence isn't a rounding error. buf.truncate(frontier) on a shorter buffer is a no-op — truncate never grows — so the resumed leg appends its bytes at the wrong position, and the assembled blob fails the cache engine's hash check after record_outcome(Delivered) has already scored the innocent upstream. (The CLI twin is safe: per-fetch ledger.)

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 resume::tests::a_concurrent_pulls_vouchers_cannot_push_the_frontier_past_decoded_bytes (deterministic) and concurrent_pulls_resume_at_their_own_frontier_not_the_channels (wire) — the latter fails 3/3 runs without the clamp.

2. A proactive refill in flight wedged the provider until channel expiry (~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 → OurDeadChannel → wedged_channel, which suppresses the provider for all hashes until channel expiry. The refill's funds then landed seconds later, and nothing clears a wedge. The visible warn! ("terms this channel cannot recover from") actively misstated the cause; the two lines explaining it were debug!.

And it's the common case: the reuse that starts a miss pull fires spawn_refill_if_low precisely when the deposit is below 20% — exactly the pulls most likely to exhaust mid-stream.

Fixed by converting the set into a map of joinable shared futures (the existing opens_in_flight/SharedOpen shape), so the reactive caller joins the in-flight refill and receives its credited deposit. Pinned by a_reactive_topup_joins_an_in_flight_refill_and_sees_its_deposit, verified to fail against the old stale-read behaviour.

Also applied

  • 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 — so the lying-peer signal could never fire. Added a distinct ResumeAction::RefuseFunding that carries it to the metric; the doc now states the causes it actually has, and a_node_crying_poverty_... asserts refused == 1. (Found independently by two reviewers.)
  • Panic supervisor on the detached funding task, mirroring spawn_open — a panic during the unbounded get_receipt wait (with the caller long dropped at outer_pull_deadline) previously took the error! and the metric with it, leaving up to a working deposit escrowed with no trace.
  • Settle-wait budget was unbounded above. event_poll_interval_ms has a config floor but no ceiling, so a 60 s chain lane bought 120 s of foreground sleep. Capped at 30 s; 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 contradicted the real impl ("a channel at the target is a no-op" vs. the impl's spendable-headroom target — a spent-to-target channel gets the full amount, which is the state this leg exists to rescue). The test double had implemented the wrong reading. Both corrected, plus unit tests on the real impl (store-miss, no-op, spent-to-target).
  • The reseed arm moved out of client-pull in Node reactive mid-pull top-up (node-to-node buyer leg) #1530 with no coverage of its own, while a_stale_nonce_rejection_... still claimed to pin the node path. Added decide tests (advancing bundle reseeds; outranks funding even on InsufficientDeposit; bounded) and rewrote that test's doc as history.
  • ResumeBudgets transition methods, so the awaiting_topup_settle/settle_waits pairing can't be half-updated across the three sites that touched it.
  • Stale cross-references invalidated by Node reactive mid-pull top-up (node-to-node buyer leg) #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.

Deliberately not done

  • Clearing wedged_providers when funding lands — filed as A wedged provider stays wedged after its channel becomes able to pay #1601. A wedge whose stated cause is "cannot pay" outliving the channel becoming able to pay is pre-existing and shared with the proactive refill, so it's out of this PR's scope. This PR removes the common way of reaching it, not the hole itself.
  • A wire test for the reseed arm through Origin::fetch. Staging a genuine advancing-bundle desync needs the buyer's ledger to lag a voucher the upstream holds, which the loopback fixture can't produce without an elaborate second harness. The decision layer is now fully pinned by decide tests, the loop wiring is six lines sharing its exits with wire-tested paths, and the client-pull-layer wire test still covers the same contract for the buffered path. Flagging it rather than leaving it implied.

Gate

cargo clippy --workspace --all-targets -- -D warnings   # clean
cargo fmt --all -- --check                              # clean
cargo nextest run --workspace --no-fail-fast            # 2786 passed
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --no-deps --document-private-items   # clean
cargo deny check                                        # ok

Still worth a rebase before merge — the branch is based on 2001ea09, behind origin/main.

@alpergundogdu

Copy link
Copy Markdown
Contributor

Code review

Found 1 issue:

  1. The successful post-top-up delivery leg is wrongly charged to paid_wait, so its real transfer time is subtracted from the peer's delivery-speed reputation. leg_started is captured at the top of the loop from awaiting_topup_settle (true after a top-up lands) and started.elapsed() is added unconditionally before the success check. But stream_leg clears the flag via note_successful_open() only inside the awaited call — after the open, and before pull_to_sink streams the entire remainder of the blob. So on the completing leg, the whole pull_to_sink delivery is folded into paid_wait and then subtracted from elapsed in pull_from_candidate, making a slow upstream score as fast (or instantaneous). This contradicts PulledBlob::paid_wait's own doc ("Blocking on a transaction says nothing about how fast the upstream serves") and fires on the feature's main success path (a top-up followed by completion). Charge paid_wait only on the failed-leg path, or time open_leg alone rather than all of stream_leg.

loop {
// While waiting out a top-up's settlement, the re-open this iteration performs
// is part of OUR funding cost, not the upstream's service — so it is timed and
// charged to `paid_wait` alongside the sleep, and kept out of the peer's
// delivery-speed score (#1600 review).
let leg_started = state.budgets.awaiting_topup_settle.then(Instant::now);
let leg = stream_leg(deps, target, ctx, ledger, deadlines, &mut state).await;
if let Some(started) = leg_started {
state.paid_wait = state.paid_wait.saturating_add(started.elapsed());
}
let Err(err) = leg else {
return Ok(PulledBlob {
bytes: state.buf,
paid_wait: state.paid_wait,
});
};

The subtraction it feeds:

match result {
Ok(resume::PulledBlob { bytes, paid_wait }) => {
// The same exclusion, for the same reason, applied to the other two things
// that are not the upstream serving bytes: the settle sleep and the `topUp`
// receipt. Both are OUR funding, and charging a peer's delivery-speed score
// for the time we spent on a chain would defame it for helping us (#1530).
let elapsed = elapsed.saturating_sub(paid_wait);
let bytes = Bytes::from(bytes);
record_outcome(
deps,
pk,
&Outcome::Delivered {
bytes: bytes.len() as u64,
elapsed,
},
);

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

@alpergundogdu
alpergundogdu merged commit d3e13fc into main Aug 5, 2026
25 checks passed
@alpergundogdu
alpergundogdu deleted the feat/1530-node-reactive-topup branch August 5, 2026 09:08
alpergundogdu added a commit that referenced this pull request Aug 5, 2026
…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]>
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.

Node reactive mid-pull top-up (node-to-node buyer leg)

2 participants