Skip to content

feat(payments): group-commit voucher fsyncs, ack after commit (#1483) - #1487

Closed
alpergundogdu wants to merge 1 commit into
claude/upbeat-babbage-dd8661from
claude/group-commit-vouchers-1483
Closed

alpergundogdu wants to merge 1 commit into
claude/upbeat-babbage-dd8661from
claude/group-commit-vouchers-1483

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

Stacked on #1477 (base branch claude/upbeat-babbage-dd8661). Review/merge that first; this PR's diff is only the group-commit work.

What

Amortise the per-voucher fsynced redb commit (measured 3.18 ms/voucher on local SSD, Durability::Immediate) across a batch of vouchers instead of one fsync each. Today a single channel caps at ~313 MiB/s at a 1 MiB interval because vouchers serialize on the per-channel mutex and each pays one fsync.

Plan: group commit, ack AFTER the commit returns (Option A). Nothing is ever acked before it is durable, so ADR 003 §Off-chain voucher state persistence stands verbatim — no ADR amendment, no new replay exposure. This builds on #1477's credit window, which takes the delayed ack off the delivery critical path (ADR 003 line 103 already anticipates this batching).

How

  • crates/incentive — ChannelState::stage_voucher validates + advances a candidate without persisting; apply_voucher is refactored to stage → record → swap (behaviour identical). Because vouchers are cumulative, the final staged state supersedes every intermediate one, so one store.record commits the whole batch (one fsync) — no new ChannelStateStore method is needed.
  • crates/node handlers/client — collect_voucher_batch gathers up to credit_window / interval vouchers: the first read blocks (preserving the park-awaiting-voucher semantics), the rest under a bounded commit interval via a cancellation-safe BufferedVoucherReader. It verifies each against the advancing candidate, commits the prefix once, then writes one VoucherAck per voucher. A failed commit fails the WHOLE batch → RetryLater, no acks, state unchanged (ADR 003 §355). A mid-batch verify rejection commits the valid prefix first, then rejects — faithful to the pre-batch per-voucher order. Both the buffered (deliver) and window pull-through (window_forward_loop) loops share the batched recoup; stop-and-wait (window = one interval) collapses to one voucher per commit exactly as before.
  • crates/protocol — parse_frame (sync, non-consuming) backs the cancellation-safe reader that read_frame's read_exact cannot survive a gather timeout.
  • config — payment.voucher_commit_interval_ms (default 5 ms) is the governable commit interval, documented with the sizing constraint credit_window >= throughput * (RTT + commit_interval).

Durability::Immediate is kept on the (now batched) commit — durability is not weakened anywhere.

Tests (TDD)

  • group_commit_amortises_the_fsync_across_a_batch — 8 cumulative vouchers commit with exactly 1 record; verified to FAIL under forced stop-and-wait.
  • group_commit_failure_rejects_whole_batch_with_retry_later — failed commit → one RetryLater, zero acks, watermark unchanged.
  • incentive stage_voucher staging tests (batch == sequential; rejection leaves candidate untouched); protocol parse_frame tests.

cargo nextest run -p decdn-node -p decdn-incentive (1143 + incentive passing), cargo clippy --all-targets, cargo fmt --check, and cargo doc -D warnings all clean.

Closes #1483

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 0a7317b7-49ce-4676-adf3-9cf99104b14b

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Code review

One non-blocking item — comment accuracy / consistency. The group-commit core (batch supersession, commit-before-ack durability, whole-batch RetryLater on commit failure, cancellation-safe BufferedVoucherReader/parse_frame, batch_cap div-by-zero guards) verified clean.

Takedown check: comment says "once per committed batch" but it runs on every non-done iteration, and it now diverges from window.rs.
This PR drops the to_collect.is_some() gate, so the check is if !done && self.takedown_landed(...), sitting outside the if !deltas.is_empty() block. The new comment says "Checked once per committed batch," which doesn't match — it runs whenever !done.

// ADR 011 §On Blacklist Event: in-flight streams for a blacklisted hash
// are terminated at the next boundary. Checked once per committed batch
// (bounded by the window, like the credit exposure) so the bytes
// already on the wire stay paid for — the takedown stops FURTHER
// delivery. Skipped when the delivery is already complete (nothing left
// to withhold; terminating would turn a fully-paid delivery into a
// reset).
if !done && self.takedown_landed(hash, funder) {
self.terminate_for_takedown(send, recv, hash);
return Ok(());
}

To be clear, this is not a correctness regression: whenever !done holds, a batch was gathered that iteration. If the deliver phase broke on the window, sum(pending) ≥ window − unvouchered > 0 so deltas is non-empty; if it broke on end-of-blob, the closing partial is folded into pending first, so an empty deltas implies done. The removed gate was redundant with !done. But the comment is inaccurate, and window.rs keeps the equivalent check nested under if collected_any, so the two paths read differently for the same invariant.

let collected_any = !deltas.is_empty();
if collected_any {
match self
.collect_voucher_batch(
send,
recv,
&mut reader,
hash,
channel_id,
Some(channel),
client_node_id,
rate_per_mb,
&deltas,
)
.await
{
Ok(outcome) => {
let paid_bytes: u64 = deltas.iter().take(outcome.committed).sum();
served_paid = served_paid.saturating_add(Bytes::new(paid_bytes));
// Re-queue deltas the client had not paid yet (short batch),
// preserving order at the front of `pending`.
for &delta in deltas
.get(outcome.committed..)
.unwrap_or_default()
.iter()
.rev()
{
pending.push_front(delta);
}
match outcome.stop {
BatchStop::Rejected => {
self.abandon_window_serve(pull, tee);
return Ok(());
}
BatchStop::Continue => {
// ADR 011 §On Blacklist Event: terminate an
// in-flight delivery at the next boundary once a
// takedown lands. This path needs it at least as
// much as the buffered one — it is simultaneously
// *pulling* the blacklisted blob from upstream, so
// continuing would both serve and re-acquire content
// under a removal order. Abandoning the pull is what
// stops the upstream spend.
if self.takedown_landed(hash, Some(funder)) {
self.abandon_window_serve(pull, tee);

Suggest: fix the comment (or re-nest the check under the batch block) so delivery.rs and window.rs stay symmetric.

🤖 Generated with Claude Code

@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Fixed in d18f971: restored the collected_any gate on the delivery.rs takedown check (equivalent to the old to_collect.is_some()) so it runs only after a committed batch, matching window_forward_loop's nesting, and corrected the comment. No behaviour change — !done already implied a batch was gathered; this just keeps the two loops symmetric for the same invariant. Takedown/blacklist tests still green.

🤖 Addressed by Claude Code

@alpergundogdu
alpergundogdu force-pushed the claude/upbeat-babbage-dd8661 branch from f25367a to 6d23558 Compare July 28, 2026 16:00
Amortise the per-voucher fsynced redb commit (~3.18 ms/voucher on local SSD,
Durability::Immediate) across a batch of vouchers instead of one fsync each.
Before this, a single channel caps at ~313 MiB/s at a 1 MiB interval because
vouchers serialize on the per-channel mutex and each pays one fsync.

Group commit with the ack sent AFTER the commit returns (Option A). Nothing is
ever acked before it is durable, so ADR 003 §Off-chain voucher state persistence
stands verbatim — no ADR amendment, no new replay exposure. Builds on #1477's
credit window, which takes the delayed ack off the delivery critical path.

Mechanism (stacked on #1477's seam):
- crates/incentive: `ChannelState::stage_voucher` validates + advances a
  candidate WITHOUT persisting; `apply_voucher` is refactored to stage + record
  + swap. Because vouchers are cumulative, the final staged state supersedes
  every intermediate one, so one `store.record` commits the whole batch (one
  fsync) — no new store method is needed.
- crates/node handlers/client: `collect_voucher_batch` gathers up to
  `credit_window / interval` vouchers (first read blocking to preserve the
  park-awaiting-voucher semantics; the rest under a bounded commit interval via
  a cancellation-safe `BufferedVoucherReader`), verifies each against the
  advancing candidate, commits the prefix once, then writes one VoucherAck per
  voucher. A failed commit fails the WHOLE batch → RetryLater, no acks, state
  unchanged (ADR 003 §355). A mid-batch verify rejection commits the valid
  prefix first, then rejects. Both the buffered (`deliver`) and window
  pull-through (`window_forward_loop`) loops use the shared batched recoup,
  gating the ADR 011 takedown check on `collected_any` so the two read
  symmetrically; stop-and-wait (window = one interval) collapses to one voucher
  per commit exactly as before.
- crates/protocol: `parse_frame` (sync, non-consuming) backs the
  cancellation-safe buffered reader that `read_frame`'s `read_exact` cannot.
- config: `payment.voucher_commit_interval_ms` (default 5 ms) is the governable
  commit interval, documented with the sizing constraint
  `credit_window >= throughput * (RTT + commit_interval)`.

Keeps Durability::Immediate on the batched commit. TDD: batched-throughput test
(8 vouchers → 1 record, proven to fail without batching) and a crash/rollback
test (failed commit → RetryLater, zero acks, watermark unchanged), plus
incentive-level staging tests.

Closes #1483

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu force-pushed the claude/group-commit-vouchers-1483 branch from d18f971 to 0f60522 Compare July 28, 2026 16:06
@alpergundogdu
alpergundogdu deleted the branch claude/upbeat-babbage-dd8661 July 28, 2026 16:09
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Auto-closed when the base branch claude/upbeat-babbage-dd8661 was deleted by #1485's squash-merge. GitHub can't reopen a PR against a deleted base, so this continues as #1490 — same commit, rebased directly onto main.

🤖 Addressed by Claude Code

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.

1 participant