Skip to content

perf(node,payments): flush lanes in redb key order, enforce monotonic floor loss - #1780

Merged
thiras merged 3 commits into
mainfrom
feat/redb-4-2-adoption
Aug 24, 2026
Merged

thiras merged 3 commits into
mainfrom
feat/redb-4-2-adoption

Conversation

@thiras

@thiras thiras commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Follow-up to #1778 (redb 4.1.0 → 4.2.0), which was lockfile-only. This is the code that exploits the bump, plus a contract contradiction and a doc drift found while surveying the call sites.

What changes

Lane flush commits in table-key order. channel_store::flush drains a HashSet of dirty lanes, so the batch reached redb in an arbitrary order. Sorting by the pool_id ‖ signer ‖ provider table key first hits redb's append fast path, which fills a leaf page before opening the next instead of leaving each one part-full at a random split point. Measured over 512 lanes: 47 leaf pages against 65-68, about 30% fewer. The gain lands on keys appended past the end of the table — new lanes and the cold-load case — since an overwrite of a hydrated lane replaces in place whatever order it arrives in.

redb = "4.2" floor. Load-bearing, not cosmetic: the append fast path arrives in 4.2, and below it the same sort is a 1.31x pessimization. A lockfile regeneration resolving under the floor would silently invert the change.

PoolFloorLossStore enforces its monotonic contract. The trait doc claimed the total was monotonic "by caller discipline", but the callers are floor-reservation drops that persist from independent blocking tasks and cannot order their writes against each other. The redb store already clamped while the in-memory store overwrote, so every test written against the memory store misrepresented what ships. Both impls now raise and never lower, with forget_loss the only downward transition. The redb store aborts instead of committing when the total does not advance, so a late, smaller write costs no fsync — this table shares one file with the lane table, where an unconditional commit contended with the periodic voucher flush.

Doc drift. Five comments named the node's database pools.redb; it is lanes.redb.

Review

Reviewed by four agents. They found no bugs in the code — abort safety, sort correctness, and the contract change were each independently confirmed — but they found several claims about the code that were wrong. All fixed in the second commit:

  • The initial Table::entry() rewrite of record_loss was a pessimization sold as an optimization: entry() traverses to decide Occupied/Vacant, OccupiedEntry::get() traverses again, insert() a third time, so the advancing path cost 3 traversals where plain get + insert cost 2. Reverted to get + conditional insert, keeping only the commit guard.
  • The 4.2 floor was first justified by a panic that cannot reach this table — 4.1 has no in-place-append path at all, and 200k ascending inserts at this key/value shape do not panic on it.
  • "About half as many pages" was redb's headline for a different value shape; the real figure here is ~30%.
  • The trait doc described callers reading their totals on blocking threads; they read under a lock and only the write is dispatched.

Testing

cargo nextest run — 2940 passed. clippy --workspace --all-targets -D warnings, the two decdn-incentive --no-default-features configs, cargo doc -D warnings, cargo deny, and pre-commit run --all-files all clean.

Seven tests added, each mutation-checked:

  • flush_of_a_large_batch_lands_packed_and_round_trips bounds TableStats::leaf_pages() at ≤55. Removing the sort_by_table_key call from flush trips it at 67 — this is the only assertion tying flush to the sort, since record's HashSet means a test cannot choose the snapshot's input order.
  • concurrent_out_of_order_totals_settle_on_the_max — 8 threads × 64 jumbled totals on one pool. Fails if the compare moves outside the write transaction.
  • floor_loss_stores_agree_on_monotonicity runs one assertion over both impls, so the memory store used in tests speaks for the redb store that ships.
  • redb_pool_floor_loss_non_regression_survives_reopen lands the smaller total last before reopening, so it pins the durable outcome rather than a value.

Notes for the reviewer

Skipping the commit on the no-op path is sound only because every writer of lanes.redb uses Durability::Immediate, so the stored total is already durable. That invariant is now stated at the return; a Durability::None writer anywhere in that file would break it silently.

Three findings are deliberately left for separate issues:

  1. The forget_loss / in-flight record_loss resurrection race is pre-existing, but monotonicity removes the only mechanism that could previously correct the row downward, so a closed pool's dead charge now leaks into every subsequent boot.
  2. No metric on floor-loss persist failure. redb 4.2 latches the database after a failed commit, so one flush failure could silently stop all dead-charge persistence for the process lifetime — lane_flush_failure has a counter, this path has none.
  3. No integration-level floor-loss coverage in tests/channel_state_store.rs.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JjiDQL7FuB8UHGBBpG1PjH

thiras and others added 2 commits August 24, 2026 04:30
…loor-loss store

Two redb 4.2.0 follow-ups, plus a contract contradiction found alongside them.

`channel_store::flush` drains a `HashSet` of dirty lanes, so the batch reached
redb in an order randomized per process. Sorting it by the table key first lets
the insert loop append rightward through the B-tree instead of splitting a page
per key: the `lane_state_v1` table holds about half as many pages and the
full-table scan at the next open runs sequentially. Tombstones sort alongside
the writes, so a flush is fully deterministic. The workspace floor moves to
`redb = "4.2"` because that is load-bearing, not cosmetic — 4.2 is the first
release that walks a large ascending batch inside one transaction without
panicking on a leaf page that fills through in-place appends, and `redb = "4"`
would let a lockfile regeneration resolve back below it.

`PoolFloorLossStore` documented its total as monotonic "by caller discipline",
but the callers are floor-reservation drops that each read their own cumulative
total on their own blocking thread, so no caller can impose an ordering. The
redb store already clamped while the in-memory store overwrote, leaving tests
written against the memory store unrepresentative of what ships. Both impls now
raise the stored total and never lower it, with `forget_loss` the only downward
transition. The redb store resolves the row through one `redb::Table::entry`
lookup and drops the transaction instead of committing when the total does not
advance, so a late, smaller write costs no fsync — this table shares one file
with the lane table, where an unconditional commit contended with the periodic
voucher flush.

Four doc comments in `crates/incentive` named the node's combined database
`pools.redb`; it is `lanes.redb`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JjiDQL7FuB8UHGBBpG1PjH
…g gap

Review of the parent commit found the `Table::entry()` rewrite of `record_loss`
was a pessimization sold as an optimization. `entry()` traverses the tree to
decide Occupied vs Vacant, `OccupiedEntry::get()` traverses again, and
`insert()` a third time, so the advancing path cost three traversals where the
plain `get` + `insert` it replaced cost two. Revert to `get` + conditional
`insert` and keep only the commit guard: one traversal when the total does not
advance, two when it does, better than either previous shape. This also drops
the `redb::Entry` import and the `StorageError::Corrupted` class that
`OccupiedEntry::get()` introduces.

The no-op path now calls `WriteTransaction::abort()` explicitly rather than
leaning on drop. redb's `Drop` discards an abort error behind its `logging`
feature, which this build does not enable, so the failure vanished entirely.
The comment also records what makes the skipped commit sound: every writer of
this file uses `Durability::Immediate`, so the stored total is already durable.
A `Durability::None` writer here would break it silently.

Three claims were wrong. The `redb = "4.2"` floor was justified by a panic that
cannot reach this table — 4.1 has no in-place-append path at all, and 200k
ascending inserts at this key and value size do not panic on it. The real
reason is that the append fast path arrives in 4.2 and the same sort is a
1.31x pessimization below it. "About half as many pages" was redb's headline
for a different value shape; measured here it is about 30% (47 leaf pages
against 65-68), and the gain lands on appends past the end of the table, not on
the overwrites that dominate a steady-state flush. The trait doc said callers
read their totals on their own blocking threads; they read under a lock and
only the write is dispatched.

`flush_of_a_large_descending_batch_round_trips` claimed a descending order that
`record`'s `HashSet` erases before the snapshot exists, and asserted nothing the
sort affects. Renamed, and it now bounds `TableStats::leaf_pages()` — removing
the `sort_by_table_key` call from `flush` trips it at 67. That closes the wiring
gap the parent commit left open and pins the performance claim.

Adds a concurrent out-of-order writer test, the interleaving the monotonic
contract exists for, which fails if the compare moves outside the write
transaction.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JjiDQL7FuB8UHGBBpG1PjH
@thiras

thiras commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

Follow-ups from the review, filed rather than folded in:

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

Optimizes redb lane flushing and enforces monotonic floor-loss persistence across implementations.

Changes:

  • Sorts lane flushes by table key and requires redb 4.2.
  • Makes floor-loss updates monotonic while skipping no-op commits.
  • Updates database documentation, changelog entries, and regression tests.

Reviewed changes

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

Show a summary per file
File Summary Review status
crates/node/src/handlers/client/mod.rs Clarifies floor-loss persistence. No final comments
crates/node/src/channel_store.rs Sorts flushes and tests persistence behavior. No final comments
crates/incentive/src/store.rs Updates the floor-loss contract and memory store. Moderate (3 votes): absent zero writes should be a no-op in memory, matching redb
crates/incentive/src/buyer_pool_table.rs Corrects node database references. Nit (3 votes): update one remaining pools.redb reference
crates/incentive/src/buyer_pool_redb.rs Updates database documentation. No final comments
crates/incentive/Cargo.toml Updates related documentation. No final comments
CHANGELOG.md Documents persistence and performance changes. Two nits (4 votes each): correct scheduling wording and malformed sentence
Cargo.toml Raises the redb dependency floor to 4.2. No final comments

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread CHANGELOG.md Resolved
Comment thread CHANGELOG.md Resolved
Comment thread crates/incentive/src/store.rs Resolved
@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.60% (was 81.57%, ▲ +0.03%) — 64835/79450 lines

File Coverage Lines Δ
crates/incentive/src/buyer_pool_redb.rs 94.25% 164/174 ● 0.00%
crates/incentive/src/buyer_pool_table.rs 90.18% 817/906 ● 0.00%
crates/incentive/src/store.rs 92.11% 280/304 ▲ +0.47%
crates/node/src/channel_store.rs 86.85% 1228/1414 ▲ +1.12%
crates/node/src/handlers/client/mod.rs 92.13% 1206/1309 ▲ +0.08%
History
Commit Total Δ vs base
df1ef34 81.60% ▲ +0.03%
775a826 (HEAD) 81.60% ▲ +0.03%

…ngelog prose

Review of #1780 caught a divergence the `entry()` revert introduced. The redb
store reads an absent row as zero and writes only when the total exceeds it, so
`record_loss(pool, 0)` on a fresh pool leaves no row. The memory store reached
the row through `entry().or_insert(0)`, which materializes a `(pool, 0)` row
before the clamp runs. Two impls disagreeing about a money-adjacent row is the
exact defect this branch set out to remove, so the memory store now mirrors the
redb one step for step: read-or-zero, compare, write only on a raise.

The shared conformance assertion gains the zero case, which is what would have
caught this — it only ever exercised non-zero totals before.

Changelog prose: a sentence lost its verb during an earlier edit ("resolves the
row aborts the transaction"), and the caller description still said drops read
their totals on their own blocking thread. They read under the pool-map lock;
only the write is dispatched. The trait doc was already corrected, the changelog
was not.

One `pools.redb` reference survived the rename, at `buyer_pool_table.rs:852`.
It shares a line with `buyer-pools.redb`, so the `grep -v` filter used to verify
the rename discarded the whole line and reported none left.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JjiDQL7FuB8UHGBBpG1PjH
@thiras
thiras merged commit 3a756a2 into main Aug 24, 2026
27 checks passed
@thiras
thiras deleted the feat/redb-4-2-adoption branch August 24, 2026 02:15
alpergundogdu added a commit that referenced this pull request Aug 24, 2026
…t failures (#1784)

* fix(node,payments): tombstone forgotten floor-loss rows, meter persist failures

Close the forget_loss/record_loss resurrection race (#1781): a
FloorReservation drop snapshots its cumulative total under the floor lock,
then persists it from an independent blocking task, so the write could land
after forget_pool_floor's durable delete and re-insert a row for a closed
pool — permanent since #1780 made record_loss monotonic. forget_loss now
deletes the row and tombstones the pool id in one redb transaction, and
record_loss checks the tombstone inside its own write transaction, making
the late write a no-op. Handler bring-up sweeps the tombstones before
hydration — the one point where no persist can be in flight — bounding
their growth to one process lifetime.

Instrument the drop-time persist (#1782): a new
decdn_floor_loss_persist_failures_total counter fires on every failed
record_loss, both dispatch paths log the µUSDC total that failed to reach
disk, and redb corruption maps to StoreError::Corrupt and logs at error! —
a corrupt or write-latched lanes.redb fails every later persist until the
file is reopened, unlike a transient fault. Registry row in the
observability appendix and a Prometheus alert added.

Add the missing integration coverage (#1783): record_loss racing the lane
flush on the shared redb file, two sequential drops through the real Drop
guard driving the store's monotonic contract, the #1781 interleaving made
deterministic with a gated store, and restart hydration distinguishable
from overwrite semantics (the smaller total lands last).

Closes #1781. Closes #1782. Closes #1783.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EtAhosYcK8HGWFRUCT2QfJ

* docs(adr): anchor the ADR 003 pool-solvency cross-link in the metrics registry

The appendix registry row for decdn_floor_loss_persist_failures_total linked
003-payments.md bare; the ADR reference-hygiene gate requires every cross-ADR
link to carry a resolving #heading anchor.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EtAhosYcK8HGWFRUCT2QfJ

* docs(node): correct tombstone-sweep comments in the floor-loss store

The sweep's existence probe distinguishes "table never created" from "no
tombstones" — any committed record_loss creates the table empty as a side
effect of its in-transaction check — and the per-tombstone row removal is a
defensive no-op, not a repair of leaked rows (a row without a tombstone is
untouched by the sweep). Say both accurately, and keep forget_loss's
no-early-return rationale in present tense.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EtAhosYcK8HGWFRUCT2QfJ

* fix(node,payments): close the floor-loss error-path and in-memory residuals (#1786)

* fix(node,payments): close the floor-loss error-path and in-memory residuals

Review follow-ups on the #1781/#1782 fix:

- forget_pool_floor: a failed forget_loss leaves the closed pool's row with
  no tombstone, open to permanent re-insertion by a late drop-dispatched
  record_loss — the #1781 leak through the error path. Count it under
  floor_loss_persist_failures so DecdnFloorLossPersistFailures covers this
  mode, and surface a corrupt payment store at error!, mirroring the
  drop-time persist. Outcome handling lives in note_forget_outcome; metric
  docs, the registry row, and the alert text now name both write paths.
- release_live_repaid: get_mut instead of entry().or_default(), so a
  repayment that lands after forget_pool_floor removed the pool's entry
  cannot re-insert a default state for the closed pool — the in-memory face
  of the same resurrection race, which the drop guard already avoids.
- sweep_forgotten: drop the separate read-transaction existence probe; the
  write transaction's no-op abort already rolls back table creation, the
  same property record_loss's in-transaction check relies on.
- Reword two test docstrings into present-tense counterfactuals.
- New tests: a repaid release after forget leaves the map untouched, and a
  failed forget bumps the persist-failure counter.

Co-Authored-By: Claude <[email protected]>
Claude-Session: https://claude.ai/code/session_013d9kpLBeSy4kRmBazVEy7x

* docs(node): name both dead-charge log lines in the alert and metric docs

Review-bot follow-up on the failure-signal wording: the alert header and
summary say "writes", not "persists", and both the alert comment and the
counter's field doc cite the warn!/error! pair for the persist and forget
paths.

Co-Authored-By: Claude <[email protected]>
Claude-Session: https://claude.ai/code/session_013d9kpLBeSy4kRmBazVEy7x

---------

Co-authored-by: Claude <[email protected]>

---------

Co-authored-by: Claude <[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.

2 participants