Repository navigation
feat(node): configurable per-channel auto-settlement trigger (#742) - #789
Conversation
Nodes accumulated vouchers indefinitely until an operator manually triggered settlement, leaving a large unsubmitted voucher balance at risk if a client went dark before the dispute window. Add two optional, operator/governance-set auto-settlement thresholds to `[blockchain]` config: - `settlement_auto_threshold_micro_usdc` — close a channel once its outstanding (un-redeemed) USDC value crosses the threshold. - `settlement_auto_by_voucher_count` — close once the un-redeemed voucher count (off-chain nonce minus on-chain `claimedNonce`) crosses it. Either trigger fires a proactive `closeChannel` via the existing seller settlement path (`send_close` + `PendingSettle`), starting the dispute window so the balance is secured on-chain; the existing settle sweep finalizes the remainder. Aligned with the ADR 003 payment-channel lifecycle. The check runs in the redeemer's per-channel logic, ahead of the `withdraw` path, and reuses the close/settle infrastructure (no new module). Both default to disabled (`None`) so behavior is unchanged unless an operator opts in; a configured `0` is rejected at resolution. Adds a `settlement_auto_triggered_total` metric. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces operator-configured auto-settlement triggers (settlement_auto_threshold_micro_usdc and settlement_auto_by_voucher_count) to proactively close payment channels and secure un-redeemed balances before clients go dark. The feedback recommends expanding the local withdrawn_cache to store both the withdrawn amount and the claimed nonce. This allows the cheap pre-check in try_redeem to verify if a channel is below all enabled thresholds, avoiding redundant getChannel RPC calls when auto-settlement is enabled.
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
Adds optional, operator-configurable per-channel auto-settlement triggers so seller nodes proactively closeChannel when outstanding value (µUSDC) or unredeemed voucher count crosses a threshold—starting the dispute window and reducing exposure if a client disappears—while reusing the existing close/settle infrastructure.
Changes:
- Extends
[blockchain]config schema + resolved config with two optional auto-settlement thresholds and validates0as invalid. - Threads an
AutoSettleConfigthrough the node settlement/redeemer path, adding a pureshould_auto_settledecision and a close-before-withdraw flow intry_redeem. - Adds a
decdn_settlement_auto_triggered_totalcounter metric and corresponding bump on successful auto-close.
Reviewed changes
Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/payment_settlement.rs | Implements auto-settlement config + decision logic; triggers closeChannel ahead of withdraw when thresholds are met; adds unit tests. |
| crates/common/src/config/types.rs | Adds new optional blockchain config fields for auto-settlement thresholds. |
| crates/common/src/config/resolved.rs | Persists resolved auto-settlement fields in ResolvedBlockchain. |
| crates/common/src/config/mod.rs | Validates and resolves new config fields; adds config-resolution unit tests. |
| crates/node/src/runtime/mod.rs | Wires resolved auto-settlement config into PaymentChannelService::bootstrap. |
| crates/node/src/metrics.rs | Adds settlement_auto_triggered counter and helper method. |
| crates/node/src/runtime/reload.rs | Updates test config scaffolding with new resolved fields. |
| crates/node/tests/anvil_settlement_e2e.rs | Updates PaymentChannelService::bootstrap callsites to pass default auto-settle config. |
| crates/node/tests/sighup_signal.rs | Updates resolved config seed with new blockchain fields. |
| crates/cli/tests/config_validate.rs | Updates resolved config sample construction with new blockchain fields. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 86.55% (was 86.60%, ▼ 0.05%) — 27009/31207 lines
History
|
…+ nonce-span semantics (#789 review) Multi-agent review of the #742 auto-settlement feature surfaced two IMPORTANT correctness findings, one HIGH observability gap, and test coverage holes. Fixes: 1. (IMPORTANT) Auto-settle close now retires the channel. `try_auto_settle_close` closed on-chain (→ Closing) but left the channel in the live serving map, so between close and the eventual ChannelSettled the node kept accepting vouchers it could no longer redeem (withdraw/close revert on non-Open; last_amount frozen). Now mirrors the expiry path: thread the handler Arc into the redeemer and `forget_channel` after a landed close; the success metric/log fire only after the forget. 2. (IMPORTANT) The "voucher count" trigger compared a NONCE SPAN, not a count. `last_nonce − claimedNonce` is an upper bound (nonces may skip values, ADR 003 §Voucher Nonce Convention), so the trigger fired earlier than configured. Renamed the config field `settlement_auto_by_voucher_count` → `settlement_auto_by_voucher_nonce_span`, the AutoSettleConfig field `voucher_count_threshold` → `voucher_nonce_span_threshold`, and reworded all doc/in-code comments to nonce-span semantics. (No new per-voucher counting state — redocument+rename only.) 3. (HIGH) Auto-settle close FAILURES were silent. Added a `settlement_auto_failures` counter (decdn_settlement_auto_failures_total), incremented on both failure paths (send returned None; awaited future false), kept distinct from the success counter so a fire-vs-secured ratio is computable. 4. Tests: anvil-e2e CHANNEL 3 brought up with a non-default AutoSettleConfig — asserts Closing + PendingSettle recorded + channel forgotten (fix #1) + supersedes-withdraw (withdrawnAmount == 0) + the success/failure metrics; a metrics unit test for both counters; and a unit test for the nonce-span derivation incl. the saturating-to-zero stale-nonce case. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
#789 review) Cache `(withdrawnAmount, claimedNonce)` per channel instead of just `withdrawnAmount`, and fold both auto-settle thresholds into the pure `can_skip_redeem_rpc` pre-check. Previously any auto-settle opt-in disabled the cheap pre-check entirely, forcing a `getChannel` RPC on every hinted channel each tick — a per-channel RPC regression for value-only nodes (Copilot) and an incomplete cache (gemini). Both cached values are lower bounds on the true on-chain ones (only this node's withdraw/closeChannel advance them), so the derived unredeemed value and nonce span are upper bounds: an idle channel now short-circuits the RPC regardless of which triggers are configured. A successful withdraw seeds the cache to `(last_amount, last_nonce)` since `withdraw` advances both watermarks. Extracted the predicate into a pure, unit-tested helper; removed the now-dead `is_enabled`. 8 new tests cover the value-only-can-still-skip and nonce-span-blocks-until-seeded boundaries. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alpergundogdu
left a comment
There was a problem hiding this comment.
Review — configurable per-channel auto-settlement trigger
Careful, well-tested PR. The decision logic is correct, OR semantics and >= boundaries match the unit tests, config validation rejects 0/defaults to None correctly, and the e2e CHANNEL 3 scenario exercises the full close → PendingSettle → forget → supersedes-withdraw → metrics path. One finding I'd consider fixing before merge, plus a smaller behavioral note.
IMPORTANT — a failed forget_channel still counts as a secured success → silent unredeemable-bytes leak
In try_auto_settle_close (crates/node/src/payment_settlement.rs), the success arm is:
if let Err(err) = handler.forget_channel(st.channel_id).await {
warn!(%err, channel_id = %st.channel_id, "auto-settle: forget after close failed");
}
metrics.settlement_auto_triggered();
info!(/* ... */ "auto-settlement trigger fired; closed + retired channel to secure balance (#742)");
trueWhen forget_channel returns Err, the channel is not removed from the handler/store, so the node keeps serving a Closing channel it can no longer redeem against — exactly the unredeemable-bytes leak this feature exists to prevent (the PR description's item #5). But settlement_auto_triggered still increments and the log claims "closed + retired", making the leak invisible. Your own comment says to "count the success / log only after the forget so the metric reflects a fully-retired close" — the current code increments regardless of the forget result, so the comment and behavior disagree.
Note the cited mirror, try_close_for_expiry, degrades more gracefully: it emits the "retired it" info! only in the forget-succeeded branch and has no success counter to corrupt. Suggest gating the success signal on a successful forget and routing the failure to the failure counter so a stranded-but-closed channel is observable:
if let Err(err) = handler.forget_channel(st.channel_id).await {
warn!(%err, channel_id = %st.channel_id, "auto-settle: forget after close failed");
// Close landed but the channel was NOT retired — we keep serving an
// unredeemable `Closing` channel. Surface it rather than claim success.
metrics.settlement_auto_failure();
return true; // still skip withdraw: the channel is Closing
}
metrics.settlement_auto_triggered();
info!(/* ... */ "auto-settlement trigger fired; closed + retired channel (#742)");
trueMINOR — try_redeem falls through to withdraw after a failed close, against the "supersedes" rationale
When try_auto_settle_close returns false because the close failed (send_close → None or a reverted receipt), control falls through to the withdraw path. The doc frames auto-settle as superseding withdraw because closing caps total at-risk exposure. Falling through to withdraw is arguably a reasonable best-effort partial recovery (the channel is still Open), but it isn't what the comment implies and there's no log at the try_redeem level distinguishing "close superseded withdraw" from "close failed, fell back to withdraw". Either add a one-line comment making the fallback intent explicit, or return Ok(()) if a failed close should not also attempt withdraw in the same tick. Flagging for a deliberate decision.
Verified correct (no action)
should_auto_settle: disabled-Nonenever fires; value-only / span-only / both-OR all correct.unredeemed_nonce_span:last_nonce.saturating_sub(claimed).try_into().unwrap_or(u64::MAX)— anti-panic clean, saturating + clamp tested. The rename to "nonce span" (upper bound, per ADR 003 skippable nonces) and the doc rewording are correct.can_skip_redeem_rpcupper-bound reasoning is sound; each enabled threshold tightens the predicate.- Config validation
!= Some(0)is the right predicate for genuinely-optional fields (intentionally not an exact mirror ofredeem_threshold's> 0, which has a non-Nonedefault). - No locks held across
.awaitin the new code.
The IMPORTANT finding is the one I'd want addressed — it directly undercuts the feature's stated guarantee.
Generated by Claude Code
…withdraw fallthrough (#789, Alper review) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Both findings addressed in 85fa28d. IMPORTANT (failed MINOR (failed-close → withdraw fallthrough). Kept the best-effort withdraw fallthrough by decision (channel still Verified: |
# Conflicts: # crates/node/src/metrics.rs
Closes #742
Summary
Nodes accumulated vouchers indefinitely until an operator manually triggered settlement, leaving a large unsubmitted voucher balance at risk if a client went dark before the dispute window.
This adds two optional, operator/governance-set auto-settlement thresholds to the
[blockchain]config section:settlement_auto_threshold_micro_usdc— close a channel once its outstanding (un-redeemed) USDC value (µUSDC) crosses the threshold.settlement_auto_by_voucher_nonce_span— close once the un-redeemed nonce span crosses it (span = off-chain latest nonce minus on-chainclaimedNonce, an upper bound on the voucher count since nonces may skip values per ADR 003 §Voucher Nonce Convention).Either trigger (logical OR) fires a proactive
closeChannelthrough the existing seller settlement path (send_close+ durablePendingSettleentry), starting the dispute window so the balance is secured on-chain; the existing settle sweep finalizes the remainder after the window. This aligns with the ADR 003 payment-channel lifecycle (closeChannel→ dispute window →settleChannel).The check runs in the redeemer's per-channel logic (
try_redeem), ahead of thewithdrawpath — once a channel is large enough to auto-settle, closing it supersedes awithdrawthat would only reclaim the same delta while leaving future exposure open. On a landed close the channel is retired from the handler (forget_channel), mirroring the expiry-close path, so the node stops serving a channel it can no longer redeem against. No new module; reuses the close/settle infrastructure.Both thresholds default to disabled (
None), so behavior is unchanged unless an operator opts in. A configured0is rejected at config resolution (it would close on the first/zero voucher). Addsdecdn_settlement_auto_triggered_total(secured closes) anddecdn_settlement_auto_failures_total(closes that fired but did not land) metrics.Changes
crates/common/src/config/{types,resolved,mod}.rs— schema fields, resolved struct, validation (mirrorsredeem_threshold_micro_usdc).crates/node/src/payment_settlement.rs—AutoSettleConfig, pureshould_auto_settle,unredeemed_nonce_span,try_auto_settle_close(retire + failure-instrument), threaded throughbootstrap/redeemer_loop/redeem_one/redeem_sweep/try_redeem.crates/node/src/metrics.rs—settlement_auto_triggered+settlement_auto_failurescounters.crates/node/src/runtime/mod.rs— wires resolved config intobootstrap.Testing
should_auto_settledecision boundaries (disabled, value-only, nonce-span-only, both-OR),unredeemed_nonce_spanderivation (incl. saturating-to-zero stale nonce), and a metrics test for both auto-settle counters.anvil-e2eCHANNEL 3: a channel brought up with a non-defaultAutoSettleConfiggoesClosing, records aPendingSettleentry, supersedeswithdraw(withdrawnAmount == 0), is forgotten from the store, and the success/failure metrics read 1/0. Verified live against anvil + forge.cargo build,cargo clippy --workspace --all-targets,cargo fmt --check,cargo nextest run -p decdn-node -p decdn-common(698 tests) all green.Review
A follow-up multi-agent code review of this PR caught two IMPORTANT correctness findings, one HIGH observability gap, and test-coverage holes. All were fixed on this branch before merge:
try_auto_settle_closeclosed the channel on-chain (→Closing) but never retired it, so between auto-close and the eventualChannelSettledthe node kept accepting vouchers/serving bytes it could no longer redeem (withdraw/closerevert on non-Open;last_amountfrozen at close; theChannelCloseInitiatedwatcher arm is observe-only, Implement cdn/watchtower/v1 channel dispute monitoring protocol #324). Fixed by threading thehandlerArcinto the redeemer and callingforget_channelafter a landed close (mirroring the expiry path); the success metric/log fire only after the forget.last_nonce − claimedNonceis a nonce span, an upper bound on the count (nonces may skip values, ADR 003), so the trigger fired earlier than configured. Renamed the fieldsettlement_auto_by_voucher_count→settlement_auto_by_voucher_nonce_span(andAutoSettleConfig::voucher_count_threshold→voucher_nonce_span_threshold) and reworded all docs/comments to nonce-span semantics. Redocument+rename only — no new per-voucher counting state.send_close→None, or the awaited receipt reverting/erroring) returnedfalsewith only awarn!and no metric, so an operator couldn't distinguish "threshold never crossed" from "crossed and every close failing." Addeddecdn_settlement_auto_failures_total, incremented on both failure paths, kept distinct from the success counter for a fire-vs-secured ratio.AutoSettleConfig::default()at both e2e bring-up sites). Added theanvil-e2eCHANNEL 3 scenario (Closing + PendingSettle + forget + supersedes-withdraw + metrics), the nonce-span derivation unit test, and the metrics unit test described under Testing.🤖 Generated with Claude Code