Skip to content

feat(node): seller-settlement robustness follow-ups (#751) - #781

Merged
thiras merged 5 commits into
mainfrom
fix/751-seller-settlement-robustness
Jun 2, 2026
Merged

thiras merged 5 commits into
mainfrom
fix/751-seller-settlement-robustness

Conversation

@thiras

@thiras thiras commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

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 ChannelOpened backfill landed in #762; this closes the across-restart downtime gap. A new WatcherCheckpointStore persists the last-scanned block; on bootstrap the watcher resumes the backfill from checkpoint − 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 rejected WrongChannel forever. The gap is walked in bounded eth_getLogs windows. The checkpoint advances past a live ChannelOpened only 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

  • Independent redeemer self-tick — a low-frequency tokio::time::interval scans load_all for above-threshold channels, so a dropped advisory hint (bounded-channel try_send Full) can't stall threshold redemption.
  • Quiesce the redeemer before shutdown close — the redeemer handle is held in a Mutex<Option<JoinHandle>>, abort()+awaited at the top of close_open_channels_on_shutdown so an in-flight withdraw can't race a shutdown closeChannel; a Drop impl is the safety net for a non-graceful drop.

Observability

  • New counters: 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 opaque anyhow::bail! stream drop.

Type hygiene

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).
  • New tests: watcher-checkpoint round-trip/independence; TrailerV2 byte-identity; wrong-length signature → Corrupt; resolve_backfill_start / backfill_windows window math; advance_checkpoint hold + monotonicity; an expiry-gate loopback test asserting VoucherRejected { Expired }; updated frozen-order + public_api snapshot tests.

🤖 Generated with Claude Code

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]>
Copilot AI review requested due to automatic review settings June 2, 2026 14:09
@thiras thiras self-assigned this Jun 2, 2026

@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 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.

Comment thread crates/node/src/payment_settlement.rs Resolved
Comment thread crates/node/src/payment_settlement.rs Resolved
Comment thread crates/node/src/payment_settlement.rs Resolved
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

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 getLogs backfill so ChannelOpened events 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 withdraw vs closeChannel races.
  • 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.

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

github-actions Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 86.58% (was 86.95%, ▼ 0.37%) — 25863/29871 lines

File Coverage Lines Δ
crates/incentive/src/channel.rs 96.08% 368/383 ▲ +0.39%
crates/incentive/src/store.rs 92.49% 160/173 ▲ +0.32%
crates/node/src/channel_store.rs 89.28% 1141/1278 ▲ +1.08%
crates/node/src/handlers/client.rs 74.86% 402/537 ▲ +0.19%
crates/node/src/metrics.rs 83.53% 416/498 ▼ 1.54%
crates/node/src/payment_settlement.rs 21.29% 188/883 ▲ +5.87%
crates/node/src/runtime/mod.rs 46.39% 514/1108 ▼ 0.17%
crates/protocol/src/client.rs 99.50% 603/606 ● 0.00%
History
Commit Total Δ vs base
0e5bca0 86.42% ▼ 0.34%
5fe7754 86.40% ▼ 0.36%
3808e19 86.41% ▼ 0.36%
af3ef83 86.41% ▼ 0.36%
0247dda (HEAD) 86.58% ▼ 0.37%

thiras and others added 2 commits June 2, 2026 17:16
…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]>
@thiras

thiras commented Jun 2, 2026

Copy link
Copy Markdown
Contributor Author

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 channel

Two reviewers independently flagged that 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 — so the reactive checkpoint_hold was set too late. If the advance exceeded REORG_MARGIN_BLOCKS before a restart, N was skipped → vouchers rejected WrongChannel forever.

Fix: advance the 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 so a resubscribe re-covers it, and the held checkpoint makes a restart re-cover it too. Removed checkpoint advancement from the topped_up/settled/close arms.

Tests — headline #751 proof

Added an end-to-end downtime-backfill-across-restart phase to the anvil e2e: drop the service (node "down"), openChannel while nothing watches, re-bootstrap against the same store, and assert the channel is registered via the checkpoint-floored backfill. This exercises the real bootstrap → checkpoint read → floored backfill path that the unit tests only cover in pieces. (Two loop-level gaps — a direct redeem_sweep test and a quiesce_redeemer idempotency assertion — are left as follow-ups: the redeemer/quiesce paths are private and exercised indirectly by the e2e's redeem + drop(service) flows; a focused harness for the 5-min self-tick is disproportionate.)

Polish

  • Documented the deliberate pub deposit/expires_at encapsulation asymmetry and the hydrate positional-arg trust boundary (single, round-trip-tested caller; an init-struct is the move if a second caller appears) — type-design review.
  • Fixed a module-header run-on and noted the post-backfill checkpoint write never regresses — comment review.

Gates: cargo nextest run --workspace 1324 pass; anvil e2e (incl. the new phase) passes; clippy/fmt/doc/deny clean.

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]>
@thiras

thiras commented Jun 2, 2026

Copy link
Copy Markdown
Contributor Author

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 (3808e19) closes the cross-arm and cross-cycle stranding paths: the checkpoint now advances only from the opened arm on a successful register, a failed open holds the checkpoint + re-arms the backfill, and unwrap_or(checkpoint_hw) on an unconfirmed block can't skip it. No new swallow. One LOW liveness note (a failed live open recovers on the next resubscribe/restart, not mid-cycle — never a strand) is now documented in the module header.

Important: the new e2e test could pass spuriously — fixed. pr-test-analyzer (criticality 8) found that without a block mined between the downtime openChannel and the re-bootstrap, head == down_block, so the pre-existing #762 within-session backfill [head, F] already covered the channel — the test passed even if the #751 checkpoint floor were ignored. Fixed by mining a block (evm_mine) so [head, F] excludes the channel and only the checkpoint floor can recover it. Verified by mutation: forcing resolve_backfill_start to ignore the checkpoint now makes the phase FAIL with "#751 checkpoint backfill failed" (it passed before the fix). Also replaced the hardcoded nonce with a live clientChannelNonce read (added that getter to the binding) so the proof survives earlier-phase churn.

Gates: 1324 workspace tests + anvil e2e pass; clippy/fmt/doc/deny clean.

@thiras
thiras requested a review from alpergundogdu June 2, 2026 15:09

@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 — 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::Expired is correctly appended (last source-order variant). The snapshot only shows it mid-list because that snapshot is alphabetized. ✅
  • ADR 527 (last_* advance only via apply_voucher): Correctly compiler-enforced — last_* are now private with apply_voucher + hydrate as the only writers. expires_at/deposit stay pub (not replay-critical), as documented. ✅
  • On-disk codec: TrailerV2 is 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_start are 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_redeemer and Drop use unwrap_or_else(PoisonError::into_inner) on the std::sync::Mutex, and the guard is dropped before handle.await (never held across await). Drop aborts (safety net) and is idempotent with quiesce_redeemer via take(). ✅

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

  1. Stranded-channel recovery window (live-stream ChannelOpened persist 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 rejected WrongChannel until 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 while checkpoint_hold is set. Worth a tracking issue at minimum.
  2. advance_checkpoint cross-cycle invariant is load-bearing but implicit: Correctness of the hold relies on the opened log stream being strictly block-ordered (so an earlier successful open is always at a lower block than a later failed one, 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.
  3. Checkpoint fsync amplification: record_last_seen_block uses Durability::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_hint drop metric (crates/node/src/handlers/client.rs): Only TrySendError::Full is counted; Closed (redeemer gone during quiesce_redeemer at 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_redeemer race claim: abort() cancels the task but the already-broadcast withdraw tx can still mine after shutdown, concurrently with closeChannel — 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 actual eth_getLogs cap (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 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.

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)));

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread crates/node/src/payment_settlement.rs Outdated
let Some(block) = block else {
return;
};
// Never advance to or past a block with an unpersisted `ChannelOpened`.

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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)

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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]>
@thiras

thiras commented Jun 2, 2026

Copy link
Copy Markdown
Contributor Author

@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 unwrap_or(U256::ZERO), so the first post-boot sweep issues one getChannel per above-threshold channel — O(channels), not "cheap on a warm cache." The doc now states the cold-start fan-out explicitly (and that it recurs whenever fresh bytes push a redeemed channel back over threshold), notes subsequent ticks are warm, and flags revisiting the cadence / seeding the cache at bootstrap if a node tracks enough channels to make it costly. One refinement to your framing: it's the first sweep after boot (and re-crossings), not literally "every tick" — line 1190 warms the entry on the first getChannel, so steady state short-circuits.

LOW (redeem_hint Closed). Added a comment: Full is counted (a real dropped hint worth alarming on a sustained rate); Closed (redeemer aborted during shutdown quiesce_redeemer) is expected and deliberately uncounted — with a "don't fix this to count both" note for the next reader.

LOW (quiesce_redeemer race). Softened the field doc, close_open_channels_on_shutdown, and quiesce_redeemer docs from "cannot race one" / "no in-flight withdraw survives" to narrowing-not-eliminating: aborting stops the redeemer from issuing further withdraws, but a tx already broadcast before the abort can still mine concurrently with a closeChannel. The residual race is benign (expected revert; settlement unchanged).

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 eth_getLogs limit (and make it configurable) if a target RPC enforces a tighter/result-count cap.

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.

@thiras
thiras merged commit f528498 into main Jun 2, 2026
36 of 38 checks passed
@thiras
thiras deleted the fix/751-seller-settlement-robustness branch June 2, 2026 17:15
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.

Seller-settlement robustness follow-ups (metrics, redeemer tick, downtime backfill)

3 participants