Repository navigation
fix(node): debounce watcher checkpoint writes (#784) - #792
Conversation
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]>
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
DebouncedCheckpointStoreto bufferrecord_last_seen_blockand only fsync on block/time thresholds. - Extend
WatcherCheckpointStorewith aflush()default no-op and wire a shutdown-time flush inPaymentChannelService. - 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.
Coverage reportTotal: 86.61% (was 86.58%, ▲ +0.03%) — 26251/30309 lines
History
|
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
left a comment
There was a problem hiding this comment.
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_BLOCKSrewind reasoning genuinely makes a lagging/lost checkpoint only ever widen the next rescan, so relaxing per-call fsync to a decorator is safe. persist_lockedleavingpending/last_persisted/last_persist_atuntouched on a failed inner write (so the nextrecord/flushretries) is the right failure semantics, anddebounce_retries_after_a_failed_writeproves it.- Seeding
last_persistedfrom the inner store on the first in-processrecord(rather than in the constructor) keeps construction I/O-free while still preventing a regression of an already-populated on-disk floor — nicely covered bydebounce_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 slowcloseChannelcan't starve it) is a good call, and the traitflushdefault 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
Summary
The settlement watcher advanced the
ChannelOpenedscan checkpoint withDurability::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_startrewinds it byREORG_MARGIN_BLOCKSandregister_open_channelis 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): aWatcherCheckpointStoredecorator that buffersrecord_last_seen_blockin 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_blockreturns 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.PaymentChannelServiceholds the checkpoint store and forces a final flush inclose_open_channels_on_shutdown(the ADR 025 runtime shutdown path), so steady-state progress survives a clean stop.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.Closes #784
Review
Multi-agent
pr-review-toolkitdispatch 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.debounce_retries_after_a_failed_write, which in turn surfaced a latent test-helper bug —RecordingCheckpointStore's derivedDefaultseededstored = 0, whichload_last_seen_blockwould misreport as a real block-0 checkpoint instead of "unset". Fixed with a hand-writtenDefaultusing theu64::MAXsentinel.record_last_seen_blockdoc note inchannel_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.into_inner,.max/saturating_*, no indexing); monotonicity and retry semantics correct.DebounceStatefully encapsulated behind the mutex; thepending >= last_persistedinvariant is maintained byrecord/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:
flush_checkpoint_on_shutdown'swarn!on a failed flush now logs the still-buffered high-water block (load_last_seen_block, which keeps the bufferedpendingon a failed flush), so a post-mortem knows how far back the next boot rescans. Nometricshandle is reachable on this shutdown path (the watcher task owns it), so thewatcher_persist_failure()counter is intentionally not plumbed through here for parity — the warn is the signal; an inline comment notes the asymmetry.last_persist_atdoc comment called the debounce clock a "wall-clock instant"; corrected to monotonicInstant(the code was already correct — comment only).debounce_first_record_writes_through_over_existing_floor, locking in thelast_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-processrecord), distinct from the existing read-through test.DebouncePolicy/Floornewtype refactors (expression-only, non-blocking) and aDrop-based flush guard (reviewer advised against) were reviewed and deliberately left out.Verification
cargo build,cargo clippy --workspace --all-targets,cargo fmt -- --checkclean.cargo nextest runfull 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 -- --checkclean;cargo nextest run -p decdn-node404 passed, 0 failed (9 checkpoint-debounce tests incl. the new first-write test); pre-commit hooks all pass.🤖 Generated with Claude Code