Skip to content

feat(id/currency_poc): bind LedgerBackend to the official TigerBeetle Rust client (#2289) - #5072

Merged
dezren39 merged 4 commits into
mainfrom
queue/8190-2289-tigerbeetle-client-binding
Nov 3, 2026
Merged

dezren39 merged 4 commits into
mainfrom
queue/8190-2289-tigerbeetle-client-binding

Conversation

@dezren39

@dezren39 dezren39 commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Closes the remaining #2289 acceptance gap (follow-on to PR #3873 / task 5239): the conversion-executor PoC scenarios now run against a live single-replica TigerBeetle cluster, not only the in-memory backend.

What

  • currency_poc::tb_ledger::TigerBeetleLedger (new, behind the new currency-poc-tb feature): implements the LedgerBackend seam over the official tigerbeetle Rust client, pinned =0.17.9 — exactly the harness's pinned server version. Default builds don't link tb_client.
    • Owns a current-thread tokio runtime to bridge the sync trait to the async client (documented: drive from sync code only).
    • Maps the PoC's status subset onto AccountError/TransferError; unmodelled statuses and transport errors panic loudly instead of being folded into a wrong variant.
    • TigerBeetle rejects code = 0; the binding sends a substitute wire code and restores original codes on lookups, so recovery's leg-equality check (found == leg) still holds.
    • transfers_with_user_data_128 uses query_transfers with a user_data_128 filter.
  • Live scenario tests (ignored by default; need the pinned binary via TIGERBEETLE_POC_BINARY or PATH): posted conversion findable by user_data_128, atomic failure moves nothing, crash-after-submission recovery without double-posting, crash-before-submission resubmission with the same IDs — all against harness::TestCluster.
  • Harness fix: verify_pinned_version rejected the real release binary, which reports 0.17.9+cc1c06a — TestCluster could never start against the pinned release. It now accepts the exact pin or pin + build-metadata suffix only (unit-tested both ways).

Verification (laptop, pinned binary 0.17.9)

  • Live: cargo test -p id --lib --features currency-poc-tb currency_poc -- --ignored → 5 passed (harness cluster smoke + 4 live scenarios).
  • With feature: cargo test -p id --lib --features currency-poc-tb currency_poc → 44 passed.
  • Default features: cargo test -p id --lib currency_poc → 44 passed (binding cfg'd out cleanly).
  • Note: full cargo test -p id still hits the pre-existing ChainExt checkpoint E0063 compile failure in unrelated integration targets (aliases etc.) that is present on current main itself — not touched by this PR; the lib target is green.

Queue: task 8190 (repo-health-code-pilot), lane code-b.


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

… Rust client (#2289)

TigerBeetleLedger implements the LedgerBackend seam over the tigerbeetle crate pinned to =0.17.9 (the harness server version), behind the new currency-poc-tb feature so default builds do not link tb_client. It owns a current-thread tokio runtime for the sync trait, maps the PoC status subset onto AccountError/TransferError, and translates code 0 to a non-zero wire code (restored on lookups so recovery leg equality holds).

Live scenario tests (ignored by default, need the pinned binary) run the acceptance paths against a real single-replica TestCluster: posted conversion findable by user_data_128, atomic failure, crash-after-submission and crash-before-submission recovery. Verified on the laptop against tigerbeetle 0.17.9: live 5/5 (incl. harness smoke), in-memory suite 44/44 with and without the feature.

Also fix harness::verify_pinned_version: the real release binary reports 0.17.9+cc1c06a, which the exact-match check rejected, so TestCluster could never start against the pinned release. Accept the pin plus build-metadata suffix only.
@dezren39
dezren39 requested a review from a team as a code owner November 3, 2026 18:38
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T21:23:34.806775Z 13cb9d2 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 11 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 43e7cf45-d6ad-442b-b65c-ae7ba12ffd52
Commits

Reviewing files that changed from the base of the PR and between bd4466c and 13cb9d2.

Files ignored due to path filters: 1
  • pkgs/id/Cargo.lock is excluded by !**/*.lock
Files selected for processing: 7
  • doc/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding.md
  • pkgs/id/Cargo.toml
  • pkgs/id/src/currency_poc/harness.rs
  • pkgs/id/src/currency_poc/ledger.rs
  • pkgs/id/src/currency_poc/mod.rs
  • pkgs/id/src/currency_poc/tb_ledger.rs
  • pkgs/id/src/currency_poc/tests.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ee226824d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread pkgs/id/src/currency_poc/tb_ledger.rs Outdated
Comment on lines +45 to +49
fn wire_code(code: u16) -> u16 {
if code == 0 {
ZERO_CODE_SUBSTITUTE
} else {
code

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve distinct identities for codes zero and one

When an account or transfer created with code = 0 is retried with the same ID and code = 1, both requests serialize identically because zero is replaced with one. TigerBeetle therefore reports Exists instead of ExistsWithDifferentFields, and the registry then makes lookups report the new code even though the original record was immutable. This violates the backend's field-sensitive idempotency contract. Use a reversible representation that distinguishes these two supported code values rather than mapping both to the same wire record.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Disposition (queue task 8190, repo-worker-code): accepted — fix required before merge. Mapping code 0 to 1 before create collapses two distinct identities into one serialized record, masking ExistsWithDifferentFields and letting the registry report a code the immutable record does not carry. Fix: preserve exact code semantics on create (no silent 0→1 substitution) and add a regression test that retries the same ID with code 0 then code 1. Task 8190 is parked on this finding set; PR #5072 will not merge past it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ecf15d3: codes are now sent shifted by one (wire_code/poc_code form a bijection on 0..=u16::MAX-1), so codes 0 and 1 serialize distinctly and a retry with a different code surfaces ExistsWithDifferentFields. Covered by live test live_codes_zero_and_one_stay_distinct (pinned tigerbeetle 0.17.9, passing).

Comment thread pkgs/id/src/currency_poc/tb_ledger.rs Outdated
Comment on lines +258 to +259
for transfer in batch {
registry.insert(transfer.id, transfer.code);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Update code registries only after successful creation

If a posted conversion transfer has code 1 and another submission reuses its ID with code 2, TigerBeetle rejects that submission with ExistsWithDifferentFields, but this unconditional insert has already replaced the cached code with 2. Subsequent lookups now misrepresent the original transfer, so reconcile in recovery.rs fails its found == leg comparison and reports an otherwise correctly posted conversion as Inconsistent. The account registry has the same problem. Preserve existing registry entries when creation is rejected and derive updates from successful results rather than attempted requests.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Disposition (queue task 8190, repo-worker-code): accepted — fix required before merge. The registry insert must happen only after TigerBeetle confirms creation; on ExistsWithDifferentFields the cached code must keep describing the original immutable transfer, otherwise reconcile in recovery.rs compares against a code that was never stored. Fix: move the registry update behind the successful-create result and add a conflicting-retry regression test. Task 8190 is parked on this finding set; PR #5072 will not merge past it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ecf15d3: both registries are now updated only after TigerBeetle accepts the creation (Created or Exists); a rejected ExistsWithDifferentFields retry leaves the registry untouched, so lookups keep reporting the stored record's code. Covered by live test live_codes_zero_and_one_stay_distinct (lookup still reports code 0 after the rejected code-1 retry), passing.

Comment thread pkgs/id/src/currency_poc/tb_ledger.rs Outdated
Comment on lines +306 to +309
let filter = tb::QueryFilter {
user_data_128: value,
limit: 8_189,
..Default::default()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve exact matching for zero-valued transfer metadata

When transfers_with_user_data_128(0) is called, this query returns transfers belonging to nonzero conversion IDs as well as zero-stamped funding transfers: TigerBeetle treats zero as disabling the metadata filter, as specified in the QueryFilter documentation. Funding transfers actually use zero in this PoC, and LedgerBackend promises exact matching, which InMemoryLedger implements with an equality predicate. Handle zero explicitly, using exact post-filtering over a complete paginated scan if necessary, rather than returning unrelated conversions.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Disposition (queue task 8190, repo-worker-code): accepted — fix required before merge. TigerBeetle treats user_data_128 = 0 in a QueryFilter as "no filter", so transfers_with_user_data_128(0) over-returns nonzero conversion transfers alongside zero-stamped funding transfers. Fix: handle the zero case exactly (post-filter or a dedicated path) so callers get exact matching, with a mixed zero/nonzero regression test. Task 8190 is parked on this finding set; PR #5072 will not merge past it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ecf15d3: transfers_with_user_data_128 now pages through query results (timestamp-advanced) and post-filters on exact user_data_128 equality for every value, so value 0 returns only zero-stamped transfers. Covered by live test live_zero_user_data_128_query_matches_exactly (only the 2 funding transfers match after a conversion posts), passing.

Status::OverflowsCreditsPending
| Status::OverflowsCreditsPosted
| Status::OverflowsCredits => Err(TransferError::CreditsMustNotExceedDebits),
other => panic!("tigerbeetle create_transfers returned unmodelled status {other:?}"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle previously failed transfer IDs during recovery

After the insufficient-liquidity failure exercised by live_atomic_failure_moves_nothing, the intent remains Submitted and none of its legs can be looked up. reconcile with RecoveryPolicy::Resubmit therefore retries those IDs, but the pinned TigerBeetle version remembers transient failures and returns IdAlreadyFailed, as documented in create_transfers. That expected recovery result reaches this panic, aborting the entire scan instead of reporting ResubmissionRejected and processing later intents as recovery.rs:110-121 intends. Represent IdAlreadyFailed as a regular non-success transfer error and add a live failure-then-recovery scenario.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Disposition (queue task 8190, repo-worker-code): accepted — fix required before merge. Recovery Resubmit replays transfer IDs that the pinned TigerBeetle version remembers as failed, so resubmission hits IdAlreadyFailed instead of recreating the legs. Fix: treat IdAlreadyFailed (and the equivalent account path, if any) as a terminal per-ID outcome in the resubmit path — record it on the intent rather than erroring the whole reconcile — with a regression test modeled on live_atomic_failure_moves_nothing. Task 8190 is parked on this finding set; PR #5072 will not merge past it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ecf15d3: CreateTransferStatus::IdAlreadyFailed now maps to a new TransferError::IdAlreadyFailed (a regular non-success error) instead of panicking, so reconcile reports ResubmissionRejected and continues. Covered by new live test live_failed_conversion_recovery_reports_resubmission_rejected, passing.

…nding (#2289)

- Preserve distinct identities for codes 0 and 1: codes are sent
  shifted by one (wire_code/poc_code bijection) instead of mapping
  0 to a substitute that collided with code 1, so a retry with a
  different code reports ExistsWithDifferentFields.
- Update the account/transfer code registries only after TigerBeetle
  accepts a creation (Created/Exists); a rejected retry no longer
  rewrites what lookups report for the stored record.
- transfers_with_user_data_128: exact matching for value 0 — the
  server treats a zero filter as no filter, so page through results
  and post-filter on equality for every value.
- Map CreateTransferStatus::IdAlreadyFailed to a new
  TransferError::IdAlreadyFailed instead of panicking, so recovery
  resubmission of a previously failed conversion reports
  ResubmissionRejected and the scan continues.

Live tests (pinned tigerbeetle 0.17.9): new
live_codes_zero_and_one_stay_distinct,
live_zero_user_data_128_query_matches_exactly, and
live_failed_conversion_recovery_reports_resubmission_rejected;
all 8 live scenarios pass (serial runs; parallel cluster starts
intermittently exceed the harness 30s readiness window under load).
In-memory suite: 44 passed. Pre-existing on main: pkgs/id
integration-test targets fail to compile (ChainExt checkpoint
field) — unrelated to this change.
@dezren39

dezren39 commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

agent-note:v1
state: Codex findings fixed (task 8190, lane code-n) — commit ecf15d3

All four P2 findings from the Codex review are fixed on this branch, each dispositioned on its thread:

  1. Code 0/1 identity collapse → wire codes are now a +1 bijection (wire_code/poc_code).
  2. Registry updated before successful creation → registries now update only on Created/Exists results.
  3. transfers_with_user_data_128(0) over-return → paginated scan with exact post-filtering for every value.
  4. IdAlreadyFailed panic on recovery resubmit → new TransferError::IdAlreadyFailed; reconcile reports ResubmissionRejected.

Verification (laptop, pinned TigerBeetle 0.17.9 binary):

  • In-memory currency_poc suite: 44 passed, 0 failed.
  • Live suite: all 8 scenarios pass, including the 3 new ones (live_codes_zero_and_one_stay_distinct, live_zero_user_data_128_query_matches_exactly, live_failed_conversion_recovery_reports_resubmission_rejected). Live runs were serial: under the laptop's current load, parallel cluster starts intermittently exceed the harness's 30s readiness window — every failure seen was a startup timeout, and every test that got a ready cluster passed.

Pre-existing, unrelated: the pkgs/id integration-test targets (tests/search.rs, tests/tag_claims.rs, tests/retention_pruning.rs, tests/documents.rs, tests/event_store_properties.rs) fail to compile on clean origin/main — ChainExt gained a checkpoint field without those initializers being updated. Not touched by this PR.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ecf15d3bca

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +9 to +13
//! - The trait is synchronous; the client is async but runtime-
//! agnostic (it runs its own off-thread event loop). The binding
//! owns a private current-thread tokio runtime and `block_on`s each
//! request. It must therefore be driven from plain synchronous code
//! (as the PoC executor is) — never from inside a tokio runtime.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add the required dated design record for the live binding

This new backend introduces architectural trade-offs around the private Tokio runtime, reversible wire-code encoding, and panic-based handling of unsupported statuses, but the commit adds no dated design record. Repository-wide Markdown searches for tb_ledger, currency-poc-tb, LedgerBackend, and related identifiers found no existing document covering this binding. pkgs/id/AGENTS.md explicitly requires significant features and non-obvious design decisions to be documented before implementation; add the required dated document explaining these decisions and their constraints rather than recording them only in module comments.

AGENTS.md reference: pkgs/id/AGENTS.md:L159-L168

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 082158d: added the dated design record at doc/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding/ (pkgs/id/docs symlinks to the repo doc/ tree), covering the private Tokio runtime behind the synchronous trait, the reversible +1 wire-code encoding, registry update rules, the status-mapping/panic stance including IdAlreadyFailed, and exact user_data_128 query semantics. The record notes it documents the as-built design and that document-first was missed on the original implementation.

…ng (#2289)

Required by pkgs/id/AGENTS.md for significant features and
non-obvious design decisions; requested by Codex review on PR #5072.
Records the as-built design of pkgs/id/src/currency_poc/tb_ledger.rs:
feature gate, private Tokio runtime behind the synchronous trait,
reversible +1 wire-code encoding, registry update rules, status
mapping and panic stance (incl. IdAlreadyFailed), and exact
user_data_128 query semantics.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 082158d334

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread pkgs/id/src/currency_poc/tb_ledger.rs Outdated
Comment on lines +309 to +312
results
.iter()
.map(|result| map_transfer_status(result.status))
.collect()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve successful retries of already-posted linked chains

When a conversion is executed again with the same request and sufficient remaining liquidity, prepare reuses its persisted intent, but this direct status mapping makes submit reject the retry. The pinned TigerBeetle implementation treats any status other than created, including exists, as breaking a linked chain: the first existing leg returns Exists and subsequent legs return LinkedEventFailed. Consequently, ConversionExecutor::submit returns an error and leaves the previously posted intent downgraded to Submitted, unlike the in-memory backend's idempotent behavior. Verify the stored legs and recognize a fully identical posted chain as successful, or avoid resubmitting an already-posted intent; add a live same-request-twice scenario.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 13cb9d2. The binding now translates the already-posted linked-chain pattern back to the in-memory semantics: when a whole chain reports Exists (first leg) + LinkedEventFailed (later legs) AND every stored leg verifies identical to the submitted leg via lookup, all legs report Err(Exists), which ConversionExecutor::submit accepts as idempotent success. A genuinely failed chain never starts with Exists, and a differing stored leg fails verification, so both keep the raw mapping. Covered by the new live scenario live_same_request_twice_posts_once (same request executed twice: Posted both times, balances unchanged, 3 legs stored once) — live suite 8/8 pass serially against the pinned 0.17.9 binary, in-memory suite 44/44. Design record updated with a "Linked-chain retry" section.

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.

1 participant