diff --git a/doc/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding.md b/doc/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding.md new file mode 100644 index 0000000000..807882672f --- /dev/null +++ b/doc/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding/2026-11-03T20-36-00Z_design_tigerbeetle_ledger_binding.md @@ -0,0 +1,125 @@ +# Design: TigerBeetle LedgerBackend binding (`tb_ledger`) + +Issue: #2289 (conversion-executor PoC, acceptance item 1). Code: +`pkgs/id/src/currency_poc/tb_ledger.rs`, behind the `currency-poc-tb` +feature. PR: #5072. + +This record documents the as-built design of the live binding. Per +`pkgs/id/AGENTS.md` ("Documenting Design & Architecture Decisions") +it should have been written before implementation; it was filed +during PR #5072 review after a Codex finding (2026-11-03) pointed +out the gap, and records the decisions and constraints the module +comments only summarized. + +## Intent + +`currency_poc` defines a synchronous `LedgerBackend` trait whose +reference implementation, `InMemoryLedger`, encodes the TigerBeetle +semantics the conversion executor depends on (atomic linked chains, +field-sensitive idempotent transfer IDs, balance-invariant flags). +The binding implements the same trait over the official TigerBeetle +Rust client (`tigerbeetle` crate, pinned to the harness server +version 0.17.9) so the executor scenarios run against a real +single-replica test cluster (`currency_poc::harness::TestCluster`), +not only the in-memory model. + +## Decisions + +### Feature gate + +The binding is behind `currency-poc-tb` so default builds of the +`id` crate do not link the client's native `tb_client` library. +The harness and live tests are gated the same way; live tests are +additionally `#[ignore]`d and need the pinned binary +(`TIGERBEETLE_POC_BINARY` or `tigerbeetle` on `PATH`). + +### Private runtime, synchronous surface + +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, where `block_on` would +panic. One client (and runtime) per ledger instance. + +### Cluster identity + +The harness formats its data file with cluster ID 0, so the client +connects with cluster ID 0. This is a test-harness binding, not a +production deployment story. + +### Reversible wire-code encoding + +TigerBeetle rejects `code = 0` on accounts and transfers, while the +PoC types use 0 as a supported chart-of-accounts code. Codes are +sent shifted by one (`wire_code`: `c -> c + 1`; `poc_code` is the +inverse). The shift is a bijection on `0..=u16::MAX - 1`, so every +supported code stays distinct on the wire. The earlier design — +substituting a constant for 0 only — serialized codes 0 and 1 +identically, so a retry with the other code reported `Exists` +instead of `ExistsWithDifferentFields`, breaking the backend's +field-sensitive idempotency contract (Codex review, PR #5072). +`u16::MAX` has no wire representation under the shift (it would +wrap to 0) and panics as a programming error; the PoC's codes are +small chart-of-accounts values. + +### Code registries + +TigerBeetle stores only the wire code, so the binding records the +original code of every account/transfer it creates and restores it +on lookups (a looked-up leg must compare equal to the persisted +intent leg the recovery scanner checks). Registries are updated +**only after** TigerBeetle accepts a creation (`Created`, or +`Exists` confirming identical fields): a rejected retry must not +overwrite the registry, or later lookups would misreport the stored +record (Codex review, PR #5072). For records the registry does not +know (e.g. created by an earlier binding instance), lookup decodes +the wire code with `poc_code`. + +### Status mapping and panic stance + +Result statuses are mapped onto the PoC error enums for the subset +the PoC models. An unmodelled status — or a transport-level client +error, for which the trait has no channel — panics with the +status/error named rather than being silently folded into a wrong +variant. One exception is modelled explicitly: `IdAlreadyFailed` +maps to `TransferError::IdAlreadyFailed`. TigerBeetle remembers +failed transfer IDs, so a recovery resubmission of a previously +failed conversion meets this status by design; as a regular error +it lets `recovery::reconcile` report `ResubmissionRejected` and +continue the scan instead of aborting it (Codex review, PR #5072). + +### Exact `user_data_128` queries + +The trait promises exact matching on `user_data_128` (the +conversion-ID lookup). TigerBeetle treats a zero `QueryFilter` +field as "no filter", so a zero query would return every transfer. +The binding therefore pages through query results (advancing +`timestamp_min` past each full page; timestamps are unique per +transfer) and post-filters on exact equality for **every** value, +zero included, so the result stays exact even if server filter +semantics change (Codex review, PR #5072). + +## Verification + +The scenario suite in `currency_poc::tests` runs against both +backends: in-memory by default, live against `TestCluster` when +ignored tests are enabled with the pinned binary. Live coverage +includes the three behaviours this record describes: distinct +0/1 codes with registry-preserving rejected retries, exact zero +`user_data_128` matching, and failure-then-recovery reporting +`ResubmissionRejected`. + +### Linked-chain retry + +TigerBeetle breaks a linked chain on any non-`Created` status, so +resubmitting an already-posted chain reports `Exists` for its first +leg and `LinkedEventFailed` for every later leg, while the +in-memory backend reports `Exists` per leg (and the executor +accepts that as idempotent success). The binding translates the +pattern back: when a whole chain shows `Exists` then +`LinkedEventFailed`s AND every stored leg verifies identical to +the submitted leg, all legs report `Exists`. A genuinely failed +chain never starts with `Exists`, and a differing stored leg fails +verification, so both keep the raw mapping. Covered live by +`live_same_request_twice_posts_once` (Codex review, PR #5072). diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 2b9f820956..5ac25d06d3 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -2990,6 +2990,7 @@ dependencies = [ "subtle", "tempfile", "thiserror 2.0.21", + "tigerbeetle", "tokio", "tokio-tungstenite", "toml", @@ -6922,6 +6923,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "tigerbeetle" +version = "0.17.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b552c5f9966fd12c9e6f0ab6cad178c2430b0a5e3909e1f5953fe8d0d457f90d" + [[package]] name = "time" version = "0.3.55" diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index d64accdac0..0182c3cd9b 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -52,6 +52,10 @@ web = [ ] # Mainline DHT address lookup (P7.3, decision 15). Off in the default build; src/dht.rs decides per server. dht = ["dep:iroh-mainline-address-lookup"] +# Live-cluster binding for the currency PoC (#2289): the official TigerBeetle +# Rust client, pinned to the harness server version (harness.rs). Off by +# default so normal builds do not link the client native tb_client library. +currency-poc-tb = ["dep:tigerbeetle"] [dependencies] # Foundation leaf modules extracted in Phase 1 of the crate split (#3447). @@ -103,6 +107,7 @@ rustyline = "18" serde = { version = "1", features = ["derive"] } serde_json = "1" tempfile = "3" +tigerbeetle = { version = "=0.17.9", optional = true } tokio = { version = "1", features = ["full"] } # TOML parser for the server config (P2.9). toml = "1" diff --git a/pkgs/id/src/currency_poc/harness.rs b/pkgs/id/src/currency_poc/harness.rs index 2b50ed3d72..d07bff0437 100644 --- a/pkgs/id/src/currency_poc/harness.rs +++ b/pkgs/id/src/currency_poc/harness.rs @@ -53,7 +53,16 @@ pub fn verify_pinned_version(binary: &PathBuf) -> Result<()> { .lines() .next() .and_then(|line| line.trim().strip_prefix("TigerBeetle version ")); - if !output.status.success() || reported_version != Some(TIGERBEETLE_PINNED_VERSION) { + // The pinned release binary reports its version with a build + // suffix (e.g. "0.17.9+cc1c06a"); accept the exact pin or the pin + // plus build metadata, nothing else. + let version_matches = reported_version.is_some_and(|reported| { + reported == TIGERBEETLE_PINNED_VERSION + || reported + .strip_prefix(TIGERBEETLE_PINNED_VERSION) + .is_some_and(|suffix| suffix.starts_with('+')) + }); + if !output.status.success() || !version_matches { bail!( "tigerbeetle binary at {} reports {:?}, expected exact pinned version {} \ (acquire it from {})", @@ -184,12 +193,22 @@ mod tests { assert!(verify_pinned_version(&binary).is_ok()); } + #[cfg(unix)] + #[test] + fn accepts_pinned_version_with_build_suffix() { + // The real 0.17.9 release binary reports "0.17.9+cc1c06a". + let (_dir, binary) = stub_binary("TigerBeetle version 0.17.9+cc1c06a\n", 0); + + assert!(verify_pinned_version(&binary).is_ok()); + } + #[cfg(unix)] #[test] fn rejects_nonexact_reported_versions() { for output in [ "TigerBeetle version 0.17.99\n", "TigerBeetle version 0.17.90\n", + "TigerBeetle version 0.17.9x\n", "TigerBeetle version 0.16.0\n", "TigerBeetle build deadbee0.17.9custom\n", ] { diff --git a/pkgs/id/src/currency_poc/ledger.rs b/pkgs/id/src/currency_poc/ledger.rs index 416980b282..999f6a11eb 100644 --- a/pkgs/id/src/currency_poc/ledger.rs +++ b/pkgs/id/src/currency_poc/ledger.rs @@ -96,6 +96,11 @@ pub enum TransferError { Exists, /// A transfer with this ID exists but with different fields. ExistsWithDifferentFields, + /// The transfer ID belongs to a transfer that already failed: + /// TigerBeetle remembers failed transfer IDs and refuses their + /// resubmission (`id_already_failed`). A recovery resubmission + /// meeting this is a rejected resubmission, not a posting. + IdAlreadyFailed, /// Another leg of the same linked chain failed; this leg did not post. LinkedEventFailed, /// The batch ended while this leg's linked chain was still open: diff --git a/pkgs/id/src/currency_poc/mod.rs b/pkgs/id/src/currency_poc/mod.rs index e83d92e5ec..2e254ba01b 100644 --- a/pkgs/id/src/currency_poc/mod.rs +++ b/pkgs/id/src/currency_poc/mod.rs @@ -16,6 +16,9 @@ //! LP→user), every leg stamped `user_data_128 = conversion_id`. //! - `recovery` — the recovery scanner reconciling unresolved intents //! by pre-generated transfer-ID lookup. +//! - `tb_ledger` (feature `currency-poc-tb`) — the same seam over the +//! official TigerBeetle Rust client, for running the scenarios against +//! a real cluster. //! - `harness` — step 0: a throwaway single-replica TigerBeetle test //! cluster (pinned binary, start/stop) for running the same //! scenarios against a real cluster once a client binding lands. @@ -32,6 +35,8 @@ pub mod harness; pub mod intent; pub mod ledger; pub mod recovery; +#[cfg(feature = "currency-poc-tb")] +pub mod tb_ledger; #[cfg(test)] mod tests; diff --git a/pkgs/id/src/currency_poc/tb_ledger.rs b/pkgs/id/src/currency_poc/tb_ledger.rs new file mode 100644 index 0000000000..051cf0d190 --- /dev/null +++ b/pkgs/id/src/currency_poc/tb_ledger.rs @@ -0,0 +1,419 @@ +//! [`LedgerBackend`] over the official TigerBeetle Rust client +//! (`tigerbeetle` crate, pinned to the harness's server version), so +//! the conversion-executor scenarios in `super::tests` can run against +//! a real test cluster (`super::harness::TestCluster`) and not only +//! the in-memory backend. This closes acceptance item 1 of #2289. +//! +//! Design notes: +//! +//! - 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. +//! - TigerBeetle requires a non-zero `code` on accounts and transfers, +//! while the PoC types use `0` as a supported code. Codes are sent +//! shifted by one ([`wire_code`]): the shift is a bijection on +//! `0..=u16::MAX - 1`, so codes `0` and `1` stay distinct on the +//! wire and a retry with a different code is reported by +//! TigerBeetle as `ExistsWithDifferentFields`, as the backend's +//! field-sensitive idempotency contract requires. The binding also +//! records the original code of every account/transfer it creates +//! and restores it on lookups, so a looked-up leg still compares +//! equal to the persisted intent leg the recovery scanner checks +//! (`super::recovery`). +//! - Status mapping covers the subset of TigerBeetle result codes the +//! PoC types model. An unmodelled status — or a transport-level +//! client error, for which the trait has no channel — panics with +//! the status/error named, rather than being silently folded into a +//! wrong variant. The scenarios exercise only the mapped subset. +//! +//! The binding is behind the `currency-poc-tb` feature so default +//! builds of the `id` crate do not link the client's native +//! `tb_client` library. + +use std::collections::HashMap; +use std::future::Future; +use std::sync::Mutex; + +use anyhow::{Context, Result}; +use tigerbeetle as tb; + +use super::ledger::{ + Account, AccountBalance, AccountError, AccountFlags, LedgerBackend, Transfer, TransferError, +}; + +/// Encode a PoC `code` for the wire. TigerBeetle rejects code `0`, +/// so codes are sent shifted by one: `0 -> 1`, `1 -> 2`, ... The +/// shift keeps every supported code distinct — mapping only `0` to a +/// substitute would serialize codes `0` and `1` identically, and a +/// retry with the other code would report `Exists` instead of +/// `ExistsWithDifferentFields`. `u16::MAX` has no wire representation +/// under this scheme (its shift would wrap to `0`); the PoC's +/// chart-of-accounts codes are small, and asking for `u16::MAX` is a +/// programming error, not a runtime condition. +fn wire_code(code: u16) -> u16 { + code.checked_add(1) + .expect("code u16::MAX has no TigerBeetle wire representation") +} + +/// Inverse of [`wire_code`], used to restore the original code on +/// lookups the registry does not know (e.g. records created by an +/// earlier binding instance). Wire codes are always non-zero. +fn poc_code(wire: u16) -> u16 { + wire.checked_sub(1) + .expect("tigerbeetle returned a zero wire code") +} + +/// A [`LedgerBackend`] backed by a live TigerBeetle cluster through +/// the official Rust client. One client (and its runtime) per ledger; +/// the harness cluster it connects to is owned by the caller. +pub struct TigerBeetleLedger { + client: tb::Client, + runtime: tokio::runtime::Runtime, + /// Original (pre-substitution) account codes by account ID. + account_codes: Mutex>, + /// Original (pre-substitution) transfer codes by transfer ID. + transfer_codes: Mutex>, +} + +impl TigerBeetleLedger { + /// Connect to the cluster at `address` (`host:port`, e.g. a + /// [`super::harness::TestCluster`]'s address). The harness formats + /// its data file with cluster ID 0, so the client uses 0 too. + pub fn connect(address: &str) -> Result { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .context("building the tigerbeetle binding runtime")?; + let client = tb::Client::new(0, address) + .map_err(|error| anyhow::anyhow!("tigerbeetle client init for {address}: {error:?}"))?; + Ok(Self { + client, + runtime, + account_codes: Mutex::new(HashMap::new()), + transfer_codes: Mutex::new(HashMap::new()), + }) + } + + fn block_on(&self, future: F) -> F::Output { + self.runtime.block_on(future) + } + + fn account_code(&self, id: u128, wire: u16) -> u16 { + self.account_codes + .lock() + .expect("account code registry poisoned") + .get(&id) + .copied() + .unwrap_or_else(|| poc_code(wire)) + } + + fn transfer_code(&self, id: u128, wire: u16) -> u16 { + self.transfer_codes + .lock() + .expect("transfer code registry poisoned") + .get(&id) + .copied() + .unwrap_or_else(|| poc_code(wire)) + } +} + +fn to_tb_account(account: &Account) -> tb::Account { + let mut flags = tb::AccountFlags::empty(); + if account.flags.debits_must_not_exceed_credits { + flags = flags | tb::AccountFlags::DebitsMustNotExceedCredits; + } + if account.flags.credits_must_not_exceed_debits { + flags = flags | tb::AccountFlags::CreditsMustNotExceedDebits; + } + tb::Account { + id: account.id, + ledger: account.ledger, + code: wire_code(account.code), + flags, + ..Default::default() + } +} + +fn from_tb_account(account: &tb::Account, code: u16) -> Account { + Account { + id: account.id, + ledger: account.ledger, + code, + flags: AccountFlags { + debits_must_not_exceed_credits: account.flags.0 + & tb::AccountFlags::DebitsMustNotExceedCredits.0 + != 0, + credits_must_not_exceed_debits: account.flags.0 + & tb::AccountFlags::CreditsMustNotExceedDebits.0 + != 0, + }, + } +} + +fn to_tb_transfer(transfer: &Transfer) -> tb::Transfer { + tb::Transfer { + id: transfer.id, + debit_account_id: transfer.debit_account_id, + credit_account_id: transfer.credit_account_id, + amount: transfer.amount, + user_data_128: transfer.user_data_128, + ledger: transfer.ledger, + code: wire_code(transfer.code), + flags: if transfer.linked { + tb::TransferFlags::Linked + } else { + tb::TransferFlags::empty() + }, + ..Default::default() + } +} + +fn from_tb_transfer(transfer: &tb::Transfer, code: u16) -> Transfer { + Transfer { + id: transfer.id, + debit_account_id: transfer.debit_account_id, + credit_account_id: transfer.credit_account_id, + amount: transfer.amount, + ledger: transfer.ledger, + user_data_128: transfer.user_data_128, + code, + linked: transfer.flags.0 & tb::TransferFlags::Linked.0 != 0, + } +} + +fn map_account_status(status: tb::CreateAccountStatus) -> Result<(), AccountError> { + use tb::CreateAccountStatus as Status; + match status { + Status::Created => Ok(()), + Status::Exists => Err(AccountError::Exists), + Status::ExistsWithDifferentFlags + | Status::ExistsWithDifferentUserData128 + | Status::ExistsWithDifferentUserData64 + | Status::ExistsWithDifferentUserData32 + | Status::ExistsWithDifferentLedger + | Status::ExistsWithDifferentCode => Err(AccountError::ExistsWithDifferentFields), + Status::LedgerMustNotBeZero => Err(AccountError::LedgerMustNotBeZero), + other => panic!("tigerbeetle create_accounts returned unmodelled status {other:?}"), + } +} + +fn map_transfer_status(status: tb::CreateTransferStatus) -> Result<(), TransferError> { + use tb::CreateTransferStatus as Status; + match status { + Status::Created => Ok(()), + Status::Exists => Err(TransferError::Exists), + Status::ExistsWithDifferentFlags + | Status::ExistsWithDifferentPendingId + | Status::ExistsWithDifferentTimeout + | Status::ExistsWithDifferentDebitAccountId + | Status::ExistsWithDifferentCreditAccountId + | Status::ExistsWithDifferentAmount + | Status::ExistsWithDifferentUserData128 + | Status::ExistsWithDifferentUserData64 + | Status::ExistsWithDifferentUserData32 + | Status::ExistsWithDifferentLedger + | Status::ExistsWithDifferentCode => Err(TransferError::ExistsWithDifferentFields), + Status::LinkedEventFailed => Err(TransferError::LinkedEventFailed), + Status::LinkedEventChainOpen => Err(TransferError::LinkedEventChainOpen), + // A transfer ID that already failed is remembered by + // TigerBeetle; resubmitting it (recovery) is a regular + // rejection, not a panic-worthy unmodelled status. + Status::IdAlreadyFailed => Err(TransferError::IdAlreadyFailed), + Status::DebitAccountNotFound => Err(TransferError::DebitAccountNotFound), + Status::CreditAccountNotFound => Err(TransferError::CreditAccountNotFound), + Status::AccountsMustBeDifferent => Err(TransferError::AccountsMustBeDifferent), + Status::AccountsMustHaveTheSameLedger + | Status::TransferMustHaveTheSameLedgerAsAccounts + | Status::LedgerMustNotBeZero => Err(TransferError::LedgerMismatch), + // TigerBeetle's exceeds_credits is the debit account's + // debits_must_not_exceed_credits guard tripping; exceeds_debits + // is the credit account's credits_must_not_exceed_debits guard. + Status::ExceedsCredits => Err(TransferError::DebitsMustNotExceedCredits), + Status::ExceedsDebits => Err(TransferError::CreditsMustNotExceedDebits), + Status::OverflowsDebitsPending + | Status::OverflowsDebitsPosted + | Status::OverflowsDebits => Err(TransferError::DebitsMustNotExceedCredits), + Status::OverflowsCreditsPending + | Status::OverflowsCreditsPosted + | Status::OverflowsCredits => Err(TransferError::CreditsMustNotExceedDebits), + other => panic!("tigerbeetle create_transfers returned unmodelled status {other:?}"), + } +} + +impl LedgerBackend for TigerBeetleLedger { + fn create_accounts(&mut self, accounts: &[Account]) -> Vec> { + let wire: Vec = accounts.iter().map(to_tb_account).collect(); + let results = self + .block_on(self.client.create_accounts(&wire)) + .expect("tigerbeetle create_accounts request failed"); + assert_eq!( + results.len(), + accounts.len(), + "tigerbeetle returned one result per account" + ); + // Record original codes only for creations TigerBeetle + // accepted (Created) or confirmed identical (Exists). A + // rejected creation (e.g. ExistsWithDifferentFields) must not + // overwrite the registry: the stored record still carries + // the earlier code, and lookups restore from the registry. + { + let mut registry = self + .account_codes + .lock() + .expect("account code registry poisoned"); + for (account, result) in accounts.iter().zip(results.iter()) { + if matches!( + result.status, + tb::CreateAccountStatus::Created | tb::CreateAccountStatus::Exists + ) { + registry.insert(account.id, account.code); + } + } + } + results + .iter() + .map(|result| map_account_status(result.status)) + .collect() + } + + fn create_transfers(&mut self, batch: &[Transfer]) -> Vec> { + let wire: Vec = batch.iter().map(to_tb_transfer).collect(); + let results = self + .block_on(self.client.create_transfers(&wire)) + .expect("tigerbeetle create_transfers request failed"); + assert_eq!( + results.len(), + batch.len(), + "tigerbeetle returned one result per transfer" + ); + // Same rule as create_accounts: record original codes only + // for accepted (Created) or identical (Exists) transfers, so + // a rejected retry cannot rewrite what lookups report for + // the stored transfer. + { + let mut registry = self + .transfer_codes + .lock() + .expect("transfer code registry poisoned"); + for (transfer, result) in batch.iter().zip(results.iter()) { + if matches!( + result.status, + tb::CreateTransferStatus::Created | tb::CreateTransferStatus::Exists + ) { + registry.insert(transfer.id, transfer.code); + } + } + } + // Linked-chain retry (Codex review, PR #5072): TigerBeetle + // breaks a linked chain on ANY non-Created status, so + // resubmitting an already-posted chain reports `Exists` for + // its first leg and `LinkedEventFailed` for every later leg — + // while the in-memory backend reports `Exists` per leg and + // the executor accepts the retry as idempotent success. When + // a whole chain shows exactly that pattern AND every stored + // leg verifies identical to the submitted leg, report + // `Exists` for all of its legs. A chain that genuinely failed + // never starts with `Exists`, and a leg whose stored fields + // differ fails the verification, so both keep the raw mapping. + let mut mapped: Vec> = results + .iter() + .map(|result| map_transfer_status(result.status)) + .collect(); + let mut chain_start = 0; + while chain_start < batch.len() { + let mut chain_end = chain_start; + while batch[chain_end].linked && chain_end + 1 < batch.len() { + chain_end += 1; + } + let chain = &batch[chain_start..=chain_end]; + let raw = &results[chain_start..=chain_end]; + let already_posted_pattern = chain.len() > 1 + && !chain[chain.len() - 1].linked + && matches!(raw[0].status, tb::CreateTransferStatus::Exists) + && raw[1..] + .iter() + .all(|r| matches!(r.status, tb::CreateTransferStatus::LinkedEventFailed)); + if already_posted_pattern + && chain + .iter() + .all(|leg| self.lookup_transfer(leg.id) == Some(leg.clone())) + { + for slot in &mut mapped[chain_start..=chain_end] { + *slot = Err(TransferError::Exists); + } + } + chain_start = chain_end + 1; + } + mapped + } + + fn lookup_transfer(&self, id: u128) -> Option { + let found = self + .block_on(self.client.lookup_transfers(&[id])) + .expect("tigerbeetle lookup_transfers request failed"); + found + .first() + .map(|transfer| from_tb_transfer(transfer, self.transfer_code(id, transfer.code))) + } + + fn lookup_account(&self, id: u128) -> Option { + let found = self + .block_on(self.client.lookup_accounts(&[id])) + .expect("tigerbeetle lookup_accounts request failed"); + found + .first() + .map(|account| from_tb_account(account, self.account_code(id, account.code))) + } + + fn account_balance(&self, id: u128) -> Option { + let found = self + .block_on(self.client.lookup_accounts(&[id])) + .expect("tigerbeetle lookup_accounts request failed"); + found.first().map(|account| AccountBalance { + debits_posted: account.debits_posted, + credits_posted: account.credits_posted, + }) + } + + fn transfers_with_user_data_128(&self, value: u128) -> Vec { + // TigerBeetle treats a zero `user_data_128` filter as "no + // filter" (QueryFilter documentation), so for value 0 the + // query pages over every transfer; the exact post-filter + // then keeps only the zero-stamped ones (the PoC's funding + // transfers). The post-filter runs for every value, so the + // result stays exact even if server filter semantics change. + // Pages advance by timestamp (unique per transfer), so a + // scan larger than one page is still complete. + const PAGE: u32 = 8_189; + let mut matched = Vec::new(); + let mut timestamp_min = 0u64; + loop { + let filter = tb::QueryFilter { + user_data_128: value, + timestamp_min, + limit: PAGE, + ..Default::default() + }; + let found = self + .block_on(self.client.query_transfers(filter)) + .expect("tigerbeetle query_transfers request failed"); + let page_full = found.len() == PAGE as usize; + let last_timestamp = found.last().map(|transfer| transfer.timestamp); + matched.extend( + found + .iter() + .filter(|transfer| transfer.user_data_128 == value) + .map(|transfer| { + from_tb_transfer(transfer, self.transfer_code(transfer.id, transfer.code)) + }), + ); + match last_timestamp { + Some(last) if page_full => timestamp_min = last.saturating_add(1), + _ => break, + } + } + matched + } +} diff --git a/pkgs/id/src/currency_poc/tests.rs b/pkgs/id/src/currency_poc/tests.rs index a8594b2162..c205ff695f 100644 --- a/pkgs/id/src/currency_poc/tests.rs +++ b/pkgs/id/src/currency_poc/tests.rs @@ -12,7 +12,8 @@ use super::executor::{ConversionExecutor, ConversionRequest, RateQuote}; use super::intent::{FileIntentStore, InMemoryIntentStore, IntentRecord, IntentState, IntentStore}; use super::ledger::{ - Account, AccountFlags, AccountId, InMemoryLedger, LedgerBackend, Transfer, TransferError, + Account, AccountError, AccountFlags, AccountId, InMemoryLedger, LedgerBackend, Transfer, + TransferError, }; use super::recovery::{ReconcileOutcome, RecoveryPolicy, reconcile}; @@ -1327,3 +1328,331 @@ fn canonically_blocked_conversion_is_skipped_and_reported_during_listing() { assert!(stray.exists(), "the blocked record's copy stays on disk"); let _ = std::fs::remove_dir_all(&dir); } +// ---- Live-cluster scenarios (#2289 acceptance item 1) ---- +// +// The scenarios above run against InMemoryLedger; the ones below run +// the same acceptance paths against a real single-replica cluster +// (super::harness::TestCluster) through the official-client binding +// (super::tb_ledger::TigerBeetleLedger). Ignored by default: they need +// the pinned TigerBeetle binary. Run with: +// TIGERBEETLE_POC_BINARY= cargo test -p id --features currency-poc-tb \ +// currency_poc::tests::live -- --ignored + +#[cfg(feature = "currency-poc-tb")] +use super::harness::TestCluster; +#[cfg(feature = "currency-poc-tb")] +use super::tb_ledger::TigerBeetleLedger; + +#[cfg(feature = "currency-poc-tb")] +fn funded_tb_ledger(address: &str) -> TigerBeetleLedger { + let mut ledger = TigerBeetleLedger::connect(address).expect("connect to live cluster"); + let results = ledger.create_accounts(&[ + account(ISSUER_SRC, SRC, false), + account(ISSUER_DST, DST, false), + account(USER_SRC, SRC, true), + account(LP_SRC, SRC, false), + account(FEE, SRC, false), + account(LP_DST, DST, true), + account(USER_DST, DST, false), + ]); + assert!( + results.iter().all(|result| result.is_ok()), + "live account creation failed: {results:?}" + ); + let results = ledger.create_transfers(&[ + funding_transfer(501, ISSUER_SRC, USER_SRC, 10_000, SRC), + funding_transfer(502, ISSUER_DST, LP_DST, 50_000, DST), + ]); + assert!( + results.iter().all(|result| result.is_ok()), + "live funding transfers failed: {results:?}" + ); + ledger +} + +#[cfg(feature = "currency-poc-tb")] +type LiveExecutor = ConversionExecutor; + +#[cfg(feature = "currency-poc-tb")] +fn live_executor(port: u16) -> (TestCluster, LiveExecutor) { + let cluster = TestCluster::start(port).expect("live cluster should start"); + let ledger = funded_tb_ledger(&cluster.address); + ( + cluster, + ConversionExecutor::new(ledger, InMemoryIntentStore::new()), + ) +} + +#[cfg(feature = "currency-poc-tb")] +#[test] +#[ignore = "requires the pinned tigerbeetle binary (TIGERBEETLE_POC_BINARY or PATH)"] +fn live_posted_conversion_legs_findable_by_user_data_128() { + let (_cluster, mut executor) = live_executor(30021); + let record = executor.execute(&request()).expect("conversion posts"); + assert_eq!(record.state, IntentState::Posted); + assert_eq!(record.amount_out, 2_000); + + let legs = executor.backend.transfers_with_user_data_128(777); + assert_eq!(legs.len(), 3); + assert!(legs.iter().all(|leg| leg.user_data_128 == 777)); + + assert_eq!( + executor + .backend + .account_balance(USER_SRC) + .unwrap() + .spendable(), + 8_975 + ); + assert_eq!( + executor + .backend + .account_balance(USER_DST) + .unwrap() + .credits_posted, + 2_000 + ); + assert_eq!( + executor + .backend + .account_balance(LP_DST) + .unwrap() + .spendable(), + 48_000 + ); +} + +#[cfg(feature = "currency-poc-tb")] +#[test] +#[ignore = "requires the pinned tigerbeetle binary (TIGERBEETLE_POC_BINARY or PATH)"] +fn live_atomic_failure_moves_nothing() { + let (_cluster, mut executor) = live_executor(30022); + let mut record = executor.prepare(&request()).expect("intent prepared"); + + let drain = funding_transfer(900, LP_DST, USER_DST, 49_000, DST); + assert!(executor.backend.create_transfers(&[drain])[0].is_ok()); + + let before_user = executor.backend.account_balance(USER_SRC).unwrap(); + let before_lp_src = executor.backend.account_balance(LP_SRC).unwrap(); + assert!(executor.submit(&mut record).is_err()); + + assert_eq!( + executor.backend.account_balance(USER_SRC).unwrap(), + before_user + ); + assert_eq!( + executor.backend.account_balance(LP_SRC).unwrap(), + before_lp_src + ); + assert!( + executor + .backend + .transfers_with_user_data_128(777) + .is_empty(), + "no leg of a failed linked batch may be stored" + ); + assert_eq!(record.state, IntentState::Submitted); +} + +#[cfg(feature = "currency-poc-tb")] +#[test] +#[ignore = "requires the pinned tigerbeetle binary (TIGERBEETLE_POC_BINARY or PATH)"] +fn live_failed_conversion_recovery_reports_resubmission_rejected() { + let (_cluster, mut executor) = live_executor(30025); + let mut record = executor.prepare(&request()).expect("intent prepared"); + + // Same insufficient-liquidity failure as + // live_atomic_failure_moves_nothing: the linked batch fails, no + // leg is stored, and the intent stays Submitted. + let drain = funding_transfer(900, LP_DST, USER_DST, 49_000, DST); + assert!(executor.backend.create_transfers(&[drain])[0].is_ok()); + assert!(executor.submit(&mut record).is_err()); + assert_eq!(record.state, IntentState::Submitted); + + // TigerBeetle remembers the failed transfer IDs, so the + // recovery resubmission is refused (id_already_failed). That + // must surface as ResubmissionRejected for this record — not a + // panic in the binding — and the record stays unresolved. + let outcomes = reconcile( + &mut executor.backend, + &mut executor.store, + RecoveryPolicy::Resubmit, + ) + .expect("reconcile"); + assert_eq!( + outcomes, + vec![(777, ReconcileOutcome::ResubmissionRejected)] + ); + let stored = executor + .store + .get(777) + .expect("read intent") + .expect("intent still stored"); + assert_eq!(stored.state, IntentState::Submitted); + assert!(executor.backend.transfers_with_user_data_128(777).is_empty()); + assert_eq!( + executor + .backend + .account_balance(USER_DST) + .unwrap() + .credits_posted, + 49_000, + "only the drain posted; the failed conversion moved nothing" + ); +} + +#[cfg(feature = "currency-poc-tb")] +#[test] +#[ignore = "requires the pinned tigerbeetle binary (TIGERBEETLE_POC_BINARY or PATH)"] +fn live_zero_user_data_128_query_matches_exactly() { + let (_cluster, mut executor) = live_executor(30026); + let record = executor.execute(&request()).expect("conversion posts"); + assert_eq!(record.state, IntentState::Posted); + + // Funding transfers are stamped user_data_128 = 0. TigerBeetle + // treats a zero query filter as "no filter", so the binding + // must post-filter exactly: only the two funding transfers + // match, never the conversion legs stamped 777. + let zero = executor.backend.transfers_with_user_data_128(0); + assert_eq!(zero.len(), 2); + assert!(zero.iter().all(|transfer| transfer.user_data_128 == 0)); +} + +#[cfg(feature = "currency-poc-tb")] +#[test] +#[ignore = "requires the pinned tigerbeetle binary (TIGERBEETLE_POC_BINARY or PATH)"] +fn live_codes_zero_and_one_stay_distinct() { + let (_cluster, mut executor) = live_executor(30027); + let backend = &mut executor.backend; + + // Accounts: code 0 is created; the same ID retried with code 1 + // is a different record, not an idempotent Exists. + let account_zero = account(424_242, SRC, false); + assert_eq!(account_zero.code, 0); + assert!(backend.create_accounts(&[account_zero.clone()])[0].is_ok()); + let mut account_one = account_zero.clone(); + account_one.code = 1; + assert_eq!( + backend.create_accounts(&[account_one])[0], + Err(AccountError::ExistsWithDifferentFields) + ); + // The rejected retry must not rewrite what lookups report. + assert_eq!(backend.lookup_account(424_242).unwrap().code, 0); + + // Transfers: the same rule on a funded pair. + let transfer_zero = funding_transfer(910, ISSUER_SRC, USER_SRC, 10, SRC); + assert!(backend.create_transfers(&[transfer_zero.clone()])[0].is_ok()); + let mut transfer_one = transfer_zero; + transfer_one.code = 1; + assert_eq!( + backend.create_transfers(&[transfer_one])[0], + Err(TransferError::ExistsWithDifferentFields) + ); + assert_eq!(backend.lookup_transfer(910).unwrap().code, 0); +} + +#[cfg(feature = "currency-poc-tb")] +#[test] +#[ignore = "requires the pinned tigerbeetle binary (TIGERBEETLE_POC_BINARY or PATH)"] +fn live_crash_after_submission_recovers_without_double_posting() { + let (_cluster, mut executor) = live_executor(30023); + let mut record = executor.prepare(&request()).expect("intent prepared"); + record.state = IntentState::Submitted; + executor.store.put(&record).unwrap(); + let results = executor.backend.create_transfers(&record.legs); + assert!( + results + .iter() + .all(|result| matches!(result, Ok(()) | Err(TransferError::Exists))) + ); + + let outcomes = reconcile( + &mut executor.backend, + &mut executor.store, + RecoveryPolicy::Resubmit, + ) + .expect("reconcile"); + assert_eq!(outcomes, vec![(777, ReconcileOutcome::AlreadyPosted)]); + assert_eq!( + executor + .backend + .account_balance(USER_DST) + .unwrap() + .credits_posted, + 2_000, + "balances must reflect exactly one posting" + ); +} + +#[cfg(feature = "currency-poc-tb")] +#[test] +#[ignore = "requires the pinned tigerbeetle binary (TIGERBEETLE_POC_BINARY or PATH)"] +fn live_crash_before_submission_resubmits_same_ids() { + let (_cluster, mut executor) = live_executor(30024); + let record = executor.prepare(&request()).expect("intent prepared"); + assert_eq!(record.state, IntentState::Recorded); + + let outcomes = reconcile( + &mut executor.backend, + &mut executor.store, + RecoveryPolicy::Resubmit, + ) + .expect("reconcile"); + assert_eq!(outcomes, vec![(777, ReconcileOutcome::Resubmitted)]); + assert_eq!(executor.backend.transfers_with_user_data_128(777).len(), 3); + assert_eq!( + executor + .backend + .account_balance(USER_DST) + .unwrap() + .credits_posted, + 2_000 + ); + + let outcomes = reconcile( + &mut executor.backend, + &mut executor.store, + RecoveryPolicy::Resubmit, + ) + .expect("second reconcile is a no-op"); + assert!(outcomes.is_empty()); +} + +#[cfg(feature = "currency-poc-tb")] +#[test] +#[ignore = "requires the pinned tigerbeetle binary (TIGERBEETLE_POC_BINARY or PATH)"] +fn live_same_request_twice_posts_once() { + // Codex review, PR #5072: resubmitting an already-posted linked + // chain must be an idempotent success, as with the in-memory + // backend — TigerBeetle reports Exists for the first leg and + // LinkedEventFailed for the rest, which the binding translates + // back to per-leg Exists after verifying the stored legs. + let (_cluster, mut executor) = live_executor(30028); + let first = executor.execute(&request()).expect("first execution posts"); + assert_eq!(first.state, IntentState::Posted); + let balances_after_first = ( + executor.backend.account_balance(USER_SRC).unwrap(), + executor.backend.account_balance(USER_DST).unwrap(), + executor.backend.account_balance(LP_DST).unwrap(), + ); + + let second = executor + .execute(&request()) + .expect("same-request retry is an idempotent success"); + assert_eq!(second.state, IntentState::Posted); + assert_eq!(second.legs, first.legs); + assert_eq!( + executor.backend.account_balance(USER_SRC).unwrap(), + balances_after_first.0, + "retry must not move balances a second time" + ); + assert_eq!( + executor.backend.account_balance(USER_DST).unwrap(), + balances_after_first.1 + ); + assert_eq!( + executor.backend.account_balance(LP_DST).unwrap(), + balances_after_first.2 + ); + assert_eq!(executor.backend.transfers_with_user_data_128(777).len(), 3); +}