Repository navigation
id: conversion-executor PoC — linked transfer pairs, write-ahead intent, recovery scanner (#2289) #3873
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
id: conversion-executor PoC — linked transfer pairs, write-ahead intent, recovery scanner (#2289) #3873
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,286 @@ | ||
| //! The conversion executor: pre-flight, write-ahead intent, linked | ||
| //! batch submission. | ||
| //! | ||
| //! A conversion is the composed pair from the TigerBeetle Currency | ||
| //! Exchange recipe (see the #2040 investigation): T1 moves the source | ||
| //! amount from the user to the liquidity provider (LP) on the source | ||
| //! ledger, an optional fee leg moves the fee from the user to the fee | ||
| //! account on the source ledger, and T3 moves the converted amount | ||
| //! from the LP to the user on the destination ledger. All legs are | ||
| //! stamped `user_data_128 = conversion_id` and submitted as ONE linked | ||
| //! batch, so either every leg posts or none does. | ||
| //! | ||
| //! Cross-ledger transfers do not exist in TigerBeetle; the exchange | ||
| //! rate and its authorisation are control-plane data (#2063), carried | ||
| //! here as a [`RateQuote`] and recorded on the intent record. | ||
|
|
||
| use anyhow::{Context, Result, bail}; | ||
|
|
||
| use super::intent::{IntentRecord, IntentState, IntentStore}; | ||
| use super::ledger::{AccountId, LedgerBackend, Transfer, TransferError}; | ||
|
|
||
| /// Transfer `code` for conversion legs (chart-of-accounts, #2063). | ||
| pub const TRANSFER_CODE_CONVERSION: u16 = 1; | ||
|
|
||
| /// An authorised rate: `amount_out = amount_in * numerator / denominator`, | ||
| /// rounded down — in the LP's favour, per the Currency Exchange recipe. | ||
| #[derive(Clone, Debug, PartialEq, Eq)] | ||
| pub struct RateQuote { | ||
| pub numerator: u128, | ||
| pub denominator: u128, | ||
| pub authorisation_id: String, | ||
| } | ||
|
|
||
| impl RateQuote { | ||
| /// The converted amount, or `None` when the quote is malformed | ||
| /// (zero denominator) or the multiplication overflows `u128`. | ||
| /// Overflow is an explicit failure, never a silent saturation: | ||
| /// a saturated product would silently change the authorised rate. | ||
| pub fn amount_out(&self, amount_in: u128) -> Option<u128> { | ||
| if self.denominator == 0 { | ||
| return None; | ||
| } | ||
| amount_in | ||
| .checked_mul(self.numerator) | ||
| .map(|product| product / self.denominator) | ||
| } | ||
| } | ||
|
|
||
| /// Everything needed to execute one conversion. Accounts are stub | ||
| /// TigerBeetle accounts created by the caller (the PoC sanctions stub | ||
| /// accounts; real account/LP representation comes from #2062). | ||
| #[derive(Clone, Debug)] | ||
| pub struct ConversionRequest { | ||
| pub conversion_id: u128, | ||
| /// Pre-generated transfer IDs, one per leg, in leg order | ||
| /// (T1, fee leg if any, T3). Generated by the caller and persisted | ||
| /// on the intent record before submission. | ||
| pub transfer_ids: Vec<u128>, | ||
| pub user_source: AccountId, | ||
| pub lp_source: AccountId, | ||
| pub fee_account: Option<AccountId>, | ||
| pub lp_dest: AccountId, | ||
| pub user_dest: AccountId, | ||
| pub source_ledger: u32, | ||
| pub dest_ledger: u32, | ||
| pub amount_in: u128, | ||
| /// Fee taken on the source ledger; 0 means no fee leg. | ||
| pub fee_amount: u128, | ||
| pub quote: RateQuote, | ||
| } | ||
|
|
||
| /// Executes conversions against a [`LedgerBackend`], writing intent | ||
| /// records to an [`IntentStore`] ahead of every submission. | ||
| pub struct ConversionExecutor<B: LedgerBackend, S: IntentStore> { | ||
| pub backend: B, | ||
| pub store: S, | ||
| } | ||
|
|
||
| impl<B: LedgerBackend, S: IntentStore> ConversionExecutor<B, S> { | ||
| pub fn new(backend: B, store: S) -> Self { | ||
| Self { backend, store } | ||
| } | ||
|
|
||
| /// Build the legs for a request. Every leg but the last is | ||
| /// `linked`; the batch is submitted as one chain. | ||
| pub fn build_legs(request: &ConversionRequest) -> Result<Vec<Transfer>> { | ||
| let amount_out = request.quote.amount_out(request.amount_in).context( | ||
| "rate quote is malformed (zero denominator) or its multiplication overflows", | ||
| )?; | ||
| let mut legs = Vec::with_capacity(3); | ||
| let mut ids = request.transfer_ids.iter(); | ||
| let mut next_id = move || -> Result<u128> { | ||
| ids.next() | ||
| .copied() | ||
| .context("transfer_ids must cover every leg (T1, fee, T3)") | ||
| }; | ||
| legs.push(Transfer { | ||
| id: next_id()?, | ||
| debit_account_id: request.user_source, | ||
| credit_account_id: request.lp_source, | ||
| amount: request.amount_in, | ||
| ledger: request.source_ledger, | ||
| user_data_128: request.conversion_id, | ||
| code: TRANSFER_CODE_CONVERSION, | ||
| linked: true, | ||
| }); | ||
| if request.fee_amount > 0 { | ||
| legs.push(Transfer { | ||
| id: next_id()?, | ||
| debit_account_id: request.user_source, | ||
| credit_account_id: request | ||
| .fee_account | ||
| .context("fee_amount > 0 requires a fee_account")?, | ||
| amount: request.fee_amount, | ||
| ledger: request.source_ledger, | ||
| user_data_128: request.conversion_id, | ||
| code: TRANSFER_CODE_CONVERSION, | ||
| linked: true, | ||
| }); | ||
| } | ||
| legs.push(Transfer { | ||
| id: next_id()?, | ||
| debit_account_id: request.lp_dest, | ||
| credit_account_id: request.user_dest, | ||
| amount: amount_out, | ||
| ledger: request.dest_ledger, | ||
| user_data_128: request.conversion_id, | ||
| code: TRANSFER_CODE_CONVERSION, | ||
| linked: false, | ||
| }); | ||
| Ok(legs) | ||
| } | ||
|
|
||
| /// Pre-flight (§4 of #2063): every account exists on the right | ||
| /// ledger, the user can cover amount + fee, and the LP holds | ||
| /// enough destination inventory. Failing here means no intent is | ||
| /// written and nothing is submitted. | ||
| pub fn preflight(&self, request: &ConversionRequest) -> Result<()> { | ||
| if request.quote.denominator == 0 { | ||
| bail!("preflight: rate quote has a zero denominator"); | ||
| } | ||
| let amount_out = request | ||
| .quote | ||
| .amount_out(request.amount_in) | ||
| .context("preflight: rate quote multiplication overflows")?; | ||
| if amount_out == 0 { | ||
| bail!("preflight: rate quote produces a zero destination amount"); | ||
| } | ||
| let check_account = |id: AccountId, ledger: u32, role: &str| -> Result<()> { | ||
| let account = self | ||
| .backend | ||
| .lookup_account(id) | ||
| .with_context(|| format!("preflight: {role} account {id} does not exist"))?; | ||
| if account.ledger != ledger { | ||
| bail!( | ||
| "preflight: {role} account {id} is on ledger {}, expected {ledger}", | ||
| account.ledger | ||
| ); | ||
| } | ||
| Ok(()) | ||
| }; | ||
| check_account(request.user_source, request.source_ledger, "user source")?; | ||
| check_account(request.lp_source, request.source_ledger, "LP source")?; | ||
| if let Some(fee_account) = request.fee_account { | ||
| check_account(fee_account, request.source_ledger, "fee")?; | ||
| } | ||
| check_account(request.lp_dest, request.dest_ledger, "LP destination")?; | ||
| check_account(request.user_dest, request.dest_ledger, "user destination")?; | ||
|
|
||
| let user_balance = self | ||
| .backend | ||
| .account_balance(request.user_source) | ||
| .context("preflight: user source balance missing")?; | ||
| let needed = request | ||
| .amount_in | ||
| .checked_add(request.fee_amount) | ||
| .context("preflight: amount + fee overflow")?; | ||
| if user_balance.spendable() < needed { | ||
| bail!( | ||
| "preflight: user source spendable {} < amount + fee {needed}", | ||
| user_balance.spendable() | ||
| ); | ||
| } | ||
| let lp_balance = self | ||
| .backend | ||
| .account_balance(request.lp_dest) | ||
| .context("preflight: LP destination balance missing")?; | ||
| if lp_balance.spendable() < amount_out { | ||
| bail!( | ||
| "preflight: insufficient LP inventory — LP destination spendable {} < amount_out {amount_out}", | ||
| lp_balance.spendable() | ||
| ); | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Write-ahead phase: pre-flight, build the legs, and persist the | ||
| /// intent record (state `Recorded`) BEFORE any submission. Kept | ||
| /// separate from [`Self::submit`] so the crash window between | ||
| /// intent and submission is directly testable. | ||
| pub fn prepare(&mut self, request: &ConversionRequest) -> Result<IntentRecord> { | ||
| self.preflight(request)?; | ||
| let legs = Self::build_legs(request)?; | ||
| let amount_out = request.quote.amount_out(request.amount_in).context( | ||
| "rate quote is malformed (zero denominator) or its multiplication overflows", | ||
| )?; | ||
| let record = IntentRecord { | ||
| conversion_id: request.conversion_id, | ||
| legs, | ||
| user_source: request.user_source, | ||
| lp_source: request.lp_source, | ||
| fee_account: request.fee_account, | ||
| lp_dest: request.lp_dest, | ||
| user_dest: request.user_dest, | ||
| source_ledger: request.source_ledger, | ||
| dest_ledger: request.dest_ledger, | ||
| amount_in: request.amount_in, | ||
| amount_out, | ||
| fee_amount: request.fee_amount, | ||
| authorisation_id: request.quote.authorisation_id.clone(), | ||
| state: IntentState::Recorded, | ||
| }; | ||
| // A conversion ID is the identity of ONE conversion: never | ||
| // replace its persisted intent. An identical retry reuses the | ||
| // original record (with its state); a conflicting request is | ||
| // rejected, so a retry can never erase the recovery record of | ||
| // an earlier, possibly-posted submission. | ||
| if let Some(existing) = self | ||
| .store | ||
| .get(record.conversion_id) | ||
| .context("intent lookup before persist failed")? | ||
| { | ||
| let mut comparable = existing.clone(); | ||
| comparable.state = record.state; | ||
| if comparable == record { | ||
| return Ok(existing); | ||
| } | ||
| bail!( | ||
| "prepare: conversion {} already has a persisted intent with different legs or amounts; refusing to replace it", | ||
| record.conversion_id | ||
| ); | ||
| } | ||
| self.store | ||
| .put(&record) | ||
| .context("write-ahead intent persist failed")?; | ||
|
Comment on lines
+243
to
+245
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
If a caller retries an existing conversion ID with newly generated transfer IDs, Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in b02ab96: prepare looks up the conversion ID first - an identical retry reuses the persisted intent (state included), a conflicting one is rejected instead of replacing the record. Regression test: conversion_id_reuse_cannot_replace_persisted_intent. |
||
| Ok(record) | ||
| } | ||
|
|
||
| /// Submission phase: mark the record `Submitted` (still ahead of | ||
| /// the ledger call), submit the linked batch, then mark `Posted`. | ||
| /// A crash between the ledger call and the `Posted` write leaves a | ||
| /// `Submitted` record the recovery scanner reconciles by lookup — | ||
| /// it never resubmits blindly, and idempotent IDs make even a | ||
| /// resubmission safe. | ||
| pub fn submit(&mut self, record: &mut IntentRecord) -> Result<()> { | ||
| record.state = IntentState::Submitted; | ||
| self.store | ||
| .put(record) | ||
| .context("intent state persist (Submitted) failed")?; | ||
| let results = self.backend.create_transfers(&record.legs); | ||
| for (leg, result) in record.legs.iter().zip(results.iter()) { | ||
| match result { | ||
| Ok(()) | Err(TransferError::Exists) => {} | ||
| Err(error) => { | ||
| bail!( | ||
| "conversion {} leg {} failed: {error:?}", | ||
| record.conversion_id, | ||
| leg.id | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| record.state = IntentState::Posted; | ||
| self.store | ||
| .put(record) | ||
| .context("intent state persist (Posted) failed")?; | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// The normal path: prepare (write-ahead) then submit. | ||
| pub fn execute(&mut self, request: &ConversionRequest) -> Result<IntentRecord> { | ||
| let mut record = self.prepare(request)?; | ||
| self.submit(&mut record)?; | ||
| Ok(record) | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a successful conversion leaves the user or LP unable to fund the same conversion again, an identical retry fails here before reaching the existing-intent lookup. For example, using the test fixture with
amount_in = 10_000andfee_amount = 0posts successfully, but retrying that request fails because the user's spendable balance is now zero, despite its persisted intent already beingPosted. This prevents callers from obtaining the successful result after a lost response. Check and validate the existing intent before applying funding preflight checks intended for a new conversion.Useful? React with 👍 / 👎.