From 2a01082b630d58e0bf33b1909b04da58c5be4f99 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:05:54 -0600 Subject: [PATCH] id(currency_poc): break linked chains on Exists legs in InMemoryLedger (#6170) TigerBeetle breaks a linked chain on ANY non-Created status, so a mixed chain whose head leg is an idempotent Exists resubmission and whose later legs are new posts nothing on the live backend - while InMemoryLedger staged and committed the new legs and moved balances. Scenario tests green against the reference backend therefore certified behavior the live backend rejects. Option A (recorded on #6170): InMemoryLedger now matches TigerBeetle. A mixed chain posts nothing: the Exists leg reports Exists, every other leg LinkedEventFailed, no balances move. The whole-chain identical resubmission stays per-leg Exists and moves nothing - the surface the tb_ledger binding presents after verifying every stored leg (PR #5072 compensation contract). An earlier Exists leg also wins over a later hard failure, matching chain-order evaluation. The create_transfers trait doc now states the Exists-leg semantics explicitly. Pinning test linked_chain_with_exists_head_leg_posts_nothing_new covers the mixed chain (result vector, lookup_transfer for the new legs, balances) plus the whole-chain resubmit control; it failed before the change with [Exists, Ok, Ok] and passes after. cargo test -p id currency_poc: 48 passed. Full id lib suite: 2249 passed, 0 failed. --- pkgs/id/src/currency_poc/ledger.rs | 83 ++++++++++++++++++++++++++---- pkgs/id/src/currency_poc/tests.rs | 60 +++++++++++++++++++++ 2 files changed, 132 insertions(+), 11 deletions(-) diff --git a/pkgs/id/src/currency_poc/ledger.rs b/pkgs/id/src/currency_poc/ledger.rs index 999f6a11eb..743d66a58a 100644 --- a/pkgs/id/src/currency_poc/ledger.rs +++ b/pkgs/id/src/currency_poc/ledger.rs @@ -136,6 +136,19 @@ pub trait LedgerBackend { /// and the transfers of a rejected open chain may be resubmitted /// (properly terminated) in a later batch. A production binding /// must implement the same rule. + /// + /// `Exists` legs inside a linked chain (#6170): TigerBeetle + /// breaks a linked chain on ANY non-`Created` status, so a chain + /// that mixes an idempotent `Exists` leg with new legs posts + /// NOTHING \u2014 the `Exists` leg reports + /// [`TransferError::Exists`] and every other leg reports + /// [`TransferError::LinkedEventFailed`]. The single exception is + /// a chain whose legs are ALL identical resubmissions: it + /// reports per-leg `Exists` and moves nothing (the surface the + /// `tb_ledger` binding presents after verifying every stored + /// leg of a resubmitted chain, PR #5072). A lone unlinked + /// transfer is a chain of one: `Exists` stays `Exists`, a new + /// transfer posts as before. fn create_transfers(&mut self, batch: &[Transfer]) -> Vec>; fn lookup_transfer(&self, id: TransferId) -> Option; fn lookup_account(&self, id: AccountId) -> Option; @@ -297,10 +310,18 @@ impl LedgerBackend for InMemoryLedger { let mut staged = self.balances.clone(); let mut staged_transfers: HashMap = HashMap::new(); // Per-leg validation outcome. An idempotent `Exists` leg - // does not fail the chain: its effects are already in the - // real balances, so it is reported as `Err(Exists)` (as - // TigerBeetle reports it) without staging anything. + // stages nothing (its effects are already in the real + // balances), but inside a linked chain it is NOT neutral: + // TigerBeetle breaks a chain on any non-`Created` status + // (#6170, and the trait doc above). The chain outcome is + // decided after the loop from these per-leg outcomes: + // all-`Exists` chains report per-leg `Exists`; a mixed + // chain posts nothing, with the first `Exists` leg (or + // the first hard failure, whichever comes first in chain + // order) reporting its own outcome and every other leg + // reporting `LinkedEventFailed`. let mut leg_outcomes: Vec> = Vec::with_capacity(chain.len()); + let mut first_exists_offset: Option = None; let mut failure: Option<(usize, TransferError)> = None; for (offset, transfer) in chain.iter().enumerate() { match self.validate_and_stage(transfer, &mut staged, &staged_transfers) { @@ -309,6 +330,9 @@ impl LedgerBackend for InMemoryLedger { leg_outcomes.push(Ok(())); } Err(TransferError::Exists) => { + if first_exists_offset.is_none() { + first_exists_offset = Some(offset); + } leg_outcomes.push(Err(TransferError::Exists)); } Err(error) => { @@ -319,19 +343,56 @@ impl LedgerBackend for InMemoryLedger { } match failure { None => { - self.balances = staged; - for transfer in chain { - if !self.transfers.contains_key(&transfer.id) { - self.transfers.insert(transfer.id, transfer.clone()); - self.transfer_order.push(transfer.id); + let exists_count = leg_outcomes + .iter() + .filter(|outcome| matches!(outcome, Err(TransferError::Exists))) + .count(); + if exists_count > 0 && exists_count < chain.len() { + // Mixed chain (#6170): an `Exists` leg ahead of + // or behind new legs breaks the chain, exactly + // as TigerBeetle breaks it. Nothing commits: + // the staged balances and transfers are dropped, + // `Exists` legs keep their outcome, and every + // new leg reports `LinkedEventFailed`. + for outcome in leg_outcomes { + results.push(match outcome { + Err(TransferError::Exists) => Err(TransferError::Exists), + _ => Err(TransferError::LinkedEventFailed), + }); + } + } else { + // No `Exists` leg (an ordinary posting chain) + // or nothing but `Exists` legs (a whole-chain + // identical resubmission: per-leg `Exists`, + // and since `Exists` legs stage nothing, the + // commit below moves no balances and stores no + // new transfers). + self.balances = staged; + for transfer in chain { + if !self.transfers.contains_key(&transfer.id) { + self.transfers.insert(transfer.id, transfer.clone()); + self.transfer_order.push(transfer.id); + } } + results.extend(leg_outcomes); } - results.extend(leg_outcomes); } Some((failing_offset, error)) => { + // The chain broke at the first non-`Created` leg in + // chain order: an earlier `Exists` leg (TigerBeetle + // breaks on it before ever reaching the hard + // failure) reports `Exists`; otherwise the failing + // leg reports its own error. Every other leg + // reports `LinkedEventFailed`. + let (breaker_offset, breaker_error) = match first_exists_offset { + Some(exists_offset) if exists_offset < failing_offset => { + (exists_offset, TransferError::Exists) + } + _ => (failing_offset, error), + }; for (offset, _) in chain.iter().enumerate() { - results.push(Err(if offset == failing_offset { - error + results.push(Err(if offset == breaker_offset { + breaker_error } else { TransferError::LinkedEventFailed })); diff --git a/pkgs/id/src/currency_poc/tests.rs b/pkgs/id/src/currency_poc/tests.rs index 21ebb53c7a..b674dbeb3c 100644 --- a/pkgs/id/src/currency_poc/tests.rs +++ b/pkgs/id/src/currency_poc/tests.rs @@ -311,6 +311,66 @@ fn unterminated_chain_does_not_block_terminated_chains() { assert!(ledger.lookup_transfer(722).is_some()); } +#[test] +fn linked_chain_with_exists_head_leg_posts_nothing_new() { + // #6170: parity with TigerBeetle (and the tb_ledger compensation + // contract, PR #5072). TigerBeetle breaks a linked chain on ANY + // non-Created status: a mixed chain whose head leg is an + // idempotent `Exists` resubmission and whose later legs are new + // posts NOTHING new \u2014 the head reports `Exists`, the new legs + // report `LinkedEventFailed`, and no balances move. The + // whole-chain identical resubmit is the one exception: it stays + // per-leg `Exists` (the surface the tb_ledger binding presents + // after verifying every stored leg), and also moves nothing. + let mut ledger = funded_ledger(); + let leg601 = Transfer { + linked: true, + ..funding_transfer(601, USER_SRC, LP_SRC, 100, SRC) + }; + let leg602 = funding_transfer(602, LP_SRC, FEE, 100, SRC); + let results = ledger.create_transfers(&[leg601.clone(), leg602.clone()]); + assert_eq!(results, vec![Ok(()), Ok(())]); + let user_after_chain = ledger.account_balance(USER_SRC).unwrap(); + let lp_after_chain = ledger.account_balance(LP_SRC).unwrap(); + let fee_after_chain = ledger.account_balance(FEE).unwrap(); + assert_eq!(user_after_chain.debits_posted, 100); + assert_eq!(lp_after_chain.credits_posted, 100); + assert_eq!(fee_after_chain.credits_posted, 100); + + // Mixed chain: leg 601 byte-identical (an `Exists` resubmission), + // legs 603/604 genuinely new. + let leg603 = Transfer { + linked: true, + ..funding_transfer(603, LP_SRC, USER_SRC, 50, SRC) + }; + let leg604 = funding_transfer(604, USER_SRC, FEE, 50, SRC); + let results = ledger.create_transfers(&[leg601.clone(), leg603, leg604]); + assert_eq!( + results, + vec![ + Err(TransferError::Exists), + Err(TransferError::LinkedEventFailed), + Err(TransferError::LinkedEventFailed), + ] + ); + assert!(ledger.lookup_transfer(603).is_none()); + assert!(ledger.lookup_transfer(604).is_none()); + assert_eq!(ledger.account_balance(USER_SRC).unwrap(), user_after_chain); + assert_eq!(ledger.account_balance(LP_SRC).unwrap(), lp_after_chain); + assert_eq!(ledger.account_balance(FEE).unwrap(), fee_after_chain); + + // Control: the whole-chain identical resubmit stays all-`Exists` + // and moves nothing. + let results = ledger.create_transfers(&[leg601, leg602]); + assert_eq!( + results, + vec![Err(TransferError::Exists), Err(TransferError::Exists)] + ); + assert_eq!(ledger.account_balance(USER_SRC).unwrap(), user_after_chain); + assert_eq!(ledger.account_balance(LP_SRC).unwrap(), lp_after_chain); + assert_eq!(ledger.account_balance(FEE).unwrap(), fee_after_chain); +} + #[test] fn crash_after_submission_recovers_without_double_posting() { // #2063 ยง4: crash between submission and the Posted state write.