Skip to content

feat(node): buyer-side unilateral close→settle for unreachable providers (#988, #989) - #1004

Merged
thiras merged 3 commits into
mainfrom
feat/buyer-unilateral-close-988
Jun 26, 2026
Merged

thiras merged 3 commits into
mainfrom
feat/buyer-unilateral-close-988

Conversation

@thiras

@thiras thiras commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

What & why

Closes #988, closes #989.

The #972 buyer-channel reconcile sweep cooperatively closes idle node→node buyer channels — but only when the provider answers. When a provider is unreachable (deregistered / offline) its channel's deposit stays locked until the on-chain expiry-reclaim (default 90 days). This adds the buyer-side unilateral path the cooperative_close module already anticipated ("the caller falls back to the ordinary closeChannel → dispute-window → settleChannel path"): the buyer holds its own voucher, so it closeChannels the idle channel at its own persisted watermark and settles after the 48h dispute window — reclaiming the deposit in ~2 days instead of ~90.

This is a capital-efficiency optimization (labelled low); the expiry-reclaim sweep remains the correctness safety net.

How

  • Reuse the seller settle machinery via a shared helper (per the issue's "mirror the seller-side close→settle"). A SettleParty enum is threaded through settle_pass/try_settle/drop_pending_if_finalized/revert-resolution in payment_settlement.rs, replacing direct metrics.settlement_finalize_*() calls with party.finalize_*(metrics). Seller behaviour is byte-for-byte preserved (its existing unit tests pass unchanged with SettleParty::Seller).
  • Isolated buyer pending-settle set. A separate redb table buyer_pending_settle_v1 (BuyerPendingSettleStoreHandle) so the buyer and seller settle sweeps never finalize — or mis-attribute the metrics of — each other's closes. The seller/buyer record/load/forget bodies share table-parameterized helpers (same fsync durability + absent-table tolerance).
  • Conservative trigger (reconcile_one): escalate to a unilateral close only on genuine unreachability — provider deregistered (node_id_for → None) or K consecutive timeout-shaped dial/waiver failures. Declined/Reverted (provider reachable) are left to the expiry safety net. The escalation decision is a pure, unit-tested helper (record_close_failure).
  • node: cooperative-close unilateral pre-expiry settle path for unreachable providers has no metric distinguishing timeout-shaped unreachability from RPC failure during the waiver-request phase #989 metric split: buyer_unilateral_close_unreachable (timeout-shaped unreachability — the escalation reason) vs buyer_unilateral_close_rpc_failure (on-chain submission fault), plus buyer_unilateral_close_ok / buyer_settle_ok / buyer_settle_deferred.

Tests

  • Pure unit tests: escalation policy (close_failures_escalate_only_at_threshold, reset-after-response, per-channel) and SettleParty routing (settle_party_routes_finalize_signals_to_the_right_family).
  • Integration: buyer_and_seller_pending_settle_sets_are_isolated (separate tables, survives reopen).
  • Regression: the seller settle finalize unit tests pass unchanged. Full suite: 673 node + 185 incentive tests green; clippy/fmt/cargo-doc/deny clean.

Follow-up (not in this PR)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added buyer-side unilateral-close escalation with dedicated pending-settle tracking isolated from seller settlement.
    • Extended settlement observability with buyer-specific metrics for unilateral-close and follow-up settle outcomes.
  • Bug Fixes
    • Prevented cross-finalization between buyer and seller settlement sweeps.
    • Ensured unilateral-close pending obligations continue draining via the always-running reclaim flow.
    • Improved cooperative-close handling when providers can’t be resolved, escalating to unilateral close.
  • Tests
    • Added/updated coverage for escalation threshold, tally reset, and buyer/seller pending-settle isolation with restart durability.

…ers (#988, #989)

The #972 buyer-channel reconcile sweep cooperatively closes idle node→node
buyer channels, but only when the provider answers; an unreachable provider's
deposit stays locked until the 90-day on-chain expiry. Add a buyer-side
unilateral path: when a provider is deregistered (`node_id_for` → `None`) or
fails K consecutive dial/waiver attempts, `closeChannel` the idle channel at the
buyer's own persisted watermark and settle after the dispute window — reclaiming
the deposit in ~2 days instead of ~90. The expiry-reclaim sweep stays the
correctness safety net; this is a capital-efficiency optimization.

- Reuse the seller settle machinery via a shared helper: thread a `SettleParty`
  enum through `settle_pass`/`try_settle`/revert-resolution so the buyer drives
  the same `settleChannel` state machine over a SEPARATE pending-settle table
  (`buyer_pending_settle_v1`), keeping seller/buyer settle sweeps and their
  metric families from finalizing or mis-attributing each other's closes.
- Conservative trigger: escalate only on genuine unreachability (deregistered,
  or K consecutive timeout-shaped failures); `Declined`/`Reverted` (provider
  reachable) are left to the expiry safety net.
- #989: buyer close/settle counters split timeout-shaped unreachability
  (`buyer_unilateral_close_unreachable`) from on-chain submission failure
  (`buyer_unilateral_close_rpc_failure`).

Tests: pure escalation-policy + SettleParty-routing unit tests, a buyer/seller
pending-set isolation integration test, and the seller settle regression.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings June 26, 2026 20:27
@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 532de548-9322-417e-9577-aa363e212b3e

📥 Commits

Reviewing files that changed from the base of the PR and between 6752464 and db6bb55.

📒 Files selected for processing (1)
  • crates/node/src/buyer_channel.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/node/src/buyer_channel.rs

Walkthrough

Buyer settlement now uses a separate pending-settle table and store handle, settlement metrics route by seller or buyer party, and buyer reconcile now escalates repeated close failures or missing providers to unilateral closes that persist pending settlement work.

Changes

Buyer pending-settle storage

Layer / File(s) Summary
Buyer pending-settle tables
crates/node/src/channel_store.rs, crates/node/tests/channel_state_store.rs
A buyer pending-settle table and buyer-facing store handle are added, shared pending-settle helpers are parameterized by table, and isolation is verified across restart.
Idle-reconcile wiring
crates/node/src/runtime/mod.rs, crates/node/src/buyer_channel.rs, crates/node/tests/anvil_settlement_e2e.rs
Buyer bootstrap receives a dedicated pending-settle store, reclaim work drains buyer settlement entries through settle_pass, and runtime and e2e bootstraps pass the new store.

Settlement metrics routing

Layer / File(s) Summary
Settlement metrics routing
crates/node/src/metrics.rs, crates/node/src/payment_settlement.rs
Buyer unilateral-close and settle counters are added, and settlement outcome recording is routed through SettleParty for seller and buyer paths.

Buyer close escalation

Layer / File(s) Summary
Buyer close escalation
crates/node/src/buyer_channel.rs
Idle reconciliation tracks consecutive cooperative-close failures, escalates repeated failures or missing providers to unilateral close, clears tallies on terminal responses, and records pending settlement after a landed unilateral close.

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main buyer-side unilateral close-to-settle flow for unreachable providers.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/buyer-unilateral-close-988

Comment @coderabbitai help to get the list of available commands.

@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 implements a unilateral close escalation mechanism for buyer channels when a provider is unreachable or repeatedly fails cooperative close attempts. It introduces a separate buyer pending-settle database table to isolate buyer and seller settlement sweeps, and adds comprehensive metrics to track these operations. The review feedback correctly identifies a critical issue where a reverting unilateral close transaction could cause an infinite, gas-burning retry loop if the channel is already closed or closing on-chain. Reconciling the local state by querying the on-chain channel status upon failure is highly recommended to prevent unnecessary gas costs.

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/buyer_channel.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 a buyer-side unilateral closeChannel → settleChannel fallback for idle buyer channels when the provider is unreachable, improving capital efficiency by reclaiming deposits after the dispute window rather than waiting for on-chain expiry. This extends the existing seller settlement machinery to support both parties while keeping buyer/seller pending-settle state and metrics isolated.

Changes:

  • Generalize settlement-finalization flow with a SettleParty so the same settle_pass/try_settle logic can drive either seller or buyer metrics.
  • Introduce an isolated buyer pending-settle redb table (buyer_pending_settle_v1) and wiring for the buyer service to persist and sweep it.
  • Add reconcile escalation logic (thresholded timeout-shaped failures / deregistration) to trigger unilateral closes, plus new buyer close/settle metrics and tests.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
crates/node/src/buyer_channel.rs Implements unreachable-provider escalation to unilateral close, records buyer pending-settle entries, and runs a buyer settle pass.
crates/node/src/channel_store.rs Adds a separate redb table + store handle for buyer pending-settle entries; factors shared table helpers.
crates/node/src/metrics.rs Adds buyer unilateral close + settle counters and introduces SettleParty to route settlement outcomes.
crates/node/src/payment_settlement.rs Threads SettleParty through settle finalization helpers so buyer and seller can share the same state machine.
crates/node/src/runtime/mod.rs Wires a buyer pending-settle store into BuyerChannelService::bootstrap.
crates/node/tests/channel_state_store.rs Adds an integration test asserting buyer/seller pending-settle table isolation + durability across reopen.
crates/node/tests/anvil_settlement_e2e.rs Updates bootstrap call sites to pass a pending-settle store implementation.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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

github-actions Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 83.14% (was 83.44%, ▼ 0.29%) — 41681/50131 lines

File Coverage Lines Δ
crates/node/src/buyer_channel.rs 30.68% 331/1079 ▼ 2.90%
crates/node/src/channel_store.rs 87.71% 1477/1684 ▲ +0.25%
crates/node/src/metrics.rs 84.70% 991/1170 ▲ +1.90%
crates/node/src/payment_settlement.rs 50.36% 898/1783 ▼ 0.03%
crates/node/src/runtime/mod.rs 49.47% 927/1874 ▼ 0.13%
History
Commit Total Δ vs base
2b83071 83.22% ▼ 0.22%
6752464 83.17% ▼ 0.27%
db6bb55 (HEAD) 83.14% ▼ 0.29%

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
crates/node/tests/anvil_settlement_e2e.rs (1)

834-847: 📐 Maintainability & Code Quality | 🔵 Trivial

Add an anvil case for the buyer idle-reconcile path. These BuyerChannelService::bootstrap calls keep reconcile = None, so this suite still doesn’t exercise the buyer unilateral close → dispute-window → settle_pass flow on-chain. Current coverage stays at bootstrap/open/reclaim plus unit/metric checks; a separate scenario with BuyerReconcileConfig enabled would cover the real close→settle path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/node/tests/anvil_settlement_e2e.rs` around lines 834 - 847, The buyer
e2e bootstrap currently leaves idle-reconcile disabled, so the unilateral close
through dispute-window to settle_pass flow is not covered. Add a dedicated anvil
test scenario around BuyerChannelService::bootstrap that passes a
BuyerReconcileConfig instead of None, then drive the buyer close and confirm the
on-chain settle path completes. Use the existing BuyerChannelService,
BuyerReconcileConfig, and settle_pass-related test helpers to keep the new case
aligned with the current suite.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/node/src/buyer_channel.rs`:
- Around line 878-889: The buyer settle sweep is currently only reached through
reconcile_loop, so pending buyer settlements can be left uncleared when
reconcile is disabled or never starts. Move the SettleParty::Buyer call to
settle_pass into an always-on path that runs regardless of reconcile
configuration, likely alongside the existing reclaim_loop/periodic maintenance
in buyer_channel.rs, and keep the settlement logic tied to the existing
pending_store/contract/metrics flow.

---

Nitpick comments:
In `@crates/node/tests/anvil_settlement_e2e.rs`:
- Around line 834-847: The buyer e2e bootstrap currently leaves idle-reconcile
disabled, so the unilateral close through dispute-window to settle_pass flow is
not covered. Add a dedicated anvil test scenario around
BuyerChannelService::bootstrap that passes a BuyerReconcileConfig instead of
None, then drive the buyer close and confirm the on-chain settle path completes.
Use the existing BuyerChannelService, BuyerReconcileConfig, and
settle_pass-related test helpers to keep the new case aligned with the current
suite.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b2f4b339-4b9a-426a-bdc3-b06b027c05c7

📥 Commits

Reviewing files that changed from the base of the PR and between e683e98 and 2b83071.

📒 Files selected for processing (7)
  • crates/node/src/buyer_channel.rs
  • crates/node/src/channel_store.rs
  • crates/node/src/metrics.rs
  • crates/node/src/payment_settlement.rs
  • crates/node/src/runtime/mod.rs
  • crates/node/tests/anvil_settlement_e2e.rs
  • crates/node/tests/channel_state_store.rs

Comment thread crates/node/src/buyer_channel.rs Resolved
- Prevent an every-sweep revert loop: when a unilateral closeChannel fails,
  reconcile against on-chain status (`reconcile_failed_close`). A channel that
  is already Closing/Closed (provider closed it, or our close landed but the
  receipt was missed) is retired locally — and a Closing one records its settle
  obligation — instead of re-submitting a guaranteed-revert close until expiry.
  Only a still-Open channel (genuine transient failure) is retried. (gemini)
- Run the buyer settle pass in the always-spawned reclaim_loop, not the optional
  idle-reconcile loop, so buyer_pending_settle_v1 entries keep draining even if
  node→node pull-through is later disabled. (copilot/coderabbit)
- Stop counting a local voucher-signing fault as buyer_unilateral_close_rpc_failure
  (it is neither #989 bucket; log-only). (copilot)
- Escalate the post-close obligation-loss logs (getChannel/record_pending failure)
  to error! — operator action required, no self-heal — matching the seller path.
  (copilot)
- Correct the shared pending-record durability comment: a lost post-close entry
  strands until settleChannel, not "until expiry". (copilot)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras

thiras commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all actionable inline comments in 6752464 (revert-loop reconciliation, settle-pass moved to the always-on reclaim_loop, signing-fault metric reclassification, error!-level obligation-loss logs, durability comment). Replies are on each thread.

On the anvil buyer-reconcile e2e nitpick (CodeRabbit / Copilot): deferring, as noted in the PR description. The reconcile→unilateral-close path runs on a background timer behind a 24-sweep idle gate, so driving it on-chain needs a public test hook plus anvil time-travel for the dispute window — it cannot reuse the existing sweep_expired_once hook. The shared closeChannel→settleChannel primitive is already anvil-covered via the seller leg, and the new buyer decision logic (escalation policy, SettleParty routing, pending-set isolation) is covered by unit + integration tests. Tracking it as a follow-up rather than expanding this PR’s surface.

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/node/src/buyer_channel.rs`:
- Around line 1242-1258: The pending-settle handoff in
record_pending_after_unilateral_close is not propagated back to the caller, so
the cleanup path in reconcile still removes obs, clears close_failures, and
calls forget_after_close even when getChannel or record_pending fails. Make
record_pending_after_unilateral_close return a success/failure result and have
the reconcile logic in buyer_channel.rs only retire the local channel state when
that handoff succeeds; if it fails, keep the record and tallies so settle_pass
can retry later. Also update the related close-failure handling paths that share
this cleanup behavior to preserve recovery on transient store/read errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 910d7821-e6a5-4361-9195-53bc950f9a49

📥 Commits

Reviewing files that changed from the base of the PR and between 2b83071 and 6752464.

📒 Files selected for processing (2)
  • crates/node/src/buyer_channel.rs
  • crates/node/src/channel_store.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/node/src/channel_store.rs

Comment thread crates/node/src/buyer_channel.rs Resolved
…#988)

CodeRabbit review: `record_pending_after_unilateral_close` logged failures but
returned nothing, so callers retired the local buyer record (forget + clear
obs/close_failures) even when the pending-settle write failed. Since the buyer
settle sweep only drains durable `PendingSettleStore` entries, a transient
getChannel/store fault dropped the only automatic-recovery handle, leaving
manual `settleChannel` as the sole path.

Make the handoff status-bearing: `record_pending_after_unilateral_close` now
returns whether the obligation was durably recorded, and a new `record_then_retire`
helper retires the local state only on success. On failure the record is KEPT,
so the next reconcile sweep retries (its `closeChannel` reverts against the
now-`Closing` channel and routes through `reconcile_failed_close`, which
re-attempts the handoff) — automatic recovery the seller gets only via its #839
restart backfill, which is provider-only. `record_then_retire` is shared by the
landed-close and the `Closing`-recovery paths; the record call moved out of
`close_unilateral` into the caller.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras
thiras merged commit 7fd14fa into main Jun 26, 2026
40 of 43 checks passed
@thiras
thiras deleted the feat/buyer-unilateral-close-988 branch June 26, 2026 21:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants