Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 72 additions & 11 deletions pkgs/id/src/currency_poc/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Result<(), TransferError>>;
fn lookup_transfer(&self, id: TransferId) -> Option<Transfer>;
fn lookup_account(&self, id: AccountId) -> Option<Account>;
Expand Down Expand Up @@ -297,10 +310,18 @@ impl LedgerBackend for InMemoryLedger {
let mut staged = self.balances.clone();
let mut staged_transfers: HashMap<TransferId, Transfer> = 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<Result<(), TransferError>> = Vec::with_capacity(chain.len());
let mut first_exists_offset: Option<usize> = 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) {
Expand All @@ -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) => {
Expand All @@ -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
}));
Expand Down
60 changes: 60 additions & 0 deletions pkgs/id/src/currency_poc/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading