Skip to content

feat(cli): auto-topUp a reused fetch payment channel when its deposit runs low (#1103) - #1104

Merged
thiras merged 3 commits into
mainfrom
claude/dazzling-leakey-26a7b9
Jul 12, 2026
Merged

thiras merged 3 commits into
mainfrom
claude/dazzling-leakey-26a7b9

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

What

decdn fetch reused a live tracked payment channel verbatim with its existing on-chain deposit; the only trigger for a replacement was an expired channel (fetch.rs open_or_reuse). A channel spent down over a sustained series of fetches against one provider had no path to add funds — even though the contract (PaymentChannel.topUp) and the Rust binding both expose it. This stranded small channels and is the prerequisite blocking the default buyer-deposit reduction (10 → 2 USDC).

This adds auto-topUp only (a manual decdn channel top-up / --top-up subcommand was explicitly dropped in the issue).

How

  • Policy (crates/cli/src/commands/fetch.rs). In open_or_reuse, when a reused channel's remaining deposit (deposit − prior_amount) falls below a low-water mark (configured_deposit / 5, i.e. 20%), topUp on-chain to restore the remaining balance to a full configured deposit, then rebuild the ChannelContext from the refreshed record.
    • The exact next-fetch cost isn't known before the delivery handshake — the per-MB rate lives only in the probe / StreamResponse, and the explicit --node-id path does no probe — so the trigger is a rate-independent low-water refill with hysteresis, not a per-fetch-cost estimate. Documented on refill_amount.
    • topUp does not extend expiresAt, so a near-expiry channel is still replaced, never topped up (the existing expiry path is untouched).
  • Shared mechanism (crates/client-pull/src/buyer_channel.rs). Extracted top_up(contract, store, provider, additional) — reads the channelId before the RPC, credits the committed deposit after (never the pre-call snapshot), and handles the escrowed-but-untracked / channel-replaced races. Mirrors BuyerChannelService::top_up (Node-to-node buyer-side openChannel for cache-miss settlement #744).
  • De-dup (crates/node/src/buyer_channel.rs). The node's BuyerChannelService::top_up now delegates to the shared kernel.

Testing

  • Pure refill_amount unit tests: thresholds, hysteresis (no re-top-up on a channel with headroom), saturation / no underflow under the anti-panic policy.
  • Anvil-backed e2e (crates/e2e/tests/cli_fetch_topup.rs, --features anvil-e2e) mirroring the node's Node-to-node buyer-side openChannel for cache-miss settlement #744 top-up test (anvil_settlement_e2e.rs:937) but for the CLI fetch buyer's stack — the shared top_up kernel driving the same RedbBuyerChannelStore — asserting both the on-chain getChannel().deposit and the persisted record rise, and the voucher watermark is untouched.
  • Verified locally: cargo build && cargo clippy (workspace + anvil-gated), cargo fmt -- --check, cargo nextest run (affected crates: 1227 + 275 pass), the new e2e passes, and the node's reference e2e_onchain_payment_channel_settlement still passes with the delegation.

Out of scope

The default-deposit reduction from 10 → 2 USDC is deferred (tracked on #1103); DEFAULT_DEPOSIT_MICRO_USDC is unchanged here.

Closes #1103

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Buyer payment channels now automatically receive on-chain USDC top-ups when their remaining deposit falls below the configured low-water threshold.
    • Reused channels are refilled toward their target deposit instead of being replaced when funds run low.
    • Channel state remains synchronized after successful top-ups.
  • Bug Fixes

    • Improved handling of insufficient deposits and unusual values without calculation errors.
    • Preserved voucher progress while deposits are replenished.

… runs low (#1103)

`decdn fetch` reused a live tracked payment channel verbatim with its
existing on-chain deposit; the only trigger for a replacement was an
expired channel. A channel spent down over a sustained series of fetches
against one provider had no way to add funds, even though the contract
and the Rust binding both expose `topUp`. This stranded small channels
and blocked lowering the default buyer deposit.

Add auto-refill inside `open_or_reuse`: when a reused channel's remaining
deposit (`deposit - prior_amount`) falls below a low-water mark
(configured deposit / 5 = 20%), `topUp` on-chain to restore the remaining
balance to a full configured deposit, then rebuild the context from the
refreshed record. The exact next-fetch cost isn't known before the
delivery handshake (the per-MB rate is only in the probe / StreamResponse,
and the explicit `--node-id` path does no probe), so the policy is a
rate-independent low-water refill with hysteresis rather than a
per-fetch-cost estimate. `topUp` does not extend expiry, so a near-expiry
channel is still replaced, not refilled.

Extract the topUp + deposit-reconciliation mechanism into a shared
`decdn_client_pull::buyer_channel::top_up` kernel (reading the channel_id
before the RPC, crediting the committed deposit after, handling the
escrowed-but-untracked / channel-replaced races) and delegate the node's
`BuyerChannelService::top_up` (#744) to it, removing the duplication.

Tests: pure `refill_amount` unit tests (thresholds, hysteresis,
saturation) plus an anvil-backed e2e mirroring the node's #744 top-up
test for the CLI fetch buyer's stack (shared kernel + RedbBuyerChannelStore),
asserting both the on-chain and persisted deposit rise.

The default-deposit reduction from 10 to 2 USDC is a deferred follow-up.

Closes #1103

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Copilot AI review requested due to automatic review settings July 11, 2026 14:24
@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@thiras, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 13 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 48b27528-0c63-4891-84ab-9c4574f3801c

📥 Commits

Reviewing files that changed from the base of the PR and between 6ce29be and 6a84e96.

📒 Files selected for processing (5)
  • crates/cli/src/commands/fetch.rs
  • crates/client-pull/src/buyer_channel.rs
  • crates/e2e/Cargo.toml
  • crates/e2e/tests/cli_fetch_topup.rs
  • crates/node/src/buyer_channel.rs

Walkthrough

Changes

The buyer channel top-up flow is centralized in client-pull, reused by the node service, and integrated into CLI channel reuse with a low-water refill policy. Unit and Anvil-backed integration tests validate deposit reconciliation and voucher watermark preservation.

Buyer channel refill

Layer / File(s) Summary
Shared top-up kernel
crates/client-pull/src/buyer_channel.rs, crates/node/src/buyer_channel.rs
Adds shared on-chain top-up and store reconciliation, then delegates node top-ups to the shared implementation.
CLI low-water refill policy
crates/cli/src/commands/fetch.rs
Calculates refill amounts for live reused channels, performs top-ups when below the low-water mark, refreshes stored state, and tests saturation and hysteresis behavior.
End-to-end top-up validation
crates/e2e/Cargo.toml, crates/e2e/tests/cli_fetch_topup.rs
Adds the redb-enabled Anvil test setup and verifies on-chain deposits, persisted deposits, and unchanged voucher watermarks.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant FetchCommand
  participant BuyerChannelStore
  participant PaymentChannel
  FetchCommand->>BuyerChannelStore: read reused channel
  FetchCommand->>FetchCommand: calculate refill amount
  FetchCommand->>PaymentChannel: submit topUp when below low-water
  PaymentChannel-->>FetchCommand: return receipt
  FetchCommand->>BuyerChannelStore: persist and re-read deposit
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

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

github-actions Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 88.71% (2452/2764 lines)
▲ +0.00pp vs base (88.71% → 88.71%)
Run: 29207901471

@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 implements an auto-refill mechanism for the CLI fetch buyer when a reused channel's remaining deposit falls below a low-water mark. It refactors the existing top_up logic into a shared helper function in decdn-client-pull used by both the node service and the CLI, and adds comprehensive unit and integration tests. Feedback is provided to ensure that the USDC allowance is checked before executing the top_up transaction in the CLI fetch path to prevent potential transaction reverts.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread crates/cli/src/commands/fetch.rs 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

This PR adds an automatic on-chain topUp path for the CLI decdn fetch buyer when it reuses an existing payment channel whose remaining deposit has fallen below a low-water mark, preventing long-running fetch usage from stranding a spent-down channel. It also extracts a shared top_up kernel into decdn-client-pull and refactors the node’s buyer-channel service to delegate to that shared implementation, keeping CLI and node behavior consistent.

Changes:

  • Add a rate-independent low-water refill policy in decdn fetch (open_or_reuse) with unit tests for the pure refill decision.
  • Introduce a shared decdn_client_pull::buyer_channel::top_up helper and delegate the node buyer’s top_up to it.
  • Add an anvil-backed e2e test that asserts topUp raises both the on-chain deposit and the persisted redb buyer-channel record.

Reviewed changes

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

Show a summary per file
File Description
crates/node/src/buyer_channel.rs Delegates node buyer top_up to the new shared decdn-client-pull kernel.
crates/client-pull/src/buyer_channel.rs Adds shared top_up implementation (RPC + deposit reconciliation via BuyerChannelStore::add_deposit).
crates/cli/src/commands/fetch.rs Implements CLI fetch auto-refill policy and adds unit tests for refill decision logic.
crates/e2e/tests/cli_fetch_topup.rs Adds an anvil-backed CLI buyer top-up e2e asserting on-chain + persisted deposit changes and unchanged watermark.
crates/e2e/Cargo.toml Enables decdn-incentive redb usage for the new e2e test (currently unconditionally).

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

Comment thread crates/e2e/Cargo.toml Resolved
Comment thread crates/e2e/tests/cli_fetch_topup.rs Resolved
@github-actions

github-actions Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.30% (was 80.33%, ▼ 0.03%) — 44958/55987 lines

File Coverage Lines Δ
crates/cli/src/commands/fetch.rs 41.32% 245/593 ▲ +3.79%
crates/client-pull/src/buyer_channel.rs 23.21% 39/168 ▼ 6.79%
crates/node/src/buyer_channel.rs 31.34% 331/1056 ▲ +0.67%
History
Commit Total Δ vs base
6ce29be 80.06% ▼ 0.02%
83e302e 80.30% ▼ 0.03%
6a84e96 (HEAD) 80.30% ▼ 0.03%

thiras and others added 2 commits July 12, 2026 23:22
Conflicts:
- fetch.rs imports: keep the new `top_up` helper alongside main's
  progress-bar imports (`ProgressCallback`, `stream_fetch_tracked_with_progress`).
- client-pull/buyer_channel.rs: keep both end-of-file additions — this
  branch's shared `top_up` kernel and main's `approve_decision` unit tests.

Review fixes:
- fetch.rs reuse path: ensure the USDC allowance before `top_up`, so a
  reused channel under a revoked/exact-mode allowance doesn't revert on
  `topUp`'s `transferFrom`. Mode-aware (unlimited under `--max-approve`,
  else exactly `additional`) — covers the exact-approve case the reviewer's
  narrower `max_approve`-only guard missed (gemini).
- e2e/Cargo.toml: enable `decdn-incentive/redb` via the `anvil-e2e` feature
  instead of the direct dep, so default builds skip that crate's redb
  module + postcard (Copilot).
- cli_fetch_topup.rs: `#[cfg(unix)]`-gate the `set_permissions` call and use
  a fully-qualified `from_mode`, matching anvil_settlement_e2e.rs, so the
  test compiles on non-Unix under `--features anvil-e2e` (Copilot).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The merge of main brought `ensure_allowance`'s new `amount: Option<U256>`
parameter (exact-vs-unlimited approval), which the pre-existing test setup
call did not pass — breaking the `anvil-e2e` build. Pass `None` (unlimited
standing allowance) so the setup covers both the initial `openChannel`
deposit and the later refill `topUp` without re-approving.

Verified: `cargo nextest run -p decdn-e2e --features anvil-e2e
cli_fetch_auto_topup_raises_and_persists_deposit` passes against a live anvil.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras
thiras merged commit 5aeeb3a into main Jul 12, 2026
25 checks passed
@thiras
thiras deleted the claude/dazzling-leakey-26a7b9 branch July 12, 2026 20:40
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.

CLI fetch buyer: no topUp/refill path when a reused payment channel's deposit runs low

3 participants