Skip to content

feat(payments): credit-window pipelined paid delivery (#1477) - #1485

Merged
alpergundogdu merged 1 commit into
mainfrom
claude/upbeat-babbage-dd8661
Jul 28, 2026
Merged

alpergundogdu merged 1 commit into
mainfrom
claude/upbeat-babbage-dd8661

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1477.

Problem

Paid delivery was stop-and-wait at every voucher boundary. The node delivered one voucher_interval_mb batch, then blocked on collect_voucher (read → verify → fsync → ack) before sending more — zero bytes in flight for a full RTT + fsync per interval. Throughput was therefore interval / (RTT + service_time), latency-bound rather than link-bound, and the repeated idle gaps kept QUIC's congestion window from reaching steady state.

Change

The serve side now streams behind a credit window: it keeps delivering while delivered − paid ≤ credit_window, consuming cumulative vouchers as they arrive instead of stalling at one interval — the same bounded-credit shape the node already uses upstream (pull_ahead_bytes).

  • Exposure is one-sided and bounded. The client's exposure stays at zero (vouchers are cumulative over bytes already delivered, so it never pays ahead). The node's credit exposure is exactly the window — the deliver loop checks delivered − paid < window before each chunk, so it never streams past the bound.
  • delivery.rs (deliver, cache-hit path): rewritten as a deliver/recoup loop mirroring the fused window path. One-interval floor guarantees progress and rules out a spin-without-await.
  • window.rs (fused cache-miss serve): its single fused window is widened to max(pull_ahead_bytes, credit_window, interval), and the deposit guard tracks the same effective window.
  • Config: new node-local payment.credit_window_bytes (default 8 MiB); node-advertised payment.voucher_interval_mb default raised to 4 MiB. Both are independent, config-driven knobs — window bounds exposure, interval bounds per-voucher overhead and the per-channel fsync-serialized voucher rate.

#1483 seam

collect_voucher is split into verify and commit-and-ack (commit_and_ack_voucher). The fsync + VoucherAck now live in one isolated method, so group-commit fsync (#1483) can batch the fsync and ack-after-commit without re-plumbing the deliver loop or the verify path. Durability is unchanged: each voucher is committed before its ack.

Wire compatibility

No wire-format change — same ChunkData / Voucher / VoucherAck / StreamEnd messages, only the cadence differs. The credit window is purely local server policy (nothing negotiated). Adding a negotiation field was rejected: appending an Option to StreamRequestExt breaks old-sender→new-receiver under postcard (DeserializeUnexpectedEnd), i.e. it would itself be a wire break.

An unconfigured window resolves to one interval (stop-and-wait), so the pre-#1477 cadence is reproduced exactly and a not-yet-pipelined requester keeps working. Pipelining a node against an un-updated stop-and-wait requester is the two-sided barrier #1477 describes; the requester half is #1484 and ships in the same release.

ADR

Amends ADR 003 (new §Credit Window) and ADR 005 (self-enforcing threshold generalized from one interval to the credit window) for the decoupled pay/deliver cadence.

Tests (TDD)

New loopback tests drive a raw read-ahead client:

  • serve_streams_a_full_credit_window_ahead_of_payment — reads a full 8 MiB window before any voucher (pipelining past one interval), then asserts the server is parked (exposure bounded to exactly the window).
  • serve_without_a_credit_window_is_stop_and_wait — unconfigured window delivers exactly one interval, then parks.
  • paying_a_voucher_slides_the_credit_window_forward — one voucher frees exactly one interval of fresh credit.

Assertions are byte-count-based with absence-based park checks, so they are deterministic under parallel load.

Verified green: cargo nextest run -p decdn-node (893), -p decdn-common/-p decdn-cli (800), cargo clippy --workspace --all-targets -- -D warnings, cargo fmt --all --check, cargo doc.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added configurable downstream payment credit windows for paid content delivery.
    • Enabled delivery to stream ahead within the configured window, reducing unnecessary pauses while keeping unpaid exposure bounded.
    • Preserved stop-and-wait behavior when no larger window is configured.
    • Added configuration defaults, validation, reload handling, and support for concurrent delivery and voucher processing.
  • Documentation

    • Documented credit-window behavior, payment pacing, defaults, and exposure limits.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 11 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: 0fab250f-68d6-445f-8a30-09e648e3c9e7

📥 Commits

Reviewing files that changed from the base of the PR and between 9a052d8 and 6d23558.

📒 Files selected for processing (15)
  • adr/003-payments.md
  • adr/005-protocol.md
  • crates/cli/tests/config_validate.rs
  • crates/common/src/config/mod.rs
  • crates/common/src/config/resolved.rs
  • crates/common/src/config/types.rs
  • crates/node/src/handlers/client/delivery.rs
  • crates/node/src/handlers/client/mod.rs
  • crates/node/src/handlers/client/voucher.rs
  • crates/node/src/handlers/client/window.rs
  • crates/node/src/runtime/mod.rs
  • crates/node/src/runtime/reload.rs
  • crates/node/tests/anvil_bringup_shutdown_e2e.rs
  • crates/node/tests/client_loopback.rs
  • crates/node/tests/sighup_signal.rs

Walkthrough

Adds a configurable downstream credit window for paid delivery, resolves and wires the setting through runtime configuration, updates delivery and voucher handling to support pipelining, adjusts pull-through bounds, and adds loopback coverage.

Changes

Credit window delivery

Layer / File(s) Summary
Credit window contract and configuration
adr/003-payments.md, adr/005-protocol.md, crates/common/src/config/*, crates/node/src/runtime/reload.rs, crates/cli/tests/config_validate.rs
Documents credit-window semantics and adds defaults, configuration parsing, resolved fields, resolution tests, and restart detection.
Paid delivery window enforcement
crates/node/src/handlers/client/mod.rs, crates/node/src/handlers/client/delivery.rs, crates/node/src/runtime/mod.rs
Threads the configured window into ClientHandler and bounds delivery by the difference between delivered and paid bytes.
Voucher commit and pull-through integration
crates/node/src/handlers/client/voucher.rs, crates/node/src/handlers/client/window.rs
Separates durable voucher commit and acknowledgement from verification, and includes the credit window in pull-through bounds.
Pipelined delivery validation
crates/node/tests/client_loopback.rs
Tests multi-interval streaming, stop-and-wait behavior, voucher acknowledgement, and window advancement.

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ClientHandler
  participant VoucherStore
  Client->>ClientHandler: request paid stream
  ClientHandler->>Client: deliver chunks within credit window
  Client->>ClientHandler: submit cumulative voucher
  ClientHandler->>VoucherStore: durably commit voucher
  VoucherStore-->>ClientHandler: commit succeeds
  ClientHandler-->>Client: send VoucherAck
  ClientHandler->>Client: resume delivery
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 Jul 28, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.24% (was 81.22%, ▲ +0.02%) — 52933/65155 lines

File Coverage Lines Δ
crates/common/src/config/mod.rs 97.04% 6828/7036 ▲ +0.01%
crates/common/src/config/resolved.rs 100.00% 33/33 ● 0.00%
crates/node/src/handlers/client/delivery.rs 96.47% 82/85 ▲ +2.03%
crates/node/src/handlers/client/mod.rs 89.57% 653/729 ▲ +0.13%
crates/node/src/handlers/client/voucher.rs 81.46% 167/205 ▲ +2.69%
crates/node/src/handlers/client/window.rs 85.02% 227/267 ▲ +0.11%
crates/node/src/runtime/mod.rs 46.96% 1083/2306 ▼ 0.02%
crates/node/src/runtime/reload.rs 96.57% 1632/1690 ▲ +0.01%
History
Commit Total Δ vs base
9a052d8 81.22% ▲ +0.02%
f25367a 81.22% ▲ +0.02%
6d23558 (HEAD) 81.24% ▲ +0.02%

@alpergundogdu
alpergundogdu force-pushed the claude/upbeat-babbage-dd8661 branch from 9a052d8 to f25367a Compare July 28, 2026 11:54
@alpergundogdu
alpergundogdu requested a review from thiras July 28, 2026 11:59
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Code review

Three non-blocking items — all documentation / consistency, none block merge. The core change (delivered/paid/pending accounting, one-interval floor, deliver→recoup ordering, deposit-guard sizing, backward-compat collapse to stop-and-wait) verified clean.

1. Takedown detection latency now scales with the credit window, not the interval.
The deliver phase streams up to a full credit_window (8 MiB default) before the recoup phase collects the first voucher and runs the ADR 011 takedown_landed check. So a takedown landing early in a stream is first detected after up to one window of egress (~8 MiB), versus ~1 MB before. The behavior is sound — the check still runs after a voucher, and the window floors at one interval — but ADR 003 §Credit Window doesn't note the trade-off and the code comment still says "next MB boundary."

// ADR 011 §On Blacklist Event: in-flight streams for a blacklisted hash
// are terminated at the next MB boundary. The check sits AFTER a voucher
// so the bytes already on the wire are still paid for — the takedown
// stops FURTHER delivery, it does not retroactively make the last
// interval free. Only meaningful while bytes remain to withhold: a
// takedown landing at the final voucher has nothing left to stop, and
// terminating there would turn a complete, fully-paid delivery into a
// reset (no `StreamEnd`).
if !done && to_collect.is_some() && self.takedown_landed(hash, funder) {
self.terminate_for_takedown(send, recv, hash);

Suggest: add a line to ADR 003 §Credit Window acknowledging that takedown latency is bounded by the window (one-interval floor as the mitigation), and update the comment.

2. Comment overstates the credit-exposure bound.
The comment claims exposure is "bounded to exactly the window, not window-plus-a-chunk," but the window check runs before the send, so delivered − paid can reach up to window + CHUNK_SIZE − 1 when the window isn't a multiple of CHUNK_SIZE. The sibling window.rs documents this honestly ("the realized frontier can overshoot by up to one chunk"). Either make the check anticipatory or soften the comment to match window.rs.

// --- deliver phase: stream chunks while the window has room. The
// window check is BEFORE the send, so `delivered − paid` never
// exceeds `window` — the credit exposure is bounded to exactly the
// window, not window-plus-a-chunk. ---
while let Some(chunk) = next_chunk {
if delivered.saturating_sub(paid) >= window {
break;
}
let frame = ChunkData::new(chunk.to_vec())

3. window.rs takedown check lacks the !done guard added to delivery.rs.
delivery.rs gained a !done guard so a takedown landing on the final voucher of a complete, fully-paid delivery doesn't turn it into a reset (no StreamEnd). The equivalent check in window.rs (the fused cache-miss path) is unconditional, so it still has that final-byte reset. The window.rs line isn't modified by this PR (pre-existing) — flagging as a consistency follow-up.

// upstream spend.
if self.takedown_landed(hash, Some(funder)) {
self.abandon_window_serve(pull, tee);
self.terminate_for_takedown(send, recv, hash);
return Ok(());

versus the guarded delivery.rs check:

// reset (no `StreamEnd`).
if !done && to_collect.is_some() && self.takedown_landed(hash, funder) {
self.terminate_for_takedown(send, recv, hash);

🤖 Generated with Claude Code

Paid delivery was stop-and-wait at every voucher boundary: the node
delivered one `voucher_interval_mb` batch, then blocked on the voucher
read + verify + fsync + ack before sending more — zero bytes in flight for
a full RTT + fsync per interval, so single-stream throughput was RTT-bound,
not link-bound.

The serve side now streams behind a credit window: it keeps delivering
while `delivered - paid <= credit_window`, collecting cumulative vouchers
as they arrive instead of stalling at one interval. Client exposure stays
zero (vouchers are cumulative over delivered bytes); node credit exposure
is bounded to exactly the window and enforced there. The same shape is
applied to the fused cache-miss serve path (its window is widened to
include the credit window). Credit window and voucher interval are
independent, config-driven knobs (defaults 8 MiB / 4 MiB).

The voucher-collection seam is split into verify / commit-and-ack
(`commit_and_ack_voucher`) so group-commit fsync (#1483) can batch the
fsync and ack-after-commit without re-plumbing the deliver loop.

Amends ADR 003 (new §Credit Window) and ADR 005 for the decoupled
pay/deliver cadence. No wire-format change: an unconfigured window resolves
to one interval (stop-and-wait), which keeps a not-yet-pipelined requester
(#1484) interoperable with a pipelined node.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu force-pushed the claude/upbeat-babbage-dd8661 branch from f25367a to 6d23558 Compare July 28, 2026 16:00
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Thanks — all three verified. Addressed in 6d235583 (amended into the feature commit):

1. Takedown latency (comment + ADR). Fixed the stale "next MB boundary" comment in delivery.rs: detection now lands up to one credit window into the stream (steady state ~one interval, since later iterations recoup one interval at a time), window-bounded and floored at one interval. Added a Takedown latency paragraph to ADR 003 § Credit Window making the trade-off explicit (and noting a strict-compliance node configures a smaller window).

2. Exposure bound (comment). Softened to the honest "≤ window + one chunk", matching window_forward_loop. I did not take the anticipatory-check option: it would break progress — an anticipatory would-this-chunk-cross check can stop short of a full interval, and at the one-interval floor (window == interval, the stop-and-wait default) it would never complete one, starving the recoup phase of a voucher to collect and deadlocking the loop. Documented that reasoning inline so the pre-send check isn't "corrected" later.

3. window.rs !done guard (consistency). Left window.rs unconditional — the asymmetry is intentional, not drift. The buffered path serves already-cached content, so a final-voucher takedown has nothing left to withhold and the !done guard just avoids a pointless reset of a complete delivery. The fused path is acquiring the blob, so a final-voucher takedown must still fire: abandon_window_serve drops the partial fill, which is what prevents promoting a just-taken-down blob into cache. Making them match would reintroduce that caching hole. Added a cross-reference in the delivery.rs comment explaining why the fused loop deliberately omits the guard.

🤖 Addressed by Claude Code

@alpergundogdu
alpergundogdu merged commit 18c6c16 into main Jul 28, 2026
24 checks passed
@alpergundogdu
alpergundogdu deleted the claude/upbeat-babbage-dd8661 branch July 28, 2026 16:09
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.

Paid delivery is stop-and-wait per voucher: throughput is RTT-bound, not link-bound

1 participant