Skip to content

id: conversion-executor PoC — linked transfer pairs, write-ahead intent, recovery scanner (#2289) - #3873

Merged
dezren39 merged 3 commits into
mainfrom
queue/5239-2289-conversion-executor-poc
Nov 2, 2026
Merged

dezren39 merged 3 commits into
mainfrom
queue/5239-2289-conversion-executor-poc

Conversation

@dezren39

@dezren39 dezren39 commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Implements the #2289 conversion-executor PoC (from the #2063 design). PoC only — not the permanent feature (program rule on #2056: review round first).

What's here (pkgs/id/src/currency_poc/)

  • Step 0 — harness (harness.rs): throwaway single-replica TigerBeetle test cluster the suite can start/stop (sanctioned shape per the cluster-topology investigation). Binary pinned to 0.17.9 (verified latest release via the GitHub releases API) and version-checked before start; release-zip acquisition URL recorded in the module. Ignored smoke test: cargo test -p id currency_poc -- --ignored.
  • Ledger seam (ledger.rs): TigerBeetle-shaped Account/Transfer types and a LedgerBackend trait, plus an in-memory backend implementing the TB semantics the executor depends on — atomic linked chains, idempotent transfer IDs (Exists on identical resubmission), balance-invariant flags, cross-ledger rejection. Per the id: investigate: TigerBeetle — multi-currency ledgers, conversions, per-coin vs balance model, 3-node cluster topology #2040 investigation, the client choice for a real binding is the official Rust client; it can implement this same trait against the harness cluster.
  • Write-ahead intent (intent.rs): conversion ID + pre-generated transfer IDs + amounts + authorisation ID persisted (fsync + atomic rename in the file store) before any submission.
  • Executor (executor.rs): LP pre-flight (accounts/ledgers, user covers amount+fee, LP destination inventory), then one linked batch — T1 user→LP (source ledger), optional fee leg, T3 LP→user (destination ledger) — every leg stamped user_data_128 = conversion_id.
  • Recovery scanner (recovery.rs): reconciles Recorded/Submitted intents by transfer-ID lookup — all present ⇒ Posted; none present ⇒ resubmit the same byte-identical IDs (or abandon); partial ⇒ reported inconsistent, never guessed.

Tests — #2063 §4 cases (tests.rs)

Standalone-verified on the laptop (module + same deps, cargo test): 7 passed, 1 ignored (the ignored one is the real-cluster smoke test).

  • posted conversion: all legs findable by user_data_128, balances move exactly once
  • atomic failure: a leg forced to fail in-batch ⇒ no balance moves, no leg stored, other legs report linked_event_failed
  • crash after submission (before the Posted write): scanner marks Posted by lookup, no double-posting
  • crash before submission: scanner resubmits the same IDs; second scan is a no-op
  • insufficient LP inventory fails pre-flight — no intent written, nothing submitted
  • file intent store survives drop/reopen and reconciles

CI (id-check.yml) is the authoritative in-tree run; this PR parks in the queue awaiting it.

Remaining / honest gaps

Closes-in-part: #2289 acceptance items 1–2 are demonstrated by the test suite above (item 1 against the semantics backend; live-cluster demonstration pending the client binding); item 3 is the #2063 comment posted with this PR.


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

…nt, recovery scanner (#2289)

PoC per #2289 from the #2063 conversion-engine design. Not the
permanent feature (#2056 review-round rule).

- ledger: TigerBeetle-shaped types, LedgerBackend seam, in-memory
  backend with TB semantics (atomic linked chains, idempotent
  transfer IDs, balance-invariant flags)
- intent: write-ahead intent records (conversion id + pre-generated
  transfer IDs + amounts + authorisation id) persisted before
  submission; file-backed store with fsync + atomic rename
- executor: LP pre-flight, one linked batch (T1 user->LP, optional
  fee leg, T3 LP->user), user_data_128 = conversion_id on all legs
- recovery: scanner reconciles Recorded/Submitted intents by
  transfer-ID lookup (present = Posted; absent = resubmit same IDs
  or abandon)
- harness: step-0 throwaway single-replica TigerBeetle test cluster,
  binary pinned to 0.17.9 (verified latest release), start/stop with
  an ignored smoke test

Tests (standalone-verified on the laptop, same module/deps):
7 passed, 1 ignored — posted conversion findable by user_data_128,
atomic failure moves nothing, crash recovery in both windows without
double-posting, LP pre-flight rejection, file-store reopen recovery.
CI (id-check) is the authoritative run for the in-tree build.
@dezren39
dezren39 requested a review from a team as a code owner November 1, 2026 17:24
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T01:47:52.833727Z 031ab3e New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 26 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 86fe584c-73f3-4eed-a3ee-e631a9beb5ae
Commits

Reviewing files that changed from the base of the PR and between d963623 and 031ab3e.

Files selected for processing: 8
  • pkgs/id/src/currency_poc/executor.rs
  • pkgs/id/src/currency_poc/harness.rs
  • pkgs/id/src/currency_poc/intent.rs
  • pkgs/id/src/currency_poc/ledger.rs
  • pkgs/id/src/currency_poc/mod.rs
  • pkgs/id/src/currency_poc/recovery.rs
  • pkgs/id/src/currency_poc/tests.rs
  • pkgs/id/src/lib.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ead200f74e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread pkgs/id/src/currency_poc/executor.rs Outdated
Comment on lines +128 to +130
let amount_out = request.quote.amount_out(request.amount_in);
if request.quote.denominator == 0 {
bail!("preflight: rate quote has a zero denominator");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check the denominator before calculating the output amount

When a request has a zero quote denominator, preflight calls amount_out before reaching the explicit validation, so integer division panics instead of returning the intended error. Move the denominator check ahead of the calculation so malformed quotes are rejected without terminating the caller.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b02ab96: preflight now checks the denominator before any calculation, and RateQuote::amount_out itself returns None on a zero denominator. Regression test: zero_denominator_quote_is_rejected_not_a_panic.

Comment thread pkgs/id/src/currency_poc/executor.rs Outdated
}

impl RateQuote {
pub fn amount_out(&self, amount_in: u128) -> u128 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid silently saturating the rate calculation

When amount_in * numerator overflows, saturation silently changes the authorised exchange rate even if the final quotient fits in u128. For example, amount_in = 2 and numerator = denominator = u128::MAX should produce 2, but this calculation produces 1, which the executor can successfully post. Use overflow-safe multiply/divide arithmetic or return an explicit overflow error rather than submitting a conversion with an incorrect destination amount.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b02ab96: amount_out uses checked_mul and returns Option; every caller bails with an explicit overflow error instead of posting a saturated rate. Regression test: overflowing_quote_is_rejected_not_saturated.

Comment on lines +143 to +144
fs::rename(&tmp, &path)?;
Ok(())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Sync the intent directory after renaming the record

On a machine crash or power loss, syncing the temporary file does not guarantee durability of the subsequent rename in the containing directory. Consequently, put can return successfully and permit ledger submission while the write-ahead intent's filename is still not durable; recovery may then lose the record needed to reconcile that submission. Sync the containing directory after the rename before returning success.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b02ab96: FileIntentStore::put now opens and sync_all's the containing directory after the rename, so the directory entry is durable before put returns.

Comment thread pkgs/id/src/currency_poc/harness.rs Outdated
Comment on lines +119 to +122
if let Ok(mut stream) = TcpStream::connect(&self.address) {
let _ = stream.write_all(b"");
let _ = stream.read(&mut [0u8; 1]);
return Ok(());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove the unbounded read from the readiness probe

If the replica accepts the TCP connection but sends no unsolicited data, this blocking read never returns: the probe sends no protocol request and sets no read timeout. The surrounding 30-second deadline is therefore never checked again, so TestCluster::start and the ignored smoke test can hang indefinitely. Treat a successful connection as readiness, or use a bounded protocol-aware probe.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b02ab96: wait_ready treats a successful TCP connect as readiness and no longer reads from the socket, so the 30s deadline is enforceable.

Comment thread pkgs/id/src/currency_poc/ledger.rs Outdated
Comment on lines +255 to +256
for (offset, transfer) in chain.iter().enumerate() {
match self.validate_and_stage(transfer, &mut staged) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject duplicate transfer IDs within a staged chain

When two legs share a transfer ID, validation checks only committed transfers, so both legs stage their balance changes and return success. The later commit loop stores only the first leg under that ID, leaving posted balance movements absent from the transfer journal. This is reachable through ConversionRequest.transfer_ids, which has no uniqueness check, and was reproduced with two linked legs returning success but only one stored transfer. Track IDs during chain validation and reject duplicates before committing any balance changes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b02ab96: create_transfers tracks staged transfer IDs per chain and rejects a duplicate (Exists if identical, ExistsWithDifferentFields otherwise) before any balance change commits. Regression test: duplicate_transfer_id_in_one_chain_is_rejected.

Comment thread pkgs/id/src/currency_poc/recovery.rs Outdated
let present = record
.legs
.iter()
.filter(|leg| backend.lookup_transfer(leg.id).is_some())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Verify transfer contents before marking an intent posted

When persisted transfer IDs collide with unrelated existing transfers, this existence-only check marks the conversion AlreadyPosted even though its requested legs never executed. For example, a prepared no-fee request using IDs 501 and 502 from the test fixture's funding transfers is incorrectly reconciled as posted. Compare each looked-up transfer with its persisted leg and report mismatches as inconsistent instead of treating ID presence as proof of posting.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b02ab96: the scanner counts a leg as posted only when the looked-up transfer equals the persisted leg; ID collisions with different contents are reported Inconsistent. Regression test: recovery_does_not_trust_transfer_id_existence_alone (your 501/502 fixture case).

Comment on lines +206 to +208
self.store
.put(&record)
.context("write-ahead intent persist failed")?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the original intent when a conversion ID is reused

If a caller retries an existing conversion ID with newly generated transfer IDs, prepare unconditionally replaces its persisted intent because both stores implement put as insert-or-replace. After an earlier successful or outcome-unknown submission, the new IDs can post the same conversion again, while the original recovery record is erased. Look up the conversion ID before preparing a replacement and either reuse the original immutable legs or reject a conflicting request.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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.

Comment thread pkgs/id/src/currency_poc/recovery.rs Outdated
Comment on lines +69 to +73
if let Some(error) = failed {
anyhow::bail!(
"recovery resubmission of conversion {} failed: {error:?}",
record.conversion_id
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Continue scanning after an individual resubmission is rejected

When a conversion becomes unfundable after preparation, as demonstrated by atomic_failure_moves_nothing, its resubmission encounters an ordinary ledger rejection and this bail! aborts recovery of every subsequent intent. The rejected record remains unresolved; with unchanged in-memory store contents, subsequent scans encounter records in the same order and repeatedly leave later valid or already-posted conversions unreconciled. Report the rejection per intent and continue scanning the remaining records.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b02ab96: a rejected resubmission now yields a per-record ResubmissionRejected outcome, leaves that record unresolved, and the scan continues with the remaining records. Regression test: recovery_scan_continues_after_a_rejected_resubmission.

#2289)

- executor: amount_out is checked (zero denominator / overflow are
  explicit errors, never a panic or silent saturation); preflight
  checks the denominator before calculating
- executor: prepare never replaces a persisted intent for a reused
  conversion ID - identical retries reuse it, conflicting ones bail
- intent: FileIntentStore syncs the containing directory after the
  rename so the write-ahead record itself is durable
- harness: readiness probe treats a successful TCP connect as ready;
  the unbounded read that defeated the 30s deadline is gone
- ledger: duplicate transfer IDs within one staged chain are
  rejected (Exists / ExistsWithDifferentFields) before any staging
- recovery: AlreadyPosted requires each looked-up transfer to equal
  the persisted leg, not just exist by ID
- recovery: a rejected resubmission is reported per-record
  (ResubmissionRejected) and the scan continues

Tests: 6 new regression tests; cargo test --lib currency_poc on the
laptop: 13 passed, 0 failed, 1 ignored (live-cluster smoke).
…rsion-executor-poc

# Conflicts:
#	pkgs/id/src/lib.rs

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b02ab96212

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +201 to +202
pub fn prepare(&mut self, request: &ConversionRequest) -> Result<IntentRecord> {
self.preflight(request)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve existing intents before checking current balances

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_000 and fee_amount = 0 posts successfully, but retrying that request fails because the user's spendable balance is now zero, despite its persisted intent already being Posted. 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 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant