Skip to content

feat(node): configurable per-channel auto-settlement trigger (#742) - #789

Merged
thiras merged 5 commits into
mainfrom
feat/742-auto-settlement-trigger
Jun 3, 2026
Merged

thiras merged 5 commits into
mainfrom
feat/742-auto-settlement-trigger

Conversation

@thiras

@thiras thiras commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

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-chain claimedNonce, 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 closeChannel through the existing seller settlement path (send_close + durable PendingSettle entry), 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 the withdraw path — once a channel is large enough to auto-settle, closing it supersedes a withdraw that 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 configured 0 is rejected at config resolution (it would close on the first/zero voucher). Adds decdn_settlement_auto_triggered_total (secured closes) and decdn_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 (mirrors redeem_threshold_micro_usdc).
  • crates/node/src/payment_settlement.rs — AutoSettleConfig, pure should_auto_settle, unredeemed_nonce_span, try_auto_settle_close (retire + failure-instrument), threaded through bootstrap/redeemer_loop/redeem_one/redeem_sweep/try_redeem.
  • crates/node/src/metrics.rs — settlement_auto_triggered + settlement_auto_failures counters.
  • crates/node/src/runtime/mod.rs — wires resolved config into bootstrap.

Testing

  • Unit tests: config-validation (zero-reject ×2, disabled-by-default, positive-accept), should_auto_settle decision boundaries (disabled, value-only, nonce-span-only, both-OR), unredeemed_nonce_span derivation (incl. saturating-to-zero stale nonce), and a metrics test for both auto-settle counters.
  • anvil-e2e CHANNEL 3: a channel brought up with a non-default AutoSettleConfig goes Closing, records a PendingSettle entry, supersedes withdraw (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:

  • IMPORTANT — unredeemable-bytes leak (resolved). try_auto_settle_close closed the channel on-chain (→ Closing) but never retired it, so between auto-close and the eventual ChannelSettled the node kept accepting vouchers/serving bytes it could no longer redeem (withdraw/close revert on non-Open; last_amount frozen at close; the ChannelCloseInitiated watcher arm is observe-only, Implement cdn/watchtower/v1 channel dispute monitoring protocol #324). Fixed by threading the handler Arc into the redeemer and calling forget_channel after a landed close (mirroring the expiry path); the success metric/log fire only after the forget.
  • IMPORTANT — "voucher count" trigger was a nonce span (resolved). last_nonce − claimedNonce is a nonce span, an upper bound on the count (nonces may skip values, ADR 003), so the trigger fired earlier than configured. Renamed the field settlement_auto_by_voucher_count → settlement_auto_by_voucher_nonce_span (and AutoSettleConfig::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.
  • HIGH — silent auto-settle failures (resolved). A failed close (send_close → None, or the awaited receipt reverting/erroring) returned false with only a warn! and no metric, so an operator couldn't distinguish "threshold never crossed" from "crossed and every close failing." Added decdn_settlement_auto_failures_total, incremented on both failure paths, kept distinct from the success counter for a fire-vs-secured ratio.
  • Coverage (resolved). The auto-settle close branch was exercised by no test (AutoSettleConfig::default() at both e2e bring-up sites). Added the anvil-e2e CHANNEL 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

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]>
Copilot AI review requested due to automatic review settings June 2, 2026 19:22

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

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

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 validates 0 as invalid.
  • Threads an AutoSettleConfig through the node settlement/redeemer path, adding a pure should_auto_settle decision and a close-before-withdraw flow in try_redeem.
  • Adds a decdn_settlement_auto_triggered_total counter 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.

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.55% (was 86.60%, ▼ 0.05%) — 27009/31207 lines

File Coverage Lines Δ
crates/common/src/config/mod.rs 96.29% 4780/4964 ▲ +0.07%
crates/common/src/config/resolved.rs 100.00% 13/13 ● 0.00%
crates/node/src/metrics.rs 86.24% 520/603 ▲ +0.57%
crates/node/src/payment_settlement.rs 46.53% 691/1485 ▲ +8.30%
crates/node/src/runtime/mod.rs 44.88% 517/1152 ▼ 0.18%
crates/node/src/runtime/reload.rs 95.51% 1404/1470 ▲ +0.01%
History
Commit Total Δ vs base
579e98f 86.47% ▼ 0.11%
4d47f55 86.46% ▼ 0.12%
3ad4601 86.50% ▼ 0.07%
85fa28d 86.52% ▼ 0.05%
f4a71d9 (HEAD) 86.55% ▼ 0.05%

thiras and others added 2 commits June 3, 2026 02:00
…+ 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 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 — 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)");
true

When 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)");
true

MINOR — 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-None never 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_rpc upper-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 of redeem_threshold's > 0, which has a non-None default).
  • No locks held across .await in 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]>
@thiras

thiras commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

Both findings addressed in 85fa28d.

IMPORTANT (failed forget_channel counted as a secured success). Fixed in 85fa28d: forget-failure now routes to settlement_auto_failure and returns true without the success counter / retired log; success is gated on a successful forget. The post-close metric/log decision is extracted into record_auto_settle_close_outcome, with a unit test pinning the regression (forget Err → triggered does NOT increment, failures increments by one, return value is true so the caller still skips the withdraw against the now-Closing channel). The forget-success path is asserted alongside it.

MINOR (failed-close → withdraw fallthrough). Kept the best-effort withdraw fallthrough by decision (channel still Open; close retries next tick); added a comment making the intent explicit in 85fa28d — no behavior change.

Verified: cargo build, cargo clippy --workspace --all-targets -- -D warnings, cargo nextest run -p decdn-node -p decdn-common (708 pass), cargo fmt -- --check all green.

# Conflicts:
#	crates/node/src/metrics.rs
@thiras
thiras merged commit e13b6b8 into main Jun 3, 2026
19 checks passed
@thiras
thiras deleted the feat/742-auto-settlement-trigger branch June 3, 2026 13:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants