Skip to content

feat(node): buyer-side PaymentChannel openChannel for cache-miss settlement (#744) - #753

Merged
thiras merged 11 commits into
mainfrom
feat/744-buyer-openchannel
Jun 1, 2026
Merged

thiras merged 11 commits into
mainfrom
feat/744-buyer-openchannel

Conversation

@thiras

@thiras thiras commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Closes #744.

Context

Split out from #327 (PR #743, seller settlement). Implements the buyer-side on-chain path from ADR 003 §node→node: when a node pulls content from an upstream provider on a cache miss it acts as the client — opens a PaymentChannel, signs cumulative vouchers (the voucher signer already existed in client_requester), and reclaims its deposit if the upstream abandons the channel.

Stack collapsed: the lower PRs (#743 seller settlement, #752 anvil e2e) have merged to main, and main is now merged into this branch (the seller PendingSettle settlement-sweep work is integrated; the anvil e2e harness carries both seller and buyer coverage). This PR now diffs against main directly.

Scope (channel-management layer only)

Wiring the cache engine's miss path to call open_or_reuse_channel needs provider-discovery (NodeId→eth-address, dialable target) which client_requester declares out of scope (ADR 001/022). So the service is bootstrapped (one-time approval + reclaim sweep) and exposes the API that future hook will call, but the hook that drives buys is not yet wired. Dispute monitor deferred (#324).

What's in this PR

  • incentive: sol! bindings for openChannel/topUp/reclaimExpired + minDeposit + ChannelExpiredReclaimed; a minimal ERC-20 binding (erc20.rs) for the one-time USDC approval; provider-keyed BuyerChannelState (with an advance() monotonic mutator), BuyerChannelStore trait (incl. forget_if_channel compare-and-delete) + MemoryBuyerChannelStore.
  • node: PersistentBuyerChannelStore as a second redb table (buyer_channel_state_v1) on the shared store handle (redb forbids two Database handles to one file), exposed via BuyerChannelStoreHandle; BuyerChannelService — one-time max approve at startup, lazy open + per-provider reuse (channelId + expiresAt decoded from the openChannel tx-receipt ChannelOpened event, atomic with the open), record_progress, top_up, and a background reclaim sweep that uses forget_if_channel to avoid clobbering a concurrently-reopened channel; ChannelContext::for_buyer_channel resume helper; runtime bootstrap that is non-fatal (a buyer-path failure never blocks the seller settlement path).
  • common: buyer_deposit_micro_usdc (default 10 USDC, ADR 003 § Deposit Economics) + buyer_max_approve config.

Design notes

  • channelId is read from the receipt, not derived locally: after the openChannel tx mines, the channelId + expiresAt are decoded from its ChannelOpened event log (filtered on client/provider == self). This is atomic with the open — a successful tx guarantees the event is present, so the channel is always persistable; there is no local keccak256(client, provider, nonce) derivation, no open_lock, and no follow-up getChannel whose transient failure could orphan the escrowed deposit.
  • One open per provider is enforced, not just documented: an in-flight-open set (opens_in_flight) serializes opens per provider — a concurrent open_or_reuse_channel for a provider already mid-open bails for retry rather than escrowing a second deposit whose record would orphan the first. The reuse fast-path never touches the set (no contention when a channel already exists); the open path claims the slot then re-checks reuse to close the TOCTOU.
  • Hydration is resilient: buyer_load_all skips-and-warn!s on a single undecodable record rather than failing the whole load. Because buyer bootstrap is non-fatal and gates the reclaim-sweep spawn, a propagated error would otherwise leave every other tracked channel's deposit unreclaimable. (The seller load_all still fails loud — its bootstrap is fatal by design, guarding the incentive: no replay-protection window enforced on incoming voucher nonces, allowing a client to resubmit a previously accepted voucher after a node restart and receive a second byte-delivery for the same payment #527 replay window.)
  • One redb file, two tables: distinct names + key widths ([u8;20] buyer vs [u8;32] seller); the buyer ops are inherent buyer_* methods + a thin BuyerChannelStoreHandle adapter to avoid trait-method-name collisions on the shared concrete store.
  • Reclaim is best-effort + safe: system-time expiry is only a candidate filter; the on-chain block.timestamp >= expiresAt check is the real gate, and a compare-and-delete (forget_if_channel) prevents a sweep from dropping a freshly-reopened channel.

Review

Ran the multi-agent PR review toolkit; addressed the high-value findings (reclaim lost-update CAS fix, ownership assertion, actionable bootstrap warning, type-design encapsulation/invariant docs + promoted advance, two binding-doc accuracy fixes, and added buyer-store corrupt/mismatch/trailing-bytes/CAS tests + e2e top_up coverage).

Verification

cargo fmt --check, clippy --workspace --all-targets -D warnings, 1302 tests pass (post-merge with main), rustdoc -D warnings, cargo deny. The anvil e2e (--features anvil-e2e) drives the buyer path end-to-end: approve → openChannel → voucher delivery → reuse → top_up → reclaimExpired with a verified full-deposit refund and Closed status. No Solidity changes (the contract already ships these functions).

🤖 Generated with Claude Code

thiras and others added 7 commits June 1, 2026 01:10
…rename (#327)

Implements the on-chain PaymentChannel client (seller/provider settlement
path) for issue #327. The CapacityBond registry read-path was already done
as ChainStakerSet; PaymentChannel.sol landed in #716, so this wires the
Rust side that drives close/withdraw/settle.

- incentive: PaymentChannel sol! bindings (reads + writes + lifecycle
  events), validated field-for-field against the compiled ABI.
- voucher: fix EIP-712 domain name "StablePaymentChannel" -> "PaymentChannel"
  to match the contract's EIP712("PaymentChannel","1") ctor — without this
  every closeChannel/withdraw reverts with InvalidVoucherSignature despite
  off-chain verification passing. Pinned with a regression test.
- store: schema v2 persists the latest voucher signature (additive trailing
  postcard segment; v1 records hydrate with an empty signature and are
  unredeemable until re-recorded). Adds a `get` point-lookup to the trait.
- node: PaymentChannelService watches ChannelOpened (provider==self) -> persist
  so the voucher handler accepts it, ChannelSettled -> forget,
  ChannelCloseInitiated -> observe-only (dispute monitor deferred, #324).
  Redeems via threshold `withdraw` (redeem hint from the voucher-accept path)
  and best-effort `closeChannel` on graceful shutdown, with on-chain v-byte
  normalization (0/1 -> 27/28).
- runtime: wallet-filled provider from the eth signer, usdc() startup
  self-check, redeem_threshold_micro_usdc config (default 1 USDC), shutdown
  close hook.

BREAKING CHANGE: renames StakingRegistry -> CapacityBond. The config TOML key
`blockchain.staking_registry_address` is now `blockchain.capacity_bond_address`,
the CLI flag `--staking-registry-address` is now `--capacity-bond-address`, and
the env var DECDN_STAKING_REGISTRY_ADDRESS is now DECDN_CAPACITY_BOND_ADDRESS.

Out of scope (deferred): buyer-side openChannel for node-to-node pulls, the
in-process dispute monitor (#324), and the live anvil e2e (no existing harness).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…pUp + expiry handling (#327)

External review (gemini-code-assist, Copilot) on PR #743:

- redeemer: cache last-known on-chain `withdrawnAmount` per channel and skip
  the `getChannel` RPC when the accrued claim is provably below threshold —
  avoids per-voucher RPC spam under active streaming. The cache is always
  `<=` the true value (only our own `withdraw` advances it), so a redemption
  is never wrongly skipped.
- shutdown close: submit `closeChannel` sequentially (nonce order) but await
  receipts concurrently via `join_all` so more channels close within the
  bounded shutdown deadline. `submit_close` refactored into a free `send_close`
  returning a receipt future (`use<P>` precise capture).
- topUp (Copilot): subscribe to `ChannelToppedUp` and raise the tracked
  `ChannelState.deposit` so `apply_voucher` stops rejecting otherwise-valid
  vouchers a client signs after topping up.
- expiry (Copilot): persist the channel's on-chain `expiresAt` (schema-v2
  second trailing segment), add a periodic pre-expiry close sweep so the
  provider redeems before `reclaimExpired` can refund the client, and gate the
  voucher handler to refuse delivery once a channel is expired (defense in
  depth). Closing earns the claim; the sweep then retires (forgets) the
  channel so the node stops serving it.

Verification: clippy --workspace --all-targets -D warnings, fmt, 1264 tests,
rustdoc -D warnings — all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ation, dead-field + doc fixes, tests (#327)

Multi-agent review of PR #743 (code/tests/errors/types/comments):

Critical:
- try_redeem / send_close now check `receipt.status()`. `get_receipt()`
  resolves Ok even for a reverted tx; previously a reverted `withdraw`
  poisoned the withdrawn-amount cache (channel silently never redeemed again
  until restart) and a reverted `closeChannel` made the expiry sweep forget an
  un-redeemed channel right before reclaimExpired. Both now leave state intact
  and retry.

Important:
- reject `blockchain.redeem_threshold_micro_usdc = 0` at config resolution (0
  withdraws on every voucher and reverts on zero-delta) — mirrors the
  rpc_watchdog floor pattern. Test added.
- correct the `as_bytes()` v-byte docs: alloy already emits 27/28, so
  `normalize_voucher_signature` is a defensive no-op today (not the active
  0/1->27/28 bridge the doc claimed).
- fix module docs: add `ChannelToppedUp` to the watcher's handled-events list;
  correct the "registered at startup" claim (startup is store hydration in
  ClientHandler::new, not register_open_channel); document the
  opened-during-downtime backfill gap.
- drop dead `redeem_threshold` / `self_address` fields from
  PaymentChannelService (read only in Debug; the live values are the copies
  moved into the tasks).

Tests (pure-logic gaps the review flagged):
- extract `is_expired` / `within_close_window` predicates (shared by the sweep
  and the handler expiry gate) + boundary table tests.
- register_open_channel idempotency preserves the voucher watermark (the #527
  replay-window guard) — was untested.
- update_channel_deposit raises / no-ops on non-increasing / no-ops on
  untracked.
- normalize empty signature.

Not changed (with rationale): kept the schema-v2 trailing-segment encoding —
the suggested "struct fields + version bump" breaks reading existing on-disk
v1 records (a v2 reader would read past end-of-input). Deferred to follow-ups:
observability metrics, an independent redeemer tick, shutdown-quiesce of the
redeemer, ChannelState type-strengthening, and the downtime log-backfill.

Verification: clippy --workspace --all-targets -D warnings, fmt, 1270 tests,
rustdoc -D warnings — all green.

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

Stand up a live, gated end-to-end test (behind the `anvil-e2e` cargo feature,
off by default) that closes the two runtime-only verification gaps called out
in PR #743:
  1. on-chain acceptance of the normalized voucher signature v-byte, and
  2. live ChannelOpened/ChannelSettled event decode by PaymentChannelService.

The test spawns anvil, deploys a mintable mock USDC + the full protocol via
`forge script DeployProtocol.s.sol`, activates the node on-chain (stake +
registerNode — the iroh ed25519 key signs the Ed25519Verifier ownership proof,
the eth key signs the EIP-712 binding), brings up PaymentChannelService + a
persistent store + ClientHandler in-process, then runs a real iroh paid
delivery and asserts: the watcher persists the opened channel (closes the #327
WrongChannel gap), the threshold withdraw lands on-chain, FeeRouter.bytesPerEpoch
increments, graceful-shutdown closeChannel moves the channel to Closing, and
settleChannel after the dispute window is decoded and forgets the row.

Supporting changes:
- contracts: add test-only MintableUSDC (6-decimal, mintable) mock.
- node tests: extract the shared iroh helpers into tests/support/mod.rs
  (client_loopback.rs now consumes it; behavior-preserving).
- node: add the `anvil-e2e` feature (no new crate deps; anvil/forge run as
  subprocesses).
- ci: add a gated `anvil-e2e` job (Rust + Foundry) wired into ci-success.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… artifact-read error

- evm_increaseTime: pass a plain u64 (JSON number) instead of U256 (hex-quantity
  string), which not every EVM client accepts for that RPC.
- deploy_mock_usdc: it returns Result, so propagate the artifact read/parse
  failures via map_err(...)?/ok_or_else instead of panicking with .expect.

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

- The redeemer/watcher warn!s (on-chain revert reasons) are emitted from tokio
  worker threads; `with_test_writer` routes through libtest's thread-local
  capture set only on the main thread, so those cross-thread logs would be
  dropped. Write to process stderr instead (nextest captures it and shows it on
  failure) — restores the intended diagnostic on a withdraw/close timeout.
- Assert the persisted channel 1's `client` and `deposit` match (free, non-flaky
  coverage that the watcher decoded ChannelOpened's non-indexed fields, not just
  the channelId topic).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lement (#744)

Split out from #327 (PR #743, seller settlement). Implements the buyer-side
on-chain path from ADR 003 §node→node: when a node pulls content from an
upstream provider on a cache miss it acts as the client — opening a channel,
signing cumulative vouchers (the voucher signer already existed in
client_requester), and reclaiming its deposit if the upstream abandons the
channel. Scope is the channel-management layer; wiring the cache engine's
miss path to call it needs provider-discovery (ADR 001/022) and stays out of
scope, so the service is bootstrapped (approval + reclaim sweep) but the hook
that drives buys is not yet wired.

What's in this PR:
- incentive: sol! bindings for openChannel/topUp/reclaimExpired +
  clientChannelNonce/minDeposit + ChannelExpiredReclaimed; a minimal ERC-20
  binding (erc20.rs) for the one-time USDC approval; provider-keyed
  BuyerChannelState (+ advance() monotonic mutator), BuyerChannelStore trait
  (incl. forget_if_channel compare-and-delete) and MemoryBuyerChannelStore.
- node: PersistentBuyerChannelStore as a second redb table on the shared
  store handle (redb forbids two handles to one file), exposed via
  BuyerChannelStoreHandle; BuyerChannelService (one-time max approve at
  startup, lazy open + per-provider reuse with channelId derived under a
  serialization lock and cross-checked on-chain, record_progress, top_up, and
  a background reclaim sweep using forget_if_channel to avoid lost updates);
  ChannelContext::for_buyer_channel resume helper; runtime bootstrap
  (non-fatal — a buyer failure never blocks the seller path).
- common: buyer_deposit_micro_usdc (default 10 USDC) + buyer_max_approve
  config.

Verification: fmt, clippy --workspace --all-targets -D warnings, 1289 tests,
rustdoc -D warnings, cargo deny; anvil e2e extended to drive the buyer path
end-to-end (approve → openChannel → voucher delivery → reuse → top_up →
reclaimExpired full-deposit refund).

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

@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 the on-chain buyer-side payment-channel service, bookkeeping, and storage to support paid cache-miss pulls. It introduces configuration parameters, ERC-20 bindings for one-time USDC approvals, persistent buyer-channel storage using redb, and a background sweep task to reclaim expired deposits. Feedback on the implementation highlights two key improvements: first, to avoid orphaned channels and double-deposits on transient RPC failures, the service should decode the ChannelOpened event directly from the transaction receipt logs instead of making an extra getChannel query; second, the reclaim sweep should explicitly handle zeroed client addresses for settled channels to prevent misleading 'bogus record' warnings.

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

…eclaim-before-reopen

- open_or_reuse_channel: decode the ChannelOpened event from the openChannel
  tx receipt for channelId + expiresAt instead of a follow-up getChannel. The
  read was non-atomic — a transient RPC failure after a successful open left
  the on-chain deposit escrowed but untracked (orphaned, re-opened on the next
  miss). Decoding the receipt log is atomic with the open. This also removes
  the clientChannelNonce read, local channelId derivation, and the open_lock
  (all only needed for the now-gone derive path), plus the clientChannelNonce
  binding. (gemini-code-assist, high)
- open_or_reuse_channel: when a tracked channel is expired, reclaim it BEFORE
  opening a replacement. The store is provider-keyed, so the old reuse-then-
  overwrite path dropped the expired record before the reclaim sweep could see
  it — silently abandoning a refundable deposit. Now try_reclaim runs inline
  and, if the record can't be cleared, the open errors instead of overwriting.
- Document the per-provider concurrency requirement on open_or_reuse_channel.
- Doc fixes: openChannel + ChannelOpened binding docs now describe the receipt-
  decode path (not local derivation).

Not changed: the "settled channel returns zeroed client" medium comment is a
false positive — PaymentChannel sets status=Closed but never deletes the
struct, so a settled channel keeps client==self and is handled by the status
check; client==0 means a genuinely phantom record where the warning is correct.

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

Copy link
Copy Markdown
Contributor

Review — buyer-side openChannel (#753)

Reviewed the incremental diff against #752. The store layering (two redb tables, distinct key widths, CAS-on-delete), the receipt-event channelId derivation, and the advance() monotonic guard are all well done, and the new corrupt/mismatch/CAS tests are good. One real bug, one stale-narrative note, one minor edge.

1. One corrupt buyer record silently disables the entire buyer path + all reclaims — crates/node/src/channel_store.rs:768, crates/node/src/buyer_channel.rs:129

buyer_load_all does out.push(decode_buyer_record(...)?) — a single corrupt or forward-incompatible row (e.g. a schema_version newer than SUPPORTED_BUYER_SCHEMA_VERSION after a downgrade) makes the whole load return Err. bootstrap calls load_all()? before it tokio::spawns the reclaim sweep (buyer_channel.rs:129 precedes the spawn at :142), and the runtime makes buyer bootstrap non-fatal (runtime/mod.rs:620-648, logs "buyer path DISABLED").

Net effect: one bad row → buyer bootstrap errors → no reclaim sweep is ever spawned → every other tracked channel's deposit (10 USDC + top-ups each) becomes unreclaimable, and no new buys can open, until the row is manually removed. The seller table fails loud (aborts startup); this fails silent.

Fix: make hydration resilient — buyer_load_all should skip-and-warn! on a single undecodable record instead of propagating (mirroring reclaim_once, which already tolerates a load error and continues). Or have bootstrap spawn the sweep even on partial hydration failure, so healthy channels stay reclaimable.

2. PR narrative describes a serialization lock that isn't in the code — crates/node/src/buyer_channel.rs:177-302

The description says channelId is derived "under a serialization lock held across read→send→mined-receipt" with a clientChannelNonce cross-check. The merged code does neither: there's no Mutex/open_lock, and channel_id comes from the receipt's ChannelOpened event (:266-279) — which is actually the better, atomic approach (the commit message agrees: "atomic open via receipt event"). Per-provider serialization is instead an unenforced caller contract documented at :177-183.

The receipt-based derivation is fine; just flagging that the PR/commit prose sends a reviewer hunting for a lock that doesn't exist. [your call] whether to enforce single-provider serialization now or when the cache-miss hook lands — but note that as written, a future concurrent caller for the same provider escrows two deposits and the second record() orphans the first (the sweep's load_all never sees the dropped one). A per-provider lock or an in-flight-open set would make the invariant real rather than documentary.

3. Clock-skew / boundary refuses a still-usable channel (already documented) — crates/node/src/buyer_channel.rs:198-238

When the host clock is >= expires_at but the chain clock isn't yet, is_expired_at(unix_now()) skips reuse, try_reclaim reverts on-chain (not actually expired), and the call bails with "not yet reclaimable" — blocking buys for that provider until the sweep clears it. This is explicitly called out as an intentional "never drop funds" tradeoff (:222-238), so probably fine. [your call]: if buy-availability matters more than the rare-skew case, you could reuse the channel when the chain still considers it open rather than bailing.

Automated multi-angle review (line-by-line + removed-behavior + cross-file), recall-biased.

@thiras
thiras force-pushed the test/745-anvil-settlement-e2e branch from a6b85c7 to 5b6295c Compare June 1, 2026 14:03
Base automatically changed from test/745-anvil-settlement-e2e to main June 1, 2026 14:12
thiras and others added 2 commits June 1, 2026 17:49
…annel

# Conflicts:
#	crates/cli/tests/config_validate.rs
#	crates/common/src/config/mod.rs
#	crates/common/src/config/resolved.rs
#	crates/common/src/config/types.rs
#	crates/incentive/src/lib.rs
#	crates/incentive/src/payment_channel.rs
#	crates/incentive/src/store.rs
#	crates/node/src/channel_store.rs
#	crates/node/src/payment_settlement.rs
#	crates/node/src/runtime/mod.rs
#	crates/node/src/runtime/reload.rs
#	crates/node/tests/anvil_settlement_e2e.rs
#	crates/node/tests/sighup_signal.rs
… + per-provider open guard

Item 1 (real bug): `buyer_load_all` propagated an error on a single
undecodable record, so one corrupt/forward-incompatible row failed buyer
bootstrap *before* the reclaim sweep was spawned (and the runtime makes
buyer bootstrap non-fatal). Net effect: one bad row left every other
tracked channel's deposit unreclaimable and blocked all new opens. Now
skip-and-`warn!` per record during hydration (the seller `load_all` still
fails loud because its bootstrap is fatal — the #527 replay window). The
point lookup `get_by_provider` still surfaces the precise decode error.
Existing `*_rejected` tests retargeted to assert the skip-keeps-healthy
contract.

Item 2 (make the documented invariant real): per-provider in-flight-open
set (`opens_in_flight`) serializes opens — a concurrent
`open_or_reuse_channel` for a provider already mid-open bails for retry
rather than escrowing a second deposit whose `record` would orphan the
first. Fast-path reuse never touches the set (no contention for the
common many-pulls-to-one-open-provider case); the open path claims the
slot then re-checks reuse to close the TOCTOU. RAII guard releases on
every exit path.

Item 3 (clock-skew bail): kept as-is — the documented "never drop funds"
tradeoff stands.

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

thiras commented Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @alpergundogdu — all three addressed in eff580c (on top of a main merge that integrates the seller PendingSettle settlement-sweep work and the merged anvil harness).

1. One corrupt buyer record disables the whole buyer path + all reclaims — fixed, this was real. buyer_load_all now skips-and-warn!s on a single undecodable record instead of propagating, so one bad row no longer fails buyer bootstrap (which gates the reclaim-sweep spawn and is non-fatal at the runtime), leaving every other channel's deposit reclaimable. Took the resilient-hydration option rather than "spawn the sweep anyway", because the sweep's own reclaim_once → load_all would keep erroring every tick — skip-and-warn fixes both the bootstrap count and every sweep. The seller load_all stays fail-loud (its bootstrap is fatal — the #527 replay window). The point lookup get_by_provider still surfaces the precise decode error (UnsupportedSchema / Corrupt); the three *_rejected store tests are retargeted to assert the new skip-keeps-healthy contract + a healthy-row-survives-a-corrupt-row case.

2. Stale lock narrative + unenforced per-provider serialization — both fixed. The PR description/design-notes no longer describe the removed open_lock/clientChannelNonce/getChannel derive path (channelId now comes from the receipt ChannelOpened event, as merged). And I made the invariant real rather than documentary: an in-flight-open set (opens_in_flight) serializes opens per provider — a concurrent open_or_reuse_channel for a provider already mid-open bails for retry instead of escrowing a second deposit whose record would orphan the first. The reuse fast-path never touches the set (no contention once a channel exists); the open path claims the slot then re-checks reuse to close the TOCTOU. RAII guard releases on every exit. Unit-tested the claim/refuse/release mechanism.

3. Clock-skew boundary refuses a still-usable channel — kept as-is, as you flagged it [your call]. The "never drop funds" tradeoff stands: prioritizing not-orphaning an escrowed deposit over buy-availability during the rare skew window is the right default while the cache-miss hook isn't wired yet. Easy to revisit (reuse-when-chain-still-open) if buy-availability turns out to matter more in practice.

Verification: fmt, clippy --all-targets, 1302 tests, anvil-e2e feature compiles + lints (buyer e2e coverage preserved through the merge).

@github-actions

github-actions Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 86.94% (was 87.79%, ▼ 0.85%) — 25076/28844 lines

File Coverage Lines Δ
crates/common/src/config/mod.rs 96.18% 4586/4768 ▼ 0.09%
crates/common/src/config/resolved.rs 100.00% 13/13 ● 0.00%
crates/incentive/src/buyer_channel.rs 92.89% 222/239 new
crates/node/src/buyer_channel.rs 17.25% 64/371 new
crates/node/src/channel_store.rs 88.20% 1024/1161 ▲ +0.89%
crates/node/src/client_requester.rs 84.38% 216/256 ▲ +1.04%
crates/node/src/runtime/mod.rs 46.98% 514/1094 ▼ 0.78%
crates/node/src/runtime/reload.rs 95.49% 1398/1464 ▲ +0.01%
History
Commit Total Δ vs base
eff580c 86.89% ▼ 0.90%
9031c34 (HEAD) 86.94% ▼ 0.85%

thiras added a commit that referenced this pull request Jun 1, 2026
…tion, type-enforced open guard, comment rot

- **Comment rot** (comment-analyzer): `BuyerChannelState` field docs still
  described the removed `getChannel`-at-open cross-check; corrected to the
  receipt-event derivation actually used.
- **Type-enforced open guard** (type-design + pr-test, convergent): fold the
  set-insert and the RAII guard into one `InFlightOpenGuard::claim`
  constructor, so the one-open-per-provider invariant can't be violated by
  construction. The unit test now exercises that production constructor
  instead of a hand-copied claim closure (the prior test was a tautology).
- **Orphaned-deposit escalation** (silent-failure C1): once `openChannel`
  escrows the deposit, the two post-escrow failure paths (missing
  `ChannelOpened` event, persist failure) now `error!` with the tx hash so an
  operator can reconcile/reclaim manually — the buyer path has no chain-log
  reconciliation yet (tracked as follow-up to the cache-miss hook). Extracted
  the open+persist tail into `open_and_persist`.
- **Hydration skip severity** (silent-failure I1): `buyer_load_all` logs a
  skipped undecodable record at `error!` (was `warn!`) — its escrowed deposit
  is unreclaimable until repaired, so it must not be filtered from alerting.

Deferred as follow-ups (need the not-yet-wired cache-miss hook / anvil
infra): bootstrap chain-log reconciliation scan; anvil e2e concurrent-open
and mixed corrupt/healthy multi-row reclaim-sweep coverage.

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

thiras commented Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

Deferred follow-ups from the multi-agent review (orphan-deposit bootstrap reconciliation + anvil e2e for concurrent-open / mixed-corrupt multi-row reclaim) are tracked in #763 — both gated on the not-yet-wired cache-miss hook. The post-escrow error! escalation and the type-enforced InFlightOpenGuard::claim shipped in c0073ea.

…tion, type-enforced open guard, comment rot

- **Comment rot** (comment-analyzer): `BuyerChannelState` field docs still
  described the removed `getChannel`-at-open cross-check; corrected to the
  receipt-event derivation actually used.
- **Type-enforced open guard** (type-design + pr-test, convergent): fold the
  set-insert and the RAII guard into one `InFlightOpenGuard::claim`
  constructor, so the one-open-per-provider invariant can't be violated by
  construction. The unit test now exercises that production constructor
  instead of a hand-copied claim closure (the prior test was a tautology).
- **Orphaned-deposit escalation** (silent-failure C1): once `openChannel`
  escrows the deposit, the two post-escrow failure paths (missing
  `ChannelOpened` event, persist failure) now `error!` with the tx hash so an
  operator can reconcile/reclaim manually — the buyer path has no chain-log
  reconciliation yet (tracked in #763, gated on the cache-miss hook).
  Extracted the open+persist tail into `open_and_persist`.
- **Hydration skip severity** (silent-failure I1): `buyer_load_all` logs a
  skipped undecodable record at `error!` (was `warn!`) — its escrowed deposit
  is unreclaimable until repaired, so it must not be filtered from alerting.

Deferred as follow-ups in #763 (need the not-yet-wired cache-miss hook /
anvil infra): bootstrap chain-log reconciliation scan; anvil e2e
concurrent-open and mixed corrupt/healthy multi-row reclaim-sweep coverage.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jul 17, 2026
…re into a shared table (#1246) (#1257)

* test(incentive): pin the buyer record encoding with a golden-bytes test

The buyer record's on-disk layout is shared by two independent stores —
`incentive`'s `buyer-channels.redb` and the node's `channels.redb` — but
the contract between them is asserted only by a doc comment
("Byte-compatible with the node's buyer table", buyer_channel_redb.rs).
Nothing tested it, so the two encoders could drift silently.

Postcard encodes struct fields positionally and unnamed, so reordering or
retyping a field rewrites the bytes with no compile error and no test
failure: every suite builds a fresh tempdir store, so they all still pass
while every record an older binary wrote is orphaned.

Pin the layout with a golden. The fixture is byte-for-byte the state the
node's `buyer_sample(7)` builds, so the golden also pins the two crates'
encoders to each other — verified: incentive's encoder reproduces the
node's bytes exactly, so the byte-compat claim held.

Lands ahead of #1246, which hoists this codec into a shared module, so
the tripwire is in place before the code moves.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(incentive): add the shared buyer-channel table codec and ops (#1246)

The buyer-channel redb store exists twice: once in `decdn-node`'s
`channel_store` (combined seller+buyer `channels.redb`) and once here as
`RedbBuyerChannelStore` (buyer-only `buyer-channels.redb`). They differ
only in which file they own — redb forbids two `Database` handles on one
file, so the node cannot adopt the buyer-only store — but that
file-ownership difference costs a second copy of the record codec AND of
every table operation, with byte-compatibility maintained by hand.

Add `buyer_channel_table`: the on-disk codec plus the seven table ops,
parameterized over the caller's `&Database` + `TableDefinition`. Both
stores can now delegate and keep only their own file wiring.

Design notes:
- One module, not two: the codec's only non-test consumer is the ops, so
  keeping them together lets `StoredBuyerChannelState` stay fully private
  — the on-disk shape is unnameable outside this module.
- The table *name* is shared (`BUYER_CHANNEL_TABLE_NAME`) while each store
  keeps its own `TableDefinition` built from it, so name drift is
  structurally impossible and the key/value types are pinned by the
  `BuyerTableDef` signature.
- A `BuyerChannelTable` handle rather than free functions: binding
  (db, table) once keeps `advance_progress` under too_many_arguments,
  which a free fn would sit exactly at.
- `insert_raw` is pub, not cfg(test): a cross-crate cfg(test) does not
  propagate, so a gated seam could not serve the node's own
  `insert_raw_buyer_record` (#763 e2e). It needs a `&Database`, which
  neither store exposes.
- `begin_durable_write` makes `Durability::Immediate` structural rather
  than repeated at six call sites where it could be forgotten.
- `TableDefinition` has no `Debug` impl, so `BuyerChannelTable` needs a
  hand-written one to satisfy missing_debug_implementations.

New `buyer-store-core` feature holds this; `redb` now implies it and adds
only `RedbBuyerChannelStore`, so a bare `decdn-incentive` build still
links neither redb nor postcard (verified via cargo tree).

Ports the node's bodies verbatim (they carry the richer rationale) with
this crate's `table_exists` factoring. No caller is rewired yet — the
transient duplication is deliberate so the follow-ups are pure deletion.

Tests port the node's 12 buyer tests, plus two additions:
- `no_row_ops_do_not_create_the_table`: the node's suite asserted the
  outcomes but never the "no table" half of its own claim — a dropped
  pre-check is exactly what this refactor could regress.
- `load_all_returns_every_recorded_channel`, imported from this crate's
  suite (the only test with no node twin).

Module doc links are fully qualified and `buyer_channel_redb` is a code
span, not a link: rustdoc merges the outer `///` on the `lib.rs` module
declaration with the inner `//!` docs and resolves in *that* scope, and
linking a `redb`-gated item breaks a `buyer-store-core`-only doc build.
Both failures are hidden by the workspace-wide CI doc job's feature
unification; verified against each feature config separately.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(incentive): delegate RedbBuyerChannelStore to the shared buyer table

Drop this store's private copy of the record codec (`StoredBuyerChannelState`,
`From`, `into_state`, `decode_buyer_record`), its schema/trailer constants,
`write_state`, `table_exists`, and all seven `BuyerChannelStore` bodies. Each
method is now a one-line delegation to `buyer_channel_table`.

What stays is what is actually specific to this store: it owns
`buyer-channels.redb`, so it keeps `open()` verbatim — the zero-length-file
guard (redb treats "empty" as "create fresh", which would silently wipe the
watermark) and the DatabaseAlreadyOpen → StoreError::AlreadyOpen mapping
(#942). The table const stays too, but is now built from the shared
BUYER_CHANNEL_TABLE_NAME, so the on-disk name has one definition.

670 → 288 lines, with no change to the on-disk format: the golden test moves
with the codec and still passes.

Tests drop to the four that earn their place here: the two `open()` guards,
the cross-invocation watermark resume (#940), and a new
`store_delegates_every_op`. That last one covers the gap the shared suite
structurally cannot — it proves the operations are correct but not that this
store's seven delegations reach the matching one, so a transposition
(`forget` wired to `forget_if_channel`) would otherwise pass everything.
The five tests deleted here are subsumed by the shared suite, which also
gives this store the decode-edge-case coverage (schema, trailer, key
mismatch) it never had.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(node): delegate the buyer channel store to decdn-incentive (#1246)

The buyer half of this file was a byte-identical re-implementation of
`decdn-incentive`'s buyer store: same table name, same key/value types,
same 9-field postcard record, same take_from_bytes decode, same
skip-undecodable-row load_all. Only the *file* differed — this store
needs the buyer table inside `channels.redb` next to the seller,
pending-settle, and watcher-checkpoint tables, because redb forbids two
`Database` handles on one file.

That is wiring, not logic, so keep the wiring and drop the logic. Delete
the codec (`StoredBuyerChannelState`, `From`, `into_state`,
`decode_buyer_record`), `BUYER_SUPPORTED_SCHEMA_VERSION`, and the entire
~360-line inherent `buyer_*` block — whose only caller was
`BuyerChannelStoreHandle`'s trait impl, which now delegates straight to
`decdn_incentive::buyer_channel_table` via `&self.inner.db`.

What stays: the `BUYER_CHANNEL_TABLE` const (now built from the shared
`BUYER_CHANNEL_TABLE_NAME`, so the on-disk name has one definition),
`SANE_TRAILER_MAX_BYTES` (the seller decode still uses it), and
`insert_raw_buyer_record` with its signature verbatim — the #763 e2e
depends on it — now a thin call to the shared `insert_raw`.

`BuyerChannelStoreHandle` survives for the reason it was introduced:
implementing `BuyerChannelStore` on `PersistentChannelStateStore` would
collide with `ChannelStateStore`'s load_all/record/forget. Its rationale
moves onto the type. Its `table()` cannot be const (it derefs an Arc).

channel_store.rs: 2740 → 1926 lines. No on-disk change — the table name,
key/value types, and record layout are unchanged, and the golden-bytes
test pins the encoding.

Tests: 12 of the 14 buyer tests move to the shared suite, where the code
they cover now lives. Two stay, because only they test what this file
still contributes:
- `buyer_and_seller_tables_are_independent` — co-tenancy of five tables in
  one file; incentive has no seller table, so this is unreachable there.
- `buyer_handle_delegates_every_op` (new) — the shared suite proves the
  ops are correct but not that these seven delegations reach the matching
  one; the co-tenancy test only exercises three of seven.

Also drops a stale comment: the future-schema test's doc claimed the
record "must refuse to load — same safety posture as the seller table",
but buyer load_all deliberately *skips* it (PR #753) — the opposite of the
seller's abort-on-error. That asymmetry is now documented on the shared
`load_all`, with the reason it must not be "unified".

decdn-node enables `decdn-incentive/buyer-store-core` (not `redb`), so it
compiles the shared table without the client-only `RedbBuyerChannelStore`.
Rewords the e2e `anvil-e2e` comment, whose claim that default builds skip
the postcard code no longer holds (and never did: postcard arrives via
decdn-protocol regardless).

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(incentive,node): address review of the buyer-table hoist (#1246)

Multi-agent review found several real defects. Each was reproduced before
being fixed.

**The hoist missed one operation.** `insert_raw_buyer_record` still
hand-rolled its own begin_write/set_durability/open_table/insert/commit
instead of delegating — the 8th write path, left duplicated. Worse, the
doc on the shared `insert_raw` justified its `pub` by claiming that seam
needed it, describing a call that did not exist. Node's seam now
delegates, which makes the claim true, removes the last duplicated table
op, and makes the file's "keeps only the wiring" banner literally true
(verified: zero redb txn machinery remains in node's buyer section).

**Drop the `TableDefinition` parameter.** Its parameter space had exactly
one inhabitant — both stores and the tests passed the same value — while
admitting `TableDefinition::new("typo_v1")`, which compiles, reads an
empty table, and tells the reclaim sweep there is nothing to reclaim.
That is worse than the duplicated code it replaced, where the name was a
private const beside its use. The table is a frozen global, not a
per-call knob: it is now one private const, `BuyerChannelTable::new(db)`
takes only the file (the sole thing the two stores legitimately differ
on), `BuyerTableDef`/`BUYER_CHANNEL_TABLE_NAME` are private, both stores'
consts are gone, and the hand-written Debug reverts to a derive. The
invariant became structural and the diff got smaller.

**The golden test could not catch the swap that matters most.** With
`state(7)`, `channel_id` is 32 bytes ending 07 and `last_nonce` is
`U256::from(7)` — the same 32 bytes — so transposing them encoded
identically and the tripwire passed. That is the catastrophic pair:
`channel_id` guards the CAS in forget_if_channel and advance_progress.
The fixture now uses a distinct pattern per field, regenerated from
main's encoder so it still pins the format across the hoist. Verified it
now fails all five same-typed swaps, including that one.

**Two proven test gaps** (found by mutation, fixed, and re-verified — each
mutant now fails where it previously survived):
- The in-txn UnknownProvider branch (table present, row absent) was
  untested; only the table_exists() short-circuit was. A deleted test had
  covered it.
- The delegation tests asserted only the outcome enum, so passing
  bytes_delivered where amount belongs — a payment-watermark corruption —
  passed. They now assert the row. Their rationale also named an
  impossible example: the types already reject `forget` wired to
  `forget_if_channel`; the reachable mistake is argument order among the
  U256s, which is exactly where they were weakest.

**`insert_raw` moves behind a `test-util` feature** rather than shipping
`pub`, matching decdn-client-pull's precedent. Confirmed absent from the
public API docs with the feature off.

**Comments that were false:**
- `redb`/`buyer-store-core` never gated out postcard — decdn-protocol
  pulls it unconditionally. Two comments claimed otherwise while the e2e
  comment (correctly) said the opposite.
- The `dep:redb` NOTE described a feature-name collision. Cargo actually
  rejects the manifest with "optional dependency `redb` is not included in
  any feature" — a maintainer would have hunted the wrong error.
- The table_exists TOCTOU note said the op "falls through to a get miss";
  it returns early. The race is real but different, and still benign.
- `RedbBuyerChannelStore::open` lost its doc + # Errors in the rewrite.
- The load_all skip claims the operator gets the provider address. True
  for the node, which installs a subscriber — but decdn-cli has no
  tracing dependency at all, so for the client store the skip is silent:
  `channel clean` can report "no tracked channels to clean" while the
  deposit is escrowed. Pre-existing and not fixable without changing the
  BuyerChannelStore trait, so the doc now says so plainly instead of
  implying coverage that isn't there. Follow-up issue to come.

**Also:** a reciprocal "do not unify" note on the seller load_all (the
asymmetry now spans two crates, and that is the direction a maintainer
arrives from); a decode-direction golden (the encode golden couldn't
catch a matched encoder/decoder drift); load_all asserts providers, not
just a count; the outer /// docs on the lib.rs mod declarations are gone,
which removes the rustdoc merged-scope trap at its root along with ten
lines of commentary explaining it.

**CI:** `--workspace` unifies features, so decdn-cli turns on
incentive/redb for everyone and the two configurations this feature split
exists to create were never compiled. Both are real (a plain
`cargo build -p decdn-node`; any consumer taking decdn-incentive alone).
Added two direct clippy runs.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
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.

Node-to-node buyer-side openChannel for cache-miss settlement

3 participants