Skip to content

fix(node): debounce watcher checkpoint writes (#784) - #792

Merged
thiras merged 3 commits into
mainfrom
fix/784-debounce-checkpoint
Jun 3, 2026
Merged

thiras merged 3 commits into
mainfrom
fix/784-debounce-checkpoint

Conversation

@thiras

@thiras thiras commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The settlement watcher advanced the ChannelOpened scan checkpoint with Durability::Immediate, fsyncing once per distinct block carrying a provider-owned open — once per block while draining a resubscribe backlog and in steady state on a high-fan-out provider (#751 follow-up, PR #781 MEDIUM-3).

The persisted checkpoint is only a floor for the resume backfill: resolve_backfill_start rewinds it by REORG_MARGIN_BLOCKS and register_open_channel is idempotent, so a checkpoint that lags the true scan position only ever widens the next rescan, never narrows it. That makes the write cadence safe to coarsen.

Change

  • DebouncedCheckpointStore (new, crates/node/src/payment_settlement.rs): a WatcherCheckpointStore decorator that buffers record_last_seen_block in memory and forwards a durable write only when the buffered block is >= 512 blocks ahead of the last persisted value or >= 30s have elapsed (whichever first). Keeps the stored value a monotonic floor; load_last_seen_block returns the max of the persisted and in-process buffered block. A failed inner write leaves the buffer intact so the next record/flush retries.
  • flush() trait method (crates/incentive/src/store.rs): default no-op (directly-durable stores have nothing buffered); the debouncer overrides it.
  • Graceful-shutdown flush: PaymentChannelService holds the checkpoint store and forces a final flush in close_open_channels_on_shutdown (the ADR 025 runtime shutdown path), so steady-state progress survives a clean stop.
  • Wiring: the runtime wraps the disk store in DebouncedCheckpointStore, keeping the domain trait and disk store free of debounce policy. The disk store stays durable per-call so the floor the debouncer does forward is crash-safe.
  • Defaults (512 blocks / 30s) are documented in code; not config-exposed (optional per the issue).

Closes #784

Review

Multi-agent pr-review-toolkit dispatch was unavailable in this environment (no Task/subagent tool), so I applied the five review lenses (code-reviewer, silent-failure-hunter, pr-test-analyzer, type-design-analyzer, comment-analyzer) directly to the working diff before committing.

  • pr-test-analyzer — addressed: flagged a missing test for the documented persist-failure-retry path. Added debounce_retries_after_a_failed_write, which in turn surfaced a latent test-helper bug — RecordingCheckpointStore's derived Default seeded stored = 0, which load_last_seen_block would misreport as a real block-0 checkpoint instead of "unset". Fixed with a hand-written Default using the u64::MAX sentinel.
  • comment-analyzer — addressed: updated the now-stale record_last_seen_block doc note in channel_store.rs (it said the write was "left immediate" pending Debounce watcher checkpoint writes to cut fsync amplification on backlog drain (#751 follow-up) #784) to point at the installed debouncer.
  • silent-failure-hunter — verified, no change: the shutdown flush is intentionally best-effort + logged (a lost flush only widens the next rescan per the floor contract); record/load errors propagate unchanged.
  • code-reviewer — verified, no change: anti-panic compliant (poison recovery via into_inner, .max/saturating_*, no indexing); monotonicity and retry semantics correct.
  • type-design-analyzer — verified, no change: DebounceState fully encapsulated behind the mutex; the pending >= last_persisted invariant is maintained by record/persist_locked.

Follow-up multi-agent review (d4cc7a1)

A second multi-agent review (correctness, silent-failure, type-design) again found the design CORRECT with no blocking findings. Applied three small polish items:

  • Shutdown-flush observability — applied: flush_checkpoint_on_shutdown's warn! on a failed flush now logs the still-buffered high-water block (load_last_seen_block, which keeps the buffered pending on a failed flush), so a post-mortem knows how far back the next boot rescans. No metrics handle is reachable on this shutdown path (the watcher task owns it), so the watcher_persist_failure() counter is intentionally not plumbed through here for parity — the warn is the signal; an inline comment notes the asymmetry.
  • Misleading comment — applied: the last_persist_at doc comment called the debounce clock a "wall-clock instant"; corrected to monotonic Instant (the code was already correct — comment only).
  • First-write test — applied: added debounce_first_record_writes_through_over_existing_floor, locking in the last_persisted.is_none() first-write-always-through semantics (a fresh wrapper over an inner store with a pre-existing persisted floor still fsyncs on the first in-process record), distinct from the existing read-through test.
  • Declined (intentional, for scope): the DebouncePolicy / Floor newtype refactors (expression-only, non-blocking) and a Drop-based flush guard (reviewer advised against) were reviewed and deliberately left out.

Verification

cargo build, cargo clippy --workspace --all-targets, cargo fmt -- --check clean. cargo nextest run full workspace: 1360 passed, 0 failed (8 new/related checkpoint tests). Pre-commit hooks (fmt, clippy, cargo doc with -D warnings, cargo deny) all pass.

Re-verified on the follow-up commit d4cc7a1: cargo build + cargo clippy --workspace --all-targets + cargo fmt -- --check clean; cargo nextest run -p decdn-node 404 passed, 0 failed (9 checkpoint-debounce tests incl. the new first-write test); pre-commit hooks all pass.

🤖 Generated with Claude Code

The settlement watcher advanced the `ChannelOpened` scan checkpoint with
`Durability::Immediate`, fsyncing once per distinct block carrying a
provider-owned open — once per block while draining a resubscribe backlog
and in steady state on a high-fan-out provider.

The persisted checkpoint is only a *floor* for the resume backfill
(`resolve_backfill_start` rewinds it by `REORG_MARGIN_BLOCKS` and
`register_open_channel` is idempotent), so the write cadence is safe to
coarsen. Introduce `DebouncedCheckpointStore`, a `WatcherCheckpointStore`
decorator that buffers in memory and forwards a durable write only every
512 blocks or 30s (whichever first), keeping the stored value a monotonic
floor. Add a `flush()` trait method (default no-op) and force a final flush
on graceful shutdown via `PaymentChannelService::close_open_channels_on_shutdown`
so steady-state progress survives a clean stop. The disk store stays durable
per-call so the floor the debouncer forwards is crash-safe; the wrapper is
installed in the runtime wiring layer, keeping the domain trait and disk
store free of debounce policy.

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

@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 introduces a debouncing decorator, DebouncedCheckpointStore, for the watcher scan checkpoint to reduce fsync write amplification. It buffers checkpoint writes in memory and only persists them to disk when either a block-count threshold (512 blocks) or a time-based threshold (30 seconds) is met. It also adds a flush method to the WatcherCheckpointStore trait to force any buffered checkpoint to durable storage on graceful shutdown. The reviewer suggested optimizing record_last_seen_block by returning early if the incoming block is less than or equal to the already persisted block, preventing redundant calculations and disk writes when the time threshold has elapsed.

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/payment_settlement.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 reduces fsync/write amplification in the node’s payment-settlement watcher by debouncing durable persistence of the ChannelOpened scan checkpoint, while preserving the “checkpoint is a monotonic floor” contract and flushing pending progress on graceful shutdown.

Changes:

  • Add DebouncedCheckpointStore to buffer record_last_seen_block and only fsync on block/time thresholds.
  • Extend WatcherCheckpointStore with a flush() default no-op and wire a shutdown-time flush in PaymentChannelService.
  • Wrap the persistent checkpoint store with the debouncer in the node runtime and update docs/tests accordingly.

Reviewed changes

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

File Description
crates/node/src/runtime/mod.rs Wraps the persistent checkpoint store with DebouncedCheckpointStore at wiring time.
crates/node/src/payment_settlement.rs Implements the debounced checkpoint decorator, adds shutdown flush plumbing, and adds unit tests.
crates/node/src/channel_store.rs Updates checkpoint persistence doc comment to reflect debounced wiring.
crates/incentive/src/store.rs Adds flush() to WatcherCheckpointStore with default no-op and updates method docs.

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

Comment thread crates/node/src/payment_settlement.rs Resolved
Comment thread crates/incentive/src/store.rs Resolved
@github-actions

github-actions Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 86.61% (was 86.58%, ▲ +0.03%) — 26251/30309 lines

File Coverage Lines Δ
crates/incentive/src/store.rs 90.91% 160/176 ▼ 1.58%
crates/node/src/channel_store.rs 89.28% 1141/1278 ● 0.00%
crates/node/src/payment_settlement.rs 38.23% 445/1164 ▲ +16.94%
crates/node/src/runtime/mod.rs 45.82% 515/1124 ▼ 0.04%
History
Commit Total Δ vs base
75a3ce5 86.60% ▲ +0.02%
d4cc7a1 86.60% ▲ +0.02%
a29b331 (HEAD) 86.61% ▲ +0.03%

thiras and others added 2 commits June 3, 2026 01:52
Multi-agent review of #792 found the DebouncedCheckpointStore design correct
with no blocking findings. Apply the small polish items:

- Shutdown-flush warn now logs the still-buffered high-water block
  (`load_last_seen_block`) so a post-mortem knows the next boot's rescan depth.
  No `metrics` handle is held on this path, so the counter parity with the
  in-loop persist sites is intentionally skipped (noted in a comment).
- Fix the `last_persist_at` doc comment: the debounce clock is a monotonic
  `Instant`, not a wall-clock instant (comment only; behavior unchanged).
- Add a test that a fresh wrapper over an inner store with a pre-existing
  persisted floor still fsyncs on the FIRST in-process `record`
  (`last_persisted.is_none()` first-write-always-through), distinct from the
  load-through test.

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

A fresh `DebouncedCheckpointStore` over an already-populated inner store left
`last_persisted` as `None` and never consulted `inner.load_last_seen_block()`,
so a first `record_last_seen_block` carrying a block BELOW the existing on-disk
checkpoint would forward that lower block and regress the monotonic floor
(unconditionally `due` via the old `last_persisted.is_none()` first-write
rule). The watcher loop never feeds such a record, but the decorator's
documented "monotonic floor for any caller" contract did not hold.

Lazily fold the inner floor into `last_persisted` on the first record (keeping
the constructor I/O-free) so the high-water guard honors it, and skip the write
entirely when the guarded high-water is already at/below the durable floor — no
regression, no redundant fsync. A separate `seeded` flag preserves the
intended first-write re-anchor for records that actually advance the floor.

Reconcile the `WatcherCheckpointStore` trait doc so the per-call fsync MUST
applies to directly disk-backed impls while a debouncing decorator may relax it
provided it preserves the monotonic-floor + flush-on-shutdown invariants.

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

@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 — debounce watcher checkpoint writes

This is high quality and I found no blocking issues. The design is correct and the safety argument is airtight:

  • The monotonic-floor + idempotent-register_open_channel + REORG_MARGIN_BLOCKS rewind reasoning genuinely makes a lagging/lost checkpoint only ever widen the next rescan, so relaxing per-call fsync to a decorator is safe.
  • persist_locked leaving pending/last_persisted/last_persist_at untouched on a failed inner write (so the next record/flush retries) is the right failure semantics, and debounce_retries_after_a_failed_write proves it.
  • Seeding last_persisted from the inner store on the first in-process record (rather than in the constructor) keeps construction I/O-free while still preventing a regression of an already-populated on-disk floor — nicely covered by debounce_seeds_floor_from_populated_inner_store.
  • Poison recovery via into_inner, .max/saturating_*, no indexing — anti-panic clean. Sync mutex never held across an .await.
  • Flushing the checkpoint before the channel-close deadline in close_open_channels_on_shutdown (so a slow closeChannel can't starve it) is a good call, and the trait flush default no-op keeps directly-durable stores unaffected.

One benign edge I want to flag for the record (no change needed): in record_last_seen_block, the first-record path sets state.seeded = true before self.inner.load_last_seen_block()?. If that load errors, the ? returns early with seeded == true but last_persisted still None, so the next successful record no longer hits the "first record always writes through" rule and may buffer instead of re-anchoring immediately. It's harmless — flush() on shutdown still persists, and the floor contract tolerates the lag — but worth a one-line comment if you want to be explicit that a failed seed-load degrades to ordinary debounce.

The RecordingCheckpointStore Default fix (hand-written u64::MAX sentinel instead of derived 0) was a real latent test-helper bug; good catch surfacing it via the new test. Test coverage (block threshold, time threshold via injected clock, monotonicity, read-through max, first-write-over-existing-floor, retry-after-failure) is comprehensive. LGTM.


Generated by Claude Code

@thiras
thiras merged commit a4e3ccd into main Jun 3, 2026
19 checks passed
@thiras
thiras deleted the fix/784-debounce-checkpoint branch June 3, 2026 13:41
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.

Debounce watcher checkpoint writes to cut fsync amplification on backlog drain (#751 follow-up)

3 participants