Browse Source

Commit each transfer in one store transaction instead of a saga

The write-ahead saga (reserve then finalize, PendingSaga, Ledger::recover)
existed only because storage could not commit a transfer atomically. But
every primitive it orchestrated lived behind one transactional store, so the
saga reimplemented in application code the atomicity the database already
provides. It also left the overdraft floor and freeze/close guards
best-effort under concurrency, and it kept the legend dependency alive for
two adapters used only by tests.

Add a CommitStore sub-trait (commit_envelope, commit_transition) that applies
the whole envelope, or a whole account-version transition, in a single
transaction (SQL BEGIN..COMMIT; in-memory one lock span). The pure core still
validates first; the transaction re-checks the stateful guards inside it:
double-spend (the delete-affected-count is the atomic single-winner claim),
freeze/close, and the overdraft floor (summed in Rust, never in SQL). Those
guards are now strict, not best-effort.

Because a commit is all-or-nothing, a crash leaves no half-applied state, so
the write-ahead machinery is gone: SagaStore, SagaKind, PendingSaga,
PendingTransition, Ledger::recover, and the reserve/finalize two-step. The
sagas table is dropped in migration 010. legend is removed; multi-transfer
composition is a plain LIFO runner (saga::run_movements) over commit/reverse.

This pins crash-safety to a per-backend transaction, giving up cross-shard
composition. That trade is deliberate: a saga belongs in a backend that
shards its data, behind the same commit_envelope contract, not in the ledger
core that has no distribution problem. Recorded in ADR-0023, superseding
ADR-0003 and ADR-0020, refining ADR-0002, amending ADR-0021.

The generic reserve_postings/release_postings primitives stay as
conformance-tested plumbing, now unused by the commit path.
Cesar Rodas 3 tháng trước cách đây
mục cha
commit
8bf5f4c00e
40 tập tin đã thay đổi với 1694 bổ sung và 2166 xóa
  1. 9 9
      CLAUDE.md
  2. 1 47
      Cargo.lock
  3. 0 1
      Cargo.toml
  4. 2 3
      crates/kuatia-dashboard/src/seed.rs
  5. 377 0
      crates/kuatia-storage-sql/src/commit.rs
  6. 3 3
      crates/kuatia-storage-sql/src/lib.rs
  7. 4 0
      crates/kuatia-storage-sql/src/migrate.rs
  8. 4 0
      crates/kuatia-storage-sql/src/migrations/010_drop_sagas.sql
  9. 2 2
      crates/kuatia-storage-sql/src/posting.rs
  10. 0 74
      crates/kuatia-storage-sql/src/saga.rs
  11. 3 0
      crates/kuatia-storage-sql/tests/sqlite.rs
  12. 7 7
      crates/kuatia-storage/README.md
  13. 179 26
      crates/kuatia-storage/src/mem_store.rs
  14. 116 55
      crates/kuatia-storage/src/store.rs
  15. 366 46
      crates/kuatia-storage/src/store_tests.rs
  16. 3 3
      crates/kuatia-storage/tests/concurrency.rs
  17. 0 1
      crates/kuatia/Cargo.toml
  18. 23 28
      crates/kuatia/README.md
  19. 0 3
      crates/kuatia/examples/create_accounts.rs
  20. 0 2
      crates/kuatia/examples/fund_and_trade.rs
  21. 0 2
      crates/kuatia/examples/inflight_hold.rs
  22. 0 2
      crates/kuatia/examples/withdraw.rs
  23. 5 0
      crates/kuatia/src/error.rs
  24. 2 3
      crates/kuatia/src/ledger.rs
  25. 98 740
      crates/kuatia/src/ledger/commit.rs
  26. 0 237
      crates/kuatia/src/ledger/pending.rs
  27. 22 44
      crates/kuatia/src/ledger/transition.rs
  28. 54 359
      crates/kuatia/src/saga.rs
  29. 20 20
      crates/kuatia/tests/concurrency.rs
  30. 72 139
      crates/kuatia/tests/saga.rs
  31. 1 1
      doc/adr/0003-dumb-storage-saga-recovery.md
  32. 1 1
      doc/adr/0020-account-transition-recovery.md
  33. 3 1
      doc/adr/0021-commit-safety-map.md
  34. 137 0
      doc/adr/0023-atomic-storage-commit.md
  35. 5 2
      doc/adr/README.md
  36. 88 170
      doc/architecture.md
  37. 50 74
      doc/crates.md
  38. 17 30
      doc/glossary.md
  39. 10 16
      doc/storage-schema.md
  40. 10 15
      doc/transfers.md

+ 9 - 9
CLAUDE.md

@@ -13,7 +13,7 @@ crates/
   kuatia-core/      Pure, sync, no-IO logic: validation, hashing, posting selection
   kuatia-storage/   Store trait (7 sub-traits), InMemoryStore, conformance tests
   kuatia-storage-sql/  SQL backend: SQLite/PostgreSQL via sqlx
-  kuatia/           Async layer: Ledger resource, saga pipeline, intent API
+  kuatia/           Async layer: Ledger resource, atomic commit engine, intent API
 doc/
   architecture.md   Architecture decisions and rationale
   crates.md         Crate reference: modules, types, APIs
@@ -31,17 +31,17 @@ doc/
 - **Envelope**: concrete postings to consume and create — the resolved form of movements.
 - **Conservation**: for each asset, `sum(consumed) == sum(created)`.
 - **Balance constraint**: one per-account flag, `AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`. Default (no flag): overdraft allowed, unbounded, a shortfall becomes a negative offset posting and the transfer records if it conserves value. Flag set: balance may not go negative and the account may not hold a negative posting. Construct with `Account::debit_must_not_exceed_credit(id)`; query with `Account::forbids_overdraft()`. There is no bounded floor and no system/external policy label; a boundary/deposit account is just a default overdraft-permitting account.
-- **Dumb storage**: the `Store` is a thin instruction follower. Write methods apply one update and return the **number of affected rows** (or an I/O error) — they never interpret counts, decide state, enforce idempotency, or compensate. The saga owns all of that. There is no monolithic `commit_transfer`; commit is a sequence of dumb primitives (`reserve_postings`, `deactivate_postings`, `insert_postings`, `store_transfer`, `append_event`), each idempotent. See [doc/adr/0003-dumb-storage-saga-recovery.md](doc/adr/0003-dumb-storage-saga-recovery.md).
+- **Atomic storage commit**: the `Store` applies a whole transfer in one transaction via `CommitStore::commit_envelope` (and a whole account-version transition via `commit_transition`). The pure core validates first; the transaction re-checks the stateful guards inside it — double-spend, freeze/close, and the overdraft floor — so they are strict, not best-effort. `commit(transfer)` = resolve (read-only) then `commit_envelope`; `reverse()` builds a reversal envelope and runs the same path. A crash leaves no half-applied state, so there is no write-ahead log and no recovery. See [doc/adr/0023-atomic-storage-commit.md](doc/adr/0023-atomic-storage-commit.md) (supersedes 0003). Reads and the `insert_postings`/`reserve_postings`/`release_postings`/`deactivate_postings` posting primitives remain as dumb single-update instructions returning affected-row counts.
 
 ## Architecture
 
-- **Pure core / async layer separation**: kuatia-core has zero IO, fully deterministic, testable with golden vectors. kuatia adds async Store trait and saga pipeline.
-- **Saga commit pipeline**: every commit is the **two-step** envelope saga `reserve → finalize` (validation runs inside the finalize step, as the last thing before the writes), with automatic retry and LIFO compensation via the `legend` crate. `commit(transfer)` = resolve (read-only) then `commit_envelope`; `reverse()` builds a reversal envelope and runs the same path. There is one commit path, not a separate "atomic" one.
-- **Count interpretation**: the saga reads each primitive's affected-row count — full = continue; partial = error → compensate; zero = read state and continue only if this same envelope/reservation already applied it (idempotency). `finalize_envelope` additionally verifies every end-state (all consumed postings `Inactive`, created exist, transfer stored).
-- **Durable recovery**: a phase-tracked write-ahead `PendingSaga {envelope, reservation, phase}` is persisted via `SagaStore` before the saga mutates anything (`Reserving`), bumped to `Finalizing` once validation passed and the consumed postings are about to turn `Inactive`. `Ledger::recover()` (call on startup) branches on phase: a `Reserving` saga is **re-run and re-validated** (aborting cleanly if a posting was taken or an account frozen); a `Finalizing` saga is rolled forward through the verified `finalize_envelope`. Roll-forward, not rollback, so there are no orphaned `PendingInactive` postings to reconcile.
+- **Pure core / async layer separation**: kuatia-core has zero IO, fully deterministic, testable with golden vectors. kuatia adds the async Store trait and the commit engine.
+- **Atomic commit path**: `commit(transfer)` = resolve (read-only) → validate in the pure core → `store.commit_envelope(..)`, one transaction that spends the consumed postings, inserts the created ones, stores the transfer, and appends the committed event. `reverse()` builds a reversal envelope and runs the same path. There is one commit path.
+- **In-transaction guards**: the store re-checks double-spend (the delete-affected-count is the atomic single-winner claim), freeze/close (over the involved accounts), and the overdraft floor (summed in Rust from live rows, never in SQL) inside the commit transaction. A domain rejection is a typed `CommitRejection` the ledger maps back to a `LedgerError`.
+- **No recovery**: because a commit is all-or-nothing, a crash leaves no half-applied state. There is no `PendingSaga`, no `SagaStore`, and no `Ledger::recover()`. Multi-transfer composition is a plain LIFO runner (`saga::run_movements`) over `commit`/`reverse`, not a saga VM.
 - **Content-addressed transfers**: EnvelopeId = double-SHA-256 of canonical bytes. Provides idempotency and tamper evidence.
-- **Append-only accounts**: versioned, never modified in place. Snapshot pinning (validate-time) prevents TOCTOU races; under the dumb-storage model the no-overdraft (zero-floor) and freeze/close guards are validate-time and best-effort under concurrency.
-- **Store uses `Arc<dyn Store>`**: Ledger is non-generic, enabling concrete saga types.
+- **Append-only accounts**: versioned, never modified in place. Snapshot pinning (validate-time) prevents TOCTOU races; the no-overdraft (zero-floor) and freeze/close guards are re-checked strictly inside the atomic commit transaction (ADR-0023), not just at validate time.
+- **Store uses `Arc<dyn Store>`**: Ledger is non-generic.
 
 ## Resolve algorithm
 
@@ -69,7 +69,7 @@ Deposit: two movements cancel to zero net debit on the system account — no pos
 ```bash
 cargo test          # runs all tests across all crates
 cargo test -p kuatia-core   # pure core tests only
-cargo test -p kuatia        # integration + saga tests
+cargo test -p kuatia        # integration + commit/concurrency tests
 ```
 
 ## Conventions

+ 1 - 47
Cargo.lock

@@ -653,17 +653,6 @@ dependencies = [
 ]
 
 [[package]]
-name = "getrandom"
-version = "0.4.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
-dependencies = [
- "cfg-if",
- "libc",
- "r-efi",
-]
-
-[[package]]
 name = "globset"
 version = "0.4.18"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1038,7 +1027,6 @@ dependencies = [
  "kuatia-storage",
  "kuatia-storage-sql",
  "kuatia-types",
- "legend",
  "serde",
  "serde_json",
  "sqlx",
@@ -1127,22 +1115,6 @@ dependencies = [
 ]
 
 [[package]]
-name = "legend"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ffc5750e79a4fb740923e73316c3176043859e24154bf874baeab765cefc806b"
-dependencies = [
- "async-trait",
- "parking_lot",
- "paste",
- "serde",
- "serde_json",
- "thiserror",
- "tokio",
- "uuid",
-]
-
-[[package]]
 name = "libc"
 version = "0.2.186"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1529,12 +1501,6 @@ dependencies = [
 ]
 
 [[package]]
-name = "r-efi"
-version = "6.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
-
-[[package]]
 name = "rand"
 version = "0.8.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1561,7 +1527,7 @@ version = "0.6.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
 dependencies = [
- "getrandom 0.2.17",
+ "getrandom",
 ]
 
 [[package]]
@@ -2375,18 +2341,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
 
 [[package]]
-name = "uuid"
-version = "1.23.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "144d6b123cef80b301b8f72a9e2ca4370ddec21950d0a103dd22c437006d2db7"
-dependencies = [
- "getrandom 0.4.3",
- "js-sys",
- "serde_core",
- "wasm-bindgen",
-]
-
-[[package]]
 name = "valuable"
 version = "0.1.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"

+ 0 - 1
Cargo.toml

@@ -30,7 +30,6 @@ async-trait = "0.1"
 tokio = { version = "1" }
 paste = "1"
 sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "any"] }
-legend = "0.1"
 tracing = "0.1"
 
 [workspace.lints.rust]

+ 2 - 3
crates/kuatia-dashboard/src/seed.rs

@@ -38,8 +38,8 @@ pub fn account_label(id: AccountId) -> Option<&'static str> {
     })
 }
 
-/// Connect to the ledger database at `db_url`, create the schema, and run
-/// recovery. The URL scheme selects the backend (e.g. `sqlite::memory:`,
+/// Connect to the ledger database at `db_url` and create the schema. The URL
+/// scheme selects the backend (e.g. `sqlite::memory:`,
 /// `sqlite://kuatia.db`, `postgres://user:pass@host/db`).
 ///
 /// The pool is capped at a single connection: `sqlite::memory:` gives each
@@ -55,7 +55,6 @@ pub async fn connect(db_url: &str) -> Result<Arc<Ledger>, Box<dyn Error>> {
     let store = SqlStore::new(pool);
     store.migrate().await?;
     let ledger = Arc::new(Ledger::new(store));
-    ledger.recover().await?;
     Ok(ledger)
 }
 

+ 377 - 0
crates/kuatia-storage-sql/src/commit.rs

@@ -0,0 +1,377 @@
+//! [`CommitStore`]: the atomic write boundary (ADR-0023).
+//!
+//! A whole transfer, or a whole account-version transition, is applied in one
+//! `BEGIN..COMMIT`. Because the write is all-or-nothing there is no half-applied
+//! state for recovery to reconcile, and the three stateful guards (double-spend,
+//! freeze/close, overdraft floor) are enforced inside the transaction rather than
+//! best-effort before it. On Postgres the account-head reads take `FOR UPDATE`
+//! before the live-posting writes; on SQLite the single write transaction
+//! serializes writers and the delete-affected-count is the double-spend backstop.
+
+use std::collections::HashSet;
+use std::str::FromStr;
+
+use async_trait::async_trait;
+use sqlx::{Row, Transaction};
+
+use kuatia_storage::error::StoreError;
+use kuatia_storage::events::{LedgerEvent, event_dedup_key};
+use kuatia_storage::store::{
+    CommitOutcome, CommitRejection, CommitRequest, CommitStore, TransitionOutcome,
+    TransitionRejection,
+};
+use kuatia_types::*;
+
+use crate::SqlStore;
+use crate::posting::{MAX_IDS_PER_QUERY, id_predicate};
+use crate::row::{deserialize_json, envelope_id_to_hex, row_to_account, serialize_json};
+
+fn internal(e: impl std::fmt::Display) -> StoreError {
+    StoreError::Internal(e.to_string())
+}
+
+impl SqlStore {
+    /// Load one account at its head version inside `tx`, taking the pessimistic
+    /// lock (`FOR UPDATE` on Postgres). `None` means no such account.
+    async fn locked_account(
+        &self,
+        tx: &mut Transaction<'_, sqlx::Any>,
+        id: &AccountId,
+    ) -> Result<Option<Account>, StoreError> {
+        let lock = self.dialect.lock_clause();
+        let row = sqlx::query(&format!(
+            "SELECT a.* FROM accounts a \
+             JOIN account_head h \
+             ON h.id = a.id AND h.subaccount = a.subaccount AND h.version = a.version \
+             WHERE h.id = $1 AND h.subaccount = $2{lock}"
+        ))
+        .bind(id.id)
+        .bind(id.sub)
+        .fetch_optional(&mut **tx)
+        .await
+        .map_err(internal)?;
+        match row {
+            Some(row) => Ok(Some(row_to_account(&row)?)),
+            None => Ok(None),
+        }
+    }
+
+    /// Sum the live-posting values for one `(owner, asset)` inside `tx`. All
+    /// arithmetic is done in Rust with checked addition; the query never sums.
+    async fn live_balance(
+        &self,
+        tx: &mut Transaction<'_, sqlx::Any>,
+        owner: &AccountId,
+        asset: &AssetId,
+    ) -> Result<Cent, StoreError> {
+        let rows = sqlx::query(
+            "SELECT value FROM live_postings WHERE owner = $1 AND subaccount = $2 AND asset = $3",
+        )
+        .bind(owner.id)
+        .bind(owner.sub)
+        .bind(asset.0 as i32)
+        .fetch_all(&mut **tx)
+        .await
+        .map_err(internal)?;
+        let mut values = Vec::with_capacity(rows.len());
+        for row in &rows {
+            let v: String = row.try_get("value").map_err(internal)?;
+            values.push(Cent::from_str(&v).map_err(internal)?);
+        }
+        Cent::checked_sum(values).map_err(internal)
+    }
+}
+
+/// Append `event` inside `tx`, deduping on its key. Mirrors the standalone
+/// `EventStore::append_event` but runs on the commit's transaction.
+async fn append_event_tx(
+    tx: &mut Transaction<'_, sqlx::Any>,
+    autoid: &kuatia_types::autoid::AutoId,
+    event: &LedgerEvent,
+) -> Result<(), StoreError> {
+    let kind_str = serde_json::to_string(&event.kind).map_err(internal)?;
+    let data = serialize_json(event)?;
+    let seq = autoid.next();
+    match event_dedup_key(&event.kind) {
+        Some(dedup_key) => {
+            sqlx::query("INSERT INTO events (seq, timestamp, kind, data, dedup_key) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (dedup_key) DO NOTHING")
+                .bind(seq)
+                .bind(event.timestamp)
+                .bind(&kind_str)
+                .bind(&data)
+                .bind(&dedup_key)
+                .execute(&mut **tx)
+                .await
+                .map_err(internal)?;
+        }
+        None => {
+            sqlx::query("INSERT INTO events (seq, timestamp, kind, data) VALUES ($1, $2, $3, $4)")
+                .bind(seq)
+                .bind(event.timestamp)
+                .bind(&kind_str)
+                .bind(&data)
+                .execute(&mut **tx)
+                .await
+                .map_err(internal)?;
+        }
+    }
+    Ok(())
+}
+
+/// Bind a chunk of posting ids onto a query as `(hex(transfer), idx)` pairs, in
+/// the order [`id_predicate`] expects.
+fn bind_ids<'q>(
+    mut q: sqlx::query::Query<'q, sqlx::Any, sqlx::any::AnyArguments<'q>>,
+    ids: &[PostingId],
+) -> sqlx::query::Query<'q, sqlx::Any, sqlx::any::AnyArguments<'q>> {
+    for id in ids {
+        q = q
+            .bind(envelope_id_to_hex(&id.transfer))
+            .bind(id.index as i16);
+    }
+    q
+}
+
+#[async_trait]
+impl CommitStore for SqlStore {
+    async fn commit_envelope(&self, req: CommitRequest<'_>) -> Result<CommitOutcome, StoreError> {
+        let lock = self.dialect.lock_clause();
+        let mut tx = self.pool.begin().await.map_err(internal)?;
+
+        let tid_hex = envelope_id_to_hex(&req.transfer_id);
+
+        // Idempotency: an already-committed transfer returns its receipt.
+        if let Some(row) = sqlx::query(&format!(
+            "SELECT receipt FROM transfers WHERE id = $1{lock}"
+        ))
+        .bind(&tid_hex)
+        .fetch_optional(&mut *tx)
+        .await
+        .map_err(internal)?
+        {
+            let receipt_json: String = row.try_get("receipt").map_err(internal)?;
+            return Ok(CommitOutcome::AlreadyCommitted(deserialize_json(
+                &receipt_json,
+            )?));
+        }
+
+        // Freeze/close guard, strict inside the transaction. Account-head reads
+        // take the lock before any live-posting write (Postgres lock order).
+        for aid in req.involved {
+            let account = self
+                .locked_account(&mut tx, aid)
+                .await?
+                .ok_or_else(|| StoreError::Internal(format!("commit: account {aid:?} missing")))?;
+            if account.is_frozen() {
+                return Ok(CommitOutcome::Rejected(CommitRejection::AccountFrozen(
+                    *aid,
+                )));
+            }
+            if account.is_closed() {
+                return Ok(CommitOutcome::Rejected(CommitRejection::AccountClosed(
+                    *aid,
+                )));
+            }
+        }
+
+        // Double-spend guard: read the still-Active consumed rows under the lock,
+        // collecting their (owner, asset) for the floor check, and reject if any
+        // consumed id is not live. Then delete them in the same transaction.
+        let mut present: HashSet<(String, i16)> = HashSet::new();
+        let mut touched: HashSet<(AccountId, AssetId)> = HashSet::new();
+        for chunk in req.consume.chunks(MAX_IDS_PER_QUERY) {
+            let sql = format!(
+                "SELECT transfer_id, idx, owner, subaccount, asset FROM live_postings WHERE ({}) AND reservation IS NULL{lock}",
+                id_predicate(chunk.len(), 1)
+            );
+            let rows = bind_ids(sqlx::query(&sql), chunk)
+                .fetch_all(&mut *tx)
+                .await
+                .map_err(internal)?;
+            for row in &rows {
+                let transfer_id: String = row.try_get("transfer_id").map_err(internal)?;
+                let idx: i16 = row.try_get("idx").map_err(internal)?;
+                let owner: i64 = row.try_get("owner").map_err(internal)?;
+                let subaccount: i64 = row.try_get("subaccount").map_err(internal)?;
+                let asset: i32 = row.try_get("asset").map_err(internal)?;
+                present.insert((transfer_id, idx));
+                touched.insert((
+                    AccountId::with_sub(owner, subaccount),
+                    AssetId::new(asset as u32),
+                ));
+            }
+        }
+        if let Some(missing) = req
+            .consume
+            .iter()
+            .find(|id| !present.contains(&(envelope_id_to_hex(&id.transfer), id.index as i16)))
+        {
+            return Ok(CommitOutcome::Rejected(CommitRejection::DoubleSpend(
+                *missing,
+            )));
+        }
+        for chunk in req.consume.chunks(MAX_IDS_PER_QUERY) {
+            let sql = format!(
+                "DELETE FROM live_postings WHERE ({}) AND reservation IS NULL",
+                id_predicate(chunk.len(), 1)
+            );
+            bind_ids(sqlx::query(&sql), chunk)
+                .execute(&mut *tx)
+                .await
+                .map_err(internal)?;
+        }
+
+        // Insert and activate the created postings.
+        for p in req.create {
+            let hex = envelope_id_to_hex(&p.id.transfer);
+            sqlx::query(
+                "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (transfer_id, idx) DO NOTHING",
+            )
+            .bind(&hex)
+            .bind(p.id.index as i16)
+            .bind(p.owner.id)
+            .bind(p.owner.sub)
+            .bind(p.asset.0 as i32)
+            .bind(p.value.to_string())
+            .execute(&mut *tx)
+            .await
+            .map_err(internal)?;
+            sqlx::query(
+                "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ($1, $2, $3, $4, $5, $6, NULL) ON CONFLICT (transfer_id, idx) DO NOTHING",
+            )
+            .bind(&hex)
+            .bind(p.id.index as i16)
+            .bind(p.owner.id)
+            .bind(p.owner.sub)
+            .bind(p.asset.0 as i32)
+            .bind(p.value.to_string())
+            .execute(&mut *tx)
+            .await
+            .map_err(internal)?;
+            touched.insert((p.owner, p.asset));
+        }
+
+        // Overdraft floor: with consumed rows deleted and created rows inserted,
+        // the live set already reflects the post-commit balance. For each
+        // overdraft-forbidding owner touched, its projected balance must be
+        // non-negative.
+        for (owner, asset) in &touched {
+            let forbids = self
+                .locked_account(&mut tx, owner)
+                .await?
+                .map(|a| a.forbids_overdraft())
+                .unwrap_or(false);
+            if !forbids {
+                continue;
+            }
+            let projected = self.live_balance(&mut tx, owner, asset).await?;
+            if projected.is_negative() {
+                return Ok(CommitOutcome::Rejected(
+                    CommitRejection::OverdraftExceeded {
+                        account: *owner,
+                        asset: *asset,
+                        projected,
+                    },
+                ));
+            }
+        }
+
+        // Store the transfer record and index it under the involved accounts.
+        let transfer_json = serialize_json(&req.record.envelope)?;
+        let receipt_json = serialize_json(&req.record.receipt)?;
+        sqlx::query("INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (id) DO NOTHING")
+            .bind(&tid_hex)
+            .bind(&transfer_json)
+            .bind(&receipt_json)
+            .bind(req.record.created_at)
+            .bind(req.record.envelope.book().0)
+            .execute(&mut *tx)
+            .await
+            .map_err(internal)?;
+        for account in req.involved {
+            sqlx::query("INSERT INTO transfer_accounts (transfer_id, account_id, subaccount) VALUES ($1, $2, $3) ON CONFLICT (transfer_id, account_id, subaccount) DO NOTHING")
+                .bind(&tid_hex)
+                .bind(account.id)
+                .bind(account.sub)
+                .execute(&mut *tx)
+                .await
+                .map_err(internal)?;
+        }
+
+        append_event_tx(&mut tx, &self.autoid, &req.event).await?;
+
+        tx.commit().await.map_err(internal)?;
+        Ok(CommitOutcome::Committed(req.record.receipt))
+    }
+
+    async fn commit_transition(
+        &self,
+        next: Account,
+        event: LedgerEvent,
+    ) -> Result<TransitionOutcome, StoreError> {
+        let mut tx = self.pool.begin().await.map_err(internal)?;
+
+        let current = self
+            .locked_account(&mut tx, &next.id)
+            .await?
+            .ok_or_else(|| {
+                StoreError::Internal(format!("transition: account {:?} missing", next.id))
+            })?;
+
+        if current.is_closed() {
+            return Ok(TransitionOutcome::Rejected(
+                TransitionRejection::AlreadyClosed(next.id),
+            ));
+        }
+        if current.version >= next.version {
+            // Already applied: ensure the (idempotent) event and report it.
+            append_event_tx(&mut tx, &self.autoid, &event).await?;
+            tx.commit().await.map_err(internal)?;
+            return Ok(TransitionOutcome::AlreadyApplied);
+        }
+        let expected = current
+            .version
+            .checked_add(1)
+            .ok_or_else(|| StoreError::Internal("account version overflow".to_string()))?;
+        if next.version != expected {
+            return Ok(TransitionOutcome::Rejected(
+                TransitionRejection::VersionConflict {
+                    account: next.id,
+                    expected: next.version,
+                },
+            ));
+        }
+
+        sqlx::query(
+            "INSERT INTO accounts (id, subaccount, version, flags, book, metadata) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id, subaccount, version) DO NOTHING",
+        )
+        .bind(next.id.id)
+        .bind(next.id.sub)
+        .bind(next.version as i64)
+        .bind(next.flags.bits() as i32)
+        .bind(next.book.0)
+        .bind(serialize_json(&next.metadata)?)
+        .execute(&mut *tx)
+        .await
+        .map_err(internal)?;
+
+        sqlx::query("DELETE FROM account_head WHERE id = $1 AND subaccount = $2")
+            .bind(next.id.id)
+            .bind(next.id.sub)
+            .execute(&mut *tx)
+            .await
+            .map_err(internal)?;
+        sqlx::query("INSERT INTO account_head (id, subaccount, version) VALUES ($1, $2, $3)")
+            .bind(next.id.id)
+            .bind(next.id.sub)
+            .bind(next.version as i64)
+            .execute(&mut *tx)
+            .await
+            .map_err(internal)?;
+
+        append_event_tx(&mut tx, &self.autoid, &event).await?;
+
+        tx.commit().await.map_err(internal)?;
+        Ok(TransitionOutcome::Applied)
+    }
+}

+ 3 - 3
crates/kuatia-storage-sql/src/lib.rs

@@ -11,8 +11,8 @@
 //! ```
 //!
 //! The [`Store`](kuatia_storage::store::Store) sub-traits are each implemented in
-//! their own module (`account`, `posting`, `transfer`, `saga`, `event`, `book`,
-//! `projection`); shared row mappers and codecs live in `row`, the schema
+//! their own module (`account`, `posting`, `transfer`, `commit`, `event`,
+//! `book`, `projection`); shared row mappers and codecs live in `row`, the schema
 //! migrations in `migrate`, and the one SQLite/PostgreSQL divergence behind the
 //! `Dialect` seam in `dialect`.
 
@@ -24,13 +24,13 @@ use crate::dialect::Dialect;
 
 mod account;
 mod book;
+mod commit;
 mod dialect;
 mod event;
 mod migrate;
 mod posting;
 mod projection;
 mod row;
-mod saga;
 mod transfer;
 
 /// SQL-backed [`Store`](kuatia_storage::store::Store) implementation.

+ 4 - 0
crates/kuatia-storage-sql/src/migrate.rs

@@ -52,6 +52,10 @@ impl SqlStore {
                 "009_saga_kind",
                 include_str!("migrations/009_saga_kind.sql"),
             ),
+            (
+                "010_drop_sagas",
+                include_str!("migrations/010_drop_sagas.sql"),
+            ),
         ];
 
         for (name, sql) in migrations {

+ 4 - 0
crates/kuatia-storage-sql/src/migrations/010_drop_sagas.sql

@@ -0,0 +1,4 @@
+-- The write-ahead saga keyspace is gone: commits and account transitions are
+-- now single atomic store transactions (ADR-0023, superseding ADR-0003), so
+-- there is no half-applied state for a `sagas` write-ahead record to recover.
+DROP TABLE IF EXISTS sagas;

+ 2 - 2
crates/kuatia-storage-sql/src/posting.rs

@@ -40,7 +40,7 @@ fn filter_source(filter: PostingFilter) -> (&'static str, &'static str) {
 /// parameters would hit. `500` stays comfortably under the expression-depth
 /// limit; callers that pass more ids are chunked, so the id-batch primitives
 /// have no practical ceiling on batch size.
-const MAX_IDS_PER_QUERY: usize = 500;
+pub(crate) const MAX_IDS_PER_QUERY: usize = 500;
 
 /// Build a portable predicate matching a set of posting ids:
 /// `(transfer_id = $s AND idx = $s+1) OR (transfer_id = $s+2 AND idx = $s+3) ...`
@@ -49,7 +49,7 @@ const MAX_IDS_PER_QUERY: usize = 500;
 /// caller binds each id as `(hex(transfer), idx as i16)` in order, matching the
 /// placeholder sequence. `ids` must be non-empty and no longer than
 /// [`MAX_IDS_PER_QUERY`]; larger sets are split into chunks by the caller.
-fn id_predicate(count: usize, start: u32) -> String {
+pub(crate) fn id_predicate(count: usize, start: u32) -> String {
     (0..count)
         .map(|i| {
             let p = start + (i as u32) * 2;

+ 0 - 74
crates/kuatia-storage-sql/src/saga.rs

@@ -1,74 +0,0 @@
-//! [`SagaStore`]: opaque write-ahead saga records stored as hex `TEXT`.
-
-use async_trait::async_trait;
-use sqlx::Row;
-
-use kuatia_storage::error::StoreError;
-use kuatia_storage::store::*;
-
-use crate::SqlStore;
-use crate::row::{from_hex, to_hex};
-
-#[async_trait]
-impl SagaStore for SqlStore {
-    async fn save_saga(&self, kind: SagaKind, id: &i64, data: Vec<u8>) -> Result<(), StoreError> {
-        sqlx::query(
-            "INSERT INTO sagas (id, kind, data) VALUES ($1, $2, $3) \
-             ON CONFLICT (id) DO UPDATE SET kind = EXCLUDED.kind, data = EXCLUDED.data",
-        )
-        .bind(*id)
-        .bind(kind.as_str())
-        .bind(to_hex(&data))
-        .execute(&self.pool)
-        .await
-        .map_err(|e| StoreError::Internal(e.to_string()))?;
-        Ok(())
-    }
-
-    async fn list_pending_sagas(&self) -> Result<Vec<(SagaKind, i64, Vec<u8>)>, StoreError> {
-        let rows = sqlx::query("SELECT id, kind, data FROM sagas")
-            .fetch_all(&self.pool)
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        let mut result = Vec::with_capacity(rows.len());
-        for row in &rows {
-            let id: i64 = row
-                .try_get("id")
-                .map_err(|e| StoreError::Internal(e.to_string()))?;
-            let kind: String = row
-                .try_get("kind")
-                .map_err(|e| StoreError::Internal(e.to_string()))?;
-            let data_hex: String = row
-                .try_get("data")
-                .map_err(|e| StoreError::Internal(e.to_string()))?;
-            result.push((SagaKind::parse(&kind)?, id, from_hex(&data_hex)?));
-        }
-        Ok(result)
-    }
-
-    async fn get_saga(&self, id: &i64) -> Result<Option<Vec<u8>>, StoreError> {
-        let row = sqlx::query("SELECT data FROM sagas WHERE id = $1")
-            .bind(*id)
-            .fetch_optional(&self.pool)
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        match row {
-            Some(row) => {
-                let data_hex: String = row
-                    .try_get("data")
-                    .map_err(|e| StoreError::Internal(e.to_string()))?;
-                Ok(Some(from_hex(&data_hex)?))
-            }
-            None => Ok(None),
-        }
-    }
-
-    async fn delete_saga(&self, id: &i64) -> Result<(), StoreError> {
-        sqlx::query("DELETE FROM sagas WHERE id = $1")
-            .bind(*id)
-            .execute(&self.pool)
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        Ok(())
-    }
-}

+ 3 - 0
crates/kuatia-storage-sql/tests/sqlite.rs

@@ -240,6 +240,7 @@ async fn migration_004_backfills_index_tables() {
         "007_balance_projection",
         "008_live_postings",
         "009_saga_kind",
+        "010_drop_sagas",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -331,6 +332,7 @@ async fn migration_005_backfills_account_head() {
         "007_balance_projection",
         "008_live_postings",
         "009_saga_kind",
+        "010_drop_sagas",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -402,6 +404,7 @@ async fn migration_008_merges_live_postings() {
         "006_drop_policy",
         "007_balance_projection",
         "009_saga_kind",
+        "010_drop_sagas",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)

+ 7 - 7
crates/kuatia-storage/README.md

@@ -11,17 +11,17 @@ macro that any backend can use to validate its implementation.
 | Trait | Purpose |
 |-------|---------|
 | `AccountStore` | Account CRUD and versioning |
-| `PostingStore` | Posting reads + lifecycle: `reserve`/`release`/`deactivate`/`insert` postings (reserve/release/deactivate carry a `ReservationId`) |
+| `PostingStore` | Posting reads + generic lifecycle primitives (`reserve`/`release`/`deactivate`/`insert`) |
 | `TransferStore` | Transfer persistence (`store_transfer`) and queries |
-| `SagaStore` | Saga state for crash recovery |
+| `CommitStore` | The atomic commit boundary: `commit_envelope` / `commit_transition` (ADR-0023) |
 | `EventStore` | Append-only ledger event log (idempotent on a per-transfer dedup key) |
 | `BookStore` | Book (transfer policy scope) persistence |
 
-The store is a **dumb instruction follower**: write methods apply one update and
-return the **number of affected rows** (or an I/O error). They do not interpret
-counts, decide state, enforce idempotency, or compensate — the saga in the
-`kuatia` crate does. There is no `commit_transfer`; commit is a sequence of these
-primitives, each idempotent.
+A transfer is committed atomically through `CommitStore::commit_envelope`, which
+applies the whole envelope in one transaction and re-checks double-spend,
+freeze/close, and the overdraft floor inside it. The remaining posting/account
+write methods are **dumb instructions**: each applies one update and returns the
+**number of affected rows** (or an I/O error), never interpreting the count.
 
 `Store` is a blanket trait — any type implementing the sub-traits is a `Store`.
 

+ 179 - 26
crates/kuatia-storage/src/mem_store.rs

@@ -3,8 +3,8 @@
 //! Accounts are stored as append-only version logs keyed by `AccountId`.
 
 use async_trait::async_trait;
-use std::collections::HashMap;
 use std::collections::hash_map::Entry;
+use std::collections::{HashMap, HashSet};
 use tokio::sync::RwLock;
 
 use kuatia_types::autoid::AutoId;
@@ -17,8 +17,9 @@ use crate::error::StoreError;
 use crate::events::{EventStore, LedgerEvent, event_dedup_key};
 use crate::query::{filter_transfers, paginate};
 use crate::store::{
-    AccountStore, BalanceProjection, BalanceProjectionStore, BookStore, EnvelopeRecord, Page,
-    PostingStore, SagaKind, SagaStore, TransferQuery, TransferStore,
+    AccountStore, BalanceProjection, BalanceProjectionStore, BookStore, CommitOutcome,
+    CommitRejection, CommitRequest, CommitStore, EnvelopeRecord, Page, PostingStore, TransferQuery,
+    TransferStore, TransitionOutcome, TransitionRejection,
 };
 
 /// Postings held as an immutable record table plus two index maps that carry
@@ -44,7 +45,6 @@ pub struct InMemoryStore {
     /// `store_transfer`, mirroring the SQL `transfer_accounts` table so both
     /// backends resolve `get_transfers_for_account` from the same instruction.
     transfer_accounts: RwLock<HashMap<EnvelopeId, Vec<AccountId>>>,
-    sagas: RwLock<HashMap<i64, (SagaKind, Vec<u8>)>>,
     events: RwLock<Vec<LedgerEvent>>,
     books: RwLock<HashMap<BookId, Book>>,
     /// Append-only balance cache points keyed by `(account, asset)` (ADR-0019).
@@ -66,7 +66,6 @@ impl InMemoryStore {
             accounts: RwLock::new(HashMap::new()),
             transfers: RwLock::new(HashMap::new()),
             transfer_accounts: RwLock::new(HashMap::new()),
-            sagas: RwLock::new(HashMap::new()),
             events: RwLock::new(Vec::new()),
             books: RwLock::new(HashMap::new()),
             projections: RwLock::new(HashMap::new()),
@@ -432,34 +431,188 @@ impl TransferStore for InMemoryStore {
 }
 
 // ---------------------------------------------------------------------------
-// SagaStore
+// CommitStore
 // ---------------------------------------------------------------------------
 
-#[async_trait]
-impl SagaStore for InMemoryStore {
-    async fn save_saga(&self, kind: SagaKind, id: &i64, data: Vec<u8>) -> Result<(), StoreError> {
-        let mut sagas = self.sagas.write().await;
-        sagas.insert(*id, (kind, data));
-        Ok(())
-    }
-
-    async fn list_pending_sagas(&self) -> Result<Vec<(SagaKind, i64, Vec<u8>)>, StoreError> {
-        let sagas = self.sagas.read().await;
-        Ok(sagas
+/// Append `event` into an already-locked event log, deduping on its key. Mirrors
+/// [`EventStore::append_event`] but takes the guard the atomic commit already
+/// holds, so the whole commit stays under one set of locks.
+fn append_event_locked(events: &mut Vec<LedgerEvent>, autoid: &AutoId, event: &LedgerEvent) {
+    if let Some(key) = event_dedup_key(&event.kind)
+        && events
             .iter()
-            .map(|(id, (kind, data))| (*kind, *id, data.clone()))
-            .collect())
+            .any(|e| event_dedup_key(&e.kind).as_deref() == Some(key.as_str()))
+    {
+        return;
     }
+    let seq = autoid.next() as u64;
+    events.push(LedgerEvent {
+        seq,
+        timestamp: event.timestamp,
+        kind: event.kind.clone(),
+    });
+}
 
-    async fn get_saga(&self, id: &i64) -> Result<Option<Vec<u8>>, StoreError> {
-        let sagas = self.sagas.read().await;
-        Ok(sagas.get(id).map(|(_, data)| data.clone()))
+#[async_trait]
+impl CommitStore for InMemoryStore {
+    async fn commit_envelope(&self, req: CommitRequest<'_>) -> Result<CommitOutcome, StoreError> {
+        let overflow = || StoreError::Internal("commit: monetary overflow".to_string());
+
+        // Fixed lock order: accounts → postings → transfers → transfer_accounts →
+        // events. The whole apply happens under these guards, so the commit is
+        // atomic and its guards cannot race a concurrent commit or transition.
+        let accounts = self.accounts.read().await;
+        let mut postings = self.postings.write().await;
+        let mut transfers = self.transfers.write().await;
+        let mut transfer_accounts = self.transfer_accounts.write().await;
+        let mut events = self.events.write().await;
+
+        let tid = req.transfer_id;
+
+        // Idempotency: an already-committed transfer returns its receipt.
+        if let Some(existing) = transfers.get(&tid) {
+            return Ok(CommitOutcome::AlreadyCommitted(existing.receipt.clone()));
+        }
+
+        let account_of = |aid: &AccountId| -> Result<&Account, StoreError> {
+            accounts
+                .get(aid)
+                .and_then(|v| v.last())
+                .ok_or_else(|| StoreError::Internal(format!("commit: account {aid:?} missing")))
+        };
+
+        // Freeze/close guard, strict inside the lock.
+        for aid in req.involved {
+            let account = account_of(aid)?;
+            if account.is_frozen() {
+                return Ok(CommitOutcome::Rejected(CommitRejection::AccountFrozen(
+                    *aid,
+                )));
+            }
+            if account.is_closed() {
+                return Ok(CommitOutcome::Rejected(CommitRejection::AccountClosed(
+                    *aid,
+                )));
+            }
+        }
+
+        // Double-spend guard: every consumed id must still be Active. This is the
+        // atomic single-winner claim; it applies nothing on a miss.
+        for id in req.consume {
+            if !postings.active.contains_key(id) {
+                return Ok(CommitOutcome::Rejected(CommitRejection::DoubleSpend(*id)));
+            }
+        }
+
+        // Overdraft floor for accounts that forbid it: the projected live balance
+        // per touched (owner, asset) must stay non-negative. Computed from the
+        // surviving active rows (post-consume) plus created deltas, in Rust with
+        // checked arithmetic, segregated by subaccount.
+        let consumed_set: HashSet<PostingId> = req.consume.iter().copied().collect();
+        for aid in req.involved {
+            if !account_of(aid)?.forbids_overdraft() {
+                continue;
+            }
+            let mut assets: HashSet<AssetId> = HashSet::new();
+            for p in req.create.iter().filter(|p| p.owner == *aid) {
+                assets.insert(p.asset);
+            }
+            for id in req.consume {
+                if let Some(p) = postings.active.get(id).filter(|p| p.owner == *aid) {
+                    assets.insert(p.asset);
+                }
+            }
+            for asset in assets {
+                let live_sum = Cent::checked_sum(
+                    postings
+                        .active
+                        .values()
+                        .filter(|p| {
+                            p.owner == *aid && p.asset == asset && !consumed_set.contains(&p.id)
+                        })
+                        .map(|p| p.value),
+                )
+                .map_err(|_| overflow())?;
+                let created_sum = Cent::checked_sum(
+                    req.create
+                        .iter()
+                        .filter(|p| p.owner == *aid && p.asset == asset)
+                        .map(|p| p.value),
+                )
+                .map_err(|_| overflow())?;
+                let projected = live_sum.checked_add(created_sum).map_err(|_| overflow())?;
+                if projected.is_negative() {
+                    return Ok(CommitOutcome::Rejected(
+                        CommitRejection::OverdraftExceeded {
+                            account: *aid,
+                            asset,
+                            projected,
+                        },
+                    ));
+                }
+            }
+        }
+
+        // Apply: spend consumed (immutable copy stays → Spent), insert+activate
+        // created, store and index the transfer, append the event.
+        for id in req.consume {
+            postings.active.remove(id);
+        }
+        for p in req.create {
+            postings.immutable.entry(p.id).or_insert_with(|| p.clone());
+            postings.active.insert(p.id, p.clone());
+        }
+        transfer_accounts.insert(tid, req.involved.to_vec());
+        let receipt = req.record.receipt.clone();
+        transfers.insert(tid, req.record);
+        append_event_locked(&mut events, &self.autoid, &req.event);
+
+        Ok(CommitOutcome::Committed(receipt))
     }
 
-    async fn delete_saga(&self, id: &i64) -> Result<(), StoreError> {
-        let mut sagas = self.sagas.write().await;
-        sagas.remove(id);
-        Ok(())
+    async fn commit_transition(
+        &self,
+        next: Account,
+        event: LedgerEvent,
+    ) -> Result<TransitionOutcome, StoreError> {
+        // Lock order accounts → events, a prefix of the commit order, so the two
+        // atomic writers never deadlock.
+        let mut accounts = self.accounts.write().await;
+        let mut events = self.events.write().await;
+
+        let id = next.id;
+        let versions = accounts
+            .get_mut(&id)
+            .ok_or_else(|| StoreError::Internal(format!("transition: account {id:?} missing")))?;
+        let current = versions.last().ok_or_else(|| {
+            StoreError::Internal(format!("transition: account {id:?} has no version"))
+        })?;
+
+        if current.is_closed() {
+            return Ok(TransitionOutcome::Rejected(
+                TransitionRejection::AlreadyClosed(id),
+            ));
+        }
+        let current_version = current.version;
+        if current_version >= next.version {
+            // Already applied: ensure the (idempotent) event and report it.
+            append_event_locked(&mut events, &self.autoid, &event);
+            return Ok(TransitionOutcome::AlreadyApplied);
+        }
+        let expected = current_version
+            .checked_add(1)
+            .ok_or_else(|| StoreError::Internal("account version overflow".to_string()))?;
+        if next.version != expected {
+            return Ok(TransitionOutcome::Rejected(
+                TransitionRejection::VersionConflict {
+                    account: id,
+                    expected: next.version,
+                },
+            ));
+        }
+        versions.push(next);
+        append_event_locked(&mut events, &self.autoid, &event);
+        Ok(TransitionOutcome::Applied)
     }
 }
 

+ 116 - 55
crates/kuatia-storage/src/store.rs

@@ -7,7 +7,7 @@
 //! - [`AccountStore`] — account CRUD and versioning
 //! - [`PostingStore`] — posting reads and lifecycle transitions
 //! - [`TransferStore`] — transfer persistence and queries
-//! - [`SagaStore`] — saga state for crash recovery
+//! - [`CommitStore`] — the atomic commit boundary (ADR-0023)
 //! - [`EventStore`] — the ledger event log
 //! - [`BookStore`] — book persistence
 //! - [`BalanceProjectionStore`] — the cached balance projection (ADR-0019)
@@ -19,7 +19,7 @@ use kuatia_types::{
 };
 
 use crate::error::StoreError;
-use crate::events::EventStore;
+use crate::events::{EventStore, LedgerEvent};
 
 /// Pairs a committed transfer with its receipt.
 #[derive(Debug, Clone)]
@@ -236,57 +236,6 @@ pub trait TransferStore: Send + Sync {
     ) -> Result<Page<EnvelopeRecord>, StoreError>;
 }
 
-/// Which kind of write-ahead record a saga row holds. A typed discriminator on
-/// the shared saga keyspace: the store stores and returns it so recovery can
-/// dispatch by type rather than by decoding the opaque blob to read an in-band
-/// tag. Persisted as its [`as_str`](SagaKind::as_str) TEXT form.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum SagaKind {
-    /// A two-step envelope commit saga (reserve → finalize).
-    Envelope,
-    /// A single account-version transition (append version + lifecycle event).
-    Transition,
-}
-
-impl SagaKind {
-    /// The stored TEXT form of this kind.
-    pub fn as_str(&self) -> &'static str {
-        match self {
-            Self::Envelope => "envelope",
-            Self::Transition => "transition",
-        }
-    }
-
-    /// Parse the stored TEXT form back into a kind.
-    pub fn parse(s: &str) -> Result<Self, StoreError> {
-        match s {
-            "envelope" => Ok(Self::Envelope),
-            "transition" => Ok(Self::Transition),
-            other => Err(StoreError::Internal(format!("unknown saga kind: {other}"))),
-        }
-    }
-}
-
-/// Saga state persistence for crash recovery.
-///
-/// One flat `id → (kind, bytes)` keyspace holds both write-ahead kinds. `id` is
-/// globally unique (all ids come from one generator), so `get`/`delete` locate a
-/// row by `id` alone; `kind` is carried so `list_pending_sagas` can hand recovery
-/// a typed discriminator instead of an in-band blob tag.
-#[async_trait]
-pub trait SagaStore: Send + Sync {
-    /// Persist a saga execution state under `id`, tagged with its [`SagaKind`].
-    async fn save_saga(&self, kind: SagaKind, id: &i64, data: Vec<u8>) -> Result<(), StoreError>;
-    /// Load all pending (incomplete) saga states with their kind.
-    async fn list_pending_sagas(&self) -> Result<Vec<(SagaKind, i64, Vec<u8>)>, StoreError>;
-    /// Load one saga state by id, or `None` if no record is stored under `id`.
-    /// A keyed read so a caller checking a single in-flight saga does not scan
-    /// every pending record.
-    async fn get_saga(&self, id: &i64) -> Result<Option<Vec<u8>>, StoreError>;
-    /// Delete a completed saga state.
-    async fn delete_saga(&self, id: &i64) -> Result<(), StoreError>;
-}
-
 /// Book persistence.
 #[async_trait]
 pub trait BookStore: Send + Sync {
@@ -353,6 +302,118 @@ pub trait BalanceProjectionStore: Send + Sync {
 }
 
 // ---------------------------------------------------------------------------
+// Atomic commit
+// ---------------------------------------------------------------------------
+
+/// Everything one transfer commits, applied in a single store transaction.
+///
+/// The pure core validates the transfer first; this request carries the
+/// validated effects. The store applies them atomically and re-enforces the
+/// three *stateful* guards inside the transaction (double-spend, freeze/close,
+/// overdraft floor), so a concurrent commit or freeze cannot slip between the
+/// check and the write.
+pub struct CommitRequest<'a> {
+    /// Content-addressed id of the transfer being committed.
+    pub transfer_id: EnvelopeId,
+    /// Postings to spend (delete from the live set). Empty for a deposit.
+    pub consume: &'a [PostingId],
+    /// New postings to insert and activate.
+    pub create: &'a [Posting],
+    /// The transfer record to persist (envelope + receipt + created_at).
+    pub record: EnvelopeRecord,
+    /// Owners of the created and consumed postings: both the transfer's account
+    /// index and the set whose freeze/close/floor the store re-checks.
+    pub involved: &'a [AccountId],
+    /// The `TransferCommitted` event to append in the same transaction.
+    pub event: LedgerEvent,
+}
+
+/// Outcome of an atomic [`CommitStore::commit_envelope`]. A domain rejection is
+/// an `Ok(Rejected(..))` value, not a [`StoreError`]: the store reports a typed
+/// reason and the ledger maps it, keeping `StoreError` IO-only.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum CommitOutcome {
+    /// The transfer was newly applied in this call.
+    Committed(Receipt),
+    /// The transfer id was already present; nothing changed (idempotent replay).
+    AlreadyCommitted(Receipt),
+    /// A stateful guard rejected the commit; nothing was applied.
+    Rejected(CommitRejection),
+}
+
+/// Why an atomic commit was refused. Each maps to a typed ledger error.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum CommitRejection {
+    /// A consumed posting was not live (already spent, missing, or taken by a
+    /// concurrent commit). Carries the first offending id.
+    DoubleSpend(PostingId),
+    /// An involved account is frozen.
+    AccountFrozen(AccountId),
+    /// An involved account is closed.
+    AccountClosed(AccountId),
+    /// The projected balance of an overdraft-forbidding account would go
+    /// negative.
+    OverdraftExceeded {
+        /// The account that would be overdrawn.
+        account: AccountId,
+        /// The asset involved.
+        asset: AssetId,
+        /// The negative balance that would result.
+        projected: Cent,
+    },
+}
+
+/// Outcome of an atomic [`CommitStore::commit_transition`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum TransitionOutcome {
+    /// The version was appended and its event recorded.
+    Applied,
+    /// The version was already present; the event was ensured (idempotent).
+    AlreadyApplied,
+    /// The transition was refused; nothing was applied.
+    Rejected(TransitionRejection),
+}
+
+/// Why an atomic transition was refused.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum TransitionRejection {
+    /// The account is already closed.
+    AlreadyClosed(AccountId),
+    /// The head was not at `expected - 1` (a concurrent transition moved it).
+    VersionConflict {
+        /// The account whose version append was rejected.
+        account: AccountId,
+        /// The version this attempt targeted.
+        expected: u64,
+    },
+}
+
+/// The atomic write boundary: a whole transfer, or a whole account-version
+/// transition, applied in one store transaction.
+///
+/// This is what replaces the multi-primitive reserve → finalize saga and its
+/// write-ahead recovery: because each method is all-or-nothing, a crash leaves
+/// no half-applied state to reconcile, and the stateful guards are strict rather
+/// than best-effort (ADR-0023, superseding ADR-0003).
+#[async_trait]
+pub trait CommitStore: Send + Sync {
+    /// Commit a validated transfer atomically. Spends `consume`, inserts and
+    /// activates `create`, stores the transfer indexed under `involved`, and
+    /// appends `event` — all in one transaction, re-checking double-spend,
+    /// freeze/close, and the overdraft floor inside it.
+    async fn commit_envelope(&self, req: CommitRequest<'_>) -> Result<CommitOutcome, StoreError>;
+
+    /// Apply one account-version transition atomically: append `next` (a version
+    /// bump with flags flipped) and its lifecycle `event` in one transaction,
+    /// guarding the version chain and a closed account.
+    async fn commit_transition(
+        &self,
+        next: Account,
+        event: LedgerEvent,
+    ) -> Result<TransitionOutcome, StoreError>;
+}
+
+// ---------------------------------------------------------------------------
 // Composite trait
 // ---------------------------------------------------------------------------
 
@@ -361,7 +422,7 @@ pub trait Store:
     AccountStore
     + PostingStore
     + TransferStore
-    + SagaStore
+    + CommitStore
     + EventStore
     + BookStore
     + BalanceProjectionStore
@@ -372,7 +433,7 @@ impl<
     T: AccountStore
         + PostingStore
         + TransferStore
-        + SagaStore
+        + CommitStore
         + EventStore
         + BookStore
         + BalanceProjectionStore,

+ 366 - 46
crates/kuatia-storage/src/store_tests.rs

@@ -1119,75 +1119,389 @@ pub async fn query_transfers_store_wide(store: &(impl Store + 'static)) {
 }
 
 // ---------------------------------------------------------------------------
-// SagaStore tests
+// CommitStore (atomic commit) tests
 // ---------------------------------------------------------------------------
 
-/// Save saga state and list it with its kind.
-pub async fn save_and_list_sagas(store: &(impl Store + 'static)) {
-    let id: i64 = 42;
-    let data = vec![1, 2, 3];
+fn committed_event(tid: EnvelopeId) -> LedgerEvent {
+    LedgerEvent {
+        seq: 0,
+        timestamp: 1000,
+        kind: LedgerEventKind::TransferCommitted { transfer_id: tid },
+    }
+}
+
+/// An atomic commit with no consumed postings creates the new ones, stores and
+/// indexes the transfer, appends the event, and returns `Committed`.
+pub async fn commit_atomic_creates_and_returns_receipt(store: &(impl Store + 'static)) {
+    store
+        .create_account(make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
+        .await
+        .unwrap();
+    store
+        .create_account(make_account(99, AccountFlags::empty()))
+        .await
+        .unwrap();
+    let (envelope, tid) = make_envelope();
+    let create = vec![
+        make_posting(tid.0, 0, 1, 1, 100),
+        make_posting(tid.0, 1, 99, 1, -100),
+    ];
+    let involved = [AccountId::new(1), AccountId::new(99)];
+    let outcome = store
+        .commit_envelope(CommitRequest {
+            transfer_id: tid,
+            consume: &[],
+            create: &create,
+            record: EnvelopeRecord {
+                envelope,
+                receipt: Receipt { transfer_id: tid },
+                created_at: 1000,
+            },
+            involved: &involved,
+            event: committed_event(tid),
+        })
+        .await
+        .unwrap();
+    assert!(matches!(outcome, CommitOutcome::Committed(_)));
+    assert_eq!(state_of(store, create[0].id).await, PostingState::Active);
+    assert!(store.get_transfer(&tid).await.unwrap().is_some());
+    assert_eq!(
+        store
+            .get_transfers_for_account(1, None)
+            .await
+            .unwrap()
+            .len(),
+        1
+    );
+    assert_eq!(store.get_events_since(0, 10).await.unwrap().len(), 1);
+}
+
+/// Committing the same transfer id twice is idempotent: the second call returns
+/// `AlreadyCommitted` and creates no duplicate posting, transfer, or event.
+pub async fn commit_atomic_idempotent(store: &(impl Store + 'static)) {
+    store
+        .create_account(make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
+        .await
+        .unwrap();
     store
-        .save_saga(SagaKind::Envelope, &id, data.clone())
+        .create_account(make_account(99, AccountFlags::empty()))
         .await
         .unwrap();
+    let (envelope, tid) = make_envelope();
+    let create = vec![
+        make_posting(tid.0, 0, 1, 1, 100),
+        make_posting(tid.0, 1, 99, 1, -100),
+    ];
+    let involved = [AccountId::new(1), AccountId::new(99)];
+    let req = || CommitRequest {
+        transfer_id: tid,
+        consume: &[],
+        create: &create,
+        record: EnvelopeRecord {
+            envelope: envelope.clone(),
+            receipt: Receipt { transfer_id: tid },
+            created_at: 1000,
+        },
+        involved: &involved,
+        event: committed_event(tid),
+    };
+    assert!(matches!(
+        store.commit_envelope(req()).await.unwrap(),
+        CommitOutcome::Committed(_)
+    ));
+    assert!(matches!(
+        store.commit_envelope(req()).await.unwrap(),
+        CommitOutcome::AlreadyCommitted(_)
+    ));
+    assert_eq!(store.get_events_since(0, 10).await.unwrap().len(), 1);
+}
 
-    let pending = store.list_pending_sagas().await.unwrap();
-    assert_eq!(pending.len(), 1);
-    assert_eq!(pending[0].0, SagaKind::Envelope);
-    assert_eq!(pending[0].1, id);
-    assert_eq!(pending[0].2, data);
+/// A consumed posting already spent by a prior commit is refused with
+/// `DoubleSpend`, and the second commit applies nothing.
+pub async fn commit_atomic_double_spend_rejects_and_applies_nothing(
+    store: &(impl Store + 'static),
+) {
+    for id in [1, 2] {
+        store
+            .create_account(make_account(id, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
+            .await
+            .unwrap();
+    }
+    let funded = make_posting([1; 32], 0, 1, 1, 100);
+    seed_active(store, 0, std::slice::from_ref(&funded)).await;
+
+    let commit = |tid: EnvelopeId| {
+        let created = make_posting(tid.0, 0, 2, 1, 100);
+        (tid, created)
+    };
+    let (tid1, created1) = commit(EnvelopeId([0xC1; 32]));
+    let involved = [AccountId::new(1), AccountId::new(2)];
+    let first = store
+        .commit_envelope(CommitRequest {
+            transfer_id: tid1,
+            consume: &[funded.id],
+            create: std::slice::from_ref(&created1),
+            record: EnvelopeRecord {
+                envelope: EnvelopeBuilder::new().consumes(vec![funded.id]).build(),
+                receipt: Receipt { transfer_id: tid1 },
+                created_at: 1000,
+            },
+            involved: &involved,
+            event: committed_event(tid1),
+        })
+        .await
+        .unwrap();
+    assert!(matches!(first, CommitOutcome::Committed(_)));
+
+    let (tid2, created2) = commit(EnvelopeId([0xC2; 32]));
+    let second = store
+        .commit_envelope(CommitRequest {
+            transfer_id: tid2,
+            consume: &[funded.id],
+            create: std::slice::from_ref(&created2),
+            record: EnvelopeRecord {
+                envelope: EnvelopeBuilder::new().consumes(vec![funded.id]).build(),
+                receipt: Receipt { transfer_id: tid2 },
+                created_at: 2000,
+            },
+            involved: &involved,
+            event: committed_event(tid2),
+        })
+        .await
+        .unwrap();
+    assert_eq!(
+        second,
+        CommitOutcome::Rejected(CommitRejection::DoubleSpend(funded.id))
+    );
+    assert!(store.get_transfer(&tid2).await.unwrap().is_none());
+    assert_eq!(state_of(store, created2.id).await, PostingState::Missing);
 }
 
-/// Delete a saga state.
-pub async fn delete_saga(store: &(impl Store + 'static)) {
-    let id: i64 = 42;
+/// A commit touching a frozen account is rejected, and nothing is applied.
+pub async fn commit_atomic_rejects_frozen(store: &(impl Store + 'static)) {
     store
-        .save_saga(SagaKind::Envelope, &id, vec![1, 2, 3])
+        .create_account(make_account(1, AccountFlags::FROZEN))
+        .await
+        .unwrap();
+    let tid = EnvelopeId([0xF1; 32]);
+    let create = make_posting(tid.0, 0, 1, 1, 100);
+    let outcome = store
+        .commit_envelope(CommitRequest {
+            transfer_id: tid,
+            consume: &[],
+            create: std::slice::from_ref(&create),
+            record: EnvelopeRecord {
+                envelope: EnvelopeBuilder::new().build(),
+                receipt: Receipt { transfer_id: tid },
+                created_at: 1000,
+            },
+            involved: &[AccountId::new(1)],
+            event: committed_event(tid),
+        })
         .await
         .unwrap();
-    store.delete_saga(&id).await.unwrap();
+    assert_eq!(
+        outcome,
+        CommitOutcome::Rejected(CommitRejection::AccountFrozen(AccountId::new(1)))
+    );
+    assert!(store.get_transfer(&tid).await.unwrap().is_none());
+    assert_eq!(state_of(store, create.id).await, PostingState::Missing);
+}
 
-    let pending = store.list_pending_sagas().await.unwrap();
-    assert!(pending.is_empty());
+/// A commit touching a closed account is rejected, and nothing is applied.
+pub async fn commit_atomic_rejects_closed(store: &(impl Store + 'static)) {
+    store
+        .create_account(make_account(1, AccountFlags::CLOSED))
+        .await
+        .unwrap();
+    let tid = EnvelopeId([0xC0; 32]);
+    let create = make_posting(tid.0, 0, 1, 1, 100);
+    let outcome = store
+        .commit_envelope(CommitRequest {
+            transfer_id: tid,
+            consume: &[],
+            create: std::slice::from_ref(&create),
+            record: EnvelopeRecord {
+                envelope: EnvelopeBuilder::new().build(),
+                receipt: Receipt { transfer_id: tid },
+                created_at: 1000,
+            },
+            involved: &[AccountId::new(1)],
+            event: committed_event(tid),
+        })
+        .await
+        .unwrap();
+    assert_eq!(
+        outcome,
+        CommitOutcome::Rejected(CommitRejection::AccountClosed(AccountId::new(1)))
+    );
+    assert!(store.get_transfer(&tid).await.unwrap().is_none());
 }
 
-/// A keyed `get_saga` returns the stored blob, and `None` for an absent or
-/// deleted id.
-pub async fn get_saga_by_id(store: &(impl Store + 'static)) {
-    let id: i64 = 42;
-    let data = vec![7, 8, 9];
-    assert!(store.get_saga(&id).await.unwrap().is_none());
+/// The overdraft floor is strict inside the commit: a projected negative balance
+/// on an overdraft-forbidding account is rejected, and nothing is applied.
+pub async fn commit_atomic_rejects_overdraft(store: &(impl Store + 'static)) {
+    store
+        .create_account(make_account(1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT))
+        .await
+        .unwrap();
+    let tid = EnvelopeId([0x0D; 32]);
+    // A negative posting on an overdraft-forbidding account drives its projected
+    // balance below zero; the store must refuse it.
+    let create = make_posting(tid.0, 0, 1, 1, -30);
+    let outcome = store
+        .commit_envelope(CommitRequest {
+            transfer_id: tid,
+            consume: &[],
+            create: std::slice::from_ref(&create),
+            record: EnvelopeRecord {
+                envelope: EnvelopeBuilder::new().build(),
+                receipt: Receipt { transfer_id: tid },
+                created_at: 1000,
+            },
+            involved: &[AccountId::new(1)],
+            event: committed_event(tid),
+        })
+        .await
+        .unwrap();
+    assert!(matches!(
+        outcome,
+        CommitOutcome::Rejected(CommitRejection::OverdraftExceeded {
+            account,
+            projected,
+            ..
+        }) if account == AccountId::new(1) && projected == Cent::from(-30)
+    ));
+    assert!(store.get_transfer(&tid).await.unwrap().is_none());
+    assert_eq!(state_of(store, create.id).await, PostingState::Missing);
+}
+
+/// An atomic transition appends the version and its event.
+pub async fn commit_transition_applies(store: &(impl Store + 'static)) {
+    store
+        .create_account(make_account(1, AccountFlags::empty()))
+        .await
+        .unwrap();
+    let mut next = make_account(1, AccountFlags::FROZEN);
+    next.version = 2;
+    let event = LedgerEvent {
+        seq: 0,
+        timestamp: 1000,
+        kind: LedgerEventKind::AccountFrozen {
+            account_id: AccountId::new(1),
+            version: 2,
+        },
+    };
+    assert_eq!(
+        store.commit_transition(next, event).await.unwrap(),
+        TransitionOutcome::Applied
+    );
+    let account = store.get_account(&AccountId::new(1)).await.unwrap();
+    assert_eq!(account.version, 2);
+    assert!(account.is_frozen());
+    assert_eq!(store.get_events_since(0, 10).await.unwrap().len(), 1);
+}
 
+/// Replaying an already-applied transition is idempotent: `AlreadyApplied`, no
+/// second version, no duplicate event.
+pub async fn commit_transition_idempotent_replay(store: &(impl Store + 'static)) {
+    store
+        .create_account(make_account(1, AccountFlags::empty()))
+        .await
+        .unwrap();
+    let mut next = make_account(1, AccountFlags::FROZEN);
+    next.version = 2;
+    let event = LedgerEvent {
+        seq: 0,
+        timestamp: 1000,
+        kind: LedgerEventKind::AccountFrozen {
+            account_id: AccountId::new(1),
+            version: 2,
+        },
+    };
     store
-        .save_saga(SagaKind::Envelope, &id, data.clone())
+        .commit_transition(next.clone(), event.clone())
         .await
         .unwrap();
-    assert_eq!(store.get_saga(&id).await.unwrap(), Some(data));
-    // A different id is still absent while this one exists.
-    assert!(store.get_saga(&99).await.unwrap().is_none());
+    assert_eq!(
+        store.commit_transition(next, event).await.unwrap(),
+        TransitionOutcome::AlreadyApplied
+    );
+    assert_eq!(
+        store.get_account(&AccountId::new(1)).await.unwrap().version,
+        2
+    );
+    assert_eq!(store.get_events_since(0, 10).await.unwrap().len(), 1);
+}
 
-    store.delete_saga(&id).await.unwrap();
-    assert!(store.get_saga(&id).await.unwrap().is_none());
+/// A transition that skips a version (a gap) is a `VersionConflict`.
+pub async fn commit_transition_version_conflict(store: &(impl Store + 'static)) {
+    store
+        .create_account(make_account(1, AccountFlags::empty()))
+        .await
+        .unwrap();
+    let mut next = make_account(1, AccountFlags::FROZEN);
+    next.version = 3;
+    let event = LedgerEvent {
+        seq: 0,
+        timestamp: 1000,
+        kind: LedgerEventKind::AccountFrozen {
+            account_id: AccountId::new(1),
+            version: 3,
+        },
+    };
+    assert_eq!(
+        store.commit_transition(next, event).await.unwrap(),
+        TransitionOutcome::Rejected(TransitionRejection::VersionConflict {
+            account: AccountId::new(1),
+            expected: 3,
+        })
+    );
 }
 
-/// Both write-ahead kinds share one keyspace: `list_pending_sagas` returns each
-/// record with the kind it was saved under, so recovery can dispatch by type
-/// rather than by decoding the blob.
-pub async fn mixed_saga_kinds_list_with_their_kinds(store: &(impl Store + 'static)) {
+/// A transition on a closed account is rejected with `AlreadyClosed`.
+pub async fn commit_transition_rejects_closed(store: &(impl Store + 'static)) {
     store
-        .save_saga(SagaKind::Envelope, &1, vec![10])
+        .create_account(make_account(1, AccountFlags::empty()))
         .await
         .unwrap();
+    let mut closed = make_account(1, AccountFlags::CLOSED);
+    closed.version = 2;
     store
-        .save_saga(SagaKind::Transition, &2, vec![20])
+        .commit_transition(
+            closed,
+            LedgerEvent {
+                seq: 0,
+                timestamp: 1000,
+                kind: LedgerEventKind::AccountClosed {
+                    account_id: AccountId::new(1),
+                    version: 2,
+                },
+            },
+        )
         .await
         .unwrap();
 
-    let mut pending = store.list_pending_sagas().await.unwrap();
-    pending.sort_by_key(|(_, id, _)| *id);
-    assert_eq!(pending.len(), 2);
-    assert_eq!(pending[0], (SagaKind::Envelope, 1, vec![10]));
-    assert_eq!(pending[1], (SagaKind::Transition, 2, vec![20]));
+    let mut next = make_account(1, AccountFlags::CLOSED | AccountFlags::FROZEN);
+    next.version = 3;
+    let outcome = store
+        .commit_transition(
+            next,
+            LedgerEvent {
+                seq: 0,
+                timestamp: 2000,
+                kind: LedgerEventKind::AccountFrozen {
+                    account_id: AccountId::new(1),
+                    version: 3,
+                },
+            },
+        )
+        .await
+        .unwrap();
+    assert_eq!(
+        outcome,
+        TransitionOutcome::Rejected(TransitionRejection::AlreadyClosed(AccountId::new(1)))
+    );
 }
 
 // ---------------------------------------------------------------------------
@@ -1431,11 +1745,17 @@ macro_rules! store_tests {
             query_transfers_pagination,
             query_transfers_by_book,
             query_transfers_store_wide,
-            // SagaStore
-            save_and_list_sagas,
-            get_saga_by_id,
-            delete_saga,
-            mixed_saga_kinds_list_with_their_kinds,
+            // CommitStore (atomic commit)
+            commit_atomic_creates_and_returns_receipt,
+            commit_atomic_idempotent,
+            commit_atomic_double_spend_rejects_and_applies_nothing,
+            commit_atomic_rejects_frozen,
+            commit_atomic_rejects_closed,
+            commit_atomic_rejects_overdraft,
+            commit_transition_applies,
+            commit_transition_idempotent_replay,
+            commit_transition_version_conflict,
+            commit_transition_rejects_closed,
             // EventStore
             append_and_query_events,
             events_sequence_ordering,

+ 3 - 3
crates/kuatia-storage/tests/concurrency.rs

@@ -2,9 +2,9 @@
 //!
 //! The generated conformance suite drives the store through a single `&store`,
 //! so it never exercises two callers racing on the same rows. `reserve_postings`
-//! is the primitive the saga relies on to make double-spends impossible: it must
-//! move each active posting into the reserved index for exactly one caller, even
-//! when many callers target the same postings at once.
+//! is a single-winner claim primitive: it must move each active posting into the
+//! reserved index for exactly one caller, even when many callers target the same
+//! postings at once.
 
 #![allow(missing_docs)]
 

+ 0 - 1
crates/kuatia/Cargo.toml

@@ -23,7 +23,6 @@ i128 = ["kuatia-types/i128", "kuatia-core/i128", "kuatia-storage/i128"]
 kuatia-types.workspace = true
 kuatia-core.workspace = true
 kuatia-storage.workspace = true
-legend.workspace = true
 tokio = { workspace = true, features = ["sync", "rt", "macros"] }
 serde.workspace = true
 serde_json.workspace = true

+ 23 - 28
crates/kuatia/README.md

@@ -2,8 +2,9 @@
 
 Async ledger resource — the main entry point for callers.
 
-Composes `kuatia-core` (validation) and `kuatia-storage` (persistence) into
-a saga-driven commit pipeline with automatic retry and compensation.
+Composes `kuatia-core` (validation) and `kuatia-storage` (persistence) into an
+atomic commit engine: resolve, validate, then apply the whole transfer in one
+store transaction.
 
 ## API layers
 
@@ -27,29 +28,21 @@ let receipt = ledger.commit(transfer).await?;
 
 ### Commit
 
-Every commit is the **envelope saga** — two steps driven by `legend` with
-automatic retry and LIFO compensation:
+Every commit is **atomic** — one store transaction:
 
 - `commit(transfer)` — resolves the intent into a concrete envelope (read-only),
   then runs `commit_envelope`.
-- `commit_envelope(envelope)` — the one commit path. Persists a write-ahead
-  `PendingSaga` record (phase `Reserving`), then:
-  1. **Reserve** — `reserve_postings`: Active → PendingInactive, stamped with this saga's `ReservationId`
-  2. **Finalize** — re-validates against current state (the last-step floor / freeze-close guard), marks the saga `Finalizing`, then runs the dumb primitives `deactivate_postings` → `insert_postings` → `store_transfer` → `append_event`, verifying every end-state
+- `commit_envelope(envelope)` — the one commit path. Validates against loaded
+  state in the pure core, then calls `store.commit_envelope(..)`, which in one
+  transaction spends the consumed postings, inserts the created ones, stores the
+  transfer, and appends the committed event — re-checking double-spend,
+  freeze/close, and the overdraft floor inside it.
 - `reverse(id)` — builds a reversal envelope and runs the same path.
 
-The store reports an **affected-row count** for each primitive; the saga
-interprets it (full = continue, partial = error → compensate, zero = read state
-and continue only if this same envelope already applied it). There is no
-monolithic `commit_transfer` and no separate "atomic" path.
-
-### Crash recovery
-
-`recover()` — call on startup. It completes any `PendingSaga` left by a crash,
-branching on the persisted phase: a `Reserving` saga is re-run (re-validating,
-aborting cleanly if a posting was taken or an account frozen); a `Finalizing`
-saga is rolled forward through the verified `finalize_envelope`. Roll-forward,
-not rollback.
+A domain refusal (double-spend, frozen, closed, overdraft) comes back as a typed
+`LedgerError`, and nothing is applied. Because the write is all-or-nothing, a
+crash leaves no half-applied state — there is no write-ahead log and no recovery
+step.
 
 ### Account lifecycle
 
@@ -70,17 +63,19 @@ not rollback.
 | `postings(account)` | All postings (any status) |
 | `get_events_since(seq, limit)` | Query ledger event log |
 
-### Saga composition
+### Multi-transfer composition
 
-Combine steps into multi-transfer workflows using the `legend!` macro:
+Combine transfers into an all-or-nothing workflow with `run_movements`, which
+commits them in order and reverses the committed ones LIFO on failure:
 
 ```rust
-legend! {
-    FundAndPay<LedgerCtx, SagaError> {
-        deposit: DepositMovementStep,
-        pay: PayMovementStep,
-    }
-}
+use kuatia::saga::{DepositInput, Movement, PayInput, run_movements};
+
+let receipts = run_movements(&ledger, &[
+    Movement::Deposit(DepositInput { to: alice, asset: usd, amount, external: bank }),
+    Movement::Pay(PayInput { from: alice, to: bob, asset: usd, amount }),
+])
+.await?;
 ```
 
 ## Examples

+ 0 - 3
crates/kuatia/examples/create_accounts.rs

@@ -62,8 +62,5 @@ async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
     let store = SqlStore::new(pool);
     store.migrate().await?;
     let ledger = Arc::new(Ledger::new(store));
-    // On startup, finish any commit a crash interrupted (idempotent roll-forward).
-    // A clean store has nothing pending, so this returns 0.
-    ledger.recover().await?;
     Ok(ledger)
 }

+ 0 - 2
crates/kuatia/examples/fund_and_trade.rs

@@ -95,7 +95,5 @@ async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
     let store = SqlStore::new(pool);
     store.migrate().await?;
     let ledger = Arc::new(Ledger::new(store));
-    // On startup, finish any commit a crash interrupted (idempotent roll-forward).
-    ledger.recover().await?;
     Ok(ledger)
 }

+ 0 - 2
crates/kuatia/examples/inflight_hold.rs

@@ -165,7 +165,5 @@ async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
     let store = SqlStore::new(pool);
     store.migrate().await?;
     let ledger = Arc::new(Ledger::new(store));
-    // On startup, finish any commit a crash interrupted (idempotent roll-forward).
-    ledger.recover().await?;
     Ok(ledger)
 }

+ 0 - 2
crates/kuatia/examples/withdraw.rs

@@ -70,7 +70,5 @@ async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
     let store = SqlStore::new(pool);
     store.migrate().await?;
     let ledger = Arc::new(Ledger::new(store));
-    // On startup, finish any commit a crash interrupted (idempotent roll-forward).
-    ledger.recover().await?;
     Ok(ledger)
 }

+ 5 - 0
crates/kuatia/src/error.rs

@@ -32,6 +32,10 @@ pub enum LedgerError {
     TransferNotFound(EnvelopeId),
     /// The posting cannot be reversed (e.g. already consumed).
     PostingNotReversible(PostingId),
+    /// A consumed posting was no longer live at commit time: already spent,
+    /// missing, or taken by a concurrent commit. The atomic commit refused it
+    /// rather than double-spend. Carries the first offending posting.
+    DoubleSpend(PostingId),
     /// The referenced account does not exist.
     AccountNotFound(AccountId),
     /// Cannot close an account that still has active postings.
@@ -99,6 +103,7 @@ impl fmt::Display for LedgerError {
             Self::Selection(e) => write!(f, "selection: {e}"),
             Self::TransferNotFound(id) => write!(f, "transfer not found: {id:?}"),
             Self::PostingNotReversible(id) => write!(f, "posting not reversible: {id:?}"),
+            Self::DoubleSpend(id) => write!(f, "posting already spent: {id:?}"),
             Self::AccountNotFound(id) => write!(f, "account not found: {id:?}"),
             Self::AccountNotEmpty(id) => write!(f, "account not empty: {id:?}"),
             Self::AccountAlreadyClosed(id) => write!(f, "account already closed: {id:?}"),

+ 2 - 3
crates/kuatia/src/ledger.rs

@@ -4,8 +4,8 @@
 //! sibling modules by concern, so the deep commit engine is not buried among
 //! shallow query re-exports:
 //!
-//! - `commit`: the write-ahead saga/commit engine (resolve, commit, reverse,
-//!   recover, finalize). This is what a ledger fundamentally *is*.
+//! - `commit`: the commit engine (resolve, validate, atomic apply, reverse).
+//!   This is what a ledger fundamentally *is*.
 //! - `lifecycle`: account create, freeze, unfreeze, close.
 //! - `balance`: per-subaccount balance queries.
 //! - `query`: read-only queries and book CRUD (thin `Store` pass-throughs that
@@ -22,7 +22,6 @@ use crate::error::LedgerError;
 mod balance;
 mod commit;
 mod lifecycle;
-mod pending;
 mod query;
 mod transition;
 

+ 98 - 740
crates/kuatia/src/ledger/commit.rs

@@ -1,10 +1,12 @@
-//! The write-ahead commit engine: resolve, reserve, finalize, recover.
+//! The commit engine: resolve, validate, apply atomically, reverse.
 //!
-//! This is the deep core of the ledger. Every commit is the linear
-//! `reserve → finalize` path (validation inside finalize), which releases its
-//! reservation to compensate a failure before the point of no return. A
-//! phase-tracked write-ahead record ([`PendingSaga`]) lets [`Ledger::recover`]
-//! complete or safely abandon a commit interrupted by a crash.
+//! This is the deep core of the ledger. Every commit resolves a [`Transfer`]
+//! intent into a concrete [`Envelope`], validates it against loaded state in the
+//! pure core, and hands the validated effects to the store's atomic
+//! [`commit_envelope`](kuatia_storage::store::CommitStore::commit_envelope). The
+//! store applies them in one transaction and re-checks the stateful guards
+//! inside it, so there is no half-applied state and nothing to recover after a
+//! crash (ADR-0023, superseding the write-ahead saga of ADR-0003).
 
 use std::collections::HashMap;
 use std::collections::hash_map::Entry;
@@ -15,19 +17,16 @@ use tracing::instrument;
 use kuatia_core::{
     Account, AccountId, AccountSnapshotId, AssetId, Book, Cent, DEFAULT_BOOK, Envelope,
     EnvelopeBuilder, EnvelopeId, NewPosting, Plan, PlanInput, Posting, PostingFilter, PostingId,
-    PostingState, Receipt, ReservationId, ResolveInput, Transfer, account_snapshot_id,
-    draft_movements, envelope_id, required_state, resolve_envelope, validate_and_plan,
+    Receipt, ResolveInput, Transfer, ValidationError, account_snapshot_id, draft_movements,
+    envelope_id, required_state, resolve_envelope, validate_and_plan,
 };
 
 use kuatia_storage::error::StoreError;
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
-use kuatia_storage::store::{EnvelopeRecord, SagaKind};
+use kuatia_storage::store::{CommitOutcome, CommitRejection, CommitRequest, EnvelopeRecord};
 
 use super::{Ledger, now_millis};
 use crate::error::LedgerError;
-use crate::saga::{apply_and_verify, consume_reserved, verify_postings};
-
-use super::pending::{PendingSaga, PendingTransition, SagaPhase};
 
 /// State loaded in phase 1, passed to the pure validation in phase 2.
 struct LoadedState {
@@ -167,26 +166,26 @@ impl Ledger {
     }
 
     // -----------------------------------------------------------------------
-    // Commit: every commit is the envelope saga (reserve -> finalize; finalize re-validates)
+    // Commit: resolve (read-only) then apply atomically
     // -----------------------------------------------------------------------
 
     /// Commit a [`Transfer`] intent. Resolves it into a concrete envelope, then
-    /// drives the envelope saga. Resolution is read-only, so a crash before the
-    /// saga's write-ahead record leaves no partial state.
+    /// validates and applies it atomically. Resolution is read-only, and the
+    /// apply is one store transaction, so a crash leaves no partial state.
     #[instrument(skip(self, transfer), fields(book = transfer.book.0), name = "ledger.commit")]
     pub async fn commit(self: &Arc<Self>, transfer: Transfer) -> Result<Receipt, LedgerError> {
         let envelope = self.resolve(&transfer).await?;
         self.commit_envelope(envelope).await
     }
 
-    /// Commit a pre-resolved [`Envelope`] through the saga pipeline (reserve ->
-    /// validate -> finalize). This is the single commit path; `commit()` and
-    /// `reverse()` both funnel through it.
-    ///
-    /// Before running, the commit (envelope + reservation) is persisted as a
-    /// pending record so a crash mid-commit is completed by [`recover`](Self::recover). The
-    /// record is deleted once the commit reaches a terminal state. The commit is
-    /// idempotent on the content-addressed transfer id.
+    /// Commit a pre-resolved [`Envelope`]. Validates it against loaded state,
+    /// then applies the validated effects through the store's atomic
+    /// [`commit_envelope`](kuatia_storage::store::CommitStore::commit_envelope):
+    /// one transaction that spends the consumed postings, creates the new ones,
+    /// stores the transfer, and appends the committed event, re-checking
+    /// double-spend, freeze/close, and the overdraft floor inside it. This is the
+    /// single commit path; `commit()` and `reverse()` both funnel through it, and
+    /// it is idempotent on the content-addressed transfer id.
     #[instrument(skip(self, envelope), name = "ledger.commit_envelope")]
     pub async fn commit_envelope(
         self: &Arc<Self>,
@@ -199,256 +198,59 @@ impl Ledger {
             envelope.set_account_snapshots(self.resolve_snapshots(&ids).await?);
         }
 
-        // Idempotency: an already-committed transfer returns its receipt.
+        // Idempotency pre-check: an already-committed transfer returns its receipt
+        // without re-validating. The store also guards this atomically.
         let tid = envelope_id(&envelope);
         if let Some(record) = self.store.get_transfer(&tid).await? {
             return Ok(record.receipt);
         }
 
-        // The write-ahead record owns its own lifecycle (persist at Reserving,
-        // drive the saga, clear only when past-the-point-of-no-return is safe), so
-        // this path and `recover()` share one contract instead of each re-deriving
-        // the phase rules.
-        PendingSaga::new(envelope, ReservationId::default())
-            .run(self)
-            .await
-    }
-
-    /// The single-commit core: reserve the consumed postings, then finalize.
-    ///
-    /// This used to be a two-step `legend` saga; for one commit the steps were
-    /// pass-throughs, so the reserve/compensation policy now lives here as a
-    /// linear path next to [`finalize_envelope`](Self::finalize_envelope).
-    /// (`legend` still drives the composed multi-transfer sagas in `saga`.)
-    ///
-    /// On any failure the reservation is released (the LIFO compensation collapsed
-    /// to its one meaningful action). Before the point of no return that returns
-    /// the postings to Active so the caller's `clear_if_safe` can drop the
-    /// write-ahead record; past `Finalizing` the postings are already spent, so
-    /// the release is a no-op and the record is instead kept for roll-forward. The
-    /// typed error (validation / overdraft / frozen) reaches the caller unchanged.
-    pub(super) async fn reserve_and_finalize(
-        &self,
-        envelope: &Envelope,
-        reservation: ReservationId,
-    ) -> Result<Receipt, LedgerError> {
-        let consumes = envelope.consumes();
+        // Pure validation against loaded state (conservation, ownership,
+        // snapshots, book policy, plus a best-effort floor/freeze read). The store
+        // then re-checks the stateful guards strictly inside the commit
+        // transaction.
+        let loaded = self.load(&envelope).await?;
+        let plan = self.plan(&envelope, &loaded)?;
+
+        // Index both created and consumed owners; this is also the set the store
+        // re-checks for freeze/close/floor.
+        let mut involved: Vec<AccountId> =
+            plan.postings_to_create.iter().map(|p| p.owner).collect();
+        involved.extend(loaded.consumed_postings.iter().map(|p| p.owner));
+        involved.sort();
+        involved.dedup();
 
-        let result = match self.reserve_consumed(consumes, reservation).await {
-            Ok(()) => self.finalize_envelope(envelope, reservation).await,
-            Err(err) => Err(err),
+        let ts = now_millis()?;
+        let receipt = Receipt {
+            transfer_id: plan.transfer_id,
         };
-
-        match result {
-            Ok(receipt) => Ok(receipt),
-            // Compensate by releasing our reservation. If the release itself fails
-            // we surface both errors, matching the old saga's `CompensationFailed`.
-            Err(err) => match self.store.release_postings(consumes, reservation).await {
-                Ok(_) => Err(err),
-                Err(comp) => Err(LedgerError::CompensationFailed {
-                    original: Box::new(err),
-                    compensation: Box::new(LedgerError::Store(comp)),
-                }),
-            },
-        }
-    }
-
-    /// Reserve every consumed posting into the reserved index under `reservation`
-    /// (a CAS out of the active index), then check the affected-row count against
-    /// the ADR-0003 contract. A short count is accepted only when the shortfall is
-    /// already reserved by us (an idempotent replay, e.g. recovery re-running a
-    /// `Reserving` saga). A deposit consumes nothing, so this is a no-op.
-    async fn reserve_consumed(
-        &self,
-        consumes: &[PostingId],
-        reservation: ReservationId,
-    ) -> Result<(), LedgerError> {
-        if consumes.is_empty() {
-            return Ok(());
-        }
-        let reserved = self
-            .store
-            .reserve_postings(consumes, reservation)
-            .await
-            .map_err(LedgerError::Store)?;
-        verify_postings(
-            self.store.as_ref(),
-            consumes,
-            reserved,
-            |s| matches!(s, PostingState::Reserved(r) if *r == reservation),
-            "reserve",
-        )
-        .await
-    }
-
-    /// Complete every pending write-ahead record left by a crash. Call on
-    /// startup; returns how many were processed.
-    ///
-    /// Each record is dispatched on its stored [`SagaKind`] and driven to a
-    /// terminal state by the completion method in the `pending` module: a
-    /// transition rolls forward; an envelope commit branches on its persisted
-    /// phase — a `Reserving` saga is re-run and re-validated, a `Finalizing` saga
-    /// is rolled forward through the verified `finalize_envelope`.
-    #[instrument(skip(self), name = "ledger.recover")]
-    pub async fn recover(self: &Arc<Self>) -> Result<usize, LedgerError> {
-        let pending = self.store.list_pending_sagas().await?;
-        let count = pending.len();
-        for (kind, saga_id, blob) in pending {
-            // Dispatch on the store's typed kind, not an in-band blob tag. The
-            // commit lifecycle (phase rules, delete-safety) lives on `PendingSaga`;
-            // a transition rolls itself forward.
-            match kind {
-                SagaKind::Envelope => PendingSaga::decode(&blob)?.complete(self).await?,
-                SagaKind::Transition => {
-                    PendingTransition::decode(&blob)?
-                        .complete(self, saga_id)
-                        .await?
-                }
-            }
-        }
-        Ok(count)
-    }
-
-    /// Idempotently finalize `envelope` to its committed state, **verifying every
-    /// step's end-state**. Used by the saga's finalize step and by recovery.
-    ///
-    /// When the consumed postings are still reserved it re-validates against
-    /// current state (the last-step floor / freeze-close guard) and then marks
-    /// the saga `Finalizing` (the point of no return). Once any consumed posting
-    /// is already spent — a prior attempt or recovery passed that point — it
-    /// rolls forward without re-validating. It never creates or stores anything
-    /// unless **all** consumed postings are confirmed spent, which is the
-    /// double-spend guard.
-    pub(crate) async fn finalize_envelope(
-        &self,
-        envelope: &Envelope,
-        reservation: ReservationId,
-    ) -> Result<Receipt, LedgerError> {
-        let tid = envelope_id(envelope);
-        if let Some(record) = self.store.get_transfer(&tid).await? {
-            // The transfer record is durable, but a crash (or a retried finalize)
-            // can land between store_transfer and the event append below. The
-            // committed end-state includes the event, so ensure it before
-            // returning — `append_committed_event` is idempotent.
-            self.append_committed_event(tid).await?;
-            return Ok(record.receipt); // already committed
-        }
-        let consumes = envelope.consumes();
-
-        // Read consumed postings (immutable rows, kept for owner indexing) and
-        // their derived states.
-        let consumed = if consumes.is_empty() {
-            Vec::new()
-        } else {
-            self.store.get_postings(consumes).await?
+        let record = EnvelopeRecord {
+            envelope: envelope.clone(),
+            receipt: receipt.clone(),
+            created_at: ts,
         };
-        let states = if consumes.is_empty() {
-            Vec::new()
-        } else {
-            self.store.get_posting_states(consumes).await?
+        let event = LedgerEvent {
+            seq: 0,
+            timestamp: ts,
+            kind: LedgerEventKind::TransferCommitted {
+                transfer_id: plan.transfer_id,
+            },
         };
-        let past_no_return = states.contains(&PostingState::Spent);
-
-        // Last-step boundary re-check: re-validate floor + freeze/close + snapshots
-        // against current state, but only while it is still safe (validation
-        // rejects a consumed posting that is no longer live).
-        if !past_no_return {
-            let loaded = self.load(envelope).await?;
-            self.plan(envelope, &loaded)?;
-        }
-
-        // Point of no return: record Finalizing before any posting is consumed.
-        PendingSaga::finalizing(envelope.clone(), reservation)
-            .persist(self)
-            .await?;
-
-        // The authoritative double-spend guard (see `consume_reserved`): consume
-        // only rows we reserved, then assert all consumed postings are spent.
-        consume_reserved(self.store.as_ref(), consumes, reservation).await?;
 
-        // Created postings, derived deterministically from the envelope.
-        let created: Vec<Posting> = envelope
-            .creates()
-            .iter()
-            .enumerate()
-            .map(|(i, np)| {
-                Posting::new(
-                    PostingId {
-                        transfer: tid,
-                        index: i as u16,
-                    },
-                    np.owner,
-                    np.asset,
-                    np.value,
-                )
-            })
-            .collect();
-        let inserted = self.store.insert_postings(&created).await?;
-        let created_ids: Vec<PostingId> = created.iter().map(|p| p.id).collect();
-        verify_postings(
-            self.store.as_ref(),
-            &created_ids,
-            inserted,
-            |s| *s != PostingState::Missing,
-            "finalize: insert created postings",
-        )
-        .await?;
-
-        // Index both created and consumed owners.
-        let mut involved: Vec<AccountId> = created.iter().map(|p| p.owner).collect();
-        involved.extend(consumed.iter().map(|p| p.owner));
-        involved.sort();
-        involved.dedup();
-
-        let receipt = Receipt { transfer_id: tid };
-        let stored = self
+        let outcome = self
             .store
-            .store_transfer(
-                EnvelopeRecord {
-                    envelope: envelope.clone(),
-                    receipt: receipt.clone(),
-                    created_at: now_millis()?,
-                },
-                &involved,
-            )
-            .await?;
-        apply_and_verify(stored, 1, "finalize: store transfer record", || async {
-            Ok(self.store.get_transfer(&tid).await?.is_some())
-        })
-        .await?;
-
-        self.append_committed_event(tid).await?;
-        Ok(receipt)
-    }
-
-    /// Idempotently append the `TransferCommitted` event for `tid`.
-    ///
-    /// The event append is the final finalize step, *after* `store_transfer`, so a
-    /// crash in that window leaves a stored transfer with no event. Recovery and a
-    /// retried finalize both call this to repair the committed end-state.
-    /// `append_event` dedups on the transfer id, so calling it more than once for
-    /// the same transfer is a no-op.
-    pub(super) async fn append_committed_event(&self, tid: EnvelopeId) -> Result<(), LedgerError> {
-        self.store
-            .append_event(&LedgerEvent {
-                seq: 0,
-                timestamp: now_millis()?,
-                kind: LedgerEventKind::TransferCommitted { transfer_id: tid },
+            .commit_envelope(CommitRequest {
+                transfer_id: plan.transfer_id,
+                consume: &plan.postings_to_deactivate,
+                create: &plan.postings_to_create,
+                record,
+                involved: &involved,
+                event,
             })
             .await?;
-        Ok(())
-    }
-
-    /// The persisted commit phase of the record stored under `saga_id`, via a
-    /// keyed read. `None` when no record exists there or it is a transition
-    /// (which has no phase). Used to decide whether a failed commit reached the
-    /// point of no return.
-    pub(super) async fn saga_phase(&self, saga_id: i64) -> Result<Option<SagaPhase>, LedgerError> {
-        // Only ever called with an envelope saga's key (its reservation id), so the
-        // record decodes as a `PendingSaga`; a transition never reaches here.
-        match self.store.get_saga(&saga_id).await? {
-            Some(blob) => Ok(Some(PendingSaga::decode(&blob)?.phase)),
-            None => Ok(None),
+        match outcome {
+            CommitOutcome::Committed(r) | CommitOutcome::AlreadyCommitted(r) => Ok(r),
+            CommitOutcome::Rejected(reason) => Err(map_rejection(reason)),
         }
     }
 
@@ -516,11 +318,34 @@ impl Ledger {
     }
 }
 
+/// Map a store-side [`CommitRejection`] to the typed ledger error callers match
+/// on, so a strict in-transaction guard surfaces the same error a snapshot-time
+/// validation would.
+fn map_rejection(reason: CommitRejection) -> LedgerError {
+    match reason {
+        CommitRejection::DoubleSpend(id) => LedgerError::DoubleSpend(id),
+        CommitRejection::AccountFrozen(id) => {
+            LedgerError::Validation(ValidationError::AccountFrozen(id))
+        }
+        CommitRejection::AccountClosed(id) => {
+            LedgerError::Validation(ValidationError::AccountClosed(id))
+        }
+        CommitRejection::OverdraftExceeded {
+            account,
+            asset,
+            projected,
+        } => LedgerError::Validation(ValidationError::OverdraftExceeded {
+            account,
+            asset,
+            projected,
+        }),
+    }
+}
+
 #[cfg(test)]
-mod recovery_tests {
-    use super::super::pending::{PendingSaga, PendingTransition};
+mod tests {
     use super::*;
-    use kuatia_core::{Account, AccountFlags, ReservationId, TransferBuilder, TransitionId};
+    use kuatia_core::{Account, AccountFlags, TransferBuilder};
     use kuatia_storage::mem_store::InMemoryStore;
     use std::collections::BTreeMap;
 
@@ -568,35 +393,11 @@ mod recovery_tests {
             .build()
     }
 
-    async fn save_pending(
-        ledger: &Arc<Ledger>,
-        envelope: &Envelope,
-        rid: ReservationId,
-        phase: SagaPhase,
-    ) {
-        let blob = serde_json::to_vec(&PendingSaga {
-            envelope: envelope.clone(),
-            reservation: rid,
-            phase,
-        })
-        .unwrap();
-        ledger
-            .store()
-            .save_saga(SagaKind::Envelope, &rid.0, blob)
-            .await
-            .unwrap();
-    }
-
-    /// A commit interrupted right after its write-ahead record (phase Reserving,
-    /// before any step) is re-run and completed by `recover()`.
+    /// A commit spends the payer's posting and credits the payee atomically.
     #[tokio::test]
-    async fn recover_redrives_reserving_saga() {
+    async fn commit_moves_value() {
         let ledger = funded_ledger().await;
-        let envelope = ledger.resolve(&pay_transfer()).await.unwrap();
-        let rid = ReservationId::default();
-        save_pending(&ledger, &envelope, rid, SagaPhase::Reserving).await;
-
-        assert_eq!(ledger.recover().await.unwrap(), 1);
+        ledger.commit(pay_transfer()).await.unwrap();
         assert_eq!(
             ledger
                 .balance(&AccountId::new(2), &AssetId::new(1))
@@ -611,169 +412,18 @@ mod recovery_tests {
                 .unwrap(),
             Cent::from(60)
         );
-        assert!(
-            ledger
-                .store()
-                .list_pending_sagas()
-                .await
-                .unwrap()
-                .is_empty()
-        );
     }
 
-    /// A commit that crashed mid-finalize (phase Finalizing; the consumed posting
-    /// is already spent) is rolled forward by `recover()`.
+    /// Committing into a frozen payer is rejected atomically: nothing moves.
     #[tokio::test]
-    async fn recover_completes_partial_finalize() {
+    async fn commit_into_frozen_account_is_rejected() {
         let ledger = funded_ledger().await;
-        let envelope = ledger.resolve(&pay_transfer()).await.unwrap();
-        let rid = ReservationId::default();
-        // Run the commit halfway: reserve + deactivate the consumed posting.
-        let consumes = envelope.consumes().to_vec();
-        ledger
-            .store()
-            .reserve_postings(&consumes, rid)
-            .await
-            .unwrap();
-        assert_eq!(
-            ledger
-                .store()
-                .deactivate_postings(&consumes, Some(rid))
-                .await
-                .unwrap(),
-            1
-        );
-        save_pending(&ledger, &envelope, rid, SagaPhase::Finalizing).await;
-
-        assert_eq!(ledger.recover().await.unwrap(), 1);
-        assert_eq!(
-            ledger
-                .balance(&AccountId::new(2), &AssetId::new(1))
-                .await
-                .unwrap(),
-            Cent::from(40)
-        );
-        assert_eq!(
-            ledger
-                .balance(&AccountId::new(1), &AssetId::new(1))
-                .await
-                .unwrap(),
-            Cent::from(60)
-        );
-        assert!(
-            ledger
-                .store()
-                .list_pending_sagas()
-                .await
-                .unwrap()
-                .is_empty()
-        );
-    }
-
-    /// A commit that crashed *after* `store_transfer` but *before* the committed
-    /// event was appended (phase Finalizing, transfer row present, event missing)
-    /// is repaired by `recover()`: the full end-state includes the event, so
-    /// recovery appends it (idempotently) instead of treating the transfer row as
-    /// proof of a complete commit.
-    #[tokio::test]
-    async fn recover_appends_missing_committed_event() {
-        let ledger = funded_ledger().await;
-        let envelope = ledger.resolve(&pay_transfer()).await.unwrap();
-        let tid = envelope_id(&envelope);
-        let rid = ReservationId::default();
-
-        // Replay finalize by hand up to and including store_transfer, stopping
-        // short of the event append — exactly the crash window.
-        let consumes = envelope.consumes().to_vec();
-        ledger
-            .store()
-            .reserve_postings(&consumes, rid)
-            .await
-            .unwrap();
-        ledger
-            .store()
-            .deactivate_postings(&consumes, Some(rid))
-            .await
-            .unwrap();
-        let created: Vec<Posting> = envelope
-            .creates()
-            .iter()
-            .enumerate()
-            .map(|(i, np)| {
-                Posting::new(
-                    PostingId {
-                        transfer: tid,
-                        index: i as u16,
-                    },
-                    np.owner,
-                    np.asset,
-                    np.value,
-                )
-            })
-            .collect();
-        ledger.store().insert_postings(&created).await.unwrap();
-        let consumed = ledger.store().get_postings(&consumes).await.unwrap();
-        let mut involved: Vec<AccountId> = created.iter().map(|p| p.owner).collect();
-        involved.extend(consumed.iter().map(|p| p.owner));
-        involved.sort();
-        involved.dedup();
-        ledger
-            .store()
-            .store_transfer(
-                EnvelopeRecord {
-                    envelope: envelope.clone(),
-                    receipt: Receipt { transfer_id: tid },
-                    created_at: 0,
-                },
-                &involved,
-            )
-            .await
-            .unwrap();
-        save_pending(&ledger, &envelope, rid, SagaPhase::Finalizing).await;
-
-        // Precondition: the transfer is stored, but no committed event exists yet.
-        let committed = |evs: &[LedgerEvent]| {
-            evs.iter().any(|e| {
-                matches!(
-                    e.kind,
-                    LedgerEventKind::TransferCommitted { transfer_id } if transfer_id == tid
-                )
-            })
-        };
-        assert!(ledger.store().get_transfer(&tid).await.unwrap().is_some());
-        assert!(!committed(&ledger.get_events_since(0, 1000).await.unwrap()));
-
-        assert_eq!(ledger.recover().await.unwrap(), 1);
-
-        // The missing event is repaired and the pending record cleared.
-        assert!(committed(&ledger.get_events_since(0, 1000).await.unwrap()));
-        assert!(
-            ledger
-                .store()
-                .list_pending_sagas()
-                .await
-                .unwrap()
-                .is_empty()
-        );
-    }
-
-    /// Recovery of a `Reserving` saga re-validates against current state: if an
-    /// account was frozen after the write-ahead record, the commit is abandoned —
-    /// no postings move, the reservation is released, and the record is cleared.
-    #[tokio::test]
-    async fn recover_revalidates_and_aborts_when_account_frozen() {
-        let ledger = funded_ledger().await;
-        let envelope = ledger.resolve(&pay_transfer()).await.unwrap();
-        let tid = envelope_id(&envelope);
-        let rid = ReservationId::default();
-        save_pending(&ledger, &envelope, rid, SagaPhase::Reserving).await;
-
-        // A freeze lands before recovery runs.
         ledger.freeze(&AccountId::new(1)).await.unwrap();
-
-        assert_eq!(ledger.recover().await.unwrap(), 1);
-        // Nothing committed; balances unchanged; reservation released.
-        assert!(ledger.store().get_transfer(&tid).await.unwrap().is_none());
+        let err = ledger.commit(pay_transfer()).await.unwrap_err();
+        assert!(matches!(
+            err,
+            LedgerError::Validation(ValidationError::AccountFrozen(_))
+        ));
         assert_eq!(
             ledger
                 .balance(&AccountId::new(1), &AssetId::new(1))
@@ -781,298 +431,6 @@ mod recovery_tests {
                 .unwrap(),
             Cent::from(100)
         );
-        assert_eq!(
-            ledger
-                .balance(&AccountId::new(2), &AssetId::new(1))
-                .await
-                .unwrap(),
-            Cent::ZERO
-        );
-        let active = ledger
-            .store()
-            .get_postings_by_account(1, None, Some(&AssetId::new(1)), PostingFilter::Active)
-            .await
-            .unwrap();
-        assert_eq!(active.len(), 1); // back to Active
-        assert!(
-            ledger
-                .store()
-                .list_pending_sagas()
-                .await
-                .unwrap()
-                .is_empty()
-        );
-    }
-
-    /// Recovery cannot double-spend: if the consumed posting was taken by another
-    /// transfer while the saga was pending, recovery aborts without creating or
-    /// storing anything.
-    #[tokio::test]
-    async fn recover_does_not_double_spend_a_taken_posting() {
-        let ledger = funded_ledger().await;
-        let envelope = ledger.resolve(&pay_transfer()).await.unwrap();
-        let tid = envelope_id(&envelope);
-        let rid = ReservationId::default();
-        save_pending(&ledger, &envelope, rid, SagaPhase::Reserving).await;
-
-        // Another transfer consumes account 1's posting and commits.
-        let steal = TransferBuilder::new()
-            .pay(
-                AccountId::new(1),
-                AccountId::new(3),
-                AssetId::new(1),
-                Cent::from(50),
-            )
-            .build();
-        ledger.commit(steal).await.unwrap();
-
-        assert_eq!(ledger.recover().await.unwrap(), 1);
-        // Our envelope never committed; only the stealing transfer applied.
-        assert!(ledger.store().get_transfer(&tid).await.unwrap().is_none());
-        assert_eq!(
-            ledger
-                .balance(&AccountId::new(1), &AssetId::new(1))
-                .await
-                .unwrap(),
-            Cent::from(50)
-        );
-        assert_eq!(
-            ledger
-                .balance(&AccountId::new(3), &AssetId::new(1))
-                .await
-                .unwrap(),
-            Cent::from(50)
-        );
-        assert_eq!(
-            ledger
-                .balance(&AccountId::new(2), &AssetId::new(1))
-                .await
-                .unwrap(),
-            Cent::ZERO
-        );
-        assert!(
-            ledger
-                .store()
-                .list_pending_sagas()
-                .await
-                .unwrap()
-                .is_empty()
-        );
-    }
-
-    // -----------------------------------------------------------------------
-    // Account-version transition recovery (freeze / unfreeze / close)
-    // -----------------------------------------------------------------------
-
-    /// Persist a transition write-ahead record by hand and return its id, so a
-    /// test can simulate a crash mid-transition.
-    async fn save_transition_record(
-        ledger: &Arc<Ledger>,
-        next: &Account,
-        event: &LedgerEventKind,
-    ) -> Result<i64, LedgerError> {
-        let saga_id = TransitionId::default().0;
-        let blob = serde_json::to_vec(&PendingTransition::new(next.clone(), event.clone()))
-            .map_err(|e| LedgerError::Store(StoreError::Internal(e.to_string())))?;
-        ledger
-            .store()
-            .save_saga(SagaKind::Transition, &saga_id, blob)
-            .await?;
-        Ok(saga_id)
-    }
-
-    fn count_frozen(events: &[LedgerEvent], id: AccountId) -> usize {
-        events
-            .iter()
-            .filter(|e| {
-                matches!(
-                    e.kind,
-                    LedgerEventKind::AccountFrozen { account_id, .. } if account_id == id
-                )
-            })
-            .count()
-    }
-
-    fn count_closed(events: &[LedgerEvent], id: AccountId) -> usize {
-        events
-            .iter()
-            .filter(|e| {
-                matches!(
-                    e.kind,
-                    LedgerEventKind::AccountClosed { account_id, .. } if account_id == id
-                )
-            })
-            .count()
-    }
-
-    /// The happy path leaves nothing to recover: a completed freeze deletes its
-    /// write-ahead record and emits exactly one event.
-    #[tokio::test]
-    async fn freeze_leaves_no_pending_record() -> Result<(), LedgerError> {
-        let ledger = funded_ledger().await;
-        ledger.freeze(&AccountId::new(1)).await?;
-
-        assert!(
-            ledger
-                .store()
-                .get_account(&AccountId::new(1))
-                .await?
-                .is_frozen()
-        );
-        let events = ledger.get_events_since(0, 1000).await?;
-        assert_eq!(count_frozen(&events, AccountId::new(1)), 1);
-        assert!(ledger.store().list_pending_sagas().await?.is_empty());
-        Ok(())
-    }
-
-    /// The reported gap: a freeze crashed after the version append but before the
-    /// event append. Recovery appends the missing event (without bumping the
-    /// version again) and clears the record.
-    #[tokio::test]
-    async fn recover_completes_transition_missing_event() -> Result<(), LedgerError> {
-        let ledger = funded_ledger().await;
-        let current = ledger.store().get_account(&AccountId::new(1)).await?;
-        let mut next = current;
-        next.version += 1;
-        next.flags |= AccountFlags::FROZEN;
-        let event = LedgerEventKind::AccountFrozen {
-            account_id: AccountId::new(1),
-            version: next.version,
-        };
-
-        // Replay the transition up to (but not including) the event append.
-        ledger.store().append_account_version(next.clone()).await?;
-        save_transition_record(&ledger, &next, &event).await?;
-
-        // Precondition: version bumped and frozen, but no event yet.
-        assert_eq!(next.version, 2);
-        assert_eq!(
-            count_frozen(&ledger.get_events_since(0, 1000).await?, AccountId::new(1)),
-            0
-        );
-
-        assert_eq!(ledger.recover().await?, 1);
-
-        // The event is appended, the version is not bumped a second time, and the
-        // record is cleared.
-        let account = ledger.store().get_account(&AccountId::new(1)).await?;
-        assert!(account.is_frozen());
-        assert_eq!(account.version, 2);
-        assert_eq!(
-            count_frozen(&ledger.get_events_since(0, 1000).await?, AccountId::new(1)),
-            1
-        );
-        assert!(ledger.store().list_pending_sagas().await?.is_empty());
-        Ok(())
-    }
-
-    /// A freeze that crashed before either write is rolled fully forward: recovery
-    /// appends the version and the event, then clears the record.
-    #[tokio::test]
-    async fn recover_completes_transition_before_any_write() -> Result<(), LedgerError> {
-        let ledger = funded_ledger().await;
-        let current = ledger.store().get_account(&AccountId::new(1)).await?;
-        let mut next = current;
-        next.version += 1;
-        next.flags |= AccountFlags::FROZEN;
-        let event = LedgerEventKind::AccountFrozen {
-            account_id: AccountId::new(1),
-            version: next.version,
-        };
-        save_transition_record(&ledger, &next, &event).await?;
-
-        // Precondition: nothing applied yet.
-        let before = ledger.store().get_account(&AccountId::new(1)).await?;
-        assert_eq!(before.version, 1);
-        assert!(!before.is_frozen());
-
-        assert_eq!(ledger.recover().await?, 1);
-
-        let account = ledger.store().get_account(&AccountId::new(1)).await?;
-        assert!(account.is_frozen());
-        assert_eq!(account.version, 2);
-        assert_eq!(
-            count_frozen(&ledger.get_events_since(0, 1000).await?, AccountId::new(1)),
-            1
-        );
-        assert!(ledger.store().list_pending_sagas().await?.is_empty());
-        Ok(())
-    }
-
-    /// A transition that fully applied but whose record survived (crash before the
-    /// final delete) recovers idempotently: no second version, no duplicate event.
-    #[tokio::test]
-    async fn recover_transition_is_idempotent_when_already_applied() -> Result<(), LedgerError> {
-        let ledger = funded_ledger().await;
-        // A real, completed freeze: version 2, one event, no record.
-        ledger.freeze(&AccountId::new(1)).await?;
-        let next = ledger.store().get_account(&AccountId::new(1)).await?;
-        let event = LedgerEventKind::AccountFrozen {
-            account_id: AccountId::new(1),
-            version: next.version,
-        };
-        // Simulate the record surviving the crash window before delete_saga.
-        save_transition_record(&ledger, &next, &event).await?;
-
-        assert_eq!(ledger.recover().await?, 1);
-
-        let account = ledger.store().get_account(&AccountId::new(1)).await?;
-        assert_eq!(account.version, 2, "no second version bump");
-        assert_eq!(
-            count_frozen(&ledger.get_events_since(0, 1000).await?, AccountId::new(1)),
-            1,
-            "event not duplicated"
-        );
-        assert!(ledger.store().list_pending_sagas().await?.is_empty());
-        Ok(())
-    }
-
-    /// A close crashed after the version append but before the event append is
-    /// rolled forward: recovery appends the `AccountClosed` event without a second
-    /// version bump and clears the record. Account 2 is empty, so it may close.
-    #[tokio::test]
-    async fn recover_completes_close_missing_event() -> Result<(), LedgerError> {
-        let ledger = funded_ledger().await;
-        let current = ledger.store().get_account(&AccountId::new(2)).await?;
-        let mut next = current;
-        next.version += 1;
-        next.flags |= AccountFlags::CLOSED;
-        let event = LedgerEventKind::AccountClosed {
-            account_id: AccountId::new(2),
-            version: next.version,
-        };
-
-        // Replay the transition up to (but not including) the event append.
-        ledger.store().append_account_version(next.clone()).await?;
-        save_transition_record(&ledger, &next, &event).await?;
-        assert_eq!(
-            count_closed(&ledger.get_events_since(0, 1000).await?, AccountId::new(2)),
-            0
-        );
-
-        assert_eq!(ledger.recover().await?, 1);
-
-        let account = ledger.store().get_account(&AccountId::new(2)).await?;
-        assert!(account.is_closed());
-        assert_eq!(account.version, 2);
-        assert_eq!(
-            count_closed(&ledger.get_events_since(0, 1000).await?, AccountId::new(2)),
-            1
-        );
-        assert!(ledger.store().list_pending_sagas().await?.is_empty());
-        Ok(())
-    }
-
-    /// A rejected close records nothing: the emptiness guard runs before the
-    /// write-ahead, so a non-empty account leaves no pending record to recover.
-    #[tokio::test]
-    async fn rejected_close_leaves_no_pending_record() -> Result<(), LedgerError> {
-        let ledger = funded_ledger().await;
-        // Account 1 holds the funded posting, so it is not empty.
-        let result = ledger.close(&AccountId::new(1)).await;
-        assert!(matches!(result, Err(LedgerError::AccountNotEmpty(_))));
-        assert!(ledger.store().list_pending_sagas().await?.is_empty());
-        Ok(())
     }
 
     /// If the loader under-fetches a balance key validation reads, `plan` fails

+ 0 - 237
crates/kuatia/src/ledger/pending.rs

@@ -1,237 +0,0 @@
-//! The write-ahead record awaiting recovery, and how each kind completes.
-//!
-//! A commit (reserve → finalize) and an account-version transition (append
-//! version → append event) are each more than one store write with no shared
-//! transaction, so a crash mid-sequence can leave a half-applied state. Before
-//! either mutates anything it persists a write-ahead record via `SagaStore`,
-//! tagged with its [`SagaKind`]; on startup
-//! [`Ledger::recover`](super::Ledger::recover) loads every surviving record and,
-//! dispatching on that kind, drives it to a terminal state.
-//!
-//! This module owns the whole write-ahead concept behind one seam: what a
-//! pending record *is* ([`PendingSaga`] / [`PendingTransition`]), how it is
-//! (de)serialized, how it is persisted, and how each kind completes. The
-//! completion primitives it calls (`finalize_envelope`, `reserve_and_finalize`)
-//! stay on [`Ledger`] because the live commit path shares them; this module
-//! sequences them for the recovery path.
-
-use std::sync::Arc;
-
-use kuatia_core::{Account, Envelope, Receipt, ReservationId, envelope_id};
-use kuatia_storage::error::StoreError;
-use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
-use kuatia_storage::store::SagaKind;
-
-use super::{Ledger, now_millis};
-use crate::error::LedgerError;
-
-/// Phase of an in-flight commit, persisted with the write-ahead record so
-/// recovery knows whether validation has completed.
-#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
-pub(super) enum SagaPhase {
-    /// Saved before reserve. Validation has not necessarily run, so recovery must
-    /// re-reserve and re-validate before it can commit.
-    Reserving,
-    /// Saved at the start of finalize — after validation passed and just before
-    /// the consumed postings begin being removed from the reserved index (the
-    /// point of no return). Recovery rolls forward without re-validating.
-    Finalizing,
-}
-
-/// Write-ahead record for an in-flight commit (reserve → finalize). Persisted
-/// before the saga mutates anything and removed once it reaches a terminal
-/// state.
-#[derive(Clone, serde::Serialize, serde::Deserialize)]
-pub(super) struct PendingSaga {
-    pub(super) envelope: Envelope,
-    pub(super) reservation: ReservationId,
-    pub(super) phase: SagaPhase,
-}
-
-/// Write-ahead record for an in-flight account-version transition
-/// (freeze/unfreeze/close). The transition appends a new account version and then
-/// its lifecycle event; a crash between the two leaves a version bump with no
-/// event. Persisting this before either write lets recovery roll the transition
-/// forward, re-appending the (idempotent) event.
-#[derive(serde::Serialize, serde::Deserialize)]
-pub(super) struct PendingTransition {
-    /// The next account version to append: version already bumped, flag flipped.
-    pub(super) next: Account,
-    /// The lifecycle event paired with this version bump. It carries the target
-    /// version, so re-appending it on recovery dedups to the original.
-    pub(super) event: LedgerEventKind,
-}
-
-/// Map a JSON (de)serialization failure to a store error. The write-ahead format
-/// is a store implementation detail, so a codec failure surfaces as `Store`.
-fn json_err(e: serde_json::Error) -> LedgerError {
-    LedgerError::Store(StoreError::Internal(e.to_string()))
-}
-
-impl PendingSaga {
-    /// A fresh write-ahead record for a new commit, at the pre-mutation phase.
-    pub(super) fn new(envelope: Envelope, reservation: ReservationId) -> Self {
-        Self {
-            envelope,
-            reservation,
-            phase: SagaPhase::Reserving,
-        }
-    }
-
-    /// The same record advanced to the point of no return, used for the finalize
-    /// bump just before the consumed postings are removed.
-    pub(super) fn finalizing(envelope: Envelope, reservation: ReservationId) -> Self {
-        Self {
-            envelope,
-            reservation,
-            phase: SagaPhase::Finalizing,
-        }
-    }
-
-    /// An envelope saga is always keyed by its reservation id, so the live commit
-    /// path and recovery agree on where the record lives.
-    fn saga_id(&self) -> i64 {
-        self.reservation.0
-    }
-
-    /// Decode an envelope commit record from its stored bytes.
-    pub(super) fn decode(blob: &[u8]) -> Result<Self, LedgerError> {
-        serde_json::from_slice(blob).map_err(json_err)
-    }
-
-    /// Persist this record at its current phase (upsert). The single writer of a
-    /// commit write-ahead record: the Reserving→Finalizing bump is just a persist
-    /// of the [`finalizing`](Self::finalizing) variant.
-    pub(super) async fn persist(&self, ledger: &Ledger) -> Result<(), LedgerError> {
-        let blob = serde_json::to_vec(self).map_err(json_err)?;
-        ledger
-            .store
-            .save_saga(SagaKind::Envelope, &self.saga_id(), blob)
-            .await?;
-        Ok(())
-    }
-
-    /// Run a fresh commit end to end: write-ahead at Reserving, reserve then
-    /// finalize, then clear the record when it is safe. The single home of the commit
-    /// write-ahead lifecycle; [`commit_envelope`](Ledger::commit_envelope) calls
-    /// this and recovery mirrors it.
-    pub(super) async fn run(self, ledger: &Arc<Ledger>) -> Result<Receipt, LedgerError> {
-        self.persist(ledger).await?;
-        // Commit does not touch the balance projection (ADR-0019): cache points
-        // are appended lazily on read, once enough credits/debits have accrued.
-        let result = ledger
-            .reserve_and_finalize(&self.envelope, self.reservation)
-            .await;
-        self.clear_if_safe(ledger, result.is_ok()).await?;
-        result
-    }
-
-    /// Delete the write-ahead record unless the saga crossed its point of no
-    /// return on a failing run. The ONE place the delete-safety rule lives: safe
-    /// on success, or on a failure that never reached `Finalizing` (compensation
-    /// released our reservation, nothing of ours applied). A failure that reached
-    /// `Finalizing` keeps the record so recovery rolls the commit forward.
-    async fn clear_if_safe(
-        &self,
-        ledger: &Arc<Ledger>,
-        succeeded: bool,
-    ) -> Result<(), LedgerError> {
-        let safe =
-            succeeded || ledger.saga_phase(self.saga_id()).await? != Some(SagaPhase::Finalizing);
-        if safe {
-            ledger.store.delete_saga(&self.saga_id()).await?;
-        }
-        Ok(())
-    }
-
-    /// Complete a crash-interrupted commit from its persisted phase, clearing the
-    /// record when safe. The recovery counterpart of [`run`](Self::run): same
-    /// lifecycle rules, entered from a decoded record instead of a fresh one.
-    pub(super) async fn complete(self, ledger: &Arc<Ledger>) -> Result<(), LedgerError> {
-        // A full commit is the transfer row plus its committed event (appended
-        // after store_transfer). If the row is present the commit reached the far
-        // side; repair the possibly-missing event (idempotent) and clear.
-        let tid = envelope_id(&self.envelope);
-        if ledger.store.get_transfer(&tid).await?.is_some() {
-            ledger.append_committed_event(tid).await?;
-            ledger.store.delete_saga(&self.saga_id()).await?;
-            return Ok(());
-        }
-
-        match self.phase {
-            // Validation passed and the postings are ours; roll forward through the
-            // verified finalize. Keep the record if it fails so a later run retries.
-            SagaPhase::Finalizing => {
-                if ledger
-                    .finalize_envelope(&self.envelope, self.reservation)
-                    .await
-                    .is_ok()
-                {
-                    ledger.store.delete_saga(&self.saga_id()).await?;
-                }
-                Ok(())
-            }
-            // Not past the point of no return: re-run the validating saga and clear
-            // under the same rule as a live commit. The saga's own failure is
-            // absorbed (record kept for the next run); only infra errors propagate.
-            SagaPhase::Reserving => {
-                let result = ledger
-                    .reserve_and_finalize(&self.envelope, self.reservation)
-                    .await;
-                self.clear_if_safe(ledger, result.is_ok()).await
-            }
-        }
-    }
-}
-
-impl PendingTransition {
-    /// A transition write-ahead record for a version bump and its lifecycle event.
-    pub(super) fn new(next: Account, event: LedgerEventKind) -> Self {
-        Self { next, event }
-    }
-
-    /// Decode a transition record from its stored bytes.
-    pub(super) fn decode(blob: &[u8]) -> Result<Self, LedgerError> {
-        serde_json::from_slice(blob).map_err(json_err)
-    }
-
-    /// Persist this record under `saga_id` (upsert).
-    pub(super) async fn save(&self, ledger: &Ledger, saga_id: i64) -> Result<(), LedgerError> {
-        let blob = serde_json::to_vec(self).map_err(json_err)?;
-        ledger
-            .store
-            .save_saga(SagaKind::Transition, &saga_id, blob)
-            .await?;
-        Ok(())
-    }
-
-    /// Roll a crash-interrupted transition forward and clear its write-ahead
-    /// record.
-    ///
-    /// Idempotent in every crash window: the version append runs only into an
-    /// empty version slot (`append_account_version` requires `version == current +
-    /// 1`, so a blind retry after it applied would fail), and the event carries its
-    /// target version so re-appending it dedups to the original. The empty-slot
-    /// guard also subsumes the forward path's is_closed check: a close always bumps
-    /// the version, so a since-closed account sits at `version >= next.version` and
-    /// is skipped.
-    pub(super) async fn complete(self, ledger: &Ledger, saga_id: i64) -> Result<(), LedgerError> {
-        // The account is guaranteed to exist here (its version was bumped, or is
-        // about to be), so a read failure is transient or a real invariant breach,
-        // not "not found": surface it verbatim so recovery retries.
-        let current = ledger.store.get_account(&self.next.id).await?;
-        if current.version < self.next.version {
-            ledger.store.append_account_version(self.next).await?;
-        }
-        ledger
-            .store
-            .append_event(&LedgerEvent {
-                seq: 0,
-                timestamp: now_millis()?,
-                kind: self.event,
-            })
-            .await?;
-        ledger.store.delete_saga(&saga_id).await?;
-        Ok(())
-    }
-}

+ 22 - 44
crates/kuatia/src/ledger/transition.rs

@@ -1,33 +1,26 @@
 //! One account-version transition, shared by freeze / unfreeze / close.
 //!
 //! Every lifecycle flag change is the same shape: load the account, reject if it
-//! is already closed, append a new version with the flag flipped, then append the
+//! is already closed, then append a new version with the flag flipped and the
 //! matching lifecycle event. This module holds that shape once, parameterized by
-//! the flag mutation and the event, and routes it through the same write-ahead /
-//! repair path the commit engine uses.
+//! the flag mutation and the event.
 //!
-//! The durability point: the version append and the event append are two separate
-//! store writes with no shared transaction. A crash between them would otherwise
-//! leave a version bump with no event and nothing to repair it. Persisting a
-//! write-ahead [`PendingTransition`](super::pending) before either write lets
-//! [`Ledger::recover`](Ledger) roll the transition forward. Recovery is
-//! idempotent both ways: the version append is skipped when the version is
-//! already present, and the event carries its target version so a second append
-//! dedups to the original.
+//! The version append and the event append are one atomic store write
+//! ([`commit_transition`](kuatia_storage::store::CommitStore::commit_transition)),
+//! so a crash cannot leave a version bump with no event. The store re-checks the
+//! version chain and a closed account inside the transaction.
 
-use kuatia_core::{AccountFlags, AccountId, TransitionId};
+use kuatia_core::{AccountFlags, AccountId};
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
+use kuatia_storage::store::{TransitionOutcome, TransitionRejection};
 
-use super::pending::PendingTransition;
 use super::{Ledger, now_millis};
 use crate::error::LedgerError;
 
 impl Ledger {
     /// Append one new account version with `mutate` applied to its flags, then
     /// emit the lifecycle event produced by `make_event` (given the account id and
-    /// the new version). Rejects a closed account. A write-ahead record persisted
-    /// before the writes lets [`recover`](Ledger::recover) complete a transition
-    /// interrupted between the two appends.
+    /// the new version), atomically. Rejects a closed account.
     ///
     /// Callers layer any transition-specific guard (e.g. close's emptiness check)
     /// before calling this.
@@ -49,36 +42,21 @@ impl Ledger {
         let mut next = current;
         next.version = next.version.checked_add(1).ok_or(LedgerError::Overflow)?;
         mutate(&mut next.flags);
-        let event = make_event(*id, next.version);
+        let event = LedgerEvent {
+            seq: 0,
+            timestamp: now_millis()?,
+            kind: make_event(*id, next.version),
+        };
 
-        // Write-ahead before either write. A crash between the version append and
-        // the event append is then repaired by recover(), not left dangling. The
-        // record is tagged `Transition` in the store, and its id comes from the
-        // shared saga-id generator, so it lands in its own typed slot without
-        // colliding with an in-flight commit saga's key.
-        let saga_id = TransitionId::default().0;
-        PendingTransition::new(next.clone(), event.clone())
-            .save(self, saga_id)
-            .await?;
-
-        let expected = next.version;
-        if self.store.append_account_version(next).await? == 0 {
-            // A concurrent transition moved the head; the guarded append matched
-            // nothing. Surface the conflict; the write-ahead record is repaired
-            // (or cleared) by recover() on the next startup.
-            return Err(LedgerError::AccountVersionConflict {
-                account: *id,
+        match self.store.commit_transition(next, event).await? {
+            TransitionOutcome::Applied | TransitionOutcome::AlreadyApplied => Ok(()),
+            TransitionOutcome::Rejected(TransitionRejection::AlreadyClosed(account)) => {
+                Err(LedgerError::AccountAlreadyClosed(account))
+            }
+            TransitionOutcome::Rejected(TransitionRejection::VersionConflict {
+                account,
                 expected,
-            });
+            }) => Err(LedgerError::AccountVersionConflict { account, expected }),
         }
-        self.store
-            .append_event(&LedgerEvent {
-                seq: 0,
-                timestamp: now_millis()?,
-                kind: event,
-            })
-            .await?;
-        self.store.delete_saga(&saga_id).await?;
-        Ok(())
     }
 }

+ 54 - 359
crates/kuatia/src/saga.rs

@@ -1,183 +1,22 @@
-//! Ledger commit helpers and high-level saga steps.
+//! Multi-transfer composition over the ledger.
 //!
-//! # Count contract
-//!
-//! `apply_and_verify`, `verify_postings`, and `consume_reserved` encode the
-//! ADR-0003 affected-row-count rule applied after every dumb write primitive in
-//! the commit path. The commit path itself (reserve → finalize) is a linear
-//! method on [`Ledger`] (`ledger::commit`), not a `legend` saga: for a single
-//! commit the two steps were pass-throughs, so collapsing them keeps the
-//! reserve/compensation policy next to the logic it governs (refines ADR-0002).
-//!
-//! # High-level composition
-//!
-//! [`PayMovementStep`] and [`DepositMovementStep`] wrap the intent-layer
-//! `Ledger::commit` as `legend` [`Step`]s, so several transfers compose into one
-//! multi-transfer saga (an FX trade, a multi-leg settlement) with LIFO
-//! compensation across the whole workflow. This is where `legend` earns its keep.
+//! [`run_movements`] commits a sequence of transfers in order and, on the first
+//! failure, reverses the already-committed ones in LIFO order via
+//! [`Ledger::reverse`], so several transfers behave as one all-or-nothing
+//! workflow (an FX trade, a multi-leg settlement). Each single commit is already
+//! atomic in the store (ADR-0023); this adds only the cross-transfer unwind,
+//! which is why it no longer needs a saga VM.
 
-use std::fmt;
-use std::future::Future;
 use std::sync::Arc;
 
-use async_trait::async_trait;
-use legend::step::{CompensationOutcome, Step, StepOutcome};
 use serde::{Deserialize, Serialize};
 
-use kuatia_core::{
-    AccountId, AssetId, Cent, PostingId, PostingState, Receipt, ReservationId, TransferBuilder,
-};
+use kuatia_core::{AccountId, AssetId, Cent, Receipt, Transfer, TransferBuilder};
 
 use crate::error::LedgerError;
 use crate::ledger::Ledger;
-use kuatia_storage::error::StoreError;
-use kuatia_storage::store::Store;
-
-/// A saga-internal plumbing fault (missing context, a short row-count that the
-/// end-state does not explain). These are genuine internal invariants, distinct
-/// from the typed domain errors ([`LedgerError::Validation`], overdraft, frozen)
-/// that flow through unchanged, so they map to [`StoreError::Internal`].
-fn internal(message: impl Into<String>) -> LedgerError {
-    LedgerError::Store(StoreError::Internal(message.into()))
-}
-
-/// The single home of the ADR-0003 affected-row count contract, used after every
-/// dumb write primitive in the commit path.
-///
-/// Interpret a primitive's affected-row `count` against the number of rows it
-/// `target`ed. `count == target` is success. A short count is acceptable only if
-/// the desired end-state already holds (a prior attempt, or this saga replayed by
-/// recovery, already applied it), which `verify` re-reads and reports as a bool.
-/// Otherwise it is a genuine failure (contended or concurrently modified) and the
-/// caller compensates.
-pub(crate) async fn apply_and_verify<F, Fut>(
-    count: u64,
-    target: usize,
-    what: &str,
-    verify: F,
-) -> Result<(), LedgerError>
-where
-    F: FnOnce() -> Fut,
-    Fut: Future<Output = Result<bool, LedgerError>>,
-{
-    if count == target as u64 {
-        return Ok(());
-    }
-    if verify().await? {
-        return Ok(());
-    }
-    Err(internal(format!(
-        "{what}: storage applied {count}/{target} rows and the end-state is not satisfied"
-    )))
-}
-
-/// Apply the count contract to a posting primitive whose end-state is a property
-/// of the targeted postings: a short count is idempotent-safe only when every
-/// targeted posting already satisfies `ok`.
-pub(crate) async fn verify_postings(
-    store: &dyn Store,
-    ids: &[PostingId],
-    count: u64,
-    ok: impl Fn(&PostingState) -> bool,
-    what: &str,
-) -> Result<(), LedgerError> {
-    apply_and_verify(count, ids.len(), what, || async {
-        let states = store
-            .get_posting_states(ids)
-            .await
-            .map_err(LedgerError::Store)?;
-        Ok(states.len() == ids.len() && states.iter().all(&ok))
-    })
-    .await
-}
-
-/// The authoritative double-spend / reservation-ownership guard.
-///
-/// Consume the reserved postings, then assert every consumed id is now `Spent`.
-/// `deactivate_postings(_, Some(rid))` removes *only* rows this saga reserved, so
-/// the "all Spent" assertion can only pass when no consumed id was left active or
-/// held by another saga: that is what forbids a double-spend.
-///
-/// This CAS is the real concurrency authority for the consumed-posting lifecycle.
-/// The pure lifecycle check in [`validate_and_plan`](kuatia_core::validate_and_plan)
-/// is a snapshot-in-time, best-effort read (ADR-0003); this is the check that
-/// holds under contention. It runs once the saga is past its point of no return
-/// (phase `Finalizing`). See ADR-0021 for the full commit-safety map.
-pub(crate) async fn consume_reserved(
-    store: &dyn Store,
-    consumes: &[PostingId],
-    reservation: ReservationId,
-) -> Result<(), LedgerError> {
-    let spent = store
-        .deactivate_postings(consumes, Some(reservation))
-        .await
-        .map_err(LedgerError::Store)?;
-    verify_postings(
-        store,
-        consumes,
-        spent,
-        |s| *s == PostingState::Spent,
-        "finalize: consume reserved postings",
-    )
-    .await
-}
-
-// ---------------------------------------------------------------------------
-// Saga context -- carries the ledger handle + state between steps
-// ---------------------------------------------------------------------------
-
-/// Saga context that wraps a ledger and collects the receipts of the transfers a
-/// multi-transfer saga commits, for LIFO compensation.
-///
-/// The ledger handle is `#[serde(skip)]`: it is supplied when the context is
-/// constructed and is not part of the serialized form.
-#[derive(Clone, Serialize, Deserialize)]
-pub struct LedgerCtx {
-    /// Receipts collected from completed steps, popped in reverse to compensate.
-    pub receipts: Vec<Receipt>,
-    #[serde(skip)]
-    ledger: Option<Arc<Ledger>>,
-}
 
-impl fmt::Debug for LedgerCtx {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_struct("LedgerCtx")
-            .field("receipts", &self.receipts)
-            .field("ledger_present", &self.ledger.is_some())
-            .finish()
-    }
-}
-
-impl LedgerCtx {
-    /// Create a new context wrapping the given ledger.
-    pub fn new(ledger: Arc<Ledger>) -> Self {
-        Self {
-            receipts: Vec::new(),
-            ledger: Some(ledger),
-        }
-    }
-
-    /// Borrow the ledger, returning an error if the handle is absent.
-    pub fn ledger(&self) -> Result<&Ledger, LedgerError> {
-        self.ledger
-            .as_ref()
-            .map(|l| l.as_ref())
-            .ok_or_else(|| internal("ledger handle missing from saga context"))
-    }
-
-    /// Clone the ledger `Arc`, returning an error if the handle is absent.
-    pub fn ledger_arc(&self) -> Result<Arc<Ledger>, LedgerError> {
-        self.ledger
-            .clone()
-            .ok_or_else(|| internal("ledger handle missing from saga context"))
-    }
-}
-
-// ===========================================================================
-// High-level steps (pay / deposit movement steps)
-// ===========================================================================
-
-/// Input for the pay movement saga step.
+/// A pay movement between two accounts.
 #[derive(Debug, Clone, Serialize, Deserialize)]
 pub struct PayInput {
     /// Source account.
@@ -190,7 +29,7 @@ pub struct PayInput {
     pub amount: Cent,
 }
 
-/// Input for the deposit movement saga step.
+/// A deposit from an external account.
 #[derive(Debug, Clone, Serialize, Deserialize)]
 pub struct DepositInput {
     /// Account receiving the deposit.
@@ -203,198 +42,54 @@ pub struct DepositInput {
     pub external: AccountId,
 }
 
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-async fn compensate_last_receipt(ctx: &mut LedgerCtx) -> Result<CompensationOutcome, LedgerError> {
-    let receipt = ctx
-        .receipts
-        .pop()
-        .ok_or_else(|| internal("no receipt to compensate"))?;
-    ctx.ledger_arc()?.reverse(&receipt.transfer_id).await?;
-    Ok(CompensationOutcome::Completed)
-}
-
-// ---------------------------------------------------------------------------
-// Steps
-// ---------------------------------------------------------------------------
-
-/// Saga step: pay between two accounts via a single-movement transfer.
-pub struct PayMovementStep;
-
-#[async_trait]
-impl Step<LedgerCtx, LedgerError> for PayMovementStep {
-    type Input = PayInput;
-
-    async fn execute(ctx: &mut LedgerCtx, input: &PayInput) -> Result<StepOutcome, LedgerError> {
-        let ledger = ctx.ledger_arc()?;
-        let transfer = TransferBuilder::new()
-            .pay(input.from, input.to, input.asset, input.amount)
-            .build();
-        let receipt = ledger.commit(transfer).await?;
-        ctx.receipts.push(receipt);
-        Ok(StepOutcome::Continue)
-    }
-
-    async fn compensate(
-        ctx: &mut LedgerCtx,
-        _input: &PayInput,
-    ) -> Result<CompensationOutcome, LedgerError> {
-        compensate_last_receipt(ctx).await
-    }
+/// One leg of a multi-transfer workflow.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum Movement {
+    /// Pay between two accounts.
+    Pay(PayInput),
+    /// Deposit from an external account.
+    Deposit(DepositInput),
 }
 
-/// Saga step: deposit value from an external account via a single-movement transfer.
-pub struct DepositMovementStep;
-
-#[async_trait]
-impl Step<LedgerCtx, LedgerError> for DepositMovementStep {
-    type Input = DepositInput;
-
-    async fn execute(
-        ctx: &mut LedgerCtx,
-        input: &DepositInput,
-    ) -> Result<StepOutcome, LedgerError> {
-        let ledger = ctx.ledger_arc()?;
-        let transfer = TransferBuilder::new()
-            .deposit(input.to, input.asset, input.amount, input.external)
-            .map_err(LedgerError::from)?
-            .build();
-        let receipt = ledger.commit(transfer).await?;
-        ctx.receipts.push(receipt);
-        Ok(StepOutcome::Continue)
-    }
-
-    async fn compensate(
-        ctx: &mut LedgerCtx,
-        _input: &DepositInput,
-    ) -> Result<CompensationOutcome, LedgerError> {
-        compensate_last_receipt(ctx).await
+impl Movement {
+    /// Build the concrete [`Transfer`] this movement commits.
+    fn build(&self) -> Result<Transfer, LedgerError> {
+        match self {
+            Movement::Pay(p) => Ok(TransferBuilder::new()
+                .pay(p.from, p.to, p.asset, p.amount)
+                .build()),
+            Movement::Deposit(d) => Ok(TransferBuilder::new()
+                .deposit(d.to, d.asset, d.amount, d.external)?
+                .build()),
+        }
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use kuatia_core::{EnvelopeId, Posting};
-    use kuatia_storage::mem_store::InMemoryStore;
-    use kuatia_storage::store::PostingStore;
-    use std::cell::Cell;
-
-    fn active_posting(store_seed: u8) -> Posting {
-        Posting::new(
-            PostingId {
-                transfer: EnvelopeId([store_seed; 32]),
-                index: 0,
-            },
-            AccountId::new(1),
-            AssetId::new(1),
-            Cent::from(100),
-        )
-    }
-
-    #[tokio::test]
-    async fn full_count_is_ok_without_re_reading() {
-        let verified = Cell::new(false);
-        let result = apply_and_verify(3, 3, "reserve", || {
-            verified.set(true);
-            async { Ok(true) }
-        })
-        .await;
-        assert!(result.is_ok());
-        assert!(
-            !verified.get(),
-            "a full count must not re-read the end-state"
-        );
-    }
-
-    #[tokio::test]
-    async fn short_count_is_ok_when_end_state_already_holds() {
-        // Idempotent replay: a prior attempt applied the shortfall.
-        let result = apply_and_verify(2, 3, "reserve", || async { Ok(true) }).await;
-        assert!(result.is_ok());
-    }
-
-    #[tokio::test]
-    async fn short_count_is_internal_error_when_end_state_missing() {
-        let result = apply_and_verify(2, 3, "reserve", || async { Ok(false) }).await;
-        assert!(matches!(
-            result,
-            Err(LedgerError::Store(StoreError::Internal(_)))
-        ));
-    }
-
-    #[tokio::test]
-    async fn verify_error_propagates() {
-        let result = apply_and_verify(0, 1, "store", || async {
-            Err(LedgerError::Store(StoreError::Internal(
-                "read failed".into(),
-            )))
-        })
-        .await;
-        assert!(matches!(
-            result,
-            Err(LedgerError::Store(StoreError::Internal(_)))
-        ));
-    }
-
-    /// The guard consumes the postings this saga reserved: they end `Spent`.
-    #[tokio::test]
-    async fn consume_reserved_spends_our_postings() {
-        let store = InMemoryStore::new();
-        let p = active_posting(1);
-        store
-            .insert_postings(std::slice::from_ref(&p))
-            .await
-            .unwrap();
-        let rid = ReservationId::default();
-        store.reserve_postings(&[p.id], rid).await.unwrap();
-
-        consume_reserved(&store, &[p.id], rid).await.unwrap();
-
-        let states = store.get_posting_states(&[p.id]).await.unwrap();
-        assert_eq!(states, vec![PostingState::Spent]);
-    }
-
-    /// An unreserved (still active) posting is refused, and left untouched:
-    /// `deactivate_postings(_, Some(rid))` removes nothing we do not own.
-    #[tokio::test]
-    async fn consume_reserved_refuses_unreserved_posting() {
-        let store = InMemoryStore::new();
-        let p = active_posting(2);
-        store
-            .insert_postings(std::slice::from_ref(&p))
-            .await
-            .unwrap();
-
-        let err = consume_reserved(&store, &[p.id], ReservationId::default())
-            .await
-            .unwrap_err();
-        assert!(matches!(err, LedgerError::Store(StoreError::Internal(_))));
-        let states = store.get_posting_states(&[p.id]).await.unwrap();
-        assert_eq!(states, vec![PostingState::Active]);
-    }
-
-    /// The double-spend guard: a posting reserved by another saga is refused, and
-    /// stays reserved by that saga. Our deactivate removes nothing, so the
-    /// "all Spent" assertion fails.
-    #[tokio::test]
-    async fn consume_reserved_refuses_posting_held_by_another_saga() {
-        let store = InMemoryStore::new();
-        let p = active_posting(3);
-        store
-            .insert_postings(std::slice::from_ref(&p))
-            .await
-            .unwrap();
-        let theirs = ReservationId::default();
-        store.reserve_postings(&[p.id], theirs).await.unwrap();
-
-        let err = consume_reserved(&store, &[p.id], ReservationId::default())
-            .await
-            .unwrap_err();
-        assert!(matches!(err, LedgerError::Store(StoreError::Internal(_))));
-        let states = store.get_posting_states(&[p.id]).await.unwrap();
-        assert_eq!(states, vec![PostingState::Reserved(theirs)]);
+/// Commit each movement in order, returning the receipts. On the first failure,
+/// reverse the already-committed receipts in LIFO order and return the original
+/// error. If a reversal itself fails, return [`LedgerError::CompensationFailed`]
+/// carrying both the original and the compensation error.
+pub async fn run_movements(
+    ledger: &Arc<Ledger>,
+    movements: &[Movement],
+) -> Result<Vec<Receipt>, LedgerError> {
+    let mut receipts: Vec<Receipt> = Vec::new();
+    for movement in movements {
+        let transfer = movement.build()?;
+        match ledger.commit(transfer).await {
+            Ok(receipt) => receipts.push(receipt),
+            Err(err) => {
+                for receipt in receipts.iter().rev() {
+                    if let Err(compensation) = ledger.reverse(&receipt.transfer_id).await {
+                        return Err(LedgerError::CompensationFailed {
+                            original: Box::new(err),
+                            compensation: Box::new(compensation),
+                        });
+                    }
+                }
+                return Err(err);
+            }
+        }
     }
+    Ok(receipts)
 }

+ 20 - 20
crates/kuatia/tests/concurrency.rs

@@ -1,14 +1,15 @@
-//! Concurrency tests for the saga commit pipeline over `InMemoryStore`.
+//! Concurrency tests for the atomic commit path over `InMemoryStore`.
 //!
-//! `InMemoryStore` guards each field with a `tokio::RwLock`, so every individual
-//! `Store` primitive is atomic. A saga, however, is a *sequence* of primitives
-//! with no overarching lock, so the interesting races live between primitives
-//! across concurrent sagas that share one `Arc<Ledger>`. The generated
+//! A commit resolves and validates read-only, then hands the effects to the
+//! store's atomic `commit_envelope`, which applies them (and re-checks
+//! double-spend, freeze/close, and the floor) under one set of locks. The races
+//! worth testing are therefore between concurrent commits that share one
+//! `Arc<Ledger>` and contend on the same postings or account. The generated
 //! conformance suite only drives the store sequentially, so none of this is
 //! covered there.
 //!
 //! These tests run on a multi-thread runtime and use `tokio::spawn` so the
-//! sagas genuinely interleave rather than run to completion one at a time.
+//! commits genuinely interleave rather than run to completion one at a time.
 
 #![allow(missing_docs)]
 
@@ -72,10 +73,9 @@ async fn deposit(ledger: &Arc<Ledger>, to: AccountId, amount: Cent) {
 // ---------------------------------------------------------------------------
 
 /// Many transfers concurrently try to spend the *same* funded posting to
-/// different recipients. Exactly one may win: the winner's `reserve_postings`
-/// claims the single active posting into the reserved index, and every other
-/// saga's reserve returns zero for a fresh reservation, so it fails and
-/// compensates.
+/// different recipients. Exactly one may win: inside the atomic commit the
+/// winner deletes the single live posting, and every other commit finds it gone
+/// and is rejected with `DoubleSpend`.
 /// The ledger stays conserved: the payer ends at zero and exactly one recipient
 /// receives the full amount.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
@@ -158,9 +158,9 @@ async fn recommit_same_envelope_is_idempotent() {
 
 /// The same envelope committed concurrently from many tasks. Because the
 /// content-addressed id is the idempotency key, value moves exactly once no
-/// matter how the sagas interleave: some tasks win or observe the stored
-/// transfer and return its receipt; the rest lose the reservation race and
-/// fail. Every successful receipt is identical, and the balances move once.
+/// matter how the commits interleave: one task applies the transfer and the rest
+/// observe the stored record and return its receipt. Every successful receipt is
+/// identical, and the balances move once.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn concurrent_identical_commits_move_value_once() {
     const TASKS: usize = 8;
@@ -220,13 +220,13 @@ async fn concurrent_identical_commits_move_value_once() {
 // ---------------------------------------------------------------------------
 
 /// Freezing an account concurrently with a payment out of it must leave a
-/// consistent state. The account is versioned and the commit pins the snapshot
-/// it validated against, so the two serialize one way or the other: either the
-/// payment finalizes first (against the unfrozen snapshot) and the freeze lands
-/// on top, or the freeze bumps the version first and the commit's last-step
-/// re-validation rejects the now-frozen account. There is no middle ground where
-/// value moves out of a frozen account against a stale snapshot. Value is always
-/// conserved and the payment is all-or-nothing.
+/// consistent state. The freeze is an atomic transition and the payment is an
+/// atomic commit that re-checks the account's frozen flag inside its
+/// transaction, so the two serialize one way or the other: either the payment
+/// commits first and the freeze lands on top, or the freeze commits first and
+/// the payment's in-transaction freeze check rejects the now-frozen account.
+/// There is no middle ground where value moves out of a frozen account. Value is
+/// always conserved and the payment is all-or-nothing.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
 async fn freeze_during_commit_stays_consistent() {
     // Race is timing-dependent; run several fresh rounds to sample interleavings.

+ 72 - 139
crates/kuatia/tests/saga.rs

@@ -1,14 +1,13 @@
 #![allow(missing_docs)]
 
+use std::collections::BTreeMap;
 use std::sync::Arc;
 
 use kuatia::error::LedgerError;
 use kuatia::ledger::Ledger;
 use kuatia::mem_store::InMemoryStore;
-use kuatia::saga::*;
+use kuatia::saga::{DepositInput, Movement, PayInput, run_movements};
 use kuatia_core::*;
-use legend::{ExecutionResult, legend};
-use std::collections::BTreeMap;
 
 fn usd() -> AssetId {
     AssetId::new(1)
@@ -52,42 +51,39 @@ async fn setup_ledger() -> Arc<Ledger> {
     ledger
 }
 
-// Define a two-step saga: deposit then pay
-legend! {
-    FundAndPay<LedgerCtx, LedgerError> {
-        deposit: DepositMovementStep,
-        pay: PayMovementStep,
-    }
+fn deposit(to: AccountId, amount: Cent) -> Movement {
+    Movement::Deposit(DepositInput {
+        to,
+        asset: usd(),
+        amount,
+        external: external(),
+    })
 }
 
+fn pay(from: AccountId, to: AccountId, amount: Cent) -> Movement {
+    Movement::Pay(PayInput {
+        from,
+        to,
+        asset: usd(),
+        amount,
+    })
+}
+
+/// A two-movement workflow (deposit then pay) commits both legs in order.
 #[tokio::test]
-async fn saga_happy_path() {
+async fn workflow_happy_path() {
     let ledger = setup_ledger().await;
 
-    let saga = FundAndPay::new(FundAndPayInputs {
-        deposit: DepositInput {
-            to: account(1),
-            asset: usd(),
-            amount: Cent::from(100),
-            external: external(),
-        },
-        pay: PayInput {
-            from: account(1),
-            to: account(2),
-            asset: usd(),
-            amount: Cent::from(60),
-        },
-    });
-
-    let ctx = LedgerCtx::new(ledger.clone());
-    let execution = saga.build(ctx);
-
-    match execution.start().await {
-        ExecutionResult::Completed(e) => {
-            assert_eq!(e.context().receipts.len(), 2);
-        }
-        other => panic!("expected Completed, got {:?}", result_debug(&other)),
-    }
+    let receipts = run_movements(
+        &ledger,
+        &[
+            deposit(account(1), Cent::from(100)),
+            pay(account(1), account(2), Cent::from(60)),
+        ],
+    )
+    .await
+    .unwrap();
+    assert_eq!(receipts.len(), 2);
 
     assert_eq!(
         ledger.balance(&account(1), &usd()).await.unwrap(),
@@ -103,105 +99,56 @@ async fn saga_happy_path() {
     );
 }
 
-// Define a saga that will fail on the second step and trigger compensation
-legend! {
-    DepositAndOverspend<LedgerCtx, LedgerError> {
-        deposit: DepositMovementStep,
-        pay: PayMovementStep,
-    }
-}
-
+/// The second movement overspends and fails; the first (deposit) is reversed
+/// LIFO, so the net effect is zero. The typed `InsufficientFunds` reaches the
+/// caller.
 #[tokio::test]
-async fn saga_compensation_on_failure() {
+async fn workflow_compensation_on_failure() {
     let ledger = setup_ledger().await;
 
-    // Deposit 50 then try to pay 100 -> pay fails -> deposit should be reversed
-    let saga = DepositAndOverspend::new(DepositAndOverspendInputs {
-        deposit: DepositInput {
-            to: account(1),
-            asset: usd(),
-            amount: Cent::from(50),
-            external: external(),
-        },
-        pay: PayInput {
-            from: account(1),
-            to: account(2),
-            asset: usd(),
-            amount: Cent::from(100), // more than available
-        },
-    });
-
-    let ctx = LedgerCtx::new(ledger.clone());
-    let execution = saga.build(ctx);
-
-    match execution.start().await {
-        ExecutionResult::Failed(_, err) => {
-            // The saga carries the typed `LedgerError` across its step seam, so
-            // the overspend surfaces as `Selection(InsufficientFunds)` rather
-            // than a stringified `Store(Internal)`.
-            assert!(
-                matches!(err, LedgerError::Selection(InsufficientFunds { .. })),
-                "expected typed InsufficientFunds, got {err:?}"
-            );
-            // The deposit should have been compensated (reversed)
-            // Note: balances won't be exactly 0 because the deposit reversal
-            // creates new postings, but the net effect should be zero
-            assert_eq!(
-                ledger.balance(&account(1), &usd()).await.unwrap(),
-                Cent::ZERO
-            );
-            assert_eq!(
-                ledger.balance(&external(), &usd()).await.unwrap(),
-                Cent::ZERO
-            );
-        }
-        other => panic!("expected Failed, got {:?}", result_debug(&other)),
-    }
-}
-
-// Three-step saga
-legend! {
-    ThreeStepFlow<LedgerCtx, LedgerError> {
-        deposit: DepositMovementStep,
-        pay_ab: PayMovementStep,
-        pay_bc: PayMovementStep,
-    }
+    // Deposit 50, then try to pay 100 (more than available) -> pay fails ->
+    // deposit is reversed.
+    let err = run_movements(
+        &ledger,
+        &[
+            deposit(account(1), Cent::from(50)),
+            pay(account(1), account(2), Cent::from(100)),
+        ],
+    )
+    .await
+    .unwrap_err();
+
+    assert!(
+        matches!(err, LedgerError::Selection(InsufficientFunds { .. })),
+        "expected typed InsufficientFunds, got {err:?}"
+    );
+    // The deposit was compensated (reversed); the net effect is zero.
+    assert_eq!(
+        ledger.balance(&account(1), &usd()).await.unwrap(),
+        Cent::ZERO
+    );
+    assert_eq!(
+        ledger.balance(&external(), &usd()).await.unwrap(),
+        Cent::ZERO
+    );
 }
 
+/// A three-movement workflow commits all legs and settles the chain.
 #[tokio::test]
-async fn saga_three_steps_happy() {
+async fn workflow_three_steps_happy() {
     let ledger = setup_ledger().await;
 
-    let saga = ThreeStepFlow::new(ThreeStepFlowInputs {
-        deposit: DepositInput {
-            to: account(1),
-            asset: usd(),
-            amount: Cent::from(100),
-            external: external(),
-        },
-        pay_ab: PayInput {
-            from: account(1),
-            to: account(2),
-            asset: usd(),
-            amount: Cent::from(60),
-        },
-        pay_bc: PayInput {
-            from: account(2),
-            to: account(3),
-            asset: usd(),
-            amount: Cent::from(30),
-        },
-    });
-
-    let ctx = LedgerCtx::new(ledger.clone());
-    let execution = saga.build(ctx);
-
-    match execution.start().await {
-        ExecutionResult::Completed(e) => {
-            assert_eq!(e.context().receipts.len(), 3);
-        }
-        other => panic!("expected Completed, got {:?}", result_debug(&other)),
-    }
+    let receipts = run_movements(
+        &ledger,
+        &[
+            deposit(account(1), Cent::from(100)),
+            pay(account(1), account(2), Cent::from(60)),
+            pay(account(2), account(3), Cent::from(30)),
+        ],
+    )
+    .await
+    .unwrap();
+    assert_eq!(receipts.len(), 3);
 
     assert_eq!(
         ledger.balance(&account(1), &usd()).await.unwrap(),
@@ -216,17 +163,3 @@ async fn saga_three_steps_happy() {
         Cent::from(30)
     );
 }
-
-fn result_debug<Ctx, Err, Steps>(r: &ExecutionResult<Ctx, Err, Steps>) -> &'static str
-where
-    Ctx: Send + Sync,
-    Err: Send + Sync + Clone,
-    Steps: legend::hlist::InstructionList<Ctx, Err>,
-{
-    match r {
-        ExecutionResult::Completed(_) => "Completed",
-        ExecutionResult::Paused(_) => "Paused",
-        ExecutionResult::Failed(_, _) => "Failed",
-        ExecutionResult::CompensationFailed { .. } => "CompensationFailed",
-    }
-}

+ 1 - 1
doc/adr/0003-dumb-storage-saga-recovery.md

@@ -1,6 +1,6 @@
 # Dumb storage + durable saga recovery
 
-* Status: accepted
+* Status: superseded by ADR-0023
 * Authors: Cesar Rodas
 * Date: 2026-06-29
 * Targeted modules: `kuatia-storage`, `kuatia-storage-sql`,

+ 1 - 1
doc/adr/0020-account-transition-recovery.md

@@ -1,6 +1,6 @@
 # Crash-safe account-version transitions
 
-* Status: accepted
+* Status: superseded by ADR-0023
 * Authors: Cesar Rodas
 * Date: 2026-07-18
 * Targeted modules: `kuatia` (`ledger`), `kuatia-storage`, `kuatia-storage-sql`

+ 3 - 1
doc/adr/0021-commit-safety-map.md

@@ -1,6 +1,8 @@
 # The commit-safety invariant and where each part is enforced
 
-* Status: accepted
+* Status: accepted (amended by ADR-0023: the double-spend, floor, and
+  freeze/close guards now live in the store's atomic `commit_envelope`, not the
+  saga's count-contract)
 * Authors: Cesar Rodas
 * Date: 2026-07-28
 * Targeted modules: `kuatia-core` (`validate`), `kuatia` (`ledger::commit`,

+ 137 - 0
doc/adr/0023-atomic-storage-commit.md

@@ -0,0 +1,137 @@
+# Atomic storage commit, retiring the write-ahead saga and `legend`
+
+* Status: accepted
+* Authors: Cesar Rodas
+* Date: 2026-08-12
+* Targeted modules: `kuatia-storage`, `kuatia-storage-sql`,
+  `kuatia` (`ledger`, `saga`)
+* Associated tickets/PRs: N/A
+
+## Context and Problem Statement
+
+ADR-0003 made storage a set of dumb single-update primitives and moved
+crash-safety into a phase-tracked write-ahead record (`PendingSaga` /
+`PendingTransition`) plus roll-forward recovery (`Ledger::recover`). A commit was
+a sequence of primitives (`reserve → deactivate → insert → store_transfer →
+append_event`) with no shared transaction, so the write-ahead log was the only
+thing protecting against a half-applied commit. That design also left the
+overdraft floor and the freeze/close guards **best-effort** under concurrency,
+re-checked just before the writes but not atomic with them.
+
+Two things prompted revisiting it. The `legend` saga VM had already been reduced
+to two thin adapters used only by tests: the single-commit path was a linear
+method, not a saga. And the whole write-ahead machinery existed only because the
+store could not commit a transfer atomically. If it can, the reservation
+two-step, the write-ahead record, and recovery all become unnecessary.
+
+Should the store apply a whole transfer atomically, reversing ADR-0003's dumb
+per-primitive model?
+
+## Decision Drivers
+
+* **Simplicity where it is safe.** Kuatia targets a single transactional
+  database (SQLite or PostgreSQL) or an in-process store. On each, a whole-commit
+  transaction is available and is the simplest correct primitive.
+* **Strict guards.** The overdraft floor and freeze/close checks should be
+  enforced atomically with the write, not best-effort.
+* **No orphaned state.** An all-or-nothing commit leaves nothing for recovery to
+  reconcile.
+* **One place for correctness.** Validation stays in the pure core; the store
+  enforces the stateful guards inside its transaction. There is no third home
+  (the saga's count-contract) to keep in sync.
+
+## Considered Options
+
+#### Option 1: Keep ADR-0003 (dumb primitives + write-ahead recovery)
+
+**Pros:**
+
+* Composes across multiple resources/shards without a database transaction.
+
+**Cons:**
+
+* The write-ahead record, phase tracking, and roll-forward recovery are a large
+  surface that exists solely to stitch non-atomic primitives together.
+* The floor and freeze/close guards stay best-effort under concurrency.
+
+#### Option 2: Atomic storage commit (chosen)
+
+Add one `CommitStore` sub-trait with `commit_envelope` and `commit_transition`,
+each applied in a single store transaction (SQL: one `BEGIN..COMMIT`; in-memory:
+all relevant locks held across the apply). The pure core still validates first;
+the transaction re-checks the three stateful guards inside it: double-spend
+(the delete-affected-count is the atomic single-winner claim), freeze/close, and
+the overdraft floor (summed in Rust from the live rows, never in SQL).
+
+**Pros:**
+
+* Deletes the reservation two-step, `PendingSaga`/`PendingTransition`,
+  `Ledger::recover`, and the `SagaStore` keyspace. A crash cannot half-apply a
+  commit, so there is nothing to recover.
+* The floor and freeze/close guards become strict, removing the ADR-0003
+  best-effort consequence.
+* `legend` and the count-contract helpers are removed; multi-transfer
+  composition is a plain LIFO runner (`run_movements`) over `commit` / `reverse`.
+
+**Cons:**
+
+* Crash-safety is pinned to a per-backend transaction: it does not compose across
+  shards or multiple databases. This forecloses the cross-shard UTXO ambition
+  ADR-0002/0003 kept open, which is an accepted trade for a single-database
+  library.
+* On SQLite, `pool.begin()` is a deferred transaction; the delete-affected-count
+  remains the double-spend backstop, the same property the prior design relied
+  on.
+
+## Decision Outcome
+
+Chosen: **Option 2.** The store owns the atomic commit boundary; the reservation
+index, write-ahead recovery, `SagaStore`, and `legend` are removed. This
+supersedes ADR-0003 and refines ADR-0002 (there is no longer a saga pipeline for
+a single commit). ADR-0020's transition recovery is subsumed by the atomic
+`commit_transition`, and ADR-0021's commit-safety map moves the double-spend,
+floor, and freeze/close guards into `commit_envelope`.
+
+### Positive Consequences
+
+* Fewer moving parts: no write-ahead log, no recovery, no saga VM.
+* Strict floor and freeze/close guards.
+* One validation home (pure core) plus one enforcement home (the store
+  transaction).
+
+### Negative Consequences
+
+* No cross-shard / multi-resource commit. If that is ever needed, it is a new
+  design, not a tweak to this one (see the next section for where it would live).
+* The generic `reserve_postings` / `release_postings` posting primitives are now
+  unused by the commit path; they remain as conformance-tested plumbing and can
+  be removed in a follow-up.
+
+## When a saga is the right tool (and why not here)
+
+Removing the saga is not a verdict against the pattern. A saga earns its keep
+when a workflow spans **moving pieces that cannot share one transaction**:
+multiple services, multiple databases, or a sharded store where a single commit
+cannot reach every partition. There it sequences local steps and compensates the
+completed ones on failure, buying atomicity the underlying resources cannot
+provide on their own, and it pays for that with write-ahead records, phase
+tracking, and compensation logic.
+
+Kuatia was not that case. Every primitive the commit saga orchestrated
+(`reserve`, `deactivate`, `insert`, `store_transfer`, `append_event`) lived in
+**one** store behind **one** transactional boundary. The saga was coordinating
+pieces that were already coupled, so it reimplemented in application code the
+atomicity the database already provides for free. When a single ACID transaction
+is available, that transaction is the simpler and stricter primitive, and the
+saga is ceremony around it.
+
+The escape hatch stays open, but it belongs one layer down. If a storage backend
+ever shards its data so that a transfer's postings span partitions no single
+transaction can cover, **that backend** implements
+`CommitStore::commit_envelope` with an internal saga (two-phase commit, per-shard
+local transactions plus compensation, or similar). The `CommitStore` contract,
+apply the whole envelope atomically or reject it, says nothing about *how* a
+backend achieves atomicity. The saga would then live where the moving pieces
+actually are, and the ledger core stays oblivious: it still just calls
+`commit_envelope` and maps the outcome. The pattern moves to the layer that has
+the distribution problem, instead of sitting in the core that does not.

+ 5 - 2
doc/adr/README.md

@@ -12,7 +12,7 @@ to reverse a decision. Instead, a new ADR supersedes it.
 |-----|-------|--------|---------|
 | [0001](0001-modified-utxo-signed-postings.md) | Modified UTXO: value as signed postings | accepted | Value is signed postings (negative = "offset positions"), not mutable balances; conservation is structural; balances are projections. |
 | [0002](0002-saga-commit-pipeline.md) | Saga commit pipeline | accepted | Commit is a compensating saga (`reserve → finalize`), not a single/distributed transaction: composable, coordinator-free, crash-recoverable. |
-| [0003](0003-dumb-storage-saga-recovery.md) | Dumb storage + durable saga recovery | accepted | Storage returns affected-row counts and makes no decisions; the saga owns interpretation/idempotency; crash-safety is phase-tracked write-ahead + roll-forward. Refines 0002. |
+| [0003](0003-dumb-storage-saga-recovery.md) | Dumb storage + durable saga recovery | superseded by 0023 | Storage returns affected-row counts and makes no decisions; the saga owns interpretation/idempotency; crash-safety is phase-tracked write-ahead + roll-forward. Refines 0002. Superseded by 0023, which makes the store commit a whole transfer atomically. |
 | [0004](0004-account-policies-overdraft-model.md) | Account policies & overdraft model | superseded by 0018 | A closed `AccountPolicy` enum per account gated negative postings + floor. Refined 0001. Superseded by 0018, which collapses the enum into a single flag. |
 | [0005](0005-intent-api-movements-vs-envelopes.md) | Intent API: movements vs. envelopes | accepted | Callers express `Movement`/`Transfer` intent; `resolve()` produces the concrete `Envelope`. UTXO mechanics stay internal; idempotency keys on the resolved id. |
 | [0006](0006-reservation-protocol-posting-lifecycle.md) | Reservation protocol & posting lifecycle | accepted (storage representation superseded by 0016) | `Active → PendingInactive → Inactive` + a durable `ReservationId` give lock-free, recoverable, exclusive ownership of inputs. The primitive behind 0002/0003. |
@@ -29,7 +29,10 @@ to reverse a decision. Instead, a new ADR supersedes it.
 | [0017](0017-correctness-first-append-only-hot-indexes.md) | Correctness-first storage: append-only value tables, disposable hot indexes | accepted | The guiding principle: value/audit tables (`postings`, `accounts`) are strictly append-only source of truth; disposable hot tables (`active_postings`, `reserved_postings`, `account_head`) index the live subset by `INSERT`/`DELETE` only and are rebuildable. Correctness first; no `UPDATE` anywhere, enforceable by DB grants. Generalizes 0016 (hot tables now hold full row copies). |
 | [0018](0018-single-debit-must-not-exceed-credit-flag.md) | Collapse account policy into a single debit-must-not-exceed-credit flag | accepted | The `AccountPolicy` enum is removed; the only per-account balance constraint is the `AccountFlags` bit `DEBIT_MUST_NOT_EXCEED_CREDIT`. Overdraft is allowed by default (unbounded); the flag forbids a negative balance and negative postings. Credit-line floors become an application concern. Supersedes 0004. |
 | [0019](0019-cached-balance-projection.md) | Cached balance projection via append-only cache points | accepted | Append-only `balance_projection` cache points (id, watermark, balance); a read takes the closest one at or before `now` and folds the tail of committed movements since its commit-time watermark (grace Δ). Correctness never depends on the cache (equals the live sum at rest). Cache points are appended lazily on read once N credits/debits accrue (configurable); no per-commit hook, no lease, no background loop. |
-| [0020](0020-account-transition-recovery.md) | Crash-safe account-version transitions | accepted | `freeze`/`unfreeze`/`close` collapse into one write-ahead `transition` primitive routed through the commit engine's `recover()`. Lifecycle events gain a `version` and dedup on `(account, version)`, so a transition interrupted between the version append and the event append rolls forward idempotently. Refines 0003 and 0010. |
+| [0020](0020-account-transition-recovery.md) | Crash-safe account-version transitions | superseded by 0023 | `freeze`/`unfreeze`/`close` collapse into one write-ahead `transition` primitive routed through the commit engine's `recover()`. Lifecycle events gain a `version` and dedup on `(account, version)`, so a transition interrupted between the version append and the event append rolls forward idempotently. Refines 0003 and 0010. Superseded by 0023, which makes a transition one atomic store write. |
+| [0021](0021-commit-safety-map.md) | The commit-safety invariant and where each part is enforced | accepted (amended by 0023) | Maps each safety property (conservation, double-spend, floor, freeze/close, snapshot) to the layer that enforces it. Amended by 0023: the double-spend, floor, and freeze/close guards now live in the store's atomic `commit_envelope`. |
+| [0022](0022-merged-live-postings-hot-index.md) | Merge the active/reserved hot indexes into one `live_postings` table | accepted | The `active_postings` and `reserved_postings` hot tables merge into one `live_postings` table whose nullable `reservation` column derives the lifecycle state. Refines 0016/0017. |
+| [0023](0023-atomic-storage-commit.md) | Atomic storage commit, retiring the write-ahead saga and `legend` | accepted | The store commits a whole transfer (and a whole account transition) in one transaction, re-checking double-spend, floor, and freeze/close inside it. Removes the reservation two-step, write-ahead recovery, `SagaStore`, and `legend`. Supersedes 0003 and 0020; refines 0002; amends 0021. |
 
 ## Recommended future ADRs
 

+ 88 - 170
doc/architecture.md

@@ -41,9 +41,8 @@ near-zero dependencies. It can be tested with golden vectors, replayed
 deterministically, and embedded in `no_std` environments.
 
 **kuatia** adds the async `Store` trait (used as `dyn Store` via trait objects)
-and composes the saga commit pipeline. The `Ledger` struct is non-generic: it
-holds an `Arc<dyn Store>`, which allows the `legend!` macro to define saga
-types with concrete `LedgerCtx`.
+and the commit engine. The `Ledger` struct is non-generic: it holds an
+`Arc<dyn Store>`.
 
 This separation keeps the auditable heart of the system deterministic and
 independently testable.
@@ -51,10 +50,11 @@ independently testable.
 ## Store Sub-Trait Architecture
 
 The `Store` trait is a composite of focused sub-traits, each responsible for a
-single domain. Every write method is a **dumb instruction**: it applies one
-update and returns the number of affected rows (or an I/O error). It never
-interprets the count, decides state, enforces idempotency, or compensates. The
-saga does.
+single domain. A transfer is committed atomically through `CommitStore`
+(`commit_envelope` / `commit_transition`); the remaining posting/account write
+methods are **dumb instructions** used by reads and setup: each applies one
+update and returns the number of affected rows (or an I/O error), never
+interpreting the count.
 
 ```mermaid
 classDiagram
@@ -80,11 +80,9 @@ classDiagram
         +get_transfers_for_account(account)
         +query_transfers(query)
     }
-    class SagaStore {
-        +save_saga(id, data)
-        +list_pending_sagas()
-        +get_saga(id)
-        +delete_saga(id)
+    class CommitStore {
+        +commit_envelope(request) CommitOutcome
+        +commit_transition(next, event) TransitionOutcome
     }
     class EventStore {
         +append_event(event)
@@ -101,101 +99,63 @@ classDiagram
     Store --|> AccountStore
     Store --|> PostingStore
     Store --|> TransferStore
-    Store --|> SagaStore
+    Store --|> CommitStore
     Store --|> EventStore
     Store --|> BookStore
 ```
 
-There is no single atomic commit boundary. A commit is a sequence of the dumb
-primitives above (`reserve_postings`, `deactivate_postings`, `insert_postings`,
-`store_transfer`, `append_event`), each its own atomic update and each
-idempotent. The saga sequences them and interprets their counts; a crash
-mid-sequence is completed by roll-forward recovery (see below).
+A whole transfer is committed atomically by `CommitStore::commit_envelope`, so
+there is a single atomic commit boundary. The store enforces the stateful guards
+(double-spend, freeze/close, overdraft floor) inside that transaction; the pure
+core validates everything else first. Balance computation, validation, and the
+resolve decision live in the Ledger and `kuatia-core`.
 
-The store only persists and reads. All domain logic (balance computation,
-validation, balance-constraint enforcement, and the interpretation of primitive
-counts) lives in the Ledger/saga and `kuatia-core`.
+## Atomic Commit
 
-## Saga Commit Pipeline
-
-Every commit is the envelope saga. `commit(transfer)` resolves the intent into
-a concrete envelope (read-only), then runs `commit_envelope`, which persists a
-write-ahead `PendingSaga` record (phase `Reserving`) and drives **two** steps.
-Validation lives inside the finalize step so it runs as late as possible,
-immediately before the writes.
+`commit(transfer)` resolves the intent into a concrete envelope (read-only),
+validates it against loaded state in the pure core, then hands the validated
+effects to `store.commit_envelope(..)`, which applies them in one transaction.
 
 ```mermaid
 sequenceDiagram
     participant C as Caller
     participant L as Ledger
-    participant R as ReserveStep
-    participant F as FinalizeStep
     participant S as Store
 
-    C->>L: commit(transfer) → resolve → commit_envelope(envelope)
-    L->>S: save_saga(PendingSaga{envelope, reservation, Reserving})
-    L->>R: execute
-    R->>S: reserve_postings(ids, rid) → count
-    Note over R: interpret count (full / partial / zero+read)
-
-    L->>F: execute (finalize_envelope)
-    F->>S: load + validate_and_plan() [last-step floor / freeze-close re-check]
-    F->>S: save_saga(... Finalizing)  [point of no return]
-    F->>S: deactivate_postings(consumed, rid) → verify all Inactive
-    F->>S: insert_postings(created) → verify exist
-    F->>S: store_transfer(record, involved) → verify transfer exists
-    F->>S: append_event(committed)
-    F-->>L: Receipt
-    L->>S: delete_saga(...)
-    L-->>C: Receipt
-```
-
-On in-process failure before the point of no return, legend compensates in LIFO
-order (finalize is a no-op if nothing committed; reserve runs
-`release_postings`). Once the finalize step has marked the saga `Finalizing`
-and begun deactivating, the half-applied commit is **rolled forward** by
-recovery
-rather than compensated (see below).
-
-## Durable Crash Recovery
-
-There is no single atomic transaction, so crash-safety comes from a
-phase-tracked write-ahead record plus idempotent roll-forward.
-`commit_envelope` persists a `PendingSaga {envelope, reservation, phase}` via
-`SagaStore` **before** the saga mutates anything (`phase = Reserving`); the
-finalize step bumps it to `Finalizing` after validation passes and just before
-the consumed postings start turning `Inactive`. The record is deleted only when
-the transfer is committed or the commit was cleanly abandoned before finalize.
-
-`Ledger::recover()` (call on startup) re-completes any surviving pending saga,
-**branching on the persisted phase** so it never commits something that did not
-validate or consume postings it does not own:
-
-```mermaid
-graph TD
-    A[get_transfer?] -->|exists| Z[delete record, done]
-    A -->|missing| P{phase}
-    P -->|Reserving| RR[re-run saga: reserve + finalize]
-    RR -->|re-validates; aborts cleanly if taken/frozen| Z
-    P -->|Finalizing| FF[finalize_envelope: roll forward, verified]
-    FF --> Z
+    C->>L: commit(transfer)
+    L->>L: resolve(transfer) → envelope   [read-only]
+    L->>L: load + validate_and_plan()     [pure core]
+    L->>S: commit_envelope(consume, create, record, involved, event)
+    Note over S: one transaction —<br/>idempotency check, freeze/close,<br/>double-spend (delete-affected-count),<br/>overdraft floor, then apply
+    S-->>L: Committed | AlreadyCommitted | Rejected
+    L-->>C: Receipt (or mapped error)
 ```
 
-- A **`Reserving`** saga had not necessarily validated, so recovery re-runs the
-  real saga, which re-reserves and **re-validates** against current state. If
-  the postings were taken by another transfer, or an account was frozen, it
-  aborts cleanly (nothing commits) and the record is deleted.
-- A **`Finalizing`** saga had already validated and owns its postings (it
-  reached the point of no return), so recovery rolls it forward through the
-  verified `finalize_envelope`, which checks every end-state and only
-  creates/stores once **all** consumed postings are confirmed `Inactive` (the
-  double-spend guard).
-
-Recovery is roll-forward, not rollback, so the reservation protocol never
-leaves orphaned `PendingInactive` postings for a separate reconciliation pass.
-
-`reverse()` builds a reversal envelope and runs the same `commit_envelope`
-path. There is no separate raw/atomic entry point.
+Inside the transaction the store checks idempotency (an already-stored transfer
+returns its receipt), then re-checks the three stateful guards strictly: the
+consumed postings must still be live (the delete-affected-count is the atomic
+single-winner claim), the involved accounts must not be frozen or closed, and an
+overdraft-forbidding account's projected balance must stay non-negative (summed
+in Rust from the live rows). A domain rejection is a typed `CommitRejection` the
+ledger maps to a `LedgerError`; nothing is applied on a rejection.
+
+Because the write is all-or-nothing, a crash either applied the whole commit or
+none of it. There is no write-ahead record and no `recover()` step. An account
+transition (freeze/unfreeze/close) is the same shape: `commit_transition`
+appends the new version and its lifecycle event in one transaction.
+
+This replaced an earlier saga pipeline. A saga is the right tool when a workflow
+spans resources that cannot share a transaction (multiple services or a sharded
+store); here every step lived behind one transactional store, so one ACID
+transaction was the simpler, stricter primitive. If a backend ever shards its
+data, the saga returns *inside* that backend's `commit_envelope`, not in the
+ledger core. See
+[ADR-0023](adr/0023-atomic-storage-commit.md) ("When a saga is the right tool").
+
+`reverse()` builds a reversal envelope and runs the same `commit_envelope` path.
+Multiple transfers compose into an all-or-nothing workflow through
+`saga::run_movements`, which commits them in order and reverses the committed
+ones LIFO on failure.
 
 ## Content-Addressed Transfers
 
@@ -270,24 +230,22 @@ negative posting on such an account. Use
 ## The Debit-Must-Not-Exceed-Credit Constraint Under Concurrency
 
 An account that forbids overdraft has a balance floor at zero that is not backed
-by the UTXO model alone: two concurrent transfers could each pass validation but
-together push the balance negative (write-skew).
-
-Under the dumb-storage model the floor (and the freeze/close snapshot check) is
-re-validated **as the last thing the finalize step does before it writes**: the
-finalize step re-loads balances and account versions and re-runs
-`validate_and_plan` immediately before `deactivate_postings`. This is the
-tightest best-effort: the check-to-write window is one step, not the whole
-saga's lifetime, and it also runs on the recovery path. It is **not strictly
-atomic**, though. Without folding the check into the write itself (a CAS) or
-serializing per account, a concurrent commit landing in that last sub-step gap
-can still slip through. Double-spend safety is unaffected and holds
-unconditionally: the reservation protocol (`reserve_postings` is a single
-atomic conditional update, so two sagas cannot both claim the same posting)
-prevents
-consuming a posting twice. Only the floor on an account that forbids overdraft
-is best-effort. This tradeoff is recorded in
-[doc/adr/0003-dumb-storage-saga-recovery.md](adr/0003-dumb-storage-saga-recovery.md).
+by the UTXO model alone: two concurrent transfers could each pass a snapshot
+validation but together push the balance negative (write-skew).
+
+Under the atomic-commit model (ADR-0023) the floor and the freeze/close checks
+are re-run **inside the commit transaction**, after the consumed postings are
+deleted and the created ones inserted, so they see the true post-commit state. A
+projected-negative balance on an overdraft-forbidding account aborts the whole
+transaction. On PostgreSQL the involved account-head rows are taken `FOR UPDATE`
+before the live-posting writes, serializing concurrent commits that touch the
+same account; on SQLite the single write transaction serializes writers. The
+floor is therefore **strict**, not best-effort. Double-spend safety comes from
+the same transaction: deleting a consumed live row is the atomic single-winner
+claim, so two commits cannot both spend it. This supersedes the best-effort
+tradeoff recorded in
+[doc/adr/0003-dumb-storage-saga-recovery.md](adr/0003-dumb-storage-saga-recovery.md);
+see [doc/adr/0023-atomic-storage-commit.md](adr/0023-atomic-storage-commit.md).
 
 An overdraft-permitting account has no floor to violate.
 
@@ -324,7 +282,10 @@ share one selection pass, avoiding double-selection of the same postings.
 
 ## Posting Lifecycle
 
-Postings follow a three-state lifecycle managed by the saga pipeline:
+A committed transfer moves a posting straight from `Active` to `Inactive` inside
+the atomic commit (the live row is deleted). The intermediate `PendingInactive`
+(reserved) state and the `reserve_postings`/`release_postings` primitives remain
+as generic single-winner claim operations, unused by the commit path:
 
 ```mermaid
 stateDiagram-v2
@@ -347,8 +308,8 @@ The batch posting methods are dumb: each id's conditional update is applied
 independently, and the method returns the number of rows it changed. There is
 no all-or-nothing batch rejection. A posting that does not meet the condition is
 simply skipped (it does not count and does not error), so a batch can apply to
-some ids and not others. The saga interprets the returned count (full continue,
-partial compensate, zero idempotent-replay); the Store never decides.
+some ids and not others. The caller interprets the returned count; the Store
+never decides.
 
 - **`reserve_postings(ids, rid)`**: flips each `Active` posting to
   `PendingInactive` stamped with `rid`. Each flip is a single atomic conditional
@@ -360,71 +321,28 @@ Each posting's update is atomic on its own row, so this enables shard-local
 writes with no cross-shard coordination. Atomicity is per posting, not across
 the batch.
 
-## Saga Composition
+## Multi-Transfer Composition
 
-### Internal pipeline steps
-
-The envelope saga is two `legend::Step` implementations operating on
-`LedgerCtx` (resolution runs before the saga, in `Ledger::commit`):
-
-| Step | Execute | Compensate | Retry |
-|------|---------|------------|-------|
-| `ReservePostingsStep` | Reserve postings `Active → PendingInactive`, interpret the count | Release back to `Active` | 3 retries |
-| `FinalizeTransferStep` | `Ledger::finalize_envelope`: re-validate (last-step floor/freeze guard) → mark `Finalizing` → `deactivate` → `insert` → `store_transfer` → `append_event`, verifying every end-state | `reverse(transfer_id)` | 3 retries |
-
-### High-level composition steps
-
-Higher-level steps compose over the intent-layer API for multi-transfer
-workflows:
-
-| Step | Execute | Compensate |
-|------|---------|------------|
-| `PayMovementStep` | Build pay transfer, `ledger.commit(...)` | `ledger.reverse(receipt.transfer_id)` |
-| `DepositMovementStep` | Build deposit transfer, `ledger.commit(...)` | `ledger.reverse(receipt.transfer_id)` |
-
-### Custom orchestration with legend
-
-You can compose any combination of steps into a saga using the `legend!` macro.
-Legend drives the steps in order, retries on transient failures, and
-compensates completed steps in reverse (LIFO) on unrecoverable failure.
+A single commit is already atomic in the store, so composing several transfers
+into one all-or-nothing workflow (an FX trade, a multi-leg settlement) needs only
+a thin runner, not a saga VM. `saga::run_movements` commits a list of
+`Movement`s in order and, on the first failure, reverses the already-committed
+receipts LIFO via `ledger.reverse(..)`:
 
 ```rust
 use std::sync::Arc;
-use legend::legend;
-use kuatia::saga::*;
-
-// Define a multi-transfer saga
-legend! {
-    FundAndPay<LedgerCtx, SagaError> {
-        deposit: DepositMovementStep,
-        pay: PayMovementStep,
-    }
-}
+use kuatia::saga::{DepositInput, Movement, PayInput, run_movements};
 
-// Build and run: Ledger uses Arc<dyn Store>, so LedgerCtx is concrete
 let ledger: Arc<Ledger> = /* ... */;
-let saga = FundAndPay::new(FundAndPayInputs {
-    deposit: DepositInput { to: alice, asset: usd, amount, external: bank },
-    pay: PayInput { from: alice, to: bob, asset: usd, amount },
-});
-let ctx = LedgerCtx::new(ledger.clone());
-let result = saga.build(ctx).start().await;
-
-match result {
-    ExecutionResult::Completed(e) => { /* all steps succeeded */ }
-    ExecutionResult::Failed(_, err) => { /* deposit was compensated */ }
-    ExecutionResult::Paused(e) => { /* serialize e for crash recovery */ }
-    ExecutionResult::CompensationFailed { .. } => { /* manual intervention */ }
-}
+let receipts = run_movements(&ledger, &[
+    Movement::Deposit(DepositInput { to: alice, asset: usd, amount, external: bank }),
+    Movement::Pay(PayInput { from: alice, to: bob, asset: usd, amount }),
+])
+.await?;
 ```
 
-Since `Ledger` uses `Arc<dyn Store>` internally, `LedgerCtx` is a concrete
-type: no generic parameters needed. This is what allows `legend!` to define
-saga types directly.
-
-The `LedgerCtx` is serializable: a paused saga can be persisted and resumed
-later, enabling crash recovery. On boot, load pending sagas and resume them;
-legend will compensate any completed steps that need rollback.
+If the pay fails, the deposit is reversed and the original error is returned; a
+failing reversal surfaces as `LedgerError::CompensationFailed`.
 
 ### Reversal
 

+ 50 - 74
doc/crates.md

@@ -29,7 +29,7 @@ dependencies (`sha2`, `serde`, `bitflags`).
 | `PostingFilter` | Read filter over derived posting state: `Active`, `Reserved`, `Live` (Active ∪ Reserved), `All` |
 | `Amount` | Parser/formatter for decimal strings. Not stored; use at API boundaries only |
 | `Posting` | Immutable signed amount of one asset owned by one account. Carries no lifecycle field; its state is derived from index-table membership (see `PostingState`) |
-| `ReservationId` | Owner token recorded in the reserved index so only the reserving saga may finalize/release a posting |
+| `ReservationId` | Owner token recorded in the reserved index by the `reserve_postings`/`release_postings` primitives (unused by the atomic commit path) |
 | `NewPosting` | Posting to be created (no id yet, assigned during validation) |
 | `Transfer` | Atomic unit: consumes postings + creates postings + metadata |
 | `EnvelopeBuilder` | Fluent builder for `Transfer` construction |
@@ -84,54 +84,44 @@ Output is a `Plan` containing `transfer_id`, `postings_to_deactivate`, and
 ## kuatia
 
 Async resource layer. Depends on `kuatia-core`, `tokio`, `async-trait`,
-`serde`, `legend`.
+`serde`.
 
 ### Modules
 
 | Module | Purpose |
 |--------|---------|
-| `kuatia` | `Ledger`: primary API (non-generic, uses `Arc<dyn Store>`), saga commit pipeline, intent layer |
-| `store` | `Store` composite trait + sub-traits (`AccountStore`, `PostingStore`, `TransferStore`, `SagaStore`, `EventStore`, `BookStore`) |
+| `kuatia` | `Ledger`: primary API (non-generic, uses `Arc<dyn Store>`), atomic commit engine, intent layer |
+| `store` | `Store` composite trait + sub-traits (`AccountStore`, `PostingStore`, `TransferStore`, `CommitStore`, `EventStore`, `BookStore`) |
 | `error` | `StoreError`, `LedgerError`: unified error hierarchy |
 | `mem_store` | `InMemoryStore`: in-memory `Store` implementation for tests |
-| `saga` | Pipeline steps (reserve, validate, finalize) + high-level legend step adapters |
+| `saga` | `run_movements`: multi-transfer LIFO composition over `commit`/`reverse` |
 
 ### Ledger API
 
-#### Commit (the envelope saga)
+#### Commit (atomic)
 
-`commit(transfer)` resolves the intent into an envelope (read-only) then runs
-the `EnvelopeSaga` (defined via `legend!`): two steps with automatic retry and
-LIFO compensation. The finalize step re-validates as its last action before the
-writes, then calls the dumb primitives, interpreting/verifying each count:
+`commit(transfer)` resolves the intent into an envelope (read-only), validates it
+in the pure core, then applies the effects through `store.commit_envelope(..)` in
+one transaction. The store re-checks the stateful guards inside it:
 
 ```mermaid
 graph LR
-    A[resolve] -->|Envelope| W[save PendingSaga: Reserving]
-    W --> B[reserve_postings]
-    B -->|active index → reserved index| F[finalize]
-    F --> V[validate_and_plan re-check]
-    V --> M[mark Finalizing]
-    M --> D[deactivate → insert → store_transfer → append_event]
-    D --> E[Receipt + delete PendingSaga]
+    A[resolve] -->|Envelope| V[load + validate_and_plan]
+    V --> C["store.commit_envelope(..)"]
+    C -->|"one tx: idempotency + double-spend + freeze/close + floor, then apply"| E[Receipt]
     style E fill:#e8f5e9
 ```
 
-Note: `commit`/`commit_envelope`/`reverse`/`recover` require `Arc<Ledger>`.
-
-#### Crash recovery
-
-`recover()` re-completes any `PendingSaga` left by a crash, pushing the
-envelope through the idempotent primitives (roll-forward). Call it on startup.
+Note: `commit`/`commit_envelope`/`reverse` require `Arc<Ledger>`. A crash leaves
+no half-applied state, so there is no recovery step.
 
 #### Convenience
 
 | Method | Description |
 |--------|-------------|
 | `commit(transfer)` | Resolve intent → `commit_envelope` (requires `Arc<Ledger>`) |
-| `commit_envelope(envelope)` | The one commit path: write-ahead → reserve → finalize (finalize re-validates, then writes); for pre-built/FX envelopes |
+| `commit_envelope(envelope)` | The one commit path: validate → atomic `store.commit_envelope`; for pre-built/FX envelopes |
 | `reverse(transfer_id)` | Builds a compensating envelope and runs `commit_envelope` |
-| `recover()` | Force-completes pending sagas after a crash (call on startup) |
 
 #### Intent Layer
 
@@ -170,16 +160,17 @@ Transfers are built via `TransferBuilder` and committed with
 
 ### Store Trait
 
-The `Store` trait is a composite of focused sub-traits. Every write method is a
-dumb instruction returning the number of affected rows (`u64`); the saga
-interprets the count.
+The `Store` trait is a composite of focused sub-traits. A transfer commits
+atomically through `CommitStore`; the remaining posting/account write methods are
+dumb instructions returning the number of affected rows (`u64`), used by reads
+and setup.
 
 ```mermaid
 graph TB
     Store --> AccountStore
     Store --> PostingStore
     Store --> TransferStore
-    Store --> SagaStore
+    Store --> CommitStore
     Store --> EventStore
     Store --> BookStore
 ```
@@ -195,20 +186,22 @@ graph TB
 - **`TransferStore`**: `get_transfer`,
   `store_transfer(record, involved) -> u64`, `get_transfers_for_account`,
   `query_transfers`
+- **`CommitStore`**: `commit_envelope(request) -> CommitOutcome`,
+  `commit_transition(next, event) -> TransitionOutcome`: the atomic write
+  boundary (ADR-0023)
 - **`EventStore`**: `append_event` (idempotent on a dedup key: a transfer's id,
   or a lifecycle transition's `(account, version)`), `get_events_since`
-- **`SagaStore`**: `save_saga`, `list_pending_sagas`, `delete_saga`: the
-  write-ahead store the saga and `recover()` use
 - **`BookStore`**: `create_book`, `get_book`, `list_books`
 
-There is no `CommitStore`/`commit_transfer`: a commit is the saga calling these
-primitives in sequence, each idempotent, with crash-safety from write-ahead
-recovery rather than a single transaction.
+A commit is one `commit_envelope` transaction, not a sequence of primitives, so
+crash-safety comes from the transaction rather than write-ahead recovery. The
+`reserve_postings`/`release_postings`/`deactivate_postings` primitives remain as
+generic dumb operations, unused by the commit path.
 
 #### Batch posting operations
 
 `reserve_postings`/`release_postings`/`deactivate_postings` apply each id's
-conditional update and return how many rows changed (the saga decides what a
+conditional update and return how many rows changed (the caller decides what a
 short count means):
 
 State is derived from which index a posting is in: active index → `Active`,
@@ -238,7 +231,7 @@ applicable). The saga interprets a 0:
 There is no all-or-nothing batch rejection: a posting whose condition does not
 hold is skipped (counted as 0, not an error), so a call can apply to some ids
 and not others. Each id's update is atomic on its own row; the batch as a whole
-is not. The saga reads the count and decides what to do.
+is not. The caller reads the count and decides what to do.
 
 Balance computation lives in the Ledger (`compute_balance`), not the Store.
 
@@ -251,12 +244,13 @@ LedgerError
 ├── Selection(SelectionError)     // insufficient funds (includes Overflow)
 ├── TransferNotFound
 ├── PostingNotReversible
+├── DoubleSpend                  // a consumed posting was not live at commit time
 ├── AccountNotFound
 ├── AccountNotEmpty              // can't close with active postings
 ├── AccountAlreadyClosed
 ├── BookNotFound                 // transfer named a book that does not exist
 ├── Overflow                     // monetary arithmetic overflow
-└── CompensationFailed           // saga compensation failed (original + compensation errors)
+└── CompensationFailed           // multi-transfer reversal failed (original + compensation errors)
 ```
 
 ```
@@ -267,46 +261,28 @@ StoreError
 └── Internal(String)
 ```
 
-The store has no semantic write-outcome errors (no "posting not active",
-"reservation mismatch", "cas conflict"). Writes return affected-row counts and
-the saga derives meaning from them.
-
-### Saga Steps
-
-#### Envelope pipeline steps (used internally by `commit_envelope`; resolution runs before the saga)
-
-| Step | Execute | Compensate | Retry |
-|------|---------|------------|-------|
-| `ReservePostingsStep` | `reserve_postings`: active index → reserved index, interpret count | Release back to `Active` | 3 |
-| `FinalizeTransferStep` | `Ledger::finalize_envelope`: re-validate (last-step floor/freeze guard) → mark `Finalizing` → `deactivate` → `insert` → `store_transfer` → `append_event`, verifying every end-state | `reverse(transfer_id)` | 3 |
+`StoreError` is IO-only (`NotFound`, `Internal`). The atomic `commit_envelope`
+reports a domain refusal as an `Ok(CommitOutcome::Rejected(CommitRejection))`
+value (double-spend, frozen, closed, overdraft) that the ledger maps to a
+`LedgerError`; the dumb posting primitives return affected-row counts and the
+caller derives meaning from them.
 
-Validation lives inside the finalize step so it runs immediately before the
-writes. Recovery (`recover()`) re-uses `finalize_envelope` for `Finalizing`
-sagas and re-runs the whole saga for `Reserving` ones.
+### Multi-Transfer Composition
 
-#### High-level steps (for custom saga composition with `legend!`)
-
-| Step | Execute | Compensate |
-|------|---------|------------|
-| `PayMovementStep` | Build pay transfer, `ledger.commit(...)` | `ledger.reverse(receipt.transfer_id)` |
-| `DepositMovementStep` | Build deposit transfer, `ledger.commit(...)` | `ledger.reverse(receipt.transfer_id)` |
-
-#### Custom orchestration
-
-Compose steps into sagas using `legend!`. The saga executor drives steps in
-order with automatic retry and LIFO compensation. `LedgerCtx` is serializable
-for crash recovery:
+`saga::run_movements(ledger, movements)` commits a list of `Movement`s
+(`Pay`/`Deposit`) in order and, on the first failure, reverses the
+already-committed receipts LIFO via `ledger.reverse(..)`. Each single commit is
+already atomic in the store, so this is a plain runner, not a saga VM.
 
 ```rust
-legend! {
-    MyFlow<LedgerCtx, SagaError> {
-        deposit: DepositMovementStep,
-        pay: PayMovementStep,
-    }
-}
-let ctx = LedgerCtx::new(ledger_arc.clone());
-let result = MyFlow::new(inputs).build(ctx).start().await;
+use kuatia::saga::{DepositInput, Movement, PayInput, run_movements};
+
+let receipts = run_movements(&ledger, &[
+    Movement::Deposit(DepositInput { to: alice, asset: usd, amount, external: bank }),
+    Movement::Pay(PayInput { from: alice, to: bob, asset: usd, amount }),
+])
+.await?;
 ```
 
-`LedgerCtx` is concrete (not generic) because `Ledger` uses `Arc<dyn Store>`
-internally.
+If a movement fails, the committed ones are reversed and the original error is
+returned; a failing reversal surfaces as `LedgerError::CompensationFailed`.

+ 17 - 30
doc/glossary.md

@@ -78,36 +78,23 @@ The resolved, concrete form of a transfer: which postings to consume and which
 to create. Produced by the resolve step (`commit`), or built directly and
 committed via `commit_envelope(envelope)`.
 
-### Dumb storage
-
-The design where every `Store` write method applies one update and returns the
-**number of affected rows** (or an I/O error), never interpreting that count,
-deciding state, enforcing idempotency, or compensating. The saga reads the
-count and decides: full = continue; partial = error → compensate; zero = read
-state and continue only if this same envelope/reservation already applied it.
-
-### Reservation protocol
-
-The concurrency-control mechanism for consumed postings: `reserve_postings`
-atomically flips `Active → PendingInactive` stamped with a `ReservationId`,
-so two sagas cannot both claim the same posting. This (not a global
-transaction) is what prevents double-spend.
-
-### Write-ahead record (PendingRecord) / recovery
-
-A record persisted via `SagaStore` before a multi-write operation mutates
-anything, so a crash mid-sequence can be completed on the next startup. There
-are two kinds (`PendingRecord`): a **commit saga** `{envelope, reservation,
-phase}`, and an **account transition** `{next, event}` (freeze/unfreeze/close).
-The `pending` module owns the concept: what a record is, how it is
-(de)serialized, and how each kind completes.
-
-`Ledger::recover()` (startup) loads each surviving record and drives it to a
-terminal state through `PendingRecord::complete`. A commit saga's `phase`
-(`Reserving` → `Finalizing`) decides how: a `Reserving` saga is re-run and
-**re-validated**; a `Finalizing` saga (already validated, owns its postings) is
-rolled forward through the verified `finalize_envelope`. A transition rolls its
-version + event forward idempotently. Roll-forward, not rollback.
+### Atomic commit
+
+The design where a whole transfer commits in one store transaction
+(`CommitStore::commit_envelope`). The pure core validates first; the transaction
+re-checks the stateful guards inside it (double-spend, freeze/close, overdraft
+floor) and applies the effects all-or-nothing. A crash leaves no half-applied
+state, so there is no write-ahead log and no recovery. See ADR-0023 (superseding
+ADR-0003). The remaining posting/account write methods stay dumb: each applies
+one update and returns the number of affected rows, never interpreting it.
+
+### Double-spend guard
+
+The concurrency-control mechanism for consumed postings: inside the atomic
+commit, deleting a consumed live posting is a single atomic conditional update,
+so two commits cannot both spend it. The loser sees the row gone and is rejected
+with `DoubleSpend`. This (not a global validation snapshot) is what prevents
+double-spend.
 
 ### Book
 

+ 10 - 16
doc/storage-schema.md

@@ -184,8 +184,8 @@ is safe because the copied columns are immutable: `postings` rows never change a
 reserve/release only flip the `reservation` column, so a copy can never drift from
 its value row. And it is bounded and disposable: only the live set is duplicated
 (spent postings live in `postings` alone), and `live_postings` is rebuildable from
-`postings` plus the saga write-ahead records, so a corrupt hot table is a
-drop-and-rebuild, not data loss.
+`postings` and the transfer log, so a corrupt hot table is a drop-and-rebuild,
+not data loss.
 
 ### `postings`
 
@@ -207,9 +207,10 @@ The immutable record. A row here that is absent from `live_postings` is Spent.
 
 The live-set hot copy: the six data columns plus a nullable `reservation`. A
 posting is here while it is spendable or reserved; `reservation IS NULL` = Active,
-a set `reservation` = Reserved by that saga. Reserve/release flip the column
-(`UPDATE`), consume deletes the row (→ Spent). Rebuildable from `postings` + the
-saga records.
+a set `reservation` = Reserved (set only by the generic `reserve_postings`
+primitive, unused by the atomic commit path). An atomic commit deletes the
+consumed row directly (→ Spent). Rebuildable from `postings` and the transfer
+log.
 
 | Column | Type | Key | Purpose |
 |---|---|---|---|
@@ -258,17 +259,10 @@ does no computation.
 
 ## Ledger plumbing
 
-### `sagas`
-
-Write-ahead saga records for crash recovery. Owned by `saga.rs` (`SagaStore`).
-See [ADR-0002 (saga commit pipeline)](adr/0002-saga-commit-pipeline.md).
-
-| Column | Type | Key | Purpose |
-|---|---|---|---|
-| `id` | `BIGINT` | PK | Saga id (the reservation id). |
-| `data` | `TEXT` | | The encoded `PendingSaga` record (hex). |
-
-- **Primary key**: `id`.
+The `sagas` write-ahead table was dropped in migration `010_drop_sagas`: a
+commit and an account transition are now single atomic store transactions
+(ADR-0023, superseding ADR-0003), so there is no half-applied state for a
+write-ahead record to recover.
 
 ### `events`
 

+ 10 - 15
doc/transfers.md

@@ -232,21 +232,16 @@ validation steps are:
 10. Balance-constraint enforcement: for an account that forbids overdraft, the
     projected balance stays `>= 0`
 
-Validation runs inside the finalize step, immediately before it writes (the
-last-step floor / freeze-close re-check). The finalize step then applies the
-effects through a sequence of dumb, idempotent store primitives
-(`deactivate_postings` → `insert_postings` → `store_transfer` → `append_event`),
-verifying every end-state. There is no single transaction; crash-safety comes
-from a phase-tracked write-ahead `PendingSaga` record plus `recover()`
-roll-forward. The zero floor of an account that forbids overdraft is re-checked
-as that last step and is best-effort (not strictly atomic) under concurrency:
-two transfers that each pass the floor check against the same pre-transfer
-balance can both commit and jointly push the account below zero. Per-asset
-conservation still holds in that case (the negative postings are real
-value owed, not minted). That floor is the only guard with this
-property; double-spend prevention is exact (see
-`crates/kuatia/tests/concurrency.rs`, which asserts the exact guarantees
-and documents the floor race with an ignored test). See
+Steps 1-8 run in the pure core before the write. The effects are then applied by
+`store.commit_envelope(..)` in one transaction, which re-checks the stateful
+guards inside it: double-spend (deleting a consumed live posting is the atomic
+single-winner claim), freeze/close, and the zero floor of an account that forbids
+overdraft (steps 9-10, summed in Rust from the post-commit live rows). Because
+the checks and the writes share the transaction, the floor is **strict**, not
+best-effort: two transfers cannot both pass and jointly push an account below
+zero (ADR-0023, superseding the best-effort floor of ADR-0003). A crash leaves no
+half-applied state, so there is no write-ahead record and no recovery. See
+`crates/kuatia/tests/concurrency.rs` for the asserted guarantees and
 [architecture.md](architecture.md).
 
 See [architecture.md](architecture.md) for details on each check.