Repository navigation
feat(node): seller-settlement robustness follow-ups (#751) - #781
Conversation
Implements the seven deferred items from the PR #743 / #327 review across correctness, robustness, observability, and type hygiene in the seller-side payment-settlement path. Correctness — opened-during-downtime backfill: - Add `WatcherCheckpointStore` (persisted last-scanned `ChannelOpened` block). On bootstrap the watcher resumes the backfill from the checkpoint (minus a reorg margin, clamped to head) instead of only the bootstrap head, so a channel opened while the node was down is registered rather than rejected `WrongChannel` forever. The gap is walked in bounded `eth_getLogs` windows. The checkpoint is advanced past a live `ChannelOpened` only once it is persisted (a hold keeps the scalar checkpoint below an unpersisted open so the resume backfill re-covers it). Robustness: - Add a low-frequency redeemer self-tick that scans `load_all` for above-threshold channels, so a dropped advisory hint can't strand a claim. - Quiesce (abort + await) the redeemer before the shutdown close so an in-flight `withdraw` can't race a `closeChannel` (benign revert + misleading warn); a `Drop` safety net aborts a non-gracefully-dropped redeemer. Observability: - New counters: `decdn_redeem_hints_dropped_total`, `decdn_redemption_failures_total`, `decdn_watcher_persist_failures_total`. - Add `VoucherRejectReason::Expired` (frozen-order append) so the expiry serve-gate sends an actionable in-band reason instead of an opaque `anyhow::bail!` stream drop. Type hygiene: - Demote `ChannelState`'s replay-critical `last_*` fields behind a `hydrate` constructor + getters so the #527 "advance only via `apply_voucher`" invariant is compiler-enforced; `last_signature` is now `Option<[u8; 65]>` (empty-or-65-bytes unrepresentable-when-wrong), converted at the codec boundary so the on-disk format is unchanged. - Bundle the schema-v2 trailing segments into a `TrailerV2` type (byte-identical on-disk layout; kept as a trailing segment for v1-record compatibility). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request improves the robustness of the payment channel settlement system by making key ChannelState fields private to enforce invariants, introducing a WatcherCheckpointStore to persist scan checkpoints across restarts, and adding a low-frequency self-tick sweep to the redeemer task. It also introduces metrics for tracking failures and handles expired channels in-band. The reviewer feedback suggests replacing tokio::sync::Mutex with std::sync::Mutex for the redeemer task handle to avoid unnecessary async overhead, along with safely handling poisoned locks using unwrap_or_else(std::sync::PoisonError::into_inner).
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
Implements the deferred follow-ups from the seller-settlement review (#751), focusing on closing watcher gaps across restarts, hardening redemption progress guarantees, improving observability, and tightening type invariants around replay-critical channel state.
Changes:
- Add a durable watcher checkpoint + bounded
getLogsbackfill soChannelOpenedevents emitted during node downtime (and the #762 bring-up gap) are discovered on the next boot. - Add a redeemer self-tick sweep and quiesce/abort the redeemer before shutdown channel-closing to prevent
withdrawvscloseChannelraces. - Improve observability and UX: new counters for dropped hints / redemption failures / watcher persist failures, plus an in-band
VoucherRejectReason::Expired.
Reviewed changes
Copilot reviewed 13 out of 13 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/protocol/tests/snapshots/public_api__public_api.snap | Updates public API snapshot for the appended Expired reject reason variant. |
| crates/protocol/src/client.rs | Adds VoucherRejectReason::Expired and documents variant-order constraints. |
| crates/node/tests/client_loopback.rs | Adjusts tests for ChannelState getters/hydration and adds an expiry rejection loopback test. |
| crates/node/tests/channel_state_store.rs | Updates store tests to use ChannelState getters after last_* encapsulation. |
| crates/node/tests/anvil_settlement_e2e.rs | Wires the new WatcherCheckpointStore into the settlement service bootstrap in e2e. |
| crates/node/src/runtime/mod.rs | Wires the checkpoint store and metrics into runtime settlement bootstrap. |
| crates/node/src/payment_settlement.rs | Core logic: checkpointed downtime backfill, bounded windows, redeemer self-tick, redeemer quiesce on shutdown, watcher persist failure metrics. |
| crates/node/src/metrics.rs | Adds counters and helper methods for the new observability signals. |
| crates/node/src/handlers/client.rs | Surfaces expiry as in-band Expired rejection; counts dropped redeem hints. |
| crates/node/src/channel_store.rs | Adds redb-backed WatcherCheckpointStore + bundles schema-v2 trailer into TrailerV2 and narrows stored signature to Option<[u8;65]>. |
| crates/incentive/src/store.rs | Introduces the WatcherCheckpointStore trait. |
| crates/incentive/src/lib.rs | Re-exports WatcherCheckpointStore. |
| crates/incentive/src/channel.rs | Encapsulates replay-critical last_* fields behind hydrate() + getters; makes signature strongly typed (Option<[u8;65]>). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 86.58% (was 86.95%, ▼ 0.37%) — 25863/29871 lines
History
|
…ll doc - `PaymentChannelService.redeemer` uses `std::sync::Mutex` instead of `tokio::sync::Mutex` (gemini-code-assist): the guard is only held to `take()` the handle, never across an `.await`, so the async mutex was unnecessary overhead. Both lock sites recover a poisoned lock via `unwrap_or_else(PoisonError::into_inner)` rather than `unwrap`/`expect` (denied workspace-wide), and `Drop` now `lock()`s (uncontended under `&mut self`) instead of `try_lock()` so the abort still runs if poisoned. - Fix the module-header description of the backfill floor `S` (Copilot): it is the *lower* of the bootstrap head and (checkpoint − reorg margin), not the maximum — matching `resolve_backfill_start`, so `[S, F]` covers both the #751 downtime gap and the #762 bring-up window. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comprehensive review (silent-failure-hunter + code-reviewer) found the scan checkpoint could advance past an unpersisted `ChannelOpened` and strand a channel — the exact #751 failure class: - The four watcher event streams are independent `.watch()` filters with no cross-stream block ordering, and the checkpoint was advanced from all four arms (the settled arm even on foreign-channel events). A later foreign event could persist the checkpoint past block N before our `ChannelOpened` at N was delivered and failed to persist, so the reactive `checkpoint_hold` was set too late; if the advance exceeded the reorg margin before a restart, N was skipped. Fix: advance the scan checkpoint ONLY from the `opened` arm, on a successful register (the only event that proves opens were scanned+registered through its block). The `opened` stream is block-ordered, so the per-cycle hold covers a later same-stream open; a failed open also re-arms `backfill_from` to its block so a resubscribe re-covers it, and the held checkpoint makes a restart re-cover it too. Removes checkpoint advancement from the topped_up/settled/close arms. Also from the review: - Add an end-to-end downtime-backfill phase to the anvil e2e (the headline #751 proof): drop the service, `openChannel` while down, re-bootstrap against the same store, assert the channel is registered via the checkpoint-floored backfill. - Document the deliberate `pub deposit`/`expires_at` encapsulation asymmetry and the `hydrate` positional-arg trust boundary (type-design review). - Fix a module-header run-on and note the post-backfill checkpoint write never regresses (comment review). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comprehensive review round (commit 3808e19)Ran a multi-agent review (code quality, tests, comments, type design, silent failures) over the diff. One genuine correctness issue surfaced, plus the headline test gap and some polish — all addressed. Correctness (must-fix) — checkpoint could strand a channelTwo reviewers independently flagged that the scan checkpoint could advance past an unpersisted
Fix: advance the checkpoint only from the Tests — headline #751 proofAdded an end-to-end downtime-backfill-across-restart phase to the anvil e2e: drop the service (node "down"), Polish
Gates: |
Re-review (pr-test-analyzer) found the new downtime-backfill e2e phase could pass spuriously: without a block mined between the downtime `openChannel` and the re-bootstrap, `head == down_block`, so the #762 within-session backfill `[head, F]` already covers the channel — the test passed even when the #751 checkpoint floor was ignored. - `evm_mine` after the downtime open so service2's bootstrap head is strictly above the channel's block; now `[head, F]` excludes it and only the persisted checkpoint floor (#751) can re-cover it. Verified by mutation: forcing `resolve_backfill_start` to ignore the checkpoint makes the phase FAIL with "#751 checkpoint backfill failed". - Derive the channel id from the live `clientChannelNonce` (read pre-open) instead of hardcoding nonce 3, so the proof survives earlier-phase churn. Adds the `clientChannelNonce` getter to the `PaymentChannel` binding. - Document (module header) that a failed *live* open-persist recovers on the next resubscribe/restart, not mid-cycle — a liveness window, never a strand (silent-failure-hunter LOW note). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Re-review round (commit af3ef83)Re-ran the multi-agent review focused on the round-2 checkpoint rewrite. Checkpoint fix confirmed correct. Both silent-failure-hunter and code-reviewer verified the hardening ( Important: the new e2e test could pass spuriously — fixed. pr-test-analyzer (criticality 8) found that without a block mined between the downtime Gates: 1324 workspace tests + anvil e2e pass; clippy/fmt/doc/deny clean. |
alpergundogdu
left a comment
There was a problem hiding this comment.
Review — seller-settlement robustness follow-ups (#751)
Read the full diff. This is a careful, well-documented PR with genuinely strong test coverage (downtime-backfill e2e, expired-rejection loopback, checkpoint round-trip, window math, trailer byte-identity). No blockers, no anti-panic violations in non-test code, no codec break. Findings below are mostly doc-accuracy and operational notes.
Positives verified
- ADR 005 (frozen variant order):
VoucherRejectReason::Expiredis correctly appended (last source-order variant). The snapshot only shows it mid-list because that snapshot is alphabetized. ✅ - ADR 527 (
last_*advance only viaapply_voucher): Correctly compiler-enforced —last_*are now private withapply_voucher+hydrateas the only writers.expires_at/depositstaypub(not replay-critical), as documented. ✅ - On-disk codec:
TrailerV2is provably byte-identical to the prior two-segment layout (postcard concatenates in declaration order), pinned by a dedicated regression test across empty/65-byte signatures. No schema bump. ✅ - Window math:
backfill_windows/resolve_backfill_startare pure and unit-tested across exact-multiple, remainder, single-block, clamp-to-head, and large-gap cases. No off-by-one found. ✅ - Anti-panic / concurrency:
quiesce_redeemerandDropuseunwrap_or_else(PoisonError::into_inner)on thestd::sync::Mutex, and the guard is dropped beforehandle.await(never held across await).Dropaborts (safety net) and is idempotent withquiesce_redeemerviatake(). ✅
HIGH — doc accuracy / cold-start cost
redeem_sweep / try_redeem (crates/node/src/payment_settlement.rs): The doc claims "a warm cache makes this cheap; a cold entry costs one getChannel." But withdrawn_cache is only populated on a successful withdraw, and the pre-check uses unwrap_or(U256::ZERO). So on the first self-tick after boot — and for any channel that has never crossed threshold in-process — cached_withdrawn = 0, and last_amount() - 0 >= threshold forces a getChannel RPC for every above-threshold channel, every tick. For a node tracking many channels this is an O(channels) RPC fan-out per sweep, not "cheap on a warm cache." Please correct the doc and/or confirm REDEEM_TICK_INTERVAL × fan-out stays within RPC budget.
MEDIUM
- Stranded-channel recovery window (live-stream
ChannelOpenedpersist failure): When a live open for this node fails to persist, recovery (re-scan) only happens on the next resubscribe/restart. On a healthy never-resubscribing stream that window is unbounded — the client's vouchers are rejectedWrongChanneluntil an unrelated restart, and the redeem self-tick doesn't help (it only redeems already-registered channels). The PR documents this honestly; suggest an inline bounded retry on the persist, or a forced resubscribe whilecheckpoint_holdis set. Worth a tracking issue at minimum. advance_checkpointcross-cycle invariant is load-bearing but implicit: Correctness of the hold relies on theopenedlog stream being strictly block-ordered (so an earlier successful open is always at a lower block than a laterfailedone, keeping the persisted checkpoint< failed). alloy streams are ordered, but since this is the invariant the whole hold rests on, please add an explicit comment/assert at the guard site.- Checkpoint fsync amplification:
record_last_seen_blockusesDurability::Immediate, so a backlog drain over a busy range fsyncs once per new block. For a popular provider this is a steady fsync/block. Consider debouncing (the rounded-down re-scan is idempotent, so a coarser cadence is safe).
LOW
redeem_hintdrop metric (crates/node/src/handlers/client.rs): OnlyTrySendError::Fullis counted;Closed(redeemer gone duringquiesce_redeemerat shutdown) is silently ignored. Likely intended, but a one-line comment distinguishing Full → counted vs Closed → expected-at-shutdown would stop a future reader from "fixing" it to count both.quiesce_redeemerrace claim:abort()cancels the task but the already-broadcastwithdrawtx can still mine after shutdown, concurrently withcloseChannel— the exact race the PR says it eliminates. Suggest softening the doc from "cannot race one" to "greatly narrows the window."MAX_BACKFILL_BLOCK_SPAN = 10_000: Hardcoded and not tied to the provider's actualeth_getLogscap (many cap lower, or by result count rather than span). A dense 10k-block window could trip a result-count cap. Consider making it configurable or documenting the deployment-RPC dependency.
Overall: mergeable. I'd address the HIGH doc claim and file a tracking issue for MEDIUM-1 before/at merge; the rest are follow-ups.
Generated by Claude Code
alpergundogdu
left a comment
There was a problem hiding this comment.
Posting the three MEDIUM findings from my earlier summary as line-anchored comments for actionability. None are blockers — they're design/operational hardening on the #751 watcher-checkpoint work.
Generated by Claude Code
| // next resubscribe re-scans and re-registers the channel | ||
| // (the held checkpoint also makes a restart re-cover it). | ||
| *backfill_from = | ||
| Some(backfill_from.map_or(failed, |b| b.min(failed))); |
There was a problem hiding this comment.
MEDIUM — recovery window can be unbounded on a healthy stream.
When a live ChannelOpened for this node fails to persist, the checkpoint is held below its block and backfill_from is re-armed here — but the re-scan only fires on the next resubscribe or restart. On a stable RPC connection that never errors/resubscribes, a transient store hiccup on one channel strands that client until an unrelated restart: its vouchers are rejected WrongChannel the whole time, and the redeem self-tick doesn't help (it only redeems already-registered channels).
The module doc acknowledges this honestly, but it's a real client-facing failure mode. Consider a bounded inline retry of apply_channel_opened before falling back to the hold/re-arm, or a forced resubscribe while checkpoint_hold.is_some(), so recovery doesn't depend on an external trigger. At minimum, worth a tracking issue.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in 0247dda with the forced-resubscribe option. run_watcher_once now returns a CycleOutcome; on a persist failure it re-arms backfill_from and returns RecoveryPending, and watcher_loop resubscribes immediately so the next cycle's backfill re-covers the channel — no longer waiting on an unrelated stream-end/restart. The resubscribe is paced by the existing exponential backoff, so a durable store failure backs off instead of hot-looping the backfill (a transient hiccup recovers within one initial-backoff interval).
Note: returning on the first failure makes the in-cycle checkpoint_hold redundant, so it's removed — the checkpoint stays <= the failed block by construction (only the opened arm advances it, the stream is block-ordered, and we return before any higher-block open is processed). That's exactly the invariant your MEDIUM-2 asked to make explicit, now documented on advance_checkpoint.
| let Some(block) = block else { | ||
| return; | ||
| }; | ||
| // Never advance to or past a block with an unpersisted `ChannelOpened`. |
There was a problem hiding this comment.
MEDIUM — load-bearing invariant; harden it here.
The whole hold scheme is correct only because the opened stream is strictly block-ordered: an earlier successful open is always at a lower block than a later failed one, so the persisted checkpoint stays < failed and this hold_below guard never lets a same-cycle open leap past it. The call site documents this ("The opened stream is block-ordered…"), but advance_checkpoint itself — the function the correctness rests on — takes it on faith.
Suggest a debug_assert!(block > *high_water || …)-style guard, or at least restate the block-ordering precondition in this function's doc, so a future refactor that feeds blocks out of order (e.g. merging another event source into the checkpoint advance) fails loudly rather than silently stranding a channel.
Generated by Claude Code
There was a problem hiding this comment.
Done in 0247dda. advance_checkpoint now carries a # Caller contract (load-bearing — #751 MEDIUM-2) doc spelling out the two properties it can't enforce from its args: (1) sole caller is the opened arm on a successful register, and (2) the opened stream is strictly block-ordered.
The hold-specific debug_assert you suggested went away with the hold itself (MEDIUM-1's early-return made it redundant), but the underlying concern is unchanged and arguably sharper now: with the early return, every advance in a cycle precedes the cycle's first failure, so block-ordering is what guarantees the persisted checkpoint never exceeds the failed block (and a restart's checkpoint − REORG_MARGIN floor re-covers it). The doc calls out that feeding blocks out of order — e.g. merging a second event source — would let an advance overshoot a later-failing open by more than the reorg margin and strand it across a crash-before-resubscribe.
| .map_err(|err| StoreError::Backend(format!("begin_write: {err}")))?; | ||
| // Force fsync-on-commit, same durability discipline as the other tables. | ||
| write_txn | ||
| .set_durability(Durability::Immediate) |
There was a problem hiding this comment.
MEDIUM — checkpoint fsync amplification on backlog drain.
Durability::Immediate here means every distinct new block with a provider-owned ChannelOpened triggers a synchronous fsynced commit. The doc notes "at most one fsync per new block" — which is exactly the concern: draining a backlog after a resubscribe over a busy range fsyncs once per block, and for a popular provider that's a steady fsync/block in steady state too.
Since the resume backfill rounds the checkpoint down by REORG_MARGIN_BLOCKS and register_open_channel is idempotent, the persisted value is safe to advance coarsely. Consider debouncing the checkpoint write (every N seconds / N blocks) to cut write amplification on high-fan-out nodes. Low risk at the testnet target, but worth a note/follow-up.
Generated by Claude Code
There was a problem hiding this comment.
Tracked in #784 (debounce the checkpoint write) and documented in 0247dda. Added a note at record_last_seen_block recording the one-fsync-per-block amplification and why coarse flushing is safe (the resume backfill rounds the checkpoint down by REORG_MARGIN_BLOCKS and register_open_channel is idempotent, so a lagging floor only widens the next rescan). Left Durability::Immediate as-is for now given the low fan-out at the testnet target, per your read.
…curacy (#751) Review follow-ups from #781. The Gemini/Copilot items were already handled in 5fe7754; these are Alper's findings. MEDIUM-1 (code): a live `ChannelOpened` persist failure on a healthy, never-resubscribing stream stranded that client (vouchers rejected `WrongChannel`) until an unrelated restart, because the re-armed backfill only ran on the next resubscribe. `run_watcher_once` now returns a `CycleOutcome`; on a persist failure it re-arms `backfill_from` and returns `RecoveryPending`, so `watcher_loop` resubscribes and re-runs the backfill immediately — paced by the existing backoff so a durable store failure backs off instead of hot-looping. Returning on the first failure makes the in-cycle `checkpoint_hold` redundant (the checkpoint stays <= the failed block via sole-`opened`-arm advancement + block-ordering + the early return), so it is removed. MEDIUM-2 (doc): spell out the load-bearing caller contract on `advance_checkpoint` (sole caller = `opened` arm on success; `opened` stream is block-ordered) so a refactor that feeds blocks out of order or from a second event source is warned at the function it would break. MEDIUM-3 (issue + doc): file #784 to debounce the `Durability::Immediate` checkpoint write (one fsync/block on backlog drain); note the amplification and the idempotent-floor rationale at `record_last_seen_block`. Left immediate at testnet fan-out. HIGH (doc): correct the `redeem_sweep` doc — the `withdrawn_cache` starts empty, so the first sweep after boot issues one `getChannel` per above-threshold channel (O(channels) fan-out), not "cheap on a warm cache." LOW (doc): clarify the `redeem_hint` drop metric counts `Full` (real drop) and deliberately not `Closed` (expected at shutdown); soften the `quiesce_redeemer` claim from eliminating to narrowing the withdraw-vs-`closeChannel` race (an already-broadcast tx can still mine); note `MAX_BACKFILL_BLOCK_SPAN` bounds block span, not result count. Gates: clippy/fmt/doc clean; 380 node tests + anvil e2e pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@alpergundogdu — addressed the rest of the summary review in 0247dda. MEDIUMs answered inline in their threads. HIGH (redeem_sweep doc). Corrected. You're right that the cache is empty at boot and the pre-check uses LOW (redeem_hint LOW (quiesce_redeemer race). Softened the field doc, LOW (MAX_BACKFILL_BLOCK_SPAN). Noted that 10k bounds the block span, not the result count — some providers cap by matched-log count or a lower span — and to tie it to the deployment provider's documented One gap I'll call out: MEDIUM-1's recovery mechanism (the backfill) is covered by the downtime-backfill-across-restart e2e, but the new trigger (resubscribe forced by a live persist failure, no restart) isn't directly tested — it'd need a fault-injecting store wrapper driving the live watcher. Happy to add that harness as a follow-up if you think it's worth it; left it out to avoid destabilizing the e2e for a path whose recovery is already proven. Gates: clippy/fmt/doc/deny clean; 380 node tests + anvil e2e pass. |
Closes #751.
Implements the seven deferred follow-ups from the PR #743 / #327 review across the four categories in the tracker. Single combined PR (per planning).
Correctness — opened-during-downtime backfill
The within-session
ChannelOpenedbackfill landed in #762; this closes the across-restart downtime gap. A newWatcherCheckpointStorepersists the last-scanned block; on bootstrap the watcher resumes the backfill fromcheckpoint − reorg_margin(clamped to head) instead of only the bootstrap head, so a channel a client opens while the node is down is registered rather than rejectedWrongChannelforever. The gap is walked in boundedeth_getLogswindows. The checkpoint advances past a liveChannelOpenedonly once it is persisted — a same-cycle hold keeps the scalar checkpoint strictly below an unpersisted open so the resume backfill re-covers it (addresses a review finding that an unconditional advance could strand a channel).Robustness
tokio::time::intervalscansload_allfor above-threshold channels, so a dropped advisory hint (bounded-channeltry_sendFull) can't stall threshold redemption.Mutex<Option<JoinHandle>>,abort()+awaited at the top ofclose_open_channels_on_shutdownso an in-flightwithdrawcan't race a shutdowncloseChannel; aDropimpl is the safety net for a non-graceful drop.Observability
decdn_redeem_hints_dropped_total,decdn_redemption_failures_total,decdn_watcher_persist_failures_total.VoucherRejectReason::Expired(appended; variant order is frozen per ADR 005) — the expiry serve-gate now sends an actionable in-band reason instead of an opaqueanyhow::bail!stream drop.Type hygiene
ChannelState's replay-criticallast_*fields are now private behind ahydrate()constructor + getters, so the incentive: no replay-protection window enforced on incoming voucher nonces, allowing a client to resubmit a previously accepted voucher after a node restart and receive a second byte-delivery for the same payment #527 "advance only viaapply_voucher" invariant is compiler-enforced.last_signatureisOption<[u8; 65]>(empty-or-exactly-65-bytes unrepresentable-when-wrong), converted at the codec boundary so the on-disk format is unchanged.TrailerV2type (byte-identical on-disk layout, kept as a trailing segment for v1-record compatibility).Verification
cargo nextest run --workspace— 1323 passed.cargo clippy --workspace --all-targets,cargo fmt --check,cargo doc,cargo deny— clean (all pre-commit hooks pass).TrailerV2byte-identity; wrong-length signature →Corrupt;resolve_backfill_start/backfill_windowswindow math;advance_checkpointhold + monotonicity; an expiry-gate loopback test assertingVoucherRejected { Expired }; updated frozen-order +public_apisnapshot tests.🤖 Generated with Claude Code