Skip to content

feat(node): bound download-receipt log with size-based rotation (#802) - #807

Merged
thiras merged 3 commits into
mainfrom
feat/receipt-log-rotation-802
Jun 4, 2026
Merged

thiras merged 3 commits into
mainfrom
feat/receipt-log-rotation-802

Conversation

@thiras

@thiras thiras commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes #802.

The append-only download-receipt audit log (download_receipts.jsonl, ~one line per accepted voucher interval) had no rotation, retention, or size cap. On a long-running, high-throughput node it grew monotonically across restarts (O_APPEND) and eventually exhausted data_dir — the lone unbounded-growth sink in its batch of work (VoucherActivity eviction, the session-ticket peer cap, and the withdrawn-cache all got explicit bounds).

This PR adds size-based rotation with N retained backups to JsonlReceiptLog, exposed via a new optional [receipts] config section.

Changes

crates/node/src/receipt_log.rs

Config (crates/common/src/config/{types,resolved,mod}.rs)

  • New optional [receipts] section: max_file_bytes (default 128 MiB) and retained_files (default 4), validated to [1 MiB, 1 GiB] and <= 100.
  • Bounds data_dir to roughly (retained_files + 1) * max_file_bytes.
  • Config-additive — an absent section preserves prior behaviour with the defaults.

crates/node/src/runtime/mod.rs

  • Threads the resolved policy into JsonlReceiptLog::open. The edit is confined to the existing receipt-log block to minimise overlap with in-flight PRs.

Behaviour notes

  • Rotates on written + line_len > max_file_bytes (not >= max) so the cap isn't delayed by one record.
  • A single line larger than the cap still writes (after one rotation) instead of looping or being dropped.
  • On Unix the freshly-opened live file and rotated backups keep mode 0o600.

Testing

  • cargo clippy -p decdn-common -p decdn-node --all-targets — clean
  • cargo fmt -- --check — clean
  • cargo doc (pre-commit, -D warnings) — clean
  • cargo nextest run — 750 node/common + 162 cli tests pass, including 10 new tests:
    • rotate-before-write creating bounded backups (.1 newest, oldest dropped)
    • oversized single line writes after a single rotation
    • retained_files == 0 truncates in place
    • reopen seeds the rotation counter from the existing file length
    • rotation preserves 0o600 on the live file and backups
    • config defaults, boundary acceptance, and floor/ceiling/cap rejection

Notes

This branch was chosen to avoid conflicts with open PRs #806, #800, and #794 — the common/config/* and node/runtime/mod.rs edits land in different, additive regions.

The append-only `download_receipts.jsonl` had no rotation, retention, or
size cap, so on a long-running, high-throughput node it grew monotonically
across restarts (`O_APPEND`) and eventually exhausted `data_dir`.

Add size-based rotation with N retained backups to `JsonlReceiptLog`:
- track the live-file size in-memory (seeded from the file length at open)
  and rotate before a write would exceed `max_file_bytes`;
- shift numbered backups `.1..=.N`, drop the oldest beyond `retained_files`,
  reopen a fresh `0o600` file; `retained_files == 0` truncates in place;
- best-effort: a failed rename/open restores the canonical path so the
  writable handle is never lost and paid delivery is never aborted; the
  in-memory counter resyncs from metadata after a write error.

Expose limits via a new optional `[receipts]` config section
(`max_file_bytes`, `retained_files`) with floor/ceiling validation
(1 MiB–1 GiB, <=100 backups) and defaults (128 MiB, 4), bounding `data_dir`
to roughly `(retained_files + 1) * max_file_bytes`. Config-additive: an
absent section preserves prior behaviour with the defaults.

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings June 3, 2026 22:21

@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 size-based rotation for the download-receipt audit log to prevent unbounded disk growth, introducing a new [receipts] configuration section with customizable limits. The review feedback points out a key issue where modifications to this new configuration section during a SIGHUP reload are silently ignored instead of triggering a warning to the operator that a restart is required, and provides clear, actionable steps to resolve it.

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/node/src/runtime/reload.rs Resolved
@github-actions

github-actions Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 86.67% (was 86.62%, ▲ +0.05%) — 27791/32064 lines

File Coverage Lines Δ
crates/common/src/config/mod.rs 96.36% 4871/5055 ▲ +0.07%
crates/common/src/config/resolved.rs 100.00% 19/19 ● 0.00%
crates/node/src/receipt_log.rs 91.85% 338/368 ▼ 2.92%
crates/node/src/runtime/mod.rs 44.62% 518/1161 ▲ +0.01%
crates/node/src/runtime/reload.rs 95.07% 1409/1482 ▼ 0.44%
History
Commit Total Δ vs base
49916e7 86.69% ▲ +0.06%
b6ffb36 86.67% ▲ +0.05%
4021f0c (HEAD) 86.67% ▲ +0.05%

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 addresses issue #802 by adding a bounded, size-based rotation/retention policy to the node’s append-only download-receipt audit log (download_receipts.jsonl). It introduces a new optional [receipts] config section, wires the resolved policy into the node runtime, and adds targeted tests to ensure rotation behavior is correct and permissions are preserved.

Changes:

  • Added RotationPolicy and rotation logic to JsonlReceiptLog, including retained numbered backups and a truncate-in-place mode when retained_files == 0.
  • Introduced new [receipts] config types + resolver validation and threaded the resolved policy into node runtime initialization.
  • Updated tests and documentation (CHANGELOG) to cover defaults, validation boundaries, and rotation scenarios.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/node/src/receipt_log.rs Implements size-based rotation/retention for the JSONL receipt log and adds unit tests for rotation behavior.
crates/node/src/runtime/mod.rs Wires ResolvedReceipts into JsonlReceiptLog::open via a RotationPolicy.
crates/common/src/config/types.rs Adds optional [receipts] config section (ReceiptsConfig).
crates/common/src/config/mod.rs Adds resolver constants + validation logic for receipts rotation settings and unit tests.
crates/common/src/config/resolved.rs Adds ResolvedReceipts and threads it into ResolvedConfig.
crates/node/src/runtime/reload.rs Updates hand-built ResolvedConfig instances in tests to include ResolvedReceipts.
crates/node/tests/sighup_signal.rs Updates test config seeding to include ResolvedReceipts.
crates/cli/tests/config_validate.rs Updates test helper ResolvedConfig construction to include ResolvedReceipts.
CHANGELOG.md Documents the new bounded rotation behavior and the [receipts] config section.

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

Comment thread crates/node/src/receipt_log.rs Resolved
Comment thread crates/node/src/receipt_log.rs Resolved
Comment thread crates/common/src/config/resolved.rs Resolved
- reload: warn when the restart-required [receipts] section changes on SIGHUP
- receipt_log: prune now-stale backups when retained_files is lowered
- receipt_log: log-and-continue on rotation failure instead of dropping the
  audit receipt (the held handle stays writable; the next append retries)
- config: derive ResolvedReceipts::default() from the DEFAULT_RECEIPT_* consts
  so test configs cannot drift from production defaults

Co-authored-by: Copilot <[email protected]>
@thiras

thiras commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews — all four inline comments are addressed in b6ffb36:

  1. reload.rs (gemini): [receipts] is restart-required, so a SIGHUP change is now captured in FileSectionSnapshot and surfaced via the changed("receipts", …) warn in log_ignored_other_sections, matching the other restart-only sections.
  2. Prune stale backups (Copilot): rotate() now calls prune_backups_above(retained) first, so lowering receipts.retained_files between runs converges disk to the smaller bound. Covered by lowering_retained_files_prunes_stale_backups.
  3. Continue on rotation failure (Copilot): append() no longer ?-propagates a rotation error (which dropped the receipt). It logs download_receipt_rotation_failed and writes to the still-valid handle; the next append retries the rotation.
  4. resolved.rs default (Copilot): ResolvedReceipts::default() now derives from DEFAULT_RECEIPT_MAX_FILE_BYTES / DEFAULT_RECEIPT_RETAINED_FILES instead of duplicated literals.

clippy, fmt, cargo doc (-D warnings), and cargo nextest run -p decdn-common -p decdn-node (751 tests) all pass.

- prune_backups_above now logs real (non-NotFound) errors via a
  download_receipt_prune_failed warn instead of silently treating them as
  end-of-run, so a leak past the disk bound is observable.
- RotationPolicy gains From<&ResolvedReceipts> as the sole production
  constructor (validation now carries across the type boundary); the raw
  new() is gated to #[cfg(test)] pub(crate). runtime builds via From.
- Document the max_file_bytes == 0 "rotation disabled" sentinel.
- Add tests: rotation_failure_still_appends_and_stays_writable (best-effort
  fall-through + canonical-path handle survives) and
  rotates_after_filling_a_multi_line_file (multi-line rotation boundary).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras

thiras commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the review feedback in 4021f0c:

  • Silent disk leak in prune_backups_above — now distinguishes NotFound (normal end-of-run) from real errors (permissions/busy/I/O), logging the latter via a structured download_receipt_prune_failed warn before stopping, so a leak past the (retained_files + 1) * max_file_bytes bound is observable rather than silent.
  • RotationPolicy discarded the validation guarantee — added From<&ResolvedReceipts> as the sole production constructor (validation now carries across the type boundary); the raw new() is gated to #[cfg(test)] pub(crate), and the runtime builds via From. Also documented the max_file_bytes == 0 "rotation disabled" sentinel.
  • Untested best-effort fall-through — new rotation_failure_still_appends_and_stays_writable: forces a rotate() failure (directory squatting the .1 path) and asserts the receipt still lands + append returns Ok, then clears the failure and verifies a later append rotates cleanly (the live handle stays writable at the canonical path).
  • Multi-line rotation boundary — new rotates_after_filling_a_multi_line_file with a 3-line cap, distinguishing > from >= in the rotation-trigger arithmetic.

One caveat: the reopen-failure rollback branch (rename(.1 → canonical)) is not separately injectable in a portable test — the rename and the reopen's file creation share the same directory and identical write-permission gate, so no black-box FS setup makes the reopen fail while the preceding rename succeeds. Its observable contract ("a failed rotation never loses the writable canonical-path handle") is covered by the new fall-through test; the rename-back line itself is verified by reasoning. Happy to add an injectable open_append seam if explicit coverage of that exact line is wanted.

All 753 decdn-node + decdn-common tests pass; clippy and fmt clean.

@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: approve

Cleanest of the current batch. The hard parts all check out: highest-to-lowest backup shift (no clobber, oldest dropped), best-effort handle preservation across mid-rotation failure (the handle never dangles — covered by the failure-injection test), counter seed/resync, and atomicity under concurrent spawn_blocking callers (single Mutex<LogState> held across the whole append). Anti-panic policy respected (unwrap_or/saturating_add/combinators only), 0o600 preserved on live + backups, config validation rejects floor/ceiling/cap with field-tagged errors, reload emits the "requires restart" warning.

Nits (non-blocking, follow-up at most)

  • receipt_log.rs:553-576 — prune_backups_above issues a wasted remove_file(.{retained+1}) (returns NotFound) on every rotation in steady state. Negligible given rotation rarity; could gate it to the lowered-retention case.
  • receipt_log.rs:618-630 — an oversized single line (> max_file_bytes) lands over-cap and can end up in a backup, so the (retained+1)*max_file_bytes disk bound is genuinely "roughly." Worth a one-line doc caveat.
  • receipt_log.rs:647-649 — counter resync ignores a second metadata() failure, leaving written stale by at most one line; self-corrects on the next successful write/rotation. A comment noting the divergence window would help.

LGTM to merge.

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: download receipt log grows unbounded — no rotation, retention, or size cap

3 participants