Skip to content

fix(node): decouple download-receipt writes from the paid-delivery hot path (#803) - #811

Merged
thiras merged 1 commit into
mainfrom
fix/803-decouple-receipt-log-writes
Jun 6, 2026
Merged

thiras merged 1 commit into
mainfrom
fix/803-decouple-receipt-log-writes

Conversation

@thiras

@thiras thiras commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

Problem

Closes #803. The download-receipt log is documented as audit-only / non-fatal, but the write was .awaited on the voucher-accept hot path before VoucherAck, and every delivery stream serialized through a single process-wide Mutex<File>. So while a failed write was non-fatal, a slow or full disk stalled the awaited flush() → stalled voucher acknowledgement → stalled active paid delivery. Combined with a full disk (the realistic end-state of #802), an "audit-only" artifact became a delivery-latency dependency.

Fix

Decouple the write via a non-blocking ReceiptSink seam, mirroring the existing redeem-hint mechanism in payment_settlement.rs:

  • ChannelReceiptSink — production sink; a bounded try_send that drops-on-Full (counted by decdn_receipt_writes_dropped_total) and leaves Closed uncounted (with a debug! trace for an unexpectedly-dead writer).
  • spawn_receipt_writer + receipt_writer_loop — a single background task owns the ReceiptLog and drains a bounded (1024) queue FIFO, doing the actual append via spawn_blocking so disk I/O never runs on a runtime worker. Being the sole caller of append also removes the cross-stream mutex contention.
  • Hot path — record_receipt is now synchronous (a non-blocking enqueue) and cannot block before VoucherAck.
  • Shutdown — a CancellationToken is cancelled after router.shutdown() (so no further receipts are produced), the writer drains its tail before exiting (preserving the audit-tail guarantee), and is awaited within SHUTDOWN_DEADLINE with a fire-and-forget abort backstop.
  • DirectReceiptSink — a #[doc(hidden)] adapter that keeps the synchronous integration-test fakes deterministic (no racing the async writer).

Tests

  • New unit tests: writer FIFO-drain-then-stop-on-cancel, continue-past-failing-append, full-queue drop+count, closed-channel drop-without-count, and the drop metric.
  • New production-path loopback test delivery_completes_while_receipt_writer_is_stalled: drives delivery through the real ChannelReceiptSink + background writer with every append stalled — the exact pre-node: audit-only download-receipt write is awaited on the paid-delivery hot path #803 regression (the old inline-await would hang) — then recovers the full audit tail after release+drain.

Verification

  • cargo build --workspace ✓ · cargo clippy -p decdn-node --tests ✓ (no warnings) · cargo fmt --check ✓
  • cargo nextest run -p decdn-node → 455 passed, 0 skipped

Review

Reviewed with the multi-agent PR toolkit (code/tests/errors/types/comments). No high-confidence blockers; the should-fix and cheap-hardening findings (structured JoinError log, Closed/abort observability, DirectReceiptSink encapsulation, module-doc refresh, the production-path + closed-branch tests) are all incorporated.

🤖 Generated with Claude Code

…t path (#803)

The download-receipt log is documented as audit-only / non-fatal, but the write
was `.await`ed on the voucher-accept hot path before `VoucherAck`, and every
delivery stream serialized through a single process-wide `Mutex<File>`. A slow
or full disk therefore stalled the awaited `flush()`, which stalled voucher
acknowledgement and active paid delivery — turning an audit artifact into a
delivery-latency dependency.

Decouple the write via a non-blocking `ReceiptSink` seam: `ChannelReceiptSink`
does a bounded `try_send` (drop-on-`Full` counted by `receipt_writes_dropped`,
`Closed` left uncounted with a `debug!` trace), feeding a single background
`receipt_writer_loop` that owns the `ReceiptLog` and drains the queue, doing the
actual `append` via `spawn_blocking` so disk I/O never touches a runtime worker.
On graceful shutdown a `CancellationToken` is cancelled after `router.shutdown()`
and the writer drains its tail before exiting, awaited within `SHUTDOWN_DEADLINE`
(with a fire-and-forget abort backstop). Making the writer the sole caller of
`append` also removes the cross-stream mutex contention. `record_receipt` is now
synchronous and cannot block before `VoucherAck`.

A `DirectReceiptSink` adapter keeps the synchronous test fakes deterministic.
The design mirrors the existing redeem-hint mechanism in payment_settlement.rs.

Tests: new unit tests for the writer (FIFO drain + cancel, continue-past-failure,
full/closed drop semantics, drop metric) and a production-path loopback test
proving delivery completes while every receipt `append` is stalled — the exact
pre-#803 regression — then recovers the full audit tail after drain.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings June 4, 2026 13:39

@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 decouples download-receipt audit logging from the paid-delivery hot path to prevent disk I/O from back-pressuring delivery (addressing issue #803). It introduces a non-blocking ReceiptSink interface and a background receipt writer task that drains enqueued receipts asynchronously. A new metric decdn_receipt_writes_dropped_total is added to track dropped receipts when the bounded queue is full. Additionally, integration and unit tests are added to verify that delivery completes even when the receipt writer is stalled, and that enqueued receipts are successfully flushed during graceful shutdown. There are no review comments to assess, and the implementation looks solid.

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.

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 removes receipt-log disk I/O from the voucher-acceptance hot path by introducing a non-blocking ReceiptSink enqueue seam and a single background receipt-writer task, preventing slow/full disks from delaying VoucherAck and paid delivery (#803).

Changes:

  • Introduced ReceiptSink with a production ChannelReceiptSink (bounded try_send, drop-on-full with a new drop counter) plus a test-only DirectReceiptSink.
  • Added a background spawn_receipt_writer task that drains receipts FIFO and performs ReceiptLog::append via spawn_blocking, with shutdown tail-drain support.
  • Updated runtime wiring, handler construction, and tests to exercise the production enqueue path (including a regression test that stalls append while delivery completes).

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated no comments.

Show a summary per file
File Description
crates/node/src/receipt_log.rs Adds ReceiptSink, bounded channel sink, background writer loop, and unit tests for drop/drain/error behavior.
crates/node/src/handlers/client.rs Switches receipt recording from awaited disk append to synchronous non-blocking enqueue via ReceiptSink.
crates/node/src/runtime/mod.rs Wires the receipt writer into the node runtime and ensures cooperative shutdown + deadline abort backstop.
crates/node/src/metrics.rs Adds decdn_receipt_writes_dropped_total counter and a test asserting correct export behavior.
crates/node/tests/support/mod.rs Updates test handler builders to accept a ReceiptSink and adds a blocking receipt-log fake for loopback testing.
crates/node/tests/client_loopback.rs Adds a production-path regression test proving delivery completes while the receipt writer is stalled, then drains on shutdown.
crates/node/Cargo.toml Adds tokio-util as a dev-dependency for integration tests using CancellationToken.

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

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown

Coverage report

Total: 87.14% (was 87.15%, ▼ 0.01%) — 28249/32417 lines

File Coverage Lines Δ
crates/node/src/handlers/client.rs 76.53% 450/588 ▼ 0.23%
crates/node/src/metrics.rs 86.53% 533/616 ▲ +0.29%
crates/node/src/receipt_log.rs 91.06% 489/537 ▼ 0.79%
crates/node/src/runtime/mod.rs 44.02% 523/1188 ▼ 0.41%
History
Commit Total Δ vs base
09ad91c (HEAD) 87.14% ▼ 0.01%

@alpergundogdu alpergundogdu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — decouple receipt-log writes from the paid-delivery hot path

Solid, well-scoped fix. The bounded-queue + single-background-writer design is the right shape for #803, the FIFO/tail-drain guarantees are preserved, and the shutdown wiring is careful (cancel after router.shutdown(), await in the drain phase, abort backstop past the deadline). Tests are excellent — the delivery_completes_while_receipt_writer_is_stalled loopback through the real ChannelReceiptSink is exactly the regression that matters. A few notes, none blocking:

1. New silent loss mode: drop-on-full (acknowledged, but worth calling out for reviewers). Pre-#803, a slow disk back-pressured delivery but never lost a receipt. Now a saturated queue drops the audit receipt (counted via decdn_receipt_writes_dropped_total) and a crash between try_send and the background append loses the tail. The PR explicitly accepts this (audit-only; payment is committed to the fsynced channel store; the log was never fsync'd anyway), and that's the correct tradeoff for a delivery-latency bug. The thing I'd flag is that the drop counter is the only durable signal a dispute record was lost — so whatever alerting consumes decdn_settlement_*/audit should also alert on receipt_writes_dropped > 0, and that ought to be noted in the observability appendix alongside the metric. Capacity 1024 (~1 GiB served before drops begin) seems reasonable for the burst envelope.

2. Closed-branch observability gap (you already note it). If the writer task panics, rx drops and every subsequent record() hits TrySendError::Closed, which is intentionally uncounted (debug-only) to avoid shutdown false-positives. That means a mid-life writer death silently drops all receipts with no metric. The append_one JoinError handler should keep the loop alive across a panicking append, so this is low-probability — but since the writer is now a single point of failure for the whole audit stream, consider whether a panicked-writer condition deserves its own counter/error! (distinct from the benign shutdown Closed). Not necessary for this PR.

3. out_of_joinset_aborts bump. The + 1 is correct since the writer is always spawned, but it's now a bare literal next to two conditional terms — a small readability snag if a third out-of-joinset task lands later. A named usize::from(true)-style or a comment tying the +1 to the receipt writer would age better. Nit.

LGTM pending CI (status currently shows no completed checks).


Generated by Claude Code

@thiras
thiras merged commit feedc49 into main Jun 6, 2026
22 checks passed
@thiras
thiras deleted the fix/803-decouple-receipt-log-writes branch June 6, 2026 11:25
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: audit-only download-receipt write is awaited on the paid-delivery hot path

3 participants