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
49 changes: 49 additions & 0 deletions pkgs/id/src/currency_poc/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ pub struct InMemoryLedger {
accounts: HashMap<AccountId, Account>,
balances: HashMap<AccountId, AccountBalance>,
transfers: HashMap<TransferId, Transfer>,
failed_transfers: HashMap<TransferId, TransferError>,
transfer_order: Vec<TransferId>,
}

Expand All @@ -183,6 +184,15 @@ impl InMemoryLedger {
staged: &mut HashMap<AccountId, AccountBalance>,
staged_transfers: &HashMap<TransferId, Transfer>,
) -> Result<(), TransferError> {
// A transfer ID previously recorded as failed is refused
// with `IdAlreadyFailed`, matching the variant's contract
// above and the live binding's status mapping (tb_ledger.rs)
// -- never the stored original error, which goes stale once
// its cause is fixed (#6628).
if self.failed_transfers.contains_key(&transfer.id) {
return Err(TransferError::IdAlreadyFailed);
}

if let Some(existing) = self.transfers.get(&transfer.id) {
return if existing == transfer {
Err(TransferError::Exists)
Expand Down Expand Up @@ -378,6 +388,45 @@ impl LedgerBackend for InMemoryLedger {
}
}
Some((failing_offset, error)) => {
// Record failed transfer IDs for IdAlreadyFailed behavior.
// When a transfer fails for its own reason (validation/balance
// errors), TigerBeetle remembers the ID and refuses resubmission.
// The stored error is kept for diagnosis; future
// submissions of the ID are refused with
// `IdAlreadyFailed`, not the stored error (#6628).
// Only record failures that are transfer-level errors (not chain-level failures).
if !matches!(
error,
TransferError::LinkedEventFailed | TransferError::LinkedEventChainOpen
) {
// Record only the leg that actually failed
// (#6627): the chain's other legs did not fail
// and must remain submittable, and an ID that
// is already posted must never be marked
// failed -- `validate_and_stage` consults
// `failed_transfers` before `transfers`, so a
// failure cached against a posted ID would
// break its idempotent `Exists` retry.
let failing = &chain[failing_offset];
// But if an earlier leg already broke the
// chain with `Exists`, TigerBeetle never
// attempted this leg at all (the result
// selection below reports only
// `LinkedEventFailed` for it): caching its
// error would refuse a leg that was never
// tried, so only cache when this leg is the
// leg the chain actually broke on.
let chain_broke_at_earlier_exists = matches!(
first_exists_offset,
Some(exists_offset) if exists_offset < failing_offset
);
if !chain_broke_at_earlier_exists
&& !self.transfers.contains_key(&failing.id)
{
self.failed_transfers.insert(failing.id, error);
Comment thread
dezren39 marked this conversation as resolved.
Resolved
}
}

// 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
Expand Down
205 changes: 205 additions & 0 deletions pkgs/id/src/currency_poc/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,82 @@ fn atomic_failure_moves_nothing() {
assert_eq!(record.state, IntentState::Submitted);
}

#[test]
fn in_memory_failed_conversion_recovery_reports_resubmission_rejected() {
// #6629: the in-memory counterpart of
// live_failed_conversion_recovery_reports_resubmission_rejected
// (whose oracle is the live binding's id_already_failed mapping).
// The in-memory failed-ID lookup in validate_and_stage must refuse
// the resubmission even after the original blocker has cleared --
// the existing in-memory reconcile tests reject via fresh balance
// validation during reconcile itself, not via a recorded failed ID.
let mut executor = executor();
let mut record = executor.prepare(&request()).expect("intent prepared");

// Fail the conversion for insufficient liquidity, exactly as in
// atomic_failure_moves_nothing: draining the LP destination makes
// the destination leg fail, its ID lands in failed_transfers, no
// leg posts, 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);
assert!(
executor
.backend
.transfers_with_user_data_128(777)
.is_empty()
);

// Restore liquidity: the blocker that caused the failure is gone,
// so a resubmission rejected now can only be refused by the
// recorded failed ID, never by balance validation.
let refill = funding_transfer(901, ISSUER_DST, LP_DST, 50_000, DST);
assert!(executor.backend.create_transfers(&[refill])[0].is_ok());
assert!(
executor
.backend
.account_balance(LP_DST)
.unwrap()
.spendable()
>= 2_000,
"liquidity restored: the destination leg would validate now"
);

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(),
"no leg of the rejected resubmission may post"
);
assert_eq!(
executor
.backend
.account_balance(USER_DST)
.unwrap()
.credits_posted,
49_000,
"only the drain posted; the rejected resubmission moved nothing"
);
}

#[test]
fn linked_chain_failure_marks_other_legs_linked_event_failed() {
let mut ledger = funded_ledger();
Expand Down Expand Up @@ -231,6 +307,135 @@ fn linked_chain_failure_marks_other_legs_linked_event_failed() {
assert!(ledger.transfers_with_user_data_128(42).is_empty());
}

#[test]
fn failed_chain_records_only_the_failing_leg() {
// #6627 (oracle: the failing leg's own error is the only outcome
// the chain may cache): when a linked chain fails on one leg,
// only that leg's ID is recorded as failed -- a valid sibling
// leg remains submittable afterwards.
let mut ledger = funded_ledger();
let sibling = Transfer {
linked: true,
..funding_transfer(700, USER_SRC, LP_SRC, 100, SRC)
};
let failing = funding_transfer(701, LP_DST, USER_DST, 999_999, DST);
let results = ledger.create_transfers(&[sibling.clone(), failing]);
assert_eq!(results[0], Err(TransferError::LinkedEventFailed));
assert_eq!(results[1], Err(TransferError::DebitsMustNotExceedCredits));
// The sibling leg was never itself invalid: resubmitted on its
// own (unlinked) it posts.
let retry = Transfer {
linked: false,
..sibling
};
assert_eq!(ledger.create_transfers(&[retry]), vec![Ok(())]);
assert!(ledger.lookup_transfer(700).is_some());
}

#[test]
fn exists_break_leaves_later_failing_leg_submittable() {
// Codex P2 on PR #6367 (oracle: TigerBeetle breaks a linked
// chain at the first non-`Created` leg -- here the earlier
// `Exists` leg -- and never attempts the legs after the break):
// a later leg whose validation would fail must NOT be recorded
// in `failed_transfers`, because it was never attempted; once
// its blocker clears it remains submittable.
let mut ledger = funded_ledger();
// Post leg 700 as the head of a two-leg chain, so the identical
// resubmission below (same `linked: true`) is a byte-identical
// `Exists`, not an `ExistsWithDifferentFields`.
let posted = Transfer {
linked: true,
..funding_transfer(700, USER_SRC, LP_SRC, 100, SRC)
};
let chain_tail = funding_transfer(702, LP_SRC, FEE, 100, SRC);
assert_eq!(
ledger.create_transfers(&[posted.clone(), chain_tail]),
vec![Ok(()), Ok(())]
);
// Chain: the posted leg byte-identical (an `Exists` break at
// offset 0), then a leg debiting an account that does not exist
// yet (a hard validation failure at offset 1).
let exists_leg = posted;
let blocked_leg = funding_transfer(701, 3001, LP_SRC, 100, SRC);
let results = ledger.create_transfers(&[exists_leg, blocked_leg.clone()]);
assert_eq!(
results,
vec![
Err(TransferError::Exists),
Err(TransferError::LinkedEventFailed),
]
);
// Clear the blocker: create and fund the debit account.
let results = ledger.create_accounts(&[account(3001, SRC, false)]);
assert!(results.iter().all(|result| result.is_ok()));
assert_eq!(
ledger.create_transfers(&[funding_transfer(703, ISSUER_SRC, 3001, 1_000, SRC)]),
vec![Ok(())]
);
// The blocked leg now posts on its own -- it was never cached
// as failed (a cached failure would return `IdAlreadyFailed`).
assert_eq!(ledger.create_transfers(&[blocked_leg]), vec![Ok(())]);
assert!(ledger.lookup_transfer(701).is_some());
}

#[test]
fn conflicting_submission_does_not_poison_a_posted_transfer() {
// #6627 (oracle: a posted transfer's byte-identical retry always
// returns `Exists`): a submission reusing a posted ID with
// different fields is rejected with `ExistsWithDifferentFields`,
// and that rejection must not be cached against the posted ID.
let mut ledger = funded_ledger();
let posted = funding_transfer(700, USER_SRC, LP_SRC, 100, SRC);
assert_eq!(ledger.create_transfers(&[posted.clone()]), vec![Ok(())]);
let conflicting = funding_transfer(700, USER_SRC, LP_SRC, 200, SRC);
assert_eq!(
ledger.create_transfers(&[conflicting]),
vec![Err(TransferError::ExistsWithDifferentFields)]
);
assert_eq!(
ledger.create_transfers(&[posted]),
vec![Err(TransferError::Exists)]
);
}

#[test]
fn resubmitted_failed_transfer_returns_id_already_failed_after_cause_fixed() {
// #6628 (oracle: the `IdAlreadyFailed` variant's doc comment and
// the live binding's `Status::IdAlreadyFailed` mapping in
// tb_ledger.rs): a transfer that failed is remembered by ID, and
// resubmitting that ID returns `IdAlreadyFailed` -- even after
// the original failure's cause has been fixed, it must not
// return the stale stored error (here `DebitAccountNotFound`).
let mut ledger = InMemoryLedger::new();
let transfer = funding_transfer(700, USER_SRC, LP_SRC, 100, SRC);
// Neither account exists yet: the transfer fails and its ID is
// recorded as failed.
assert_eq!(
ledger.create_transfers(&[transfer.clone()]),
vec![Err(TransferError::DebitAccountNotFound)]
);
// Fix the cause: create both accounts and fund the debit side,
// so the same transfer would now post if it were a fresh ID.
let results = ledger.create_accounts(&[
account(ISSUER_SRC, SRC, false),
account(USER_SRC, SRC, false),
account(LP_SRC, SRC, false),
]);
assert!(results.iter().all(|result| result.is_ok()));
assert_eq!(
ledger.create_transfers(&[funding_transfer(701, ISSUER_SRC, USER_SRC, 1_000, SRC)]),
vec![Ok(())]
);
// Resubmission of the failed ID is still refused, with
// `IdAlreadyFailed`, and nothing posts.
assert_eq!(
ledger.create_transfers(&[transfer]),
vec![Err(TransferError::IdAlreadyFailed)]
);
assert!(ledger.lookup_transfer(700).is_none());
}

#[test]
fn single_unterminated_linked_transfer_rejected() {
// #4121: a lone transfer with `linked: true` promises a following
Expand Down
Loading