Skip to content

refactor(node,incentive): hoist the duplicated buyer-channel redb store into a shared table (#1246) - #1257

Merged
thiras merged 5 commits into
mainfrom
refactor/1246-shared-buyer-channel-table
Jul 17, 2026
Merged

thiras merged 5 commits into
mainfrom
refactor/1246-shared-buyer-channel-table

Conversation

@thiras

@thiras thiras commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1246.

Problem

The buyer-channel redb store was implemented twice, byte-identically:

  • crates/node/src/channel_store.rs — buyer table inside the combined channels.redb (alongside seller, pending-settle, watcher-checkpoint).
  • crates/incentive/src/buyer_channel_redb.rs — RedbBuyerChannelStore, buyer-only buyer-channels.redb, for the CLI's decdn fetch.

They differ only in which file they own — redb forbids two Database handles on one file, so the node can't adopt the buyer-only store. That's file ownership, not logic, and it cost a second copy of the record codec and of every table operation, with byte-compatibility maintained by hand ("Byte-compatible with the node's buyer table" — a doc comment, untested).

They had already drifted: the excess-trailer warning text differed between the copies.

Scope note — wider than the issue prescribed

The issue proposed hoisting only the codec, but scoped the problem as "~500-570 duplicated lines". Those don't match: the codec is ~88 lines; the ~363-line block of store methods is the bulk, and it was logic-identical too. A codec-only hoist would have removed ~88 lines and left the real duplication.

This hoists codec + table operations, still with no on-disk change — each store keeps its own file, Database, and transactions. The issue's rejected alternative (node adopts RedbBuyerChannelStore, separate buyer file) remains correctly rejected; that one would change on-disk layout. This is the middle path.

Mirrors an existing precedent: pending_record_in already shares one body across two tables "so the seller and buyer pending sets stay byte-for-byte consistent."

Result

  • StoredBuyerChannelState exists in one file (was two); six inlined encode sites collapse to one encode_record.
  • channel_store.rs 2740 → ~1950; buyer_channel_redb.rs 670 → ~290.
  • New buyer-store-core feature holds the shared table; redb implies it and adds only RedbBuyerChannelStore. A bare decdn-incentive build still links no redb. Node enables buyer-store-core only.
  • Byte- and behaviour-compat are now compiler-enforced rather than comment-enforced.

Verification

  • 2379 workspace tests; fmt / clippy / rustdoc (-D warnings) / doctests green, including the gated anvil-e2e and each feature config separately.
  • Golden-bytes test landed first, before any refactoring, captured from the pre-change encoder — and verified to actually trip (a field swap that compiles cleanly and breaks no other test is caught only by it). It also proved the byte-compat claim that had only ever been asserted in prose.
  • On-disk compatibility checked manually, which no suite can do (every suite builds a fresh store): wrote a channels.redb with the pre-change binary, opened it with the new code — buyer rows identical incl. an advanced watermark + deposit, seller co-tenant intact, new writes accepted. Re-run after the final table-plumbing change, since the golden pins record bytes but not the table name.

Review round (d7f747a)

A multi-agent review found real defects; each was reproduced before being fixed:

  • The hoist missed an operation — insert_raw_buyer_record never delegated, so the 8th write path stayed duplicated and the doc justifying insert_raw's visibility cited a caller that didn't exist. Now delegates; insert_raw moved behind a test-util feature (confirmed absent from the public API docs).
  • Dropped the TableDefinition parameter — it had exactly one valid inhabitant while admitting TableDefinition::new("typo_v1"), which compiles, reads an empty table, and tells the reclaim sweep there's nothing to reclaim. Making the table a private const made the invariant structural and shrank the diff.
  • The golden was blind to the worst swap — state(7) made channel_id and last_nonce byte-identical, so transposing the CAS guard passed. Regenerated with distinct per-field patterns; now catches all five same-typed swaps.
  • Two test gaps proven by mutation — the in-txn UnknownProvider branch had genuinely lost coverage, and the delegation tests asserted only the outcome enum, so swapping bytes_delivered/amount (a payment-watermark corruption) passed. Both mutants now fail.
  • Comments corrected — the dep:redb note described a collision (Cargo actually errors optional dependency 'redb' is not included in any feature); the TOCTOU note described the wrong race; open() had lost its doc; two comments claimed postcard was gated out when decdn-protocol pulls it unconditionally.
  • CI — --workspace unifies features, so decdn-cli turned on incentive/redb for everyone and the configs this split exists to create were never compiled. Added two direct clippy runs.

Known gap (pre-existing, follow-up)

decdn-cli has no tracing dependency and installs no subscriber, so load_all's skip-undecodable-row error! is a no-op for the client store — decdn channel clean can report "no tracked channels to clean" while the deposit is escrowed. Not introduced here (both stores behaved this way), and not fixable without changing the BuyerChannelStore trait to return the skipped providers. The doc now states this plainly rather than implying coverage that isn't there. Worth its own issue.

Deliberately preserved

  • Buyer load_all skips undecodable rows; seller load_all aborts startup. Asymmetric on purpose (PR feat(node): buyer-side PaymentChannel openChannel for cache-miss settlement (#744) #753) — propagating would stop the reclaim sweep and strand every other channel's deposit. Now documented on both sides, since the two live in different crates.
  • forget_if_channel commits even when nothing matched. Pre-existing in both stores; a hoist shouldn't change durability behaviour.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a shared buyer-channel storage layer with durable recording, lookup, updates, deposits, and safe removal.
    • Added feature options for buyer storage support and test utilities.
    • Improved compatibility with older and forward-compatible stored data.
  • Bug Fixes

    • Prevented lost updates during concurrent progress and deposit changes.
    • Added validation for corrupted, mismatched, or incompatible records.
    • Improved seller-record decoding and startup safety.
  • Tests

    • Expanded coverage for storage compatibility, corruption handling, concurrency, and feature configurations.

thiras and others added 5 commits July 17, 2026 03:58
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]>
)

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]>
…er 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]>
…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]>
)

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]>
Copilot AI review requested due to automatic review settings July 17, 2026 02:11
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 8408994a-f63f-4dea-8a83-272e5d1ab382

📥 Commits

Reviewing files that changed from the base of the PR and between bffef4f and d7f747a.

📒 Files selected for processing (8)
  • .github/workflows/ci.yml
  • crates/e2e/Cargo.toml
  • crates/incentive/Cargo.toml
  • crates/incentive/src/buyer_channel_redb.rs
  • crates/incentive/src/buyer_channel_table.rs
  • crates/incentive/src/lib.rs
  • crates/node/Cargo.toml
  • crates/node/src/channel_store.rs

Walkthrough

The PR centralizes buyer-channel redb persistence in a shared BuyerChannelTable, delegates incentive and node store operations to it, adds schema and corruption handling, wires feature gates across crates, tightens seller decoding, and expands tests and CI feature coverage.

Changes

Buyer channel storage

Layer / File(s) Summary
Shared table contract and codec
crates/incentive/Cargo.toml, crates/incentive/src/lib.rs, crates/incentive/src/buyer_channel_table.rs
Adds the buyer-store-core and test-util features, exposes the shared table module, and defines stable schema/versioned buyer record encoding and decoding.
Durable table operations and validation
crates/incentive/src/buyer_channel_table.rs
Implements durable CRUD, compare-and-delete, atomic progress/deposit updates, raw test insertion, corruption handling, compatibility checks, and concurrency tests.
Store delegation and seller decoding
crates/incentive/src/buyer_channel_redb.rs, crates/node/src/channel_store.rs
Delegates buyer-store operations through BuyerChannelTable, consolidates wiring tests, and tightens seller trailer decoding and startup error behavior.
Feature wiring and CI coverage
crates/node/Cargo.toml, crates/e2e/Cargo.toml, .github/workflows/ci.yml
Enables shared and test-only features in dependent builds, documents feature gating, and adds clippy checks for both feature-split configurations.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant BuyerStore
  participant BuyerChannelTable
  participant RedbDatabase
  BuyerStore->>BuyerChannelTable: record or mutate buyer state
  BuyerChannelTable->>RedbDatabase: read and update buyer row
  RedbDatabase-->>BuyerChannelTable: durable commit result
  BuyerChannelTable-->>BuyerStore: return state or operation outcome
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

Copy link
Copy Markdown

Contracts coverage

Line coverage: 88.92% (2488/2798 lines)
▲ +0.00pp vs base (88.92% → 88.92%)
Run: 29549316697

@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 consolidates the buyer-channel database logic by extracting the shared redb table operations and record codec from both the client-side and node-side stores into a single, unified BuyerChannelTable module. This refactoring eliminates duplicate code and ensures byte-compatibility across components. The review feedback suggests optimizing the forget and forget_if_channel operations in the new table implementation to avoid expensive synchronous disk writes (fsync) when no database records are actually modified.

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 on lines +335 to +346
let write_txn = self.begin_durable_write()?;
{
let mut table = write_txn
.open_table(BUYER_CHANNEL_TABLE)
.map_err(|err| StoreError::Backend(format!("open_table: {err}")))?;
table
.remove(&key)
.map_err(|err| StoreError::Backend(format!("remove: {err}")))?;
}
write_txn
.commit()
.map_err(|err| StoreError::Backend(format!("commit (fsync): {err}")))?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

In forget, if the provider key does not exist in the table, table.remove returns Ok(None) and no changes are made. Committing the transaction in this case still triggers a synchronous disk write (fsync). We can optimize this by checking if a record was actually removed and only committing the transaction if removed is true.

        let write_txn = self.begin_durable_write()?;
        let removed = {
            let mut table = write_txn
                .open_table(BUYER_CHANNEL_TABLE)
                .map_err(|err| StoreError::Backend(format!("open_table: {err}")))?;
            table
                .remove(&key)
                .map_err(|err| StoreError::Backend(format!("remove: {err}")))?
                .is_some()
        };
        if removed {
            write_txn
                .commit()
                .map_err(|err| StoreError::Backend(format!("commit (fsync): {err}")))?;
        }
References
  1. When performing database operations inside a write transaction with immediate durability (such as redb with Durability::Immediate), return early on no-write outcomes to allow the uncommitted transaction to abort naturally on drop, avoiding the expensive overhead of a synchronous disk flush (fsync) on a no-op commit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not taking this in this PR, for two reasons — but the underlying observation is right and I'll track it.

1. It's a behavior change to code this PR only moved. The unconditional commit is pre-existing and identical in both stores this hoist merges — on main, node's buyer_forget and incentive's forget both call .remove() then .commit() with no if removed guard. The whole value of this PR is that it's behavior-preserving: that's what lets the golden-bytes test and the pre-change-fixture round-trip actually mean something, and what makes it bisectable if a buyer-channel bug shows up later. Slipping a durability change into the same commit forfeits that.

2. The suggestion is incomplete, in a way that matters. Skipping the commit makes the table_exists() pre-check above it redundant, not just unnecessary — so the fix is bigger than this diff.

The pre-check exists only because the commit is unconditional. WriteTransaction::open_table creates the table, so today a forget on a never-written store would commit that creation. If you skip the commit, the txn drops uncommitted and redb rolls the creation back on its own.

I verified this rather than assuming it: deleting the pre-check from advance_progress (which already early-returns from inside the txn) leaves no_row_ops_do_not_create_the_table passing. The abort really does roll back the table creation.

So applying this patch as written trades one cost for another — you'd stop paying an fsync but keep paying a whole extra read transaction on every forget to guard against something that can no longer happen. The complete change drops the pre-check too, which means re-reasoning about no_row_ops_do_not_create_the_table and the same coupling in forget_if_channel. That deserves its own commit and its own justification, not a rider on a dedup.

Worth noting the cost is small: one wasted fsync per forget of an already-absent row, which is off the hot path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Tracked as #1260 — including the table_exists() coupling, since the complete fix removes the pre-check too.

Comment on lines +422 to +434
if matches {
table
.remove(&key)
.map_err(|err| StoreError::Backend(format!("remove: {err}")))?;
}
matches
};
// NOTE: unlike `advance_progress`/`add_deposit`, this commits even when
// nothing matched (an empty txn + fsync). Pre-existing behaviour in both
// stores; preserved deliberately rather than "fixed" here.
write_txn
.commit()
.map_err(|err| StoreError::Backend(format!("commit (fsync): {err}")))?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

In forget_if_channel, if matches is false, no changes are made to the table. Committing the transaction in this case is a no-op but still incurs the overhead of a synchronous disk write (fsync) due to Durability::Immediate. We can optimize this by only committing the transaction if deleted is true, allowing the transaction to be safely aborted on drop otherwise.

Suggested change
if matches {
table
.remove(&key)
.map_err(|err| StoreError::Backend(format!("remove: {err}")))?;
}
matches
};
// NOTE: unlike `advance_progress`/`add_deposit`, this commits even when
// nothing matched (an empty txn + fsync). Pre-existing behaviour in both
// stores; preserved deliberately rather than "fixed" here.
write_txn
.commit()
.map_err(|err| StoreError::Backend(format!("commit (fsync): {err}")))?;
if matches {
table
.remove(&key)
.map_err(|err| StoreError::Backend(format!("remove: {err}")))?;
}
matches
};
if deleted {
write_txn
.commit()
.map_err(|err| StoreError::Backend(format!("commit (fsync): {err}")))?;
}
References
  1. When performing database operations inside a write transaction with immediate durability (such as redb with Durability::Immediate), return early on no-write outcomes to allow the uncommitted transaction to abort naturally on drop, avoiding the expensive overhead of a synchronous disk flush (fsync) on a no-op commit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same call as the forget thread, and this one is preserved deliberately rather than by oversight — there's a NOTE on the commit saying so:

// NOTE: unlike `advance_progress`/`add_deposit`, this commits even when
// nothing matched (an empty txn + fsync). Pre-existing behaviour in both
// stores; preserved deliberately rather than "fixed" here.

Both pre-hoist implementations committed unconditionally here, so changing it would make this PR no longer a pure hoist — which is the property the golden-bytes test and the pre-change-fixture round-trip are there to certify.

The table_exists() coupling from the other thread applies here too: this op's unconditional commit is why the pre-check exists, so skipping the commit makes the pre-check redundant and the real change larger than the diff.

One correction to the framing: the reference note says "return early on no-write outcomes to allow the uncommitted transaction to abort naturally on drop." That's exactly what advance_progress and add_deposit already do in this module — and their doc comments say why. forget_if_channel is the deliberate exception, and making all four consistent is a reasonable follow-up. It just isn't this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Tracked as #1260, alongside the forget case — the fix should make all four no-row ops consistent rather than doing them piecemeal.

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

This PR removes the byte-identical duplication of the buyer-channel redb storage logic between decdn-node and decdn-incentive by hoisting the buyer table’s on-disk codec and all table operations into a single shared implementation (BuyerChannelTable). Both the node’s combined channels.redb store and the CLI’s buyer-only buyer-channels.redb store now delegate to that shared table, preserving on-disk format while making byte/behavior compatibility compiler-enforced.

Changes:

  • Introduce decdn_incentive::buyer_channel_table (feature buyer-store-core) containing the buyer record codec + all table operations + shared test suite (incl. golden-bytes pin).
  • Refactor both node and incentive buyer stores to delegate all operations to BuyerChannelTable, leaving each store responsible only for its own DB/file wiring.
  • Update feature wiring and CI to ensure the split feature configurations are actually compiled (non-unified decdn-incentive builds).

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated no comments.

Show a summary per file
File Description
crates/node/src/channel_store.rs Removes in-file buyer table implementation; delegates buyer ops and keeps node-specific wiring (combined channels.redb).
crates/node/Cargo.toml Enables decdn-incentive/buyer-store-core for node; wires test-util for anvil-e2e/tests to keep corruption seeding gated.
crates/incentive/src/lib.rs Exposes new buyer_channel_table module behind buyer-store-core; keeps module docs localized.
crates/incentive/src/buyer_channel_table.rs New shared buyer-table codec + ops + comprehensive tests, including golden-bytes compatibility pin.
crates/incentive/src/buyer_channel_redb.rs Slims to buyer-only file ownership + open() guards; delegates all operations to shared table.
crates/incentive/Cargo.toml Adds buyer-store-core feature (redb+postcard) and keeps redb as the buyer-only store feature; adds test-util gate for raw inserts.
crates/e2e/Cargo.toml Updates commentary to reflect that the shared buyer-table core now compiles via node dependency.
.github/workflows/ci.yml Adds explicit clippy runs for decdn-incentive with --no-default-features and with buyer-store-core to avoid feature-unification blind spots.

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

@github-actions

Copy link
Copy Markdown

Coverage report

Total: 81.21% (was 81.13%, ▲ +0.08%) — 48328/59510 lines

File Coverage Lines Δ
crates/incentive/src/buyer_channel_redb.rs 96.43% 162/168 ▲ +8.98%
crates/incentive/src/buyer_channel_table.rs 91.26% 637/698 new
crates/node/src/channel_store.rs 89.73% 970/1081 ▲ +1.85%
History
Commit Total Δ vs base
d7f747a (HEAD) 81.21% ▲ +0.08%

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.

refactor(node,incentive): delete node's byte-identical buyer-store re-implementation; hoist the shared codec into incentive

2 participants