Просмотр исходного кода

Retire the reservation model and the API shapes it left behind

ADR-0023 made a commit one atomic store transaction but left the data
model the old saga had needed. A posting could be reserved by a token no
code could set, and the write primitives that moved postings one at a time
stayed on the Store trait with no caller. Because Ledger::store() hands out
the whole trait, those were a public route to spend a posting or append an
account version while skipping the double-spend, freeze/close and overdraft
checks the commit transaction enforces. A posting is now live or spent with
nothing in between, and the atomic commit is the only way either is
written.

The surface carried the same kind of residue. Every commit took the ledger
as an Arc that no body used, the builder spelled one push several ways, the
public types said envelope where the API said transfer, and the balance
reads gave a caller nothing to choose between them by. Those are gone or
renamed, and the cache maintenance that sat among the balance reads moved
to a handle of its own.

One of these was losing money rather than clarity. A transfer's id is the
hash of its content, so a deposit, which consumes nothing, could not
distinguish itself from an identical earlier one and the second commit was
discarded as a replay. A repeated top-up went missing with no error.
Metadata was always part of that hash, so the fix was to ask the caller for
a reference rather than to change the rule.

Nothing stored moves except the dropped reservation column. The renamed id
is a newtype over the same bytes, so content addresses and dedup keys are
unchanged and no row means anything different than it did.
C 4 дней назад
Родитель
Сommit
2e22e01d71
74 измененных файлов с 1589 добавлено и 1991 удалено
  1. 53 0
      CHANGELOG.md
  2. 11 12
      CLAUDE.md
  3. 4 6
      README.md
  4. 1 1
      crates/kuatia-core/README.md
  5. 9 9
      crates/kuatia-core/src/hash.rs
  6. 1 1
      crates/kuatia-core/src/posting_resolution.rs
  7. 16 16
      crates/kuatia-core/src/validate.rs
  8. 4 5
      crates/kuatia-dashboard/src/data.rs
  9. 3 3
      crates/kuatia-dashboard/static/dashboard.css
  10. 0 80
      crates/kuatia-storage-sql/src/account.rs
  11. 8 8
      crates/kuatia-storage-sql/src/commit.rs
  12. 4 0
      crates/kuatia-storage-sql/src/migrate.rs
  13. 7 0
      crates/kuatia-storage-sql/src/migrations/012_drop_reservation.sql
  14. 38 256
      crates/kuatia-storage-sql/src/posting.rs
  15. 7 7
      crates/kuatia-storage-sql/src/row.rs
  16. 8 53
      crates/kuatia-storage-sql/src/transfer.rs
  17. 42 5
      crates/kuatia-storage-sql/tests/postgres.rs
  18. 89 33
      crates/kuatia-storage-sql/tests/sqlite.rs
  19. 9 9
      crates/kuatia-storage/README.md
  20. 4 5
      crates/kuatia-storage/src/error.rs
  21. 2 2
      crates/kuatia-storage/src/events.rs
  22. 29 166
      crates/kuatia-storage/src/mem_store.rs
  23. 3 3
      crates/kuatia-storage/src/query.rs
  24. 28 91
      crates/kuatia-storage/src/store.rs
  25. 211 491
      crates/kuatia-storage/src/store_tests.rs
  26. 164 35
      crates/kuatia-storage/tests/concurrency.rs
  27. 2 2
      crates/kuatia-types/README.md
  28. 2 3
      crates/kuatia-types/src/autoid.rs
  29. 4 4
      crates/kuatia-types/src/canonical.rs
  30. 4 4
      crates/kuatia-types/src/envelope.rs
  31. 5 67
      crates/kuatia-types/src/ids.rs
  32. 2 5
      crates/kuatia-types/src/lib.rs
  33. 13 39
      crates/kuatia-types/src/posting.rs
  34. 42 21
      crates/kuatia-types/src/transfer.rs
  35. 1 1
      crates/kuatia/Cargo.toml
  36. 7 7
      crates/kuatia/README.md
  37. 2 3
      crates/kuatia/examples/create_accounts.rs
  38. 3 5
      crates/kuatia/examples/fund_and_trade.rs
  39. 5 6
      crates/kuatia/examples/inflight_hold.rs
  40. 3 5
      crates/kuatia/examples/overdraft.rs
  41. 2 4
      crates/kuatia/examples/withdraw.rs
  42. 11 10
      crates/kuatia/src/error.rs
  43. 21 32
      crates/kuatia/src/inflight.rs
  44. 17 17
      crates/kuatia/src/inflight/projection.rs
  45. 35 18
      crates/kuatia/src/ledger.rs
  46. 15 29
      crates/kuatia/src/ledger/balance.rs
  47. 11 16
      crates/kuatia/src/ledger/commit.rs
  48. 3 4
      crates/kuatia/src/ledger/lifecycle.rs
  49. 46 0
      crates/kuatia/src/ledger/projection.rs
  50. 4 4
      crates/kuatia/src/ledger/query.rs
  51. 6 5
      crates/kuatia/src/lib.rs
  52. 0 95
      crates/kuatia/src/saga.rs
  53. 41 0
      crates/kuatia/src/workflow.rs
  54. 1 1
      crates/kuatia/tests/inflight.rs
  55. 86 22
      crates/kuatia/tests/integration.rs
  56. 33 20
      crates/kuatia/tests/projection.rs
  57. 11 20
      crates/kuatia/tests/workflow.rs
  58. 2 0
      doc/SUMMARY.md
  59. 12 12
      doc/accounting-mapping.md
  60. 9 11
      doc/accounts.md
  61. 1 1
      doc/adr/0006-reservation-protocol-posting-lifecycle.md
  62. 1 1
      doc/adr/0008-conformance-tested-storage.md
  63. 1 1
      doc/adr/0012-subaccounts.md
  64. 1 1
      doc/adr/0022-merged-live-postings-hot-index.md
  65. 94 0
      doc/adr/0025-one-live-set-no-reservations.md
  66. 94 0
      doc/adr/0026-public-api-vocabulary.md
  67. 6 4
      doc/adr/README.md
  68. 35 53
      doc/architecture.md
  69. 62 80
      doc/crates.md
  70. 7 7
      doc/glossary.md
  71. 5 4
      doc/inflight.md
  72. 5 5
      doc/journaling.md
  73. 16 26
      doc/storage-schema.md
  74. 45 19
      doc/transfers.md

+ 53 - 0
CHANGELOG.md

@@ -7,14 +7,67 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ## [Unreleased]
 
+### Added
+
+- `TransferBuilder::reference(..)`, which writes a caller-supplied reference
+  under the reserved `REFERENCE_KEY` metadata key. A transfer's id is the hash
+  of its content, so a transfer that consumes nothing (a deposit, an issuance)
+  cannot distinguish itself from an identical earlier one and the second commit
+  is reported as a replay. Setting a distinct reference makes two real deposits
+  two transfers; repeating one keeps a retry idempotent. See
+  [doc/transfers.md](doc/transfers.md#transfer-identity-give-every-distinct-transfer-a-reference).
+
 ### Changed
 
+- The ledger no longer has to be held in an `Arc`. `commit`, `commit_envelope`,
+  `reverse`, the inflight entry points and `workflow::run_transfers` take
+  `&self`, so `Ledger::new(store)` is usable directly; an `Arc<Ledger>` still
+  derefs, so sharing stays available to callers who want it. *(breaking only
+  for code naming the receiver type)* (ADR-0026)
+- `EnvelopeId` is `TransferId` and `EnvelopeRecord` is `TransferRecord`, so the
+  public surface speaks of transfers throughout. `Envelope`, `EnvelopeBuilder`
+  and `commit_envelope` keep their names as the resolved form. Nothing stored
+  changes: no migration, no content address and no dedup key moves.
+  *(breaking)* (ADR-0026)
+- `Ledger::compute_balance` is `balance_exact`, beside `balance`, so a call site
+  says whether it took the cached read or the authoritative one. *(breaking)*
+  (ADR-0026)
+- `Ledger::with_snapshot_interval` and `with_projection_grace_ms` become one
+  `with_projection_config(ProjectionConfig { .. })`. *(breaking)* (ADR-0026)
+- `kuatia::saga` is now `kuatia::workflow`, and `run_movements` is
+  `run_transfers`, taking the transfers themselves. Its own `Movement`,
+  `PayInput` and `DepositInput` described legs it then rebuilt with
+  `TransferBuilder`, and that `Movement` shadowed `kuatia_types::Movement`.
+  *(breaking)*
 - `ValidationError::OverdraftExceeded` no longer carries a `floor` field. The
   balance model is binary (an account either permits unbounded overdraft or
   forbids any negative balance), so the floor was always zero and implied a
   configurable bound that does not exist. *(breaking for callers matching on the
   variant)*
 
+### Removed
+
+- `TransferBuilder::movement_ref` and `pay_ref`. Both pushed the same `Movement`
+  as `movement` and `pay`: ADR-0012 meant them for subaccount endpoints, but
+  every endpoint is a full `AccountId` already. *(breaking)* (ADR-0026)
+- `Ledger::append_cache_point` moves to `ledger.projection().append_cache_point(..)`,
+  since it maintains the balance cache rather than reading a balance.
+  *(breaking)* (ADR-0026)
+- The reservation protocol, which the atomic commit of ADR-0023 had left without
+  a producer. `PostingState::Reserved`, `PostingFilter::{Active, Reserved}`,
+  `ReservationId` and `TransitionId` are gone, and `live_postings.reservation` is
+  dropped by migration `012_drop_reservation`. A posting is live or spent, with
+  nothing in between. *(breaking: `PostingState::Active` is now `Live`, which
+  also changes its serde representation, and the dashboard reports a posting's
+  status as "Live" rather than "Active")* (ADR-0025)
+- Six `Store` write methods: `reserve_postings`, `release_postings`,
+  `deactivate_postings`, `insert_postings`, `append_account_version` and
+  `store_transfer`. Nothing called them, and because `Ledger::store()` returns
+  the trait they were a public route to spend a posting or append a version while
+  skipping the guards the commit transaction enforces. `CommitStore` is now the
+  only way either is written. *(breaking for out-of-tree backends)* (ADR-0025)
+
+
 ## [0.3.0] - 2026-07-30
 
 ### Added

+ 11 - 12
CLAUDE.md

@@ -26,20 +26,20 @@ doc/
 
 ## Key concepts
 
-- **Posting**: signed amount of one asset owned by one account. Lifecycle: Active → PendingInactive → Inactive.
+- **Posting**: signed amount of one asset owned by one account. State is live-index membership, so it is Live (unspent) or Spent, with nothing in between.
 - **Movement**: `{ from, to, asset, amount }` — the fundamental unit of intent. All operations (pay, deposit, withdraw) are one or more movements.
 - **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.
-- **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.
+- **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). `commit_envelope` is the only way a posting is ever written and `commit_transition` the only way a version is ever appended, so no caller can skip the guards (ADR-0025). Everything else on `Store` reads, apart from `create_account`, `create_book`, `append_event` and `append_balance_projection`.
 
 ## Architecture
 
 - **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 (one exact aggregate over the live rows, ADR-0024) 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.
+- **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 (`workflow::run_transfers`) over `commit`/`reverse`, not a saga VM.
+- **Content-addressed transfers**: TransferId = 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; 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.
 
@@ -55,14 +55,13 @@ Deposit: two movements cancel to zero net debit on the system account — no pos
 
 1. Non-empty
 2. No duplicate consumed PostingIds
-3. Consumed postings exist
-4. Consumed postings Active or PendingInactive
-5. Referenced accounts exist, not frozen, not closed
-6. Account snapshot pinning
-7. Book policy (if a book is loaded): referenced assets/accounts/flags allowed by the book
-8. Per-asset conservation
-9. Negative postings forbidden only on accounts with `DEBIT_MUST_NOT_EXCEED_CREDIT` (allowed on overdraft-permitting accounts)
-10. Zero-floor enforcement for accounts that forbid overdraft
+3. Consumed postings exist in the immutable record (liveness is re-checked inside the commit transaction, not here)
+4. Referenced accounts exist, not frozen, not closed
+5. Account snapshot pinning
+6. Book policy (if a book is loaded): referenced assets/accounts/flags allowed by the book
+7. Per-asset conservation
+8. Negative postings forbidden only on accounts with `DEBIT_MUST_NOT_EXCEED_CREDIT` (allowed on overdraft-permitting accounts)
+9. Zero-floor enforcement for accounts that forbid overdraft
 
 ## Testing
 

+ 4 - 6
README.md

@@ -26,9 +26,8 @@ reconstructs every balance, so the ledger is auditable by construction. See
 │                   kuatia (async)                    │
 │                                                     │
 │  Intent layer:  TransferBuilder + commit · balance  │
-│  Saga pipeline: resolve → reserve → validate → fin. │
-│  Raw pipeline:  load  →  plan  →  apply             │
-│  Saga steps:    legend step adapters                │
+│  Commit path:   resolve → validate → atomic commit  │
+│  Composition:   workflow::run_transfers (LIFO)      │
 ├─────────────────────────────────────────────────────┤
 │               kuatia-core (pure)                    │
 │                                                     │
@@ -47,19 +46,18 @@ reconstructs every balance, so the ledger is auditable by construction. See
 | **kuatia-core** | Pure, sans-IO decision logic — validation, hashing, posting selection. |
 | **kuatia-storage** | `Store` trait (7 sub-traits), `InMemoryStore`, `store_tests!` conformance macro. |
 | **kuatia-storage-sql** | SQL-backed `Store` — SQLite and PostgreSQL via sqlx. |
-| **kuatia** | Async resource layer — `Ledger`, saga commit pipeline, intent-layer API. |
+| **kuatia** | Async resource layer: `Ledger`, the atomic commit engine, intent-layer API. |
 
 ## Quick Example
 
 ```rust
-use std::sync::Arc;
 use kuatia::ledger::Ledger;
 use kuatia::mem_store::InMemoryStore;
 use kuatia_core::*;
 
 #[tokio::main]
 async fn main() -> Result<(), Box<dyn std::error::Error>> {
-    let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    let ledger = Ledger::new(InMemoryStore::new());
 
     let usd = AssetId::new(1);
     let alice = AccountId::new(1);

+ 1 - 1
crates/kuatia-core/README.md

@@ -20,7 +20,7 @@ with golden vectors. Depends only on `kuatia-types` and `sha2`.
 1. Non-empty transfer
 2. No duplicate consumed postings
 3. All consumed postings exist
-4. All consumed postings are Active or PendingInactive
+4. All consumed postings exist in the immutable record
 5. All accounts exist, not frozen, not closed
 6. Account snapshot pinning (OCC)
 7. Book policy (if a book is loaded): referenced assets/accounts/flags allowed

+ 9 - 9
crates/kuatia-core/src/hash.rs

@@ -1,12 +1,12 @@
 //! Hashing and tamper-evidence for the ledger.
 //!
-//! Every transfer gets a content-addressed [`EnvelopeId`] (double-SHA256 of its
+//! Every transfer gets a content-addressed [`TransferId`] (double-SHA256 of its
 //! canonical serialization), which serves as both the idempotency key and the
 //! tamper-evidence artifact.
 
 use sha2::{Digest, Sha256};
 
-use kuatia_types::{Account, AccountSnapshotId, Envelope, EnvelopeId, ToBytes};
+use kuatia_types::{Account, AccountSnapshotId, Envelope, ToBytes, TransferId};
 
 // ---------------------------------------------------------------------------
 // Double-SHA256
@@ -31,13 +31,13 @@ pub fn canonical_bytes(envelope: &Envelope) -> Vec<u8> {
     envelope.to_bytes()
 }
 
-/// Double-SHA256 content hash. Returns a [`EnvelopeId`].
-pub fn content_hash(data: &[u8]) -> EnvelopeId {
-    EnvelopeId(double_sha256(data))
+/// Double-SHA256 content hash. Returns a [`TransferId`].
+pub fn content_hash(data: &[u8]) -> TransferId {
+    TransferId(double_sha256(data))
 }
 
-/// Convenience: `envelope.to_bytes()` → double-SHA256 → [`EnvelopeId`].
-pub fn envelope_id(envelope: &Envelope) -> EnvelopeId {
+/// Convenience: `envelope.to_bytes()` → double-SHA256 → [`TransferId`].
+pub fn envelope_id(envelope: &Envelope) -> TransferId {
     content_hash(&envelope.to_bytes())
 }
 
@@ -96,9 +96,9 @@ mod tests {
     }
 
     #[test]
-    fn payer_does_not_affect_envelope_id() {
+    fn payer_does_not_affect_transfer_id() {
         // payer is provenance, not identity: two envelopes differing only in
-        // payer must share an EnvelopeId, and thus one idempotency key.
+        // payer must share an TransferId, and thus one idempotency key.
         let a = sample_envelope();
         let mut b = sample_envelope();
         b.creates[0].payer = Some(AccountId::new(9));

+ 1 - 1
crates/kuatia-core/src/posting_resolution.rs

@@ -281,7 +281,7 @@ mod tests {
     fn posting(owner: AccountId, index: u16, value: i64) -> Posting {
         Posting::new(
             PostingId {
-                transfer: EnvelopeId([index as u8; 32]),
+                transfer: TransferId([index as u8; 32]),
                 index,
             },
             owner,

+ 16 - 16
crates/kuatia-core/src/validate.rs

@@ -40,7 +40,7 @@ pub struct PlanInput<'a> {
 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
 pub struct Plan {
     /// Content-addressed id of the validated transfer.
-    pub transfer_id: EnvelopeId,
+    pub transfer_id: TransferId,
     /// Postings the consumer must spend (mark `Spent`).
     pub postings_to_deactivate: Vec<PostingId>,
     /// New postings to persist.
@@ -322,11 +322,11 @@ pub fn validate_and_plan(input: PlanInput<'_>) -> Result<Plan, ValidationError>
     let consumed_by_id: HashMap<PostingId, &Posting> =
         input.consumed_postings.iter().map(|p| (p.id, p)).collect();
 
-    // 3. Every consumed posting exists. Its lifecycle state (not already
-    // spent / owned by this saga) is not decidable here: a `Posting` carries no
-    // state and this check is a snapshot-in-time read. The authoritative
-    // double-spend guard is the reserve CAS plus `consume_reserved` in the
-    // finalize step (ADR-0021 maps the full commit-safety invariant).
+    // 3. Every consumed posting exists. Whether it is still unspent is not
+    // decidable here: a `Posting` carries no state and this check is a
+    // snapshot-in-time read. The authoritative double-spend guard is the
+    // commit transaction's own delete (ADR-0021 maps the full commit-safety
+    // invariant).
     for pid in envelope.consumes() {
         consumed_by_id
             .get(pid)
@@ -651,7 +651,7 @@ mod tests {
     #[test]
     fn posting_not_found() {
         let missing_pid = PostingId {
-            transfer: EnvelopeId([0; 32]),
+            transfer: TransferId([0; 32]),
             index: 0,
         };
         let envelope = Envelope {
@@ -722,7 +722,7 @@ mod tests {
     #[test]
     fn no_overdraft_exceeded() {
         let pid = PostingId {
-            transfer: EnvelopeId([1; 32]),
+            transfer: TransferId([1; 32]),
             index: 0,
         };
         let posting = Posting {
@@ -773,7 +773,7 @@ mod tests {
     #[test]
     fn overdraft_may_spend_past_positive_balance() {
         let pid = PostingId {
-            transfer: EnvelopeId([1; 32]),
+            transfer: TransferId([1; 32]),
             index: 0,
         };
         let posting = Posting {
@@ -819,7 +819,7 @@ mod tests {
     #[test]
     fn debit_must_not_exceed_credit_rejects_negative_projection() {
         let pid = PostingId {
-            transfer: EnvelopeId([1; 32]),
+            transfer: TransferId([1; 32]),
             index: 0,
         };
         let posting = Posting {
@@ -867,7 +867,7 @@ mod tests {
     #[test]
     fn overdraft_allows_negative_balance() {
         let pid = PostingId {
-            transfer: EnvelopeId([1; 32]),
+            transfer: TransferId([1; 32]),
             index: 0,
         };
         let posting = Posting {
@@ -912,7 +912,7 @@ mod tests {
     #[test]
     fn duplicate_consumed_posting_rejected() {
         let pid = PostingId {
-            transfer: EnvelopeId([1; 32]),
+            transfer: TransferId([1; 32]),
             index: 0,
         };
         let envelope = Envelope {
@@ -942,7 +942,7 @@ mod tests {
     fn internal_transfer_with_change() {
         // account1 has a 100 posting, sends 60 to account2, gets 40 change
         let pid = PostingId {
-            transfer: EnvelopeId([1; 32]),
+            transfer: TransferId([1; 32]),
             index: 0,
         };
         let posting = Posting {
@@ -1236,7 +1236,7 @@ mod tests {
         // must appear even though the envelope's creates never name it as a
         // debit source directly.
         let pid = PostingId {
-            transfer: EnvelopeId([1; 32]),
+            transfer: TransferId([1; 32]),
             index: 0,
         };
         let posting = Posting {
@@ -1288,11 +1288,11 @@ mod tests {
         // accounts 2 and 3. Balance keys are per (owner, asset), so account 1
         // contributes one key per asset it spends.
         let pid_a = PostingId {
-            transfer: EnvelopeId([1; 32]),
+            transfer: TransferId([1; 32]),
             index: 0,
         };
         let pid_b = PostingId {
-            transfer: EnvelopeId([2; 32]),
+            transfer: TransferId([2; 32]),
             index: 0,
         };
         let consumed = vec![

+ 4 - 5
crates/kuatia-dashboard/src/data.rs

@@ -16,7 +16,7 @@ use kuatia::error::LedgerError;
 use kuatia::ledger::Ledger;
 use kuatia_core::{Account, AccountId, AssetId, Cent, PostingId, PostingState};
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
-use kuatia_storage::store::{EnvelopeRecord, TransferQuery};
+use kuatia_storage::store::{TransferQuery, TransferRecord};
 use serde::Serialize;
 use tera::Tera;
 
@@ -156,7 +156,7 @@ async fn account_dto(state: &AppState, account: &Account) -> Result<AccountDto,
     })
 }
 
-fn transfer_dto(record: &EnvelopeRecord) -> TransferDto {
+fn transfer_dto(record: &TransferRecord) -> TransferDto {
     let legs = record
         .envelope
         .creates
@@ -253,11 +253,10 @@ pub async fn accounts(state: &AppState) -> Result<Vec<AccountDto>, ApiError> {
     Ok(out)
 }
 
-/// Human-readable label for a posting's derived lifecycle state.
+/// Human-readable label for a posting's derived state.
 fn posting_state_label(state: &PostingState) -> &'static str {
     match state {
-        PostingState::Active => "Active",
-        PostingState::Reserved(_) => "Reserved",
+        PostingState::Live => "Live",
         PostingState::Spent => "Spent",
         PostingState::Missing => "Missing",
     }

+ 3 - 3
crates/kuatia-dashboard/static/dashboard.css

@@ -232,9 +232,9 @@ table.grid tbody tr:hover {
 .flag.closed { background: #4a2a2a; color: #e8736b; }
 .flag.sub { background: #2f3a2b; color: #a6cf7f; }
 
-.status.Active { color: var(--pos); }
-.status.PendingInactive { color: #e0b25a; }
-.status.Inactive { color: var(--muted); }
+.status.Live { color: var(--pos); }
+.status.Spent { color: var(--muted); }
+.status.Missing { color: #e0b25a; }
 
 /* Money */
 .money {

+ 0 - 80
crates/kuatia-storage-sql/src/account.rs

@@ -1,7 +1,6 @@
 //! [`AccountStore`]: append-only account versions with a head pointer.
 
 use async_trait::async_trait;
-use sqlx::Row;
 
 use kuatia_storage::error::StoreError;
 use kuatia_storage::store::*;
@@ -97,85 +96,6 @@ impl AccountStore for SqlStore {
         Ok(1)
     }
 
-    async fn append_account_version(&self, account: Account) -> Result<u64, StoreError> {
-        // Pessimistic locking: inside one transaction, lock the account's head
-        // row with `SELECT ... FOR UPDATE` so a concurrent appender waits here
-        // until we commit, then check the version, append the new immutable row,
-        // and move the head. `ON CONFLICT` is the portable backstop (SQLite has
-        // no `FOR UPDATE`, and it covers the append phantom-insert a row lock
-        // does not). The head is maintained by delete + insert, never `UPDATE`,
-        // so the write path issues only inserts and deletes.
-        let lock = self.dialect.lock_clause();
-        let mut tx = self
-            .pool
-            .begin()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-
-        // A guarded write: no such account, or a version that is not exactly one
-        // past the head, matches nothing and reports 0. This is what keeps the
-        // chain gap-free (a stale or skipped version never lands) and makes a
-        // replay of an already-applied version a no-op.
-        let current = sqlx::query(&format!(
-            "SELECT version FROM account_head WHERE id = $1 AND subaccount = $2{lock}"
-        ))
-        .bind(account.id.id)
-        .bind(account.id.sub)
-        .fetch_optional(&mut *tx)
-        .await
-        .map_err(|e| StoreError::Internal(e.to_string()))?;
-        let Some(current) = current else {
-            return Ok(0);
-        };
-
-        let current_version: i64 = current
-            .try_get("version")
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        let expected = current_version
-            .checked_add(1)
-            .ok_or_else(|| StoreError::Internal("account version overflow".to_string()))?;
-
-        if account.version as i64 != expected {
-            return Ok(0);
-        }
-
-        let res = 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(account.id.id)
-            .bind(account.id.sub)
-            .bind(account.version as i64)
-            .bind(account.flags.bits() as i32)
-            .bind(account.book.0)
-            .bind(serialize_json(&account.metadata)?)
-            .execute(&mut *tx)
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        if res.rows_affected() == 0 {
-            return Ok(0);
-        }
-
-        // Move the head to the new version (delete + insert, never update).
-        sqlx::query("DELETE FROM account_head WHERE id = $1 AND subaccount = $2")
-            .bind(account.id.id)
-            .bind(account.id.sub)
-            .execute(&mut *tx)
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        sqlx::query("INSERT INTO account_head (id, subaccount, version) VALUES ($1, $2, $3)")
-            .bind(account.id.id)
-            .bind(account.id.sub)
-            .bind(account.version as i64)
-            .execute(&mut *tx)
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-
-        tx.commit()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        Ok(1)
-    }
-
     async fn get_account_history(&self, id: &AccountId) -> Result<Vec<Account>, StoreError> {
         let rows = sqlx::query(
             "SELECT * FROM accounts WHERE id = $1 AND subaccount = $2 ORDER BY version ASC",

+ 8 - 8
crates/kuatia-storage-sql/src/commit.rs

@@ -24,7 +24,7 @@ use kuatia_types::*;
 use crate::SqlStore;
 use crate::posting::{MAX_IDS_PER_QUERY, id_predicate, live_balance_sql};
 use crate::row::{
-    bind_money, deserialize_json, envelope_id_to_hex, row_to_account, row_to_cent, serialize_json,
+    bind_money, deserialize_json, row_to_account, row_to_cent, serialize_json, transfer_id_to_hex,
 };
 
 fn internal(e: impl std::fmt::Display) -> StoreError {
@@ -126,7 +126,7 @@ fn bind_ids<'q>(
 ) -> sqlx::query::Query<'q, sqlx::Any, sqlx::any::AnyArguments<'q>> {
     for id in ids {
         q = q
-            .bind(envelope_id_to_hex(&id.transfer))
+            .bind(transfer_id_to_hex(&id.transfer))
             .bind(id.index as i16);
     }
     q
@@ -138,7 +138,7 @@ impl CommitStore for SqlStore {
         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);
+        let tid_hex = transfer_id_to_hex(&req.transfer_id);
 
         // Idempotency: an already-committed transfer returns its receipt.
         if let Some(row) = sqlx::query(&format!(
@@ -181,7 +181,7 @@ impl CommitStore for SqlStore {
         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}",
+                "SELECT transfer_id, idx, owner, subaccount, asset FROM live_postings WHERE ({}){lock}",
                 id_predicate(chunk.len(), 1)
             );
             let rows = bind_ids(sqlx::query(&sql), chunk)
@@ -204,7 +204,7 @@ impl CommitStore for SqlStore {
         if let Some(missing) = req
             .consume
             .iter()
-            .find(|id| !present.contains(&(envelope_id_to_hex(&id.transfer), id.index as i16)))
+            .find(|id| !present.contains(&(transfer_id_to_hex(&id.transfer), id.index as i16)))
         {
             return Ok(CommitOutcome::Rejected(CommitRejection::DoubleSpend(
                 *missing,
@@ -212,7 +212,7 @@ impl CommitStore for SqlStore {
         }
         for chunk in req.consume.chunks(MAX_IDS_PER_QUERY) {
             let sql = format!(
-                "DELETE FROM live_postings WHERE ({}) AND reservation IS NULL",
+                "DELETE FROM live_postings WHERE ({})",
                 id_predicate(chunk.len(), 1)
             );
             bind_ids(sqlx::query(&sql), chunk)
@@ -223,7 +223,7 @@ impl CommitStore for SqlStore {
 
         // Insert and activate the created postings.
         for p in req.create {
-            let hex = envelope_id_to_hex(&p.id.transfer);
+            let hex = transfer_id_to_hex(&p.id.transfer);
             let sql = format!(
                 "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ($1, $2, $3, $4, $5, {}) ON CONFLICT (transfer_id, idx) DO NOTHING",
                 self.dialect.money_bind(6)
@@ -239,7 +239,7 @@ impl CommitStore for SqlStore {
                 .await
                 .map_err(internal)?;
             let sql = format!(
-                "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ($1, $2, $3, $4, $5, {}, NULL) ON CONFLICT (transfer_id, idx) DO NOTHING",
+                "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ($1, $2, $3, $4, $5, {}) ON CONFLICT (transfer_id, idx) DO NOTHING",
                 self.dialect.money_bind(6)
             );
             let q = sqlx::query(&sql)

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

@@ -109,6 +109,10 @@ impl SqlStore {
                     sqlite: include_str!("migrations/011_native_amounts.sqlite.sql"),
                 },
             ),
+            (
+                "012_drop_reservation",
+                Migration::Shared(include_str!("migrations/012_drop_reservation.sql")),
+            ),
         ];
 
         for (name, migration) in migrations {

+ 7 - 0
crates/kuatia-storage-sql/src/migrations/012_drop_reservation.sql

@@ -0,0 +1,7 @@
+-- Nothing can set `live_postings.reservation` any more: the reserve and release
+-- primitives are gone and the commit transaction treats membership of this table
+-- as the whole of a posting's liveness (ADR-0025). A surviving row that still
+-- carries a token becomes spendable, which is correct: it was never consumed, so
+-- it always counted toward the balance, and the write-ahead saga that owned the
+-- token no longer exists to finalize or release it.
+ALTER TABLE live_postings DROP COLUMN reservation;

+ 38 - 256
crates/kuatia-storage-sql/src/posting.rs

@@ -1,10 +1,10 @@
 //! [`PostingStore`]: the immutable posting record plus one `live_postings` hot
-//! table whose `reservation` column derives each posting's lifecycle state.
+//! table whose membership is each posting's state.
 //!
-//! A posting is in `live_postings` while it is spendable or reserved:
-//! `reservation IS NULL` = Active, `reservation = rid` = Reserved by that saga.
-//! Once consumed the row is deleted, leaving the posting only in the immutable
-//! `postings` table (= Spent). See ADR-0022 (merged hot index) and ADR-0016.
+//! A posting is in `live_postings` while it is spendable. Once consumed the row
+//! is deleted, leaving the posting only in the immutable `postings` table, so
+//! the two tables never disagree about what is spent. See ADR-0022 (merged hot
+//! index) and ADR-0016.
 
 use std::collections::HashMap;
 
@@ -18,7 +18,7 @@ use kuatia_types::*;
 
 use crate::SqlStore;
 use crate::dialect::Dialect;
-use crate::row::{bind_money, envelope_id_to_hex, row_to_cent, row_to_posting};
+use crate::row::{row_to_cent, row_to_posting, transfer_id_to_hex};
 
 /// The live-balance aggregate, shared by [`PostingStore::live_balance`] and the
 /// in-transaction overdraft floor in `commit`, so both read the balance the same
@@ -32,16 +32,12 @@ pub(crate) fn live_balance_sql(dialect: Dialect) -> String {
     )
 }
 
-/// The `(source_table, state_predicate)` a posting read of the given filter
-/// targets. Live/Active/Reserved read the single `live_postings` hot table,
-/// narrowed by the `reservation` column; `All` reads the immutable record. No
-/// UNION: the live set is one table.
-fn filter_source(filter: PostingFilter) -> (&'static str, &'static str) {
+/// The source table a posting read of the given filter targets. No UNION and no
+/// predicate: the live set is exactly one table's rows.
+fn filter_source(filter: PostingFilter) -> &'static str {
     match filter {
-        PostingFilter::Active => ("live_postings", " AND reservation IS NULL"),
-        PostingFilter::Reserved => ("live_postings", " AND reservation IS NOT NULL"),
-        PostingFilter::Live => ("live_postings", ""),
-        PostingFilter::All => ("postings", ""),
+        PostingFilter::Live => "live_postings",
+        PostingFilter::All => "postings",
     }
 }
 
@@ -93,7 +89,7 @@ impl PostingStore for SqlStore {
             let mut q = sqlx::query(&sql);
             for id in chunk {
                 q = q
-                    .bind(envelope_id_to_hex(&id.transfer))
+                    .bind(transfer_id_to_hex(&id.transfer))
                     .bind(id.index as i16);
             }
             let rows = q
@@ -105,7 +101,7 @@ impl PostingStore for SqlStore {
             for row in &rows {
                 let posting = row_to_posting(self.dialect, row)?;
                 let key = (
-                    envelope_id_to_hex(&posting.id.transfer),
+                    transfer_id_to_hex(&posting.id.transfer),
                     posting.id.index as i16,
                 );
                 found.insert(key, posting);
@@ -116,7 +112,7 @@ impl PostingStore for SqlStore {
         // (matching the per-id lookup's `NotFound` semantics).
         let mut result = Vec::with_capacity(ids.len());
         for id in ids {
-            let key = (envelope_id_to_hex(&id.transfer), id.index as i16);
+            let key = (transfer_id_to_hex(&id.transfer), id.index as i16);
             let posting = found
                 .get(&key)
                 .ok_or_else(|| StoreError::NotFound(format!("posting {id:?}")))?;
@@ -134,9 +130,8 @@ impl PostingStore for SqlStore {
     ) -> Result<Vec<Posting>, StoreError> {
         // Build the predicate dynamically: `sub == None` spans every subaccount
         // of `id`, `Some(s)` restricts to one. The subaccount is compared only
-        // for equality, never as a magnitude. The filter picks the source table
-        // and, for the live table, the `reservation` state predicate.
-        let (source, state) = filter_source(filter);
+        // for equality, never as a magnitude.
+        let source = filter_source(filter);
         let mut sql = format!(
             "SELECT {} FROM {source} WHERE owner = $1",
             self.dialect.posting_columns()
@@ -149,7 +144,6 @@ impl PostingStore for SqlStore {
         if asset.is_some() {
             sql.push_str(&format!(" AND asset = ${placeholder}"));
         }
-        sql.push_str(state);
         // Deterministic order by the posting primary key, matching
         // `query_postings`, so callers (and pagination built on top) see a
         // stable sequence.
@@ -188,12 +182,11 @@ impl PostingStore for SqlStore {
             return Ok(Vec::new());
         }
 
-        // Two set-based queries per chunk (was three, before the hot tables were
-        // merged): the live table carries both Active (`reservation IS NULL`) and
-        // Reserved (`reservation = rid`) in one row, and `postings` decides Spent
-        // vs Missing for ids absent from the live set. Reuses the portable
-        // `id_predicate` (an OR of equality pairs; row-value `IN` is not portable
-        // across SQLite and PostgreSQL), binding each id as `(hex, idx)`.
+        // Two set-based queries per chunk: membership of the live table decides
+        // Live, and `postings` decides Spent vs Missing for ids absent from it.
+        // Reuses the portable `id_predicate` (an OR of equality pairs; row-value
+        // `IN` is not portable across SQLite and PostgreSQL), binding each id as
+        // `(hex, idx)`.
 
         // Key membership by the same `(hex, idx)` values that were bound, so the
         // per-id lookup below matches without decoding transfer ids back.
@@ -207,23 +200,20 @@ impl PostingStore for SqlStore {
             Ok((transfer_id, idx))
         };
 
-        // `live` maps each present id to its reservation: `None` = Active,
-        // `Some(rid)` = Reserved. `present` is every id in the immutable record,
-        // used to tell Spent (present, not live) from Missing (absent).
-        let mut live: HashMap<(String, i16), Option<i64>> = HashMap::new();
+        // `present` is every id in the immutable record, which is what tells
+        // Spent (present, not live) from Missing (absent).
+        let mut live: std::collections::HashSet<(String, i16)> = std::collections::HashSet::new();
         let mut present: std::collections::HashSet<(String, i16)> =
             std::collections::HashSet::new();
 
         for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
             let predicate = id_predicate(chunk.len(), 1);
 
-            let live_sql = format!(
-                "SELECT transfer_id, idx, reservation FROM live_postings WHERE {predicate}"
-            );
+            let live_sql = format!("SELECT transfer_id, idx FROM live_postings WHERE {predicate}");
             let mut live_q = sqlx::query(&live_sql);
             for id in chunk {
                 live_q = live_q
-                    .bind(envelope_id_to_hex(&id.transfer))
+                    .bind(transfer_id_to_hex(&id.transfer))
                     .bind(id.index as i16);
             }
             let live_rows = live_q
@@ -231,18 +221,14 @@ impl PostingStore for SqlStore {
                 .await
                 .map_err(|e| StoreError::Internal(e.to_string()))?;
             for row in &live_rows {
-                // `reservation` is nullable: NULL decodes to `None` = Active.
-                let rid: Option<i64> = row
-                    .try_get("reservation")
-                    .map_err(|e| StoreError::Internal(e.to_string()))?;
-                live.insert(row_key(row)?, rid);
+                live.insert(row_key(row)?);
             }
 
             let present_sql = format!("SELECT transfer_id, idx FROM postings WHERE {predicate}");
             let mut present_q = sqlx::query(&present_sql);
             for id in chunk {
                 present_q = present_q
-                    .bind(envelope_id_to_hex(&id.transfer))
+                    .bind(transfer_id_to_hex(&id.transfer))
                     .bind(id.index as i16);
             }
             let present_rows = present_q
@@ -254,16 +240,17 @@ impl PostingStore for SqlStore {
             }
         }
 
-        // Reconstruct each id's state in input order, preserving the active >
-        // reserved > spent > missing precedence of the original probes.
+        // Reconstruct each id's state in input order, live before spent before
+        // missing, so a duplicated id resolves to the same state both times.
         let mut out = Vec::with_capacity(ids.len());
         for id in ids {
-            let key = (envelope_id_to_hex(&id.transfer), id.index as i16);
-            out.push(match live.get(&key) {
-                Some(None) => PostingState::Active,
-                Some(Some(rid)) => PostingState::Reserved(ReservationId::new(*rid)),
-                None if present.contains(&key) => PostingState::Spent,
-                None => PostingState::Missing,
+            let key = (transfer_id_to_hex(&id.transfer), id.index as i16);
+            out.push(if live.contains(&key) {
+                PostingState::Live
+            } else if present.contains(&key) {
+                PostingState::Spent
+            } else {
+                PostingState::Missing
             });
         }
         Ok(out)
@@ -271,7 +258,7 @@ impl PostingStore for SqlStore {
 
     async fn query_postings(&self, query: &PostingQuery) -> Result<Page<Posting>, StoreError> {
         let (where_clause, count_clause) = {
-            let (source, state) = filter_source(query.filter);
+            let source = filter_source(query.filter);
             let mut w = String::from("WHERE owner = $1");
             let mut idx = 2u32;
             if query.sub.is_some() {
@@ -281,7 +268,6 @@ impl PostingStore for SqlStore {
             if query.asset.is_some() {
                 w.push_str(&format!(" AND asset = ${idx}"));
             }
-            w.push_str(state);
             let c = format!("SELECT COUNT(*) as cnt FROM {source} {w}");
             let (offset, limit) = kuatia_storage::query::window(query.offset, query.limit);
             // Order by the posting primary key so pagination is deterministic:
@@ -336,208 +322,4 @@ impl PostingStore for SqlStore {
             total: total as u64,
         })
     }
-
-    async fn reserve_postings(
-        &self,
-        ids: &[PostingId],
-        reservation: ReservationId,
-    ) -> Result<u64, StoreError> {
-        // Dumb instruction over the whole id set: flip each still-Active row's
-        // `reservation` from NULL to this saga's id. `WHERE reservation IS NULL`
-        // is the atomic single-winner claim: concurrent reserves serialize on the
-        // row lock, and the loser's predicate no longer matches, so exactly one
-        // wins each contended id. `rows_affected` is the number claimed; an
-        // already-reserved or spent id does not match and is not counted.
-        if ids.is_empty() {
-            return Ok(0);
-        }
-        let mut tx = self
-            .pool
-            .begin()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-
-        // Chunked so a large id set stays under the bind-parameter limit; all
-        // chunks share one transaction so the whole claim is atomic.
-        let mut claimed: u64 = 0;
-        for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
-            // Reservation is $1; each id pair follows starting at $2.
-            let sql = format!(
-                "UPDATE live_postings SET reservation = $1 WHERE ({}) AND reservation IS NULL",
-                id_predicate(chunk.len(), 2)
-            );
-            let mut q = sqlx::query(&sql).bind(reservation.0);
-            for id in chunk {
-                q = q
-                    .bind(envelope_id_to_hex(&id.transfer))
-                    .bind(id.index as i16);
-            }
-            let res = q
-                .execute(&mut *tx)
-                .await
-                .map_err(|e| StoreError::Internal(e.to_string()))?;
-            claimed += res.rows_affected();
-        }
-
-        tx.commit()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        Ok(claimed)
-    }
-
-    async fn release_postings(
-        &self,
-        ids: &[PostingId],
-        reservation: ReservationId,
-    ) -> Result<u64, StoreError> {
-        // Dumb instruction over the whole id set: clear the `reservation` of the
-        // rows this saga holds, returning them to Active. `rows_affected` is the
-        // number released; an id already Active or reserved by another saga does
-        // not match `reservation = rid` and is left untouched.
-        if ids.is_empty() {
-            return Ok(0);
-        }
-        let mut tx = self
-            .pool
-            .begin()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-
-        let mut released: u64 = 0;
-        for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
-            // Reservation is $1; each id pair follows starting at $2.
-            let sql = format!(
-                "UPDATE live_postings SET reservation = NULL WHERE ({}) AND reservation = $1",
-                id_predicate(chunk.len(), 2)
-            );
-            let mut q = sqlx::query(&sql).bind(reservation.0);
-            for id in chunk {
-                q = q
-                    .bind(envelope_id_to_hex(&id.transfer))
-                    .bind(id.index as i16);
-            }
-            let res = q
-                .execute(&mut *tx)
-                .await
-                .map_err(|e| StoreError::Internal(e.to_string()))?;
-            released += res.rows_affected();
-        }
-
-        tx.commit()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        Ok(released)
-    }
-
-    async fn deactivate_postings(
-        &self,
-        ids: &[PostingId],
-        reservation: Option<ReservationId>,
-    ) -> Result<u64, StoreError> {
-        // Dumb instruction over the whole id set: DELETE the ids from the live
-        // table so they become spent (present only in the immutable `postings`).
-        // The raw path removes still-Active rows (`reservation IS NULL`); the saga
-        // path removes only the rows reserved by `rid`. `rows_affected` is the
-        // count; the caller interprets a shortfall. Chunked under one transaction.
-        if ids.is_empty() {
-            return Ok(0);
-        }
-        let mut tx = self
-            .pool
-            .begin()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        let mut removed: u64 = 0;
-        for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
-            let (sql, rid) = match reservation {
-                // Raw path: remove still-Active rows.
-                None => (
-                    format!(
-                        "DELETE FROM live_postings WHERE ({}) AND reservation IS NULL",
-                        id_predicate(chunk.len(), 1)
-                    ),
-                    None,
-                ),
-                // Saga path: remove only the rows reserved by `rid`.
-                Some(rid) => (
-                    format!(
-                        "DELETE FROM live_postings WHERE ({}) AND reservation = $1",
-                        id_predicate(chunk.len(), 2)
-                    ),
-                    Some(rid),
-                ),
-            };
-            let mut q = sqlx::query(&sql);
-            if let Some(rid) = rid {
-                q = q.bind(rid.0);
-            }
-            for id in chunk {
-                q = q
-                    .bind(envelope_id_to_hex(&id.transfer))
-                    .bind(id.index as i16);
-            }
-            let res = q
-                .execute(&mut *tx)
-                .await
-                .map_err(|e| StoreError::Internal(e.to_string()))?;
-            removed += res.rows_affected();
-        }
-        tx.commit()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        Ok(removed)
-    }
-
-    async fn insert_postings(&self, postings: &[Posting]) -> Result<u64, StoreError> {
-        // Dumb instruction: insert each posting into the immutable table and, only
-        // when the row was newly inserted, add it to the live table as Active
-        // (reservation NULL). Return the count of immutable rows inserted. The
-        // newness gate stops a replayed finalize from re-activating a since-spent
-        // posting.
-        let mut tx = self
-            .pool
-            .begin()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        let mut inserted: u64 = 0;
-        for posting in postings {
-            let hex = envelope_id_to_hex(&posting.id.transfer);
-            let sql = format!(
-                "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ($1, $2, $3, $4, $5, {}) ON CONFLICT (transfer_id, idx) DO NOTHING",
-                self.dialect.money_bind(6)
-            );
-            let q = sqlx::query(&sql)
-                .bind(hex.clone())
-                .bind(posting.id.index as i16)
-                .bind(posting.owner.id)
-                .bind(posting.owner.sub)
-                .bind(posting.asset.0 as i32);
-            let res = bind_money(q, self.dialect, posting.value)
-                .execute(&mut *tx)
-                .await
-                .map_err(|e| StoreError::Internal(e.to_string()))?;
-            if res.rows_affected() == 1 {
-                // Activate a full copy (reservation NULL) so spendable reads never merge.
-                let sql = format!(
-                    "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ($1, $2, $3, $4, $5, {}, NULL) ON CONFLICT (transfer_id, idx) DO NOTHING",
-                    self.dialect.money_bind(6)
-                );
-                let q = sqlx::query(&sql)
-                    .bind(hex)
-                    .bind(posting.id.index as i16)
-                    .bind(posting.owner.id)
-                    .bind(posting.owner.sub)
-                    .bind(posting.asset.0 as i32);
-                bind_money(q, self.dialect, posting.value)
-                    .execute(&mut *tx)
-                    .await
-                    .map_err(|e| StoreError::Internal(e.to_string()))?;
-                inserted += 1;
-            }
-        }
-        tx.commit()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        Ok(inserted)
-    }
 }

+ 7 - 7
crates/kuatia-storage-sql/src/row.rs

@@ -74,9 +74,9 @@ pub(crate) fn deserialize_json<T: serde::de::DeserializeOwned>(s: &str) -> Resul
     serde_json::from_str(s).map_err(|e| StoreError::Internal(format!("bad json: {e}")))
 }
 
-/// Lower-case hex encoding. Binary identifiers (content-addressed hashes) and
-/// opaque saga bytes are stored as hex `TEXT` so a row is legible in any SQL
-/// client and matches the hex form used in logs and `Debug` output.
+/// Lower-case hex encoding. Binary identifiers (content-addressed hashes) are
+/// stored as hex `TEXT` so a row is legible in any SQL client and matches the
+/// hex form used in logs and `Debug` output.
 pub(crate) fn to_hex(bytes: &[u8]) -> String {
     const HEX: &[u8; 16] = b"0123456789abcdef";
     let mut s = String::with_capacity(bytes.len() * 2);
@@ -100,16 +100,16 @@ pub(crate) fn from_hex(s: &str) -> Result<Vec<u8>, StoreError> {
         .collect()
 }
 
-pub(crate) fn envelope_id_to_hex(id: &EnvelopeId) -> String {
+pub(crate) fn transfer_id_to_hex(id: &TransferId) -> String {
     to_hex(&id.0)
 }
 
-pub(crate) fn envelope_id_from_hex(s: &str) -> Result<EnvelopeId, StoreError> {
+pub(crate) fn transfer_id_from_hex(s: &str) -> Result<TransferId, StoreError> {
     let bytes = from_hex(s)?;
     let arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
         StoreError::Internal(format!("expected 32-byte id, got {} bytes", bytes.len()))
     })?;
-    Ok(EnvelopeId(arr))
+    Ok(TransferId(arr))
 }
 
 pub(crate) fn row_to_account(row: &AnyRow) -> Result<Account, StoreError> {
@@ -161,7 +161,7 @@ pub(crate) fn row_to_posting(dialect: Dialect, row: &AnyRow) -> Result<Posting,
 
     Ok(Posting {
         id: PostingId {
-            transfer: envelope_id_from_hex(&transfer_id)?,
+            transfer: transfer_id_from_hex(&transfer_id)?,
             index: idx as u16,
         },
         owner: AccountId::with_sub(owner, subaccount),

+ 8 - 53
crates/kuatia-storage-sql/src/transfer.rs

@@ -8,13 +8,13 @@ use kuatia_storage::store::*;
 use kuatia_types::*;
 
 use crate::SqlStore;
-use crate::row::{deserialize_json, envelope_id_to_hex, serialize_json};
+use crate::row::{deserialize_json, transfer_id_to_hex};
 
 #[async_trait]
 impl TransferStore for SqlStore {
-    async fn get_transfer(&self, id: &EnvelopeId) -> Result<Option<EnvelopeRecord>, StoreError> {
+    async fn get_transfer(&self, id: &TransferId) -> Result<Option<TransferRecord>, StoreError> {
         let row = sqlx::query("SELECT transfer, receipt, created_at FROM transfers WHERE id = $1")
-            .bind(envelope_id_to_hex(id))
+            .bind(transfer_id_to_hex(id))
             .fetch_optional(&self.pool)
             .await
             .map_err(|e| StoreError::Internal(e.to_string()))?;
@@ -31,7 +31,7 @@ impl TransferStore for SqlStore {
                 let created_at: i64 = row
                     .try_get("created_at")
                     .map_err(|e| StoreError::Internal(e.to_string()))?;
-                Ok(Some(EnvelopeRecord {
+                Ok(Some(TransferRecord {
                     envelope: deserialize_json(&transfer_json)?,
                     receipt: deserialize_json(&receipt_json)?,
                     created_at,
@@ -40,56 +40,11 @@ impl TransferStore for SqlStore {
         }
     }
 
-    async fn store_transfer(
-        &self,
-        record: EnvelopeRecord,
-        involved: &[AccountId],
-    ) -> Result<u64, StoreError> {
-        let tid = record.receipt.transfer_id;
-        let tid_hex = envelope_id_to_hex(&tid);
-        let transfer_json = serialize_json(&record.envelope)?;
-        let receipt_json = serialize_json(&record.receipt)?;
-
-        let mut tx = self
-            .pool
-            .begin()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-
-        let res = 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(record.created_at)
-            .bind(record.envelope.book().0)
-            .execute(&mut *tx)
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        let inserted = res.rows_affected();
-
-        // Index every involved account (caller supplies the set; storage does no
-        // computation). Idempotent so a replay is harmless.
-        for account in 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(|e| StoreError::Internal(e.to_string()))?;
-        }
-
-        tx.commit()
-            .await
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
-        Ok(inserted)
-    }
-
     async fn get_transfers_for_account(
         &self,
         id: i64,
         sub: Option<i64>,
-    ) -> Result<Vec<EnvelopeRecord>, StoreError> {
+    ) -> Result<Vec<TransferRecord>, StoreError> {
         // `sub == None` spans every subaccount of `id`; `Some(s)` restricts to
         // one. The subaccount is matched only for equality.
         let mut sql = String::from(
@@ -120,7 +75,7 @@ impl TransferStore for SqlStore {
             let created_at: i64 = row
                 .try_get("created_at")
                 .map_err(|e| StoreError::Internal(e.to_string()))?;
-            result.push(EnvelopeRecord {
+            result.push(TransferRecord {
                 envelope: deserialize_json(&transfer_json)?,
                 receipt: deserialize_json(&receipt_json)?,
                 created_at,
@@ -132,7 +87,7 @@ impl TransferStore for SqlStore {
     async fn query_transfers(
         &self,
         query: &TransferQuery,
-    ) -> Result<Page<EnvelopeRecord>, StoreError> {
+    ) -> Result<Page<TransferRecord>, StoreError> {
         // Push every predicate into SQL so the database returns only the
         // requested page, not the whole table (or the account's whole history).
         // This is what bounds the `balance()` tail scan by the watermark
@@ -217,7 +172,7 @@ impl TransferStore for SqlStore {
             let created_at: i64 = row
                 .try_get("created_at")
                 .map_err(|e| StoreError::Internal(e.to_string()))?;
-            items.push(EnvelopeRecord {
+            items.push(TransferRecord {
                 envelope: deserialize_json(&transfer_json)?,
                 receipt: deserialize_json(&receipt_json)?,
                 created_at,

+ 42 - 5
crates/kuatia-storage-sql/tests/postgres.rs

@@ -18,6 +18,7 @@
 use std::sync::atomic::{AtomicU64, Ordering};
 
 use kuatia_storage::store::PostingStore;
+use kuatia_storage::store_tests::seed_live;
 use kuatia_storage_sql::SqlStore;
 use kuatia_types::*;
 use sqlx::{Any, Pool, Row};
@@ -69,17 +70,14 @@ async fn amount_columns_are_numeric() {
     let (store, pool) = new_store_with_pool().await;
     let posting = Posting::new(
         PostingId {
-            transfer: EnvelopeId([0x3f; 32]),
+            transfer: TransferId([0x3f; 32]),
             index: 0,
         },
         AccountId::new(1),
         AssetId::new(1),
         Cent::from(-4321),
     );
-    store
-        .insert_postings(std::slice::from_ref(&posting))
-        .await
-        .unwrap();
+    seed_live(&store, 0x3f, std::slice::from_ref(&posting)).await;
 
     let got = store.get_postings(&[posting.id]).await.unwrap();
     assert_eq!(got[0].value, Cent::from(-4321));
@@ -113,6 +111,45 @@ async fn amount_columns_are_numeric() {
     }
 }
 
+/// The 012 migration drops the reservation column and leaves every live row
+/// live, including one that still carried a token: it was never consumed, so it
+/// must stay spendable and keep counting toward the balance.
+#[tokio::test]
+async fn migration_012_drops_reservation_and_keeps_rows_live() {
+    let (_store, pool) = new_store_with_pool().await;
+
+    // Put the column back, with a reserved row in it, then replay 012 alone.
+    for stmt in [
+        "ALTER TABLE live_postings ADD COLUMN reservation BIGINT",
+        "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, 100, NULL)",
+        "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('bb', 0, 1, 0, 1, 250, 77)",
+        "DELETE FROM _migrations WHERE name = '012_drop_reservation'",
+    ] {
+        sqlx::query(stmt).execute(&pool).await.unwrap();
+    }
+
+    let store = SqlStore::new(pool.clone());
+    store.migrate().await.unwrap();
+
+    let columns = sqlx::query(
+        "SELECT column_name FROM information_schema.columns \
+         WHERE table_schema = current_schema() AND table_name = 'live_postings' \
+         AND column_name = 'reservation'",
+    )
+    .fetch_all(&pool)
+    .await
+    .unwrap();
+    assert!(columns.is_empty(), "the reservation column is gone");
+
+    // Both rows are still live, and the previously reserved one still sums in.
+    let row = sqlx::query("SELECT COUNT(*) AS n, CAST(SUM(value) AS TEXT) AS s FROM live_postings")
+        .fetch_one(&pool)
+        .await
+        .unwrap();
+    assert_eq!(row.try_get::<i64, _>("n").unwrap(), 2);
+    assert_eq!(row.try_get::<String, _>("s").unwrap(), "350");
+}
+
 /// The 011 migration rewrites the existing text amounts into `NUMERIC`, keeping
 /// their values (including negatives).
 #[tokio::test]

+ 89 - 33
crates/kuatia-storage-sql/tests/sqlite.rs

@@ -2,6 +2,7 @@
 #![cfg(feature = "sqlite")]
 
 use kuatia_storage::store::{AccountStore, PostingStore};
+use kuatia_storage::store_tests::{seed_live, spend_live};
 use kuatia_storage_sql::SqlStore;
 use kuatia_types::*;
 use sqlx::{Any, Pool, Row};
@@ -44,7 +45,7 @@ async fn columns_store_hex_ids_and_json_text() {
     };
     store.create_account(account).await.unwrap();
 
-    let tid = EnvelopeId([0xab; 32]);
+    let tid = TransferId([0xab; 32]);
     let posting = Posting::new(
         PostingId {
             transfer: tid,
@@ -54,7 +55,7 @@ async fn columns_store_hex_ids_and_json_text() {
         AssetId::new(1),
         Cent::from(100),
     );
-    store.insert_postings(&[posting]).await.unwrap();
+    seed_live(&store, 0xab, &[posting]).await;
 
     // The 32-byte transfer id is stored as its 64-char lower-case hex form.
     let row = sqlx::query("SELECT transfer_id FROM postings")
@@ -107,14 +108,14 @@ async fn subaccount_columns_round_trip() {
 
     let posting = Posting::new(
         PostingId {
-            transfer: EnvelopeId([0xcd; 32]),
+            transfer: TransferId([0xcd; 32]),
             index: 0,
         },
         sub,
         AssetId::new(1),
         Cent::from(500),
     );
-    store.insert_postings(&[posting]).await.unwrap();
+    seed_live(&store, 0xcd, &[posting]).await;
 
     // Filtering by the subaccount returns it; the main account holds nothing.
     let by_sub = store
@@ -254,6 +255,7 @@ async fn migration_004_backfills_index_tables() {
         "009_saga_kind",
         "010_drop_sagas",
         "011_native_amounts",
+        "012_drop_reservation",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -347,6 +349,7 @@ async fn migration_005_backfills_account_head() {
         "009_saga_kind",
         "010_drop_sagas",
         "011_native_amounts",
+        "012_drop_reservation",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -420,6 +423,7 @@ async fn migration_008_merges_live_postings() {
         "009_saga_kind",
         "010_drop_sagas",
         "011_native_amounts",
+        "012_drop_reservation",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -483,16 +487,15 @@ async fn migrate_is_idempotent() {
 
 /// The id-batch primitives chunk a large id set so it never exceeds the
 /// backend's bind-parameter limit (SQLite caps a statement at 32766 variables).
-/// A batch larger than one chunk must reserve, read, and deactivate every id
-/// exactly as a small one does.
+/// A batch larger than one chunk must be created, read, and spent exactly as a
+/// small one is. The commit's consume SELECT and DELETE are the chunked writes
+/// this guards.
 #[tokio::test]
-async fn id_batch_primitives_chunk_large_batches() {
-    // Comfortably larger than the internal chunk size so the batch spans
-    // multiple statements.
+async fn id_batches_chunk_across_reads_and_commit() {
     const N: u16 = 9000;
     let store = new_store().await;
 
-    let tid = EnvelopeId([0xcd; 32]);
+    let tid = TransferId([0xcd; 32]);
     let postings: Vec<Posting> = (0..N)
         .map(|i| {
             Posting::new(
@@ -508,29 +511,15 @@ async fn id_batch_primitives_chunk_large_batches() {
         .collect();
     let ids: Vec<PostingId> = postings.iter().map(|p| p.id).collect();
 
-    assert_eq!(
-        store.insert_postings(&postings).await.unwrap(),
-        u64::from(N)
-    );
-
-    // Reserve the whole batch in one call: every id is claimed across chunks.
-    let rid = ReservationId::new(1);
-    assert_eq!(
-        store.reserve_postings(&ids, rid).await.unwrap(),
-        u64::from(N)
-    );
+    seed_live(&store, 0xcd, &postings).await;
 
-    // Reads span chunks and return every id.
     let states = store.get_posting_states(&ids).await.unwrap();
     assert_eq!(states.len(), N as usize);
-    assert!(states.iter().all(|s| *s == PostingState::Reserved(rid)));
+    assert!(states.iter().all(|s| *s == PostingState::Live));
     assert_eq!(store.get_postings(&ids).await.unwrap().len(), N as usize);
 
-    // Deactivating the whole batch spends every id.
-    assert_eq!(
-        store.deactivate_postings(&ids, Some(rid)).await.unwrap(),
-        u64::from(N)
-    );
+    spend_live(&store, 0xce, &ids).await;
+
     let after = store.get_posting_states(&ids).await.unwrap();
     assert!(after.iter().all(|s| *s == PostingState::Spent));
 }
@@ -683,17 +672,14 @@ async fn value_beyond_i64_round_trips() {
     let value = Cent::from_str("170141183460469231731687303715884105727").unwrap();
     let posting = Posting::new(
         PostingId {
-            transfer: EnvelopeId([0x5c; 32]),
+            transfer: TransferId([0x5c; 32]),
             index: 0,
         },
         AccountId::new(1),
         AssetId::new(1),
         value,
     );
-    store
-        .insert_postings(std::slice::from_ref(&posting))
-        .await
-        .unwrap();
+    seed_live(&store, 0x5c, std::slice::from_ref(&posting)).await;
 
     let got = store.get_postings(&[posting.id]).await.unwrap();
     assert_eq!(got[0].value, value);
@@ -706,6 +692,75 @@ async fn value_beyond_i64_round_trips() {
     );
 }
 
+/// The 012 migration drops the reservation column and leaves every live row
+/// live, including one that still carried a token: it was never consumed, so it
+/// must stay spendable and keep counting toward the balance.
+#[tokio::test]
+async fn migration_012_drops_reservation_and_keeps_rows_live() {
+    let pool = new_pool().await;
+
+    // Post-011 shape: native blob amounts, reservation column still present.
+    for ddl in [
+        "CREATE TABLE postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value BLOB NOT NULL, PRIMARY KEY (transfer_id, idx))",
+        "CREATE TABLE live_postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value BLOB NOT NULL, reservation BIGINT, PRIMARY KEY (transfer_id, idx))",
+    ] {
+        sqlx::query(ddl).execute(&pool).await.unwrap();
+    }
+    for (tid, value, reservation) in [("aa", 100i128, None), ("bb", 250i128, Some(77i64))] {
+        sqlx::query("INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ($1, 0, 1, 0, 1, $2, $3)")
+            .bind(tid)
+            .bind(encoded(value))
+            .bind(reservation)
+            .execute(&pool)
+            .await
+            .unwrap();
+    }
+
+    // Record every migration except 012 as applied so migrate() runs only 012.
+    sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
+        .execute(&pool)
+        .await
+        .unwrap();
+    for m in [
+        "001_init",
+        "002_subaccounts",
+        "003_drop_user_data",
+        "004_index_tables",
+        "005_account_head",
+        "006_drop_policy",
+        "007_balance_projection",
+        "008_live_postings",
+        "009_saga_kind",
+        "010_drop_sagas",
+        "011_native_amounts",
+    ] {
+        sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
+            .bind(m)
+            .execute(&pool)
+            .await
+            .unwrap();
+    }
+
+    let store = SqlStore::new(pool.clone());
+    store.migrate().await.unwrap();
+
+    assert!(
+        sqlx::query("SELECT reservation FROM live_postings")
+            .fetch_all(&pool)
+            .await
+            .is_err(),
+        "the reservation column is gone"
+    );
+
+    // Both rows are still live, and the previously reserved one still sums in.
+    let row = sqlx::query("SELECT COUNT(*) AS n, kuatia_i128_sum(value) AS s FROM live_postings")
+        .fetch_one(&pool)
+        .await
+        .unwrap();
+    assert_eq!(row.try_get::<i64, _>("n").unwrap(), 2);
+    assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 350);
+}
+
 /// The 011 migration rewrites the existing text amounts into the native blob
 /// encoding, keeping their values (including negatives) and the rest of the row.
 #[tokio::test]
@@ -741,6 +796,7 @@ async fn migration_011_converts_text_amounts() {
         "008_live_postings",
         "009_saga_kind",
         "010_drop_sagas",
+        "012_drop_reservation",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)

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

@@ -10,20 +10,20 @@ macro that any backend can use to validate its implementation.
 
 | Trait | Purpose |
 |-------|---------|
-| `AccountStore` | Account CRUD and versioning |
-| `PostingStore` | Posting reads + generic lifecycle primitives (`reserve`/`release`/`deactivate`/`insert`) |
-| `TransferStore` | Transfer persistence (`store_transfer`) and queries |
+| `AccountStore` | Account creation and version reads |
+| `PostingStore` | Posting reads and the live balance |
+| `TransferStore` | Committed transfer reads and queries |
 | `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 |
+| `BalanceProjectionStore` | Append-only balance cache points (ADR-0019) |
 
-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.
+Every posting and account-version write goes through `CommitStore`, which
+applies a whole transfer or a whole transition in one transaction and re-checks
+double-spend, freeze/close, and the overdraft floor inside it. A backend has no
+other way to change a posting, so no caller can leave half a transfer applied.
 
-`Store` is a blanket trait — any type implementing the sub-traits is a `Store`.
+`Store` is a blanket trait: any type implementing the sub-traits is a `Store`.
 
 ## Conformance testing
 

+ 4 - 5
crates/kuatia-storage/src/error.rs

@@ -5,11 +5,10 @@ use std::fmt;
 
 /// Errors produced by [`Store`](crate::store::Store) implementations.
 ///
-/// The store is a dumb instruction follower: writes report affected-row counts,
-/// not semantic verdicts, so there are no "posting not active"/"reservation
-/// mismatch"/"cas conflict"/"already exists"/"version conflict" variants — every
-/// caller derives those from counts. The only outcomes a write can report are a
-/// count and an I/O fault. [`Misconfigured`](Self::Misconfigured) is not a write
+/// A `StoreError` is an I/O fault, never a domain verdict: a commit reports a
+/// refusal as a typed [`CommitRejection`](crate::store::CommitRejection) and the
+/// count-returning writes report a count, so there is no "already exists" or
+/// "version conflict" variant for a caller to match on here. [`Misconfigured`](Self::Misconfigured) is not a write
 /// outcome at all: it reports that the backend was never set up correctly, which
 /// no amount of retrying will fix.
 #[derive(Debug, Clone)]

+ 2 - 2
crates/kuatia-storage/src/events.rs

@@ -3,7 +3,7 @@
 use async_trait::async_trait;
 use serde::{Deserialize, Serialize};
 
-use kuatia_types::{AccountId, EnvelopeId};
+use kuatia_types::{AccountId, TransferId};
 
 use crate::error::StoreError;
 
@@ -13,7 +13,7 @@ pub enum LedgerEventKind {
     /// A transfer was committed.
     TransferCommitted {
         /// The content-addressed id of the committed transfer.
-        transfer_id: EnvelopeId,
+        transfer_id: TransferId,
     },
     /// An account was created.
     AccountCreated {

+ 29 - 166
crates/kuatia-storage/src/mem_store.rs

@@ -3,14 +3,13 @@
 //! Accounts are stored as append-only version logs keyed by `AccountId`.
 
 use async_trait::async_trait;
-use std::collections::hash_map::Entry;
 use std::collections::{HashMap, HashSet};
 use tokio::sync::RwLock;
 
 use kuatia_types::autoid::AutoId;
 use kuatia_types::{
-    Account, AccountId, AssetId, Book, BookId, Cent, EnvelopeId, Posting, PostingFilter, PostingId,
-    PostingState, ReservationId,
+    Account, AccountId, AssetId, Book, BookId, Cent, Posting, PostingFilter, PostingId,
+    PostingState, TransferId,
 };
 
 use crate::error::StoreError;
@@ -18,33 +17,30 @@ use crate::events::{EventStore, LedgerEvent, event_dedup_key};
 use crate::query::{filter_transfers, paginate};
 use crate::store::{
     AccountStore, BalanceProjection, BalanceProjectionStore, BookStore, CommitOutcome,
-    CommitRejection, CommitRequest, CommitStore, EnvelopeRecord, Page, PostingStore, TransferQuery,
+    CommitRejection, CommitRequest, CommitStore, Page, PostingStore, TransferQuery, TransferRecord,
     TransferStore, TransitionOutcome, TransitionRejection,
 };
 
-/// Postings held as an immutable record table plus two index maps that carry
-/// full row copies of the live set, so a live-set read never merges back to the
-/// immutable record. Kept under one lock so the reserve claim (remove from
-/// active + insert into reserved) is atomic.
+/// Postings held as an immutable record table plus a live index carrying full
+/// row copies, so a live-set read never merges back to the immutable record.
+/// Both sit under one lock so a commit's spend is atomic.
 #[derive(Default)]
 struct PostingTables {
     /// The append-only record of every posting; never mutated or removed.
     immutable: HashMap<PostingId, Posting>,
-    /// Full copies of spendable postings.
-    active: HashMap<PostingId, Posting>,
-    /// Full copies of reserved postings, each with its owning reservation.
-    reserved: HashMap<PostingId, (Posting, ReservationId)>,
+    /// Full copies of the unspent postings.
+    live: HashMap<PostingId, Posting>,
 }
 
 /// In-memory [`Store`](crate::store::Store) implementation backed by `RwLock<HashMap>`.
 pub struct InMemoryStore {
     postings: RwLock<PostingTables>,
     accounts: RwLock<HashMap<AccountId, Vec<Account>>>,
-    transfers: RwLock<HashMap<EnvelopeId, EnvelopeRecord>>,
+    transfers: RwLock<HashMap<TransferId, TransferRecord>>,
     /// Transfer-participation index: the `involved` set the caller passed to
-    /// `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>>>,
+    /// the commit, mirroring the SQL `transfer_accounts` table so both backends
+    /// resolve `get_transfers_for_account` from the same instruction.
+    transfer_accounts: RwLock<HashMap<TransferId, Vec<AccountId>>>,
     events: RwLock<Vec<LedgerEvent>>,
     books: RwLock<HashMap<BookId, Book>>,
     /// Append-only balance cache points keyed by `(account, asset)` (ADR-0019).
@@ -158,27 +154,6 @@ impl AccountStore for InMemoryStore {
         Ok(1)
     }
 
-    async fn append_account_version(&self, account: Account) -> Result<u64, StoreError> {
-        let id = account.id;
-        let mut accounts = self.accounts.write().await;
-        // A guarded write: no such account, or a version that is not exactly one
-        // past the head, matches nothing and reports 0. This is what keeps the
-        // chain gap-free (a stale or skipped version never lands) and makes a
-        // replay of an already-applied version a no-op.
-        let Some(versions) = accounts.get_mut(&id) else {
-            return Ok(0);
-        };
-        let current_version = versions.last().map(|a| a.version).unwrap_or(0);
-        let expected = current_version
-            .checked_add(1)
-            .ok_or_else(|| StoreError::Internal("account version overflow".to_string()))?;
-        if account.version != expected {
-            return Ok(0);
-        }
-        versions.push(account);
-        Ok(1)
-    }
-
     async fn get_account_history(&self, id: &AccountId) -> Result<Vec<Account>, StoreError> {
         let accounts = self.accounts.read().await;
         accounts
@@ -228,19 +203,10 @@ impl PostingStore for InMemoryStore {
                 && sub.is_none_or(|s| p.owner.sub == s)
                 && asset.is_none_or(|a| p.asset == *a)
         };
-        // Read from the relevant set directly — no merge back to the immutable
-        // record. `Live` is the two disjoint live sets chained together.
-        let reserved = || postings.reserved.values().map(|(p, _)| p);
+        // Read the requested set directly, with no merge back to the immutable
+        // record.
         let mut result: Vec<Posting> = match filter {
-            PostingFilter::Active => postings.active.values().filter(matches).cloned().collect(),
-            PostingFilter::Reserved => reserved().filter(matches).cloned().collect(),
-            PostingFilter::Live => postings
-                .active
-                .values()
-                .chain(reserved())
-                .filter(matches)
-                .cloned()
-                .collect(),
+            PostingFilter::Live => postings.live.values().filter(matches).cloned().collect(),
             PostingFilter::All => postings
                 .immutable
                 .values()
@@ -272,10 +238,8 @@ impl PostingStore for InMemoryStore {
         Ok(ids
             .iter()
             .map(|id| {
-                if postings.active.contains_key(id) {
-                    PostingState::Active
-                } else if let Some((_, rid)) = postings.reserved.get(id) {
-                    PostingState::Reserved(*rid)
+                if postings.live.contains_key(id) {
+                    PostingState::Live
                 } else if postings.immutable.contains_key(id) {
                     PostingState::Spent
                 } else {
@@ -284,85 +248,6 @@ impl PostingStore for InMemoryStore {
             })
             .collect())
     }
-
-    async fn reserve_postings(
-        &self,
-        ids: &[PostingId],
-        reservation: ReservationId,
-    ) -> Result<u64, StoreError> {
-        let mut postings = self.postings.write().await;
-        let mut reserved: u64 = 0;
-        for id in ids {
-            // Removing the active copy is the atomic claim: only one caller can
-            // remove a given id, and only then is the copy moved to the reserved
-            // set (carrying its data, so reserved reads never merge).
-            if let Some(p) = postings.active.remove(id) {
-                postings.reserved.insert(*id, (p, reservation));
-                reserved += 1;
-            }
-        }
-        Ok(reserved)
-    }
-
-    async fn release_postings(
-        &self,
-        ids: &[PostingId],
-        reservation: ReservationId,
-    ) -> Result<u64, StoreError> {
-        let mut postings = self.postings.write().await;
-        let mut released: u64 = 0;
-        for id in ids {
-            if postings.reserved.get(id).map(|(_, r)| *r) == Some(reservation) {
-                if let Some((p, _)) = postings.reserved.remove(id) {
-                    postings.active.insert(*id, p);
-                    released += 1;
-                }
-            }
-        }
-        Ok(released)
-    }
-
-    async fn deactivate_postings(
-        &self,
-        ids: &[PostingId],
-        reservation: Option<ReservationId>,
-    ) -> Result<u64, StoreError> {
-        let mut postings = self.postings.write().await;
-        let mut changed: u64 = 0;
-        for id in ids {
-            let removed = match reservation {
-                None => postings.active.remove(id).is_some(),
-                Some(rid) => {
-                    if postings.reserved.get(id).map(|(_, r)| *r) == Some(rid) {
-                        postings.reserved.remove(id);
-                        true
-                    } else {
-                        false
-                    }
-                }
-            };
-            if removed {
-                changed += 1;
-            }
-        }
-        Ok(changed)
-    }
-
-    async fn insert_postings(&self, postings: &[Posting]) -> Result<u64, StoreError> {
-        let mut store = self.postings.write().await;
-        let mut inserted: u64 = 0;
-        for posting in postings {
-            if let Entry::Vacant(e) = store.immutable.entry(posting.id) {
-                e.insert(posting.clone());
-                // Only newly-inserted postings are activated; a since-spent
-                // posting is not re-activated on a replayed insert. The active
-                // set carries a full copy so spendable reads never merge.
-                store.active.insert(posting.id, posting.clone());
-                inserted += 1;
-            }
-        }
-        Ok(inserted)
-    }
 }
 
 // ---------------------------------------------------------------------------
@@ -371,45 +256,23 @@ impl PostingStore for InMemoryStore {
 
 #[async_trait]
 impl TransferStore for InMemoryStore {
-    async fn get_transfer(&self, id: &EnvelopeId) -> Result<Option<EnvelopeRecord>, StoreError> {
+    async fn get_transfer(&self, id: &TransferId) -> Result<Option<TransferRecord>, StoreError> {
         let transfers = self.transfers.read().await;
         Ok(transfers.get(id).cloned())
     }
 
-    async fn store_transfer(
-        &self,
-        record: EnvelopeRecord,
-        involved: &[AccountId],
-    ) -> Result<u64, StoreError> {
-        // Index the transfer under exactly the accounts the caller supplied,
-        // deriving nothing — the same instruction the SQL backend follows into
-        // its `transfer_accounts` table. Idempotent: a replay writes the same
-        // set. The returned count reflects only whether the transfer row was
-        // newly inserted; the caller decides what `0` means.
-        let tid = record.receipt.transfer_id;
-        // Lock order transfers → transfer_accounts, matching every other reader.
-        let mut transfers = self.transfers.write().await;
-        let mut transfer_accounts = self.transfer_accounts.write().await;
-        transfer_accounts.insert(tid, involved.to_vec());
-        if transfers.contains_key(&tid) {
-            return Ok(0);
-        }
-        transfers.insert(tid, record);
-        Ok(1)
-    }
-
     async fn get_transfers_for_account(
         &self,
         id: i64,
         sub: Option<i64>,
-    ) -> Result<Vec<EnvelopeRecord>, StoreError> {
+    ) -> Result<Vec<TransferRecord>, StoreError> {
         // Resolve participation from the `involved` index, not from postings, so
-        // this backend answers exactly what `store_transfer` was told — matching
-        // the SQL `transfer_accounts` join. Lock order transfers → index.
+        // this backend answers exactly what the commit was told, matching the SQL
+        // `transfer_accounts` join. Lock order transfers then index.
         let transfers = self.transfers.read().await;
         let transfer_accounts = self.transfer_accounts.read().await;
         let matches = |owner: &AccountId| owner.id == id && sub.is_none_or(|s| owner.sub == s);
-        let mut result: Vec<EnvelopeRecord> = transfer_accounts
+        let mut result: Vec<TransferRecord> = transfer_accounts
             .iter()
             .filter(|(_, accounts)| accounts.iter().any(matches))
             .filter_map(|(tid, _)| transfers.get(tid).cloned())
@@ -421,7 +284,7 @@ impl TransferStore for InMemoryStore {
     async fn query_transfers(
         &self,
         query: &TransferQuery,
-    ) -> Result<Page<EnvelopeRecord>, StoreError> {
+    ) -> Result<Page<TransferRecord>, StoreError> {
         // Load candidates: narrow by the participation index when an account is
         // given, otherwise scan every stored transfer (the same store-wide
         // answer the SQL backend gives for `account == None`). Then apply the
@@ -430,7 +293,7 @@ impl TransferStore for InMemoryStore {
             Some(account) => self.get_transfers_for_account(account, query.sub).await?,
             None => {
                 let transfers = self.transfers.read().await;
-                let mut all: Vec<EnvelopeRecord> = transfers.values().cloned().collect();
+                let mut all: Vec<TransferRecord> = transfers.values().cloned().collect();
                 all.sort_by_key(|r| r.created_at);
                 all
             }
@@ -512,7 +375,7 @@ impl CommitStore for InMemoryStore {
         // 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) {
+            if !postings.live.contains_key(id) {
                 return Ok(CommitOutcome::Rejected(CommitRejection::DoubleSpend(*id)));
             }
         }
@@ -531,14 +394,14 @@ impl CommitStore for InMemoryStore {
                 assets.insert(p.asset);
             }
             for id in req.consume {
-                if let Some(p) = postings.active.get(id).filter(|p| p.owner == *aid) {
+                if let Some(p) = postings.live.get(id).filter(|p| p.owner == *aid) {
                     assets.insert(p.asset);
                 }
             }
             for asset in assets {
                 let live_sum = Cent::checked_sum(
                     postings
-                        .active
+                        .live
                         .values()
                         .filter(|p| {
                             p.owner == *aid && p.asset == asset && !consumed_set.contains(&p.id)
@@ -569,11 +432,11 @@ impl CommitStore for InMemoryStore {
         // 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);
+            postings.live.remove(id);
         }
         for p in req.create {
             postings.immutable.entry(p.id).or_insert_with(|| p.clone());
-            postings.active.insert(p.id, p.clone());
+            postings.live.insert(p.id, p.clone());
         }
         transfer_accounts.insert(tid, req.involved.to_vec());
         let receipt = req.record.receipt.clone();

+ 3 - 3
crates/kuatia-storage/src/query.rs

@@ -7,7 +7,7 @@
 //! the time-window/book predicate and the `total` + `skip`/`take` cut, is the
 //! same contract regardless of backend and lives here.
 
-use crate::store::{EnvelopeRecord, Page, TransferQuery};
+use crate::store::{Page, TransferQuery, TransferRecord};
 
 /// Keep only the transfers matching a query's time-window and book predicates.
 ///
@@ -17,9 +17,9 @@ use crate::store::{EnvelopeRecord, Page, TransferQuery};
 /// backend can push down. This covers every remaining predicate so both
 /// backends agree on the contract.
 pub fn filter_transfers(
-    records: Vec<EnvelopeRecord>,
+    records: Vec<TransferRecord>,
     query: &TransferQuery,
-) -> Vec<EnvelopeRecord> {
+) -> Vec<TransferRecord> {
     records
         .into_iter()
         .filter(|r| {

+ 28 - 91
crates/kuatia-storage/src/store.rs

@@ -1,21 +1,21 @@
 //! Storage abstraction separating the pure decision logic from IO.
 //!
-//! The [`Store`] trait composes focused sub-traits, each a dumb instruction
-//! follower: writes apply one update and report an affected-row count (or an I/O
-//! error). The saga, not the store, interprets counts and owns idempotency and
-//! compensation.
-//! - [`AccountStore`] — account CRUD and versioning
-//! - [`PostingStore`] — posting reads and lifecycle transitions
-//! - [`TransferStore`] — transfer persistence and queries
-//! - [`CommitStore`] — the atomic commit boundary (ADR-0023)
-//! - [`EventStore`] — the ledger event log
-//! - [`BookStore`] — book persistence
-//! - [`BalanceProjectionStore`] — the cached balance projection (ADR-0019)
+//! The [`Store`] trait composes focused sub-traits. Every posting and
+//! account-version write goes through [`CommitStore`], which applies a whole
+//! transfer or a whole transition in one transaction (ADR-0023), so no caller
+//! can leave half of one applied.
+//! - [`AccountStore`]: account creation and version reads
+//! - [`PostingStore`]: posting reads and the live balance
+//! - [`TransferStore`]: committed transfer reads
+//! - [`CommitStore`]: the atomic commit boundary (ADR-0023)
+//! - [`EventStore`]: the ledger event log
+//! - [`BookStore`]: book persistence
+//! - [`BalanceProjectionStore`]: the cached balance projection (ADR-0019)
 
 use async_trait::async_trait;
 use kuatia_types::{
-    Account, AccountId, AssetId, Book, BookId, Cent, Envelope, EnvelopeId, Posting, PostingFilter,
-    PostingId, PostingState, Receipt, ReservationId,
+    Account, AccountId, AssetId, Book, BookId, Cent, Envelope, Posting, PostingFilter, PostingId,
+    PostingState, Receipt, TransferId,
 };
 
 use crate::error::StoreError;
@@ -23,7 +23,7 @@ use crate::events::{EventStore, LedgerEvent};
 
 /// Pairs a committed transfer with its receipt.
 #[derive(Debug, Clone)]
-pub struct EnvelopeRecord {
+pub struct TransferRecord {
     /// The envelope that was committed.
     pub envelope: Envelope,
     /// The receipt proving commitment.
@@ -87,7 +87,8 @@ pub struct Page<T> {
 // Sub-traits
 // ---------------------------------------------------------------------------
 
-/// Account persistence: create, version, query.
+/// Account creation and version reads; a version is only ever appended by
+/// [`CommitStore::commit_transition`].
 #[async_trait]
 pub trait AccountStore: Send + Sync {
     /// Fetch a single account by id.
@@ -99,27 +100,18 @@ pub trait AccountStore: Send + Sync {
     /// was newly created, **0** if an account with this id already existed. The
     /// caller decides what `0` means.
     async fn create_account(&self, account: Account) -> Result<u64, StoreError>;
-    /// Append a new version to an existing account. A dumb instruction with a
-    /// guarded write: the version lands only when it is exactly one past the
-    /// current head (`version == current + 1`) and not already present, which
-    /// keeps the version chain gap-free and single-winner under contention.
-    /// Returns the **number of versions appended** — **1** if it landed, **0**
-    /// otherwise (no such account, a gap/stale append, or an already-applied
-    /// replay). The caller reads state to disambiguate a `0`.
-    async fn append_account_version(&self, account: Account) -> Result<u64, StoreError>;
     /// Return the full version history for an account.
     async fn get_account_history(&self, id: &AccountId) -> Result<Vec<Account>, StoreError>;
     /// List all accounts (latest version of each).
     async fn list_accounts(&self) -> Result<Vec<Account>, StoreError>;
 }
 
-/// Posting persistence: an immutable posting table plus two id-only index
-/// tables (active, reserved) whose membership expresses lifecycle state.
+/// Posting reads over an immutable posting table plus an index of the live set.
 ///
-/// A posting is written once into the immutable table and never updated. Its
-/// state is derived from which index it is in: active → spendable, reserved →
-/// claimed by a saga, neither → spent. All lifecycle transitions are inserts
-/// and deletes on the index tables; the posting row itself never changes.
+/// A posting is written once and never updated, so [`PostingState`] is derived
+/// from index membership rather than stored: in the index it is spendable, and
+/// out of it (but still in the immutable table) it is spent. Only
+/// [`CommitStore::commit_envelope`] moves a posting between the two.
 #[async_trait]
 pub trait PostingStore: Send + Sync {
     /// Fetch postings by their ids from the immutable table. Consumed (spent)
@@ -138,50 +130,8 @@ pub trait PostingStore: Send + Sync {
         filter: PostingFilter,
     ) -> Result<Vec<Posting>, StoreError>;
     /// Return the derived [`PostingState`] of each id, aligned to the input
-    /// order. This is the single membership probe used by the saga verifier and
-    /// the finalize guards. An id absent from the immutable table is `Missing`.
+    /// order. An id absent from the immutable table is `Missing`.
     async fn get_posting_states(&self, ids: &[PostingId]) -> Result<Vec<PostingState>, StoreError>;
-    /// Reserve postings: move each id from the active index into the reserved
-    /// index under `reservation`. A dumb instruction — an id moves only if it
-    /// was in the active index (the delete-returns-one is the atomic
-    /// single-winner claim under contention); returns the **number of rows
-    /// reserved** (0 ≤ n ≤ ids.len()). The caller (saga) interprets a short
-    /// count.
-    async fn reserve_postings(
-        &self,
-        ids: &[PostingId],
-        reservation: ReservationId,
-    ) -> Result<u64, StoreError>;
-    /// Release postings: move each id reserved by `reservation` back into the
-    /// active index. A dumb instruction — only ids reserved by this
-    /// `reservation` move; returns the **number of rows released**. Releasing an
-    /// id that is already active or reserved by another saga does not count.
-    async fn release_postings(
-        &self,
-        ids: &[PostingId],
-        reservation: ReservationId,
-    ) -> Result<u64, StoreError>;
-
-    /// Deactivate postings: remove each id from an index so it becomes spent
-    /// (present only in the immutable table). A dumb instruction — it applies
-    /// the conditional delete and returns the **number of rows removed**.
-    /// - `reservation == None` (raw): remove ids from the active index.
-    /// - `reservation == Some(rid)`: remove ids from the reserved index that are
-    ///   owned by `rid`.
-    /// Returns the count actually removed (0 ≤ n ≤ ids.len()).
-    async fn deactivate_postings(
-        &self,
-        ids: &[PostingId],
-        reservation: Option<ReservationId>,
-    ) -> Result<u64, StoreError>;
-
-    /// Insert postings if absent, and add each newly-inserted id to the active
-    /// index. A dumb instruction — inserts each posting into the immutable table
-    /// unless one with the same id already exists, activating only the rows that
-    /// were newly inserted, and returns the **number of immutable rows
-    /// inserted** (already-present postings contribute 0, and do not get
-    /// re-activated). The caller decides what a short count means.
-    async fn insert_postings(&self, postings: &[Posting]) -> Result<u64, StoreError>;
 
     /// Sum the live postings of one `(account, asset)` pair: the account's
     /// balance in that asset.
@@ -204,31 +154,18 @@ pub trait PostingStore: Send + Sync {
     }
 }
 
-/// Transfer persistence: store and query committed transfers.
+/// Committed transfer reads; the commit transaction is what writes them.
 #[async_trait]
 pub trait TransferStore: Send + Sync {
     /// Fetch a transfer record by its content-addressed id.
-    async fn get_transfer(&self, id: &EnvelopeId) -> Result<Option<EnvelopeRecord>, StoreError>;
-    /// Persist a transfer record if absent (idempotent) and index it under every
-    /// account in `involved` (both created and consumed owners — the caller
-    /// supplies the set so storage computes nothing). Every backend indexes the
-    /// transfer under exactly these accounts and derives participation from
-    /// nowhere else, so `get_transfers_for_account` returns the same set of
-    /// transfers regardless of backend. A dumb instruction: returns **1** if the
-    /// transfer row was newly inserted, **0** if it already existed. The caller
-    /// decides what `0` means.
-    async fn store_transfer(
-        &self,
-        record: EnvelopeRecord,
-        involved: &[AccountId],
-    ) -> Result<u64, StoreError>;
+    async fn get_transfer(&self, id: &TransferId) -> Result<Option<TransferRecord>, StoreError>;
     /// Return all transfers involving the given base account. `sub == None`
     /// spans every subaccount of `id`; `sub == Some(s)` restricts to one.
     async fn get_transfers_for_account(
         &self,
         id: i64,
         sub: Option<i64>,
-    ) -> Result<Vec<EnvelopeRecord>, StoreError>;
+    ) -> Result<Vec<TransferRecord>, StoreError>;
 
     /// Query transfers with filtering and pagination.
     ///
@@ -242,7 +179,7 @@ pub trait TransferStore: Send + Sync {
     async fn query_transfers(
         &self,
         query: &TransferQuery,
-    ) -> Result<Page<EnvelopeRecord>, StoreError>;
+    ) -> Result<Page<TransferRecord>, StoreError>;
 }
 
 /// Book persistence.
@@ -323,13 +260,13 @@ pub trait BalanceProjectionStore: Send + Sync {
 /// check and the write.
 pub struct CommitRequest<'a> {
     /// Content-addressed id of the transfer being committed.
-    pub transfer_id: EnvelopeId,
+    pub transfer_id: TransferId,
     /// 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,
+    pub record: TransferRecord,
     /// 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],

Разница между файлами не показана из-за своего большого размера
+ 211 - 491
crates/kuatia-storage/src/store_tests.rs


+ 164 - 35
crates/kuatia-storage/tests/concurrency.rs

@@ -1,24 +1,43 @@
-//! Concurrency tests for `InMemoryStore` primitives.
+//! Concurrency tests for `InMemoryStore`.
 //!
 //! 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 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.
+//! so it never exercises two callers racing on the same rows. The atomic commit
+//! is the single-winner claim: of many commits consuming one posting, exactly
+//! one may apply.
 
 #![allow(missing_docs)]
 
 use std::sync::Arc;
 
+use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
 use kuatia_storage::mem_store::InMemoryStore;
-use kuatia_storage::store::PostingStore;
+use kuatia_storage::store::{
+    AccountStore, CommitOutcome, CommitRejection, CommitRequest, CommitStore, TransferRecord,
+    TransitionOutcome,
+};
+use kuatia_storage::store_tests::{seed_live, state_of};
 use kuatia_types::*;
+use std::collections::BTreeMap;
 
-fn posting(index: u16) -> Posting {
+fn account(id: i64) -> Account {
+    Account {
+        id: AccountId::new(id),
+        version: 1,
+        flags: AccountFlags::empty(),
+        book: BookId(0),
+        metadata: BTreeMap::new(),
+    }
+}
+
+/// The posting every racing commit tries to spend. Its transfer id is marked so
+/// it cannot equal a racing task's own transfer id: a commit that consumed and
+/// re-created the same posting id would leave it spendable again, and a second
+/// task could then legitimately win too.
+fn funded() -> Posting {
     Posting::new(
         PostingId {
-            transfer: EnvelopeId([1; 32]),
-            index,
+            transfer: TransferId([0xAA; 32]),
+            index: 0,
         },
         AccountId::new(1),
         AssetId::new(1),
@@ -26,48 +45,158 @@ fn posting(index: u16) -> Posting {
     )
 }
 
-/// Many tasks concurrently reserve the same set of postings, each with its own
-/// reservation id. Reservation is a claim, so each posting may be reserved by
-/// exactly one task: the per-task counts sum to the number of postings, and
-/// every posting ends reserved.
+/// Many tasks concurrently commit transfers that all consume the same posting.
+/// The commit's delete is the atomic claim, so exactly one task may apply and
+/// every other must be refused as a double spend.
 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
-async fn concurrent_reserve_claims_each_posting_once() {
-    const POSTINGS: u16 = 32;
-    const TASKS: i64 = 8;
+async fn concurrent_commits_spend_a_posting_once() {
+    const TASKS: u8 = 8;
 
     let store = Arc::new(InMemoryStore::new());
-    let all: Vec<Posting> = (0..POSTINGS).map(posting).collect();
-    store.insert_postings(&all).await.unwrap();
-
-    let ids: Vec<PostingId> = all.iter().map(|p| p.id).collect();
+    for id in [1, 2] {
+        store.create_account(account(id)).await.unwrap();
+    }
+    let p = funded();
+    seed_live(store.as_ref(), 1, std::slice::from_ref(&p)).await;
 
     let mut handles = Vec::new();
     for t in 0..TASKS {
         let store = Arc::clone(&store);
-        let ids = ids.clone();
         handles.push(tokio::spawn(async move {
+            let tid = TransferId([t; 32]);
+            let create = vec![Posting::new(
+                PostingId {
+                    transfer: tid,
+                    index: 0,
+                },
+                AccountId::new(2),
+                AssetId::new(1),
+                Cent::from(100),
+            )];
+            let involved = [AccountId::new(1), AccountId::new(2)];
             store
-                .reserve_postings(&ids, ReservationId::new(t + 1))
+                .commit_envelope(CommitRequest {
+                    transfer_id: tid,
+                    consume: &[p.id],
+                    create: &create,
+                    record: TransferRecord {
+                        envelope: Envelope::default(),
+                        receipt: Receipt { transfer_id: tid },
+                        created_at: 1000,
+                    },
+                    involved: &involved,
+                    event: LedgerEvent {
+                        seq: 0,
+                        timestamp: 1000,
+                        kind: LedgerEventKind::TransferCommitted { transfer_id: tid },
+                    },
+                })
                 .await
                 .unwrap()
         }));
     }
 
-    let mut total_reserved: u64 = 0;
+    let mut committed = 0;
+    let mut rejected = 0;
     for h in handles {
-        total_reserved += h.await.unwrap();
+        match h.await.unwrap() {
+            CommitOutcome::Committed(_) => committed += 1,
+            CommitOutcome::Rejected(CommitRejection::DoubleSpend(id)) => {
+                assert_eq!(id, p.id);
+                rejected += 1;
+            }
+            other => panic!("unexpected outcome: {other:?}"),
+        }
+    }
+
+    assert_eq!(committed, 1, "exactly one commit claims the posting");
+    assert_eq!(rejected, i32::from(TASKS) - 1);
+    assert_eq!(state_of(store.as_ref(), p.id).await, PostingState::Spent);
+}
+
+/// Commits and account transitions race on the same account. Both take the
+/// account guard before any other, so the two atomic writers must not deadlock,
+/// and whichever order they take, the commit either applied before the freeze or
+/// was refused by it: a half-applied state is not reachable.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn concurrent_commit_and_transition_do_not_deadlock() {
+    let store = Arc::new(InMemoryStore::new());
+    for id in [1, 2] {
+        store.create_account(account(id)).await.unwrap();
     }
+    let p = funded();
+    seed_live(store.as_ref(), 1, std::slice::from_ref(&p)).await;
 
-    assert_eq!(
-        total_reserved, POSTINGS as u64,
-        "each posting is reserved by exactly one task"
-    );
+    let committer = {
+        let store = Arc::clone(&store);
+        tokio::spawn(async move {
+            let tid = TransferId([21; 32]);
+            let create = vec![Posting::new(
+                PostingId {
+                    transfer: tid,
+                    index: 0,
+                },
+                AccountId::new(2),
+                AssetId::new(1),
+                Cent::from(100),
+            )];
+            let involved = [AccountId::new(1), AccountId::new(2)];
+            store
+                .commit_envelope(CommitRequest {
+                    transfer_id: tid,
+                    consume: &[p.id],
+                    create: &create,
+                    record: TransferRecord {
+                        envelope: Envelope::default(),
+                        receipt: Receipt { transfer_id: tid },
+                        created_at: 1000,
+                    },
+                    involved: &involved,
+                    event: LedgerEvent {
+                        seq: 0,
+                        timestamp: 1000,
+                        kind: LedgerEventKind::TransferCommitted { transfer_id: tid },
+                    },
+                })
+                .await
+                .unwrap()
+        })
+    };
 
-    let states = store.get_posting_states(&ids).await.unwrap();
-    assert!(
-        states
-            .iter()
-            .all(|s| matches!(s, PostingState::Reserved(_))),
-        "every posting ends reserved"
-    );
+    let freezer = {
+        let store = Arc::clone(&store);
+        tokio::spawn(async move {
+            let mut next = account(2);
+            next.version = 2;
+            next.flags = AccountFlags::FROZEN;
+            store
+                .commit_transition(
+                    next,
+                    LedgerEvent {
+                        seq: 0,
+                        timestamp: 2000,
+                        kind: LedgerEventKind::AccountFrozen {
+                            account_id: AccountId::new(2),
+                            version: 2,
+                        },
+                    },
+                )
+                .await
+                .unwrap()
+        })
+    };
+
+    let commit = committer.await.unwrap();
+    assert_eq!(freezer.await.unwrap(), TransitionOutcome::Applied);
+
+    match commit {
+        CommitOutcome::Committed(_) => {
+            assert_eq!(state_of(store.as_ref(), p.id).await, PostingState::Spent)
+        }
+        CommitOutcome::Rejected(CommitRejection::AccountFrozen(id)) => {
+            assert_eq!(id, AccountId::new(2));
+            assert_eq!(state_of(store.as_ref(), p.id).await, PostingState::Live);
+        }
+        other => panic!("unexpected outcome: {other:?}"),
+    }
 }

+ 2 - 2
crates/kuatia-types/README.md

@@ -11,14 +11,14 @@ This crate is the foundation — every other kuatia crate depends on it.
 |------|-------------|
 | `AccountId(i64)` | Stable account identity |
 | `AssetId(u32)` | Asset identifier — conservation boundary |
-| `EnvelopeId([u8; 32])` | Content-addressed transfer hash |
+| `TransferId([u8; 32])` | Content-addressed transfer hash |
 | `PostingId { transfer, index }` | Posting identity within a transfer |
 | `Cent(i64)` | Smallest monetary unit, checked arithmetic |
 | `Posting` | Signed amount owned by one account (positive = held, negative = offset) |
 | `Transfer` | Atomic unit: consumes + creates postings |
 | `Account` | Versioned entity with policy, flags, and book |
 | `Book` / `BookId` | Transfer policy scope — gates which accounts/assets may participate |
-| `PostingStatus` | `Active` → `PendingInactive` → `Inactive` |
+| `PostingState` | Derived from live-index membership: `Live`, `Spent`, `Missing` |
 
 ## Traits
 

+ 2 - 3
crates/kuatia-types/src/autoid.rs

@@ -42,9 +42,8 @@ pub struct AutoId {
 impl AutoId {
     /// Create a new generator with counter starting at zero.
     ///
-    /// `const` so a single generator can back a process-global `static` (see
-    /// `ReservationId::default`), giving ids that are unique across threads
-    /// rather than per-thread.
+    /// `const` so a single generator can back a process-global `static`, giving
+    /// ids that are unique across threads rather than per-thread.
     pub const fn new() -> Self {
         Self {
             counter: AtomicU32::new(0),

+ 4 - 4
crates/kuatia-types/src/canonical.rs

@@ -2,7 +2,7 @@
 //!
 //! Everything that defines the hash preimage lives here in one place: the
 //! [`ToBytes`] trait, the [`CANONICAL_VERSION`] byte, the big-endian write
-//! helpers, and every `impl ToBytes`. [`EnvelopeId`](crate::EnvelopeId) and the
+//! helpers, and every `impl ToBytes`. [`TransferId`](crate::TransferId) and the
 //! account snapshot hashes are the double-SHA256 of these bytes, so a change to
 //! any impl below changes those ids. Keeping the trait, the version, and all the
 //! impls together makes the preimage auditable at a glance: what bytes are
@@ -14,7 +14,7 @@
 
 use crate::{
     Account, AccountFlags, AccountId, AccountSnapshotId, AssetId, BookId, Cent, Envelope,
-    EnvelopeId, NewPosting, Posting, PostingId, Receipt,
+    NewPosting, Posting, PostingId, Receipt, TransferId,
 };
 
 /// Deterministic binary serialization. Every domain type can produce its
@@ -91,7 +91,7 @@ impl ToBytes for AssetId {
     }
 }
 
-impl ToBytes for EnvelopeId {
+impl ToBytes for TransferId {
     fn to_bytes(&self) -> Vec<u8> {
         self.0.to_vec()
     }
@@ -121,7 +121,7 @@ impl ToBytes for BookId {
 impl ToBytes for NewPosting {
     fn to_bytes(&self) -> Vec<u8> {
         // `payer` is provenance, not identity: it is deliberately excluded from
-        // the content-address preimage so an EnvelopeId reflects only economic
+        // the content-address preimage so an TransferId reflects only economic
         // content (owner, asset, value). Two envelopes that differ only in a
         // payer annotation share an id, hence one idempotency key. Provenance is
         // still persisted on the envelope record for audit.

+ 4 - 4
crates/kuatia-types/src/envelope.rs

@@ -1,4 +1,4 @@
-//! The [`Envelope`] — the resolved, atomic unit produced by the saga pipeline.
+//! The [`Envelope`]: the atomic unit a [`Transfer`](crate::Transfer) resolves into.
 
 use crate::ids::{AccountId, AccountSnapshotId, BookId, PostingId};
 use crate::posting::NewPosting;
@@ -8,9 +8,9 @@ use std::collections::BTreeMap;
 /// Free-form key→value metadata.
 pub type Metadata = BTreeMap<String, Vec<u8>>;
 
-/// The unit of atomicity — all of its consumptions and creations apply together
-/// or not at all. This is the resolved, internal form produced by the saga
-/// pipeline from a [`Transfer`](crate::Transfer) intent.
+/// The unit of atomicity: all of its consumptions and creations apply together
+/// or not at all. This is the resolved, internal form that `resolve` produces
+/// from a [`Transfer`](crate::Transfer) intent.
 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Envelope {
     /// Posting ids consumed (spent) by this envelope.

+ 5 - 67
crates/kuatia-types/src/ids.rs

@@ -55,7 +55,7 @@ pub struct AssetId(pub u32);
 /// serialization. This makes the id both the idempotency key and the
 /// tamper-evidence artifact.
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
-pub struct EnvelopeId(pub [u8; 32]);
+pub struct TransferId(pub [u8; 32]);
 
 /// Uniquely identifies a posting within the ledger. The `(transfer, index)` pair
 /// ties every posting back to the transfer that created it, which is the basis
@@ -63,7 +63,7 @@ pub struct EnvelopeId(pub [u8; 32]);
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
 pub struct PostingId {
     /// The transfer that created this posting.
-    pub transfer: EnvelopeId,
+    pub transfer: TransferId,
     /// Zero-based position within the transfer's created postings.
     pub index: u16,
 }
@@ -72,19 +72,6 @@ pub struct PostingId {
 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
 pub struct BookId(pub i64);
 
-/// Identifies a reservation — the owner token recorded in the reserved index
-/// while a posting is claimed, so only the saga that reserved it may finalize
-/// or release it.
-#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
-pub struct ReservationId(pub i64);
-
-/// Identifies an account-version transition's write-ahead record. A distinct
-/// type from [`ReservationId`] so a transition does not masquerade as a
-/// reservation, but drawn from the same generator (see [`ReservationId::default`])
-/// so the two write-ahead kinds share one collision-free id space.
-#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
-pub struct TransitionId(pub i64);
-
 // ---------------------------------------------------------------------------
 // Debug impls for identifiers
 // ---------------------------------------------------------------------------
@@ -105,9 +92,9 @@ impl fmt::Debug for AssetId {
     }
 }
 
-impl fmt::Debug for EnvelopeId {
+impl fmt::Debug for TransferId {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "EnvelopeId({})", hex(&self.0))
+        write!(f, "TransferId({})", hex(&self.0))
     }
 }
 
@@ -126,18 +113,6 @@ impl fmt::Debug for BookId {
     }
 }
 
-impl fmt::Debug for ReservationId {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "ReservationId({})", self.0)
-    }
-}
-
-impl fmt::Debug for TransitionId {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "TransitionId({})", self.0)
-    }
-}
-
 fn hex(bytes: &[u8]) -> String {
     bytes.iter().map(|b| format!("{b:02x}")).collect()
 }
@@ -197,7 +172,7 @@ impl AssetId {
 }
 
 /// The implicit book used when a transfer does not name one. Fixed so that two
-/// otherwise-identical transfers hash to the same [`EnvelopeId`] — a random
+/// otherwise-identical transfers hash to the same [`TransferId`] — a random
 /// default would break content-addressed idempotency.
 pub const DEFAULT_BOOK: BookId = BookId(0);
 
@@ -225,40 +200,3 @@ impl BookId {
         Self(GEN.next())
     }
 }
-
-impl ReservationId {
-    /// Create a `ReservationId` from an `i64`.
-    pub const fn new(id: i64) -> Self {
-        Self(id)
-    }
-}
-
-/// The one process-global id source behind every write-ahead saga key —
-/// reservation ids and transition ids alike. One atomic counter, not one per
-/// thread: a `thread_local` generator lets two sagas on different threads mint
-/// the same id within a millisecond, which collapses the reservation-ownership
-/// check and allows a double-spend under concurrency. Sharing it across both
-/// kinds is also what keeps their keys unique in the single saga keyspace.
-fn next_saga_id() -> i64 {
-    static GEN: AutoId = AutoId::new();
-    GEN.next()
-}
-
-impl Default for ReservationId {
-    fn default() -> Self {
-        Self(next_saga_id())
-    }
-}
-
-impl TransitionId {
-    /// Create a `TransitionId` from an `i64`.
-    pub const fn new(id: i64) -> Self {
-        Self(id)
-    }
-}
-
-impl Default for TransitionId {
-    fn default() -> Self {
-        Self(next_saga_id())
-    }
-}

+ 2 - 5
crates/kuatia-types/src/lib.rs

@@ -35,9 +35,6 @@ pub use kuatia_money::{
 pub use account::{Account, AccountFlags};
 pub use book::{Book, BookBuilder, BookPolicy};
 pub use envelope::{Envelope, EnvelopeBuilder, Metadata};
-pub use ids::{
-    AccountId, AccountSnapshotId, AssetId, BookId, DEFAULT_BOOK, EnvelopeId, PostingId,
-    ReservationId, TransitionId,
-};
+pub use ids::{AccountId, AccountSnapshotId, AssetId, BookId, DEFAULT_BOOK, PostingId, TransferId};
 pub use posting::{NewPosting, Posting, PostingFilter, PostingState};
-pub use transfer::{Movement, Receipt, Transfer, TransferBuilder};
+pub use transfer::{Movement, REFERENCE_KEY, Receipt, Transfer, TransferBuilder};

+ 13 - 39
crates/kuatia-types/src/posting.rs

@@ -1,53 +1,27 @@
 //! Posting records and their derived lifecycle state.
 
-use crate::ids::{AccountId, AssetId, PostingId, ReservationId};
+use crate::ids::{AccountId, AssetId, PostingId};
 use kuatia_money::Cent;
 use serde::{Deserialize, Serialize};
 
-/// Read filter over the derived lifecycle state of postings.
-///
-/// A posting's state is no longer stored on the posting itself; it is derived
-/// from index-table membership. This filter selects which postings a read
-/// returns:
-///
-/// - `Active` — spendable (present in the active index).
-/// - `Reserved` — claimed by an in-flight saga (present in the reserved index).
-/// - `Live` — `Active ∪ Reserved`; everything that still counts toward balance.
-/// - `All` — every posting in the immutable table, including spent ones.
+/// Which postings a read returns, by derived state.
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
 pub enum PostingFilter {
-    /// Spendable postings only.
-    Active,
-    /// Reserved (in-flight) postings only.
-    Reserved,
-    /// Active or reserved: the balance-bearing set (everything not yet Spent).
+    /// The unspent, balance-bearing set: present in the live index.
     Live,
     /// Every posting ever created, including spent ones.
     All,
 }
 
-/// The derived lifecycle state of a single [`Posting`], computed from
-/// index-table membership rather than stored on the posting.
-///
-/// ```text
-/// Active ──reserve──▶ Reserved(rid) ──consume──▶ Spent
-///   ▲  ▲                   │
-///   │  └── release ────────┘  (compensation)
-///   └── (id in active index)
-/// ```
-///
-/// `Reserved` carries the owning [`ReservationId`] so a saga can confirm it
-/// still holds a posting before finalizing or releasing it. `Missing` means the
-/// id is not present in the immutable postings table at all.
+/// The derived state of a single [`Posting`]: liveness is index membership, so
+/// a posting is spendable or spent and never both, with no state in between.
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
 pub enum PostingState {
-    /// Present in the active index — spendable, counts toward balance.
-    Active,
-    /// Present in the reserved index, claimed by the given reservation.
-    Reserved(ReservationId),
-    /// Present only in the immutable table — consumed by a committed transfer.
+    /// In the live index: spendable, and counts toward balance.
+    Live,
+    /// In the immutable table only: consumed by a committed transfer.
     Spent,
-    /// Not present in the immutable table.
+    /// Not present in the immutable table at all.
     Missing,
 }
 
@@ -59,8 +33,8 @@ pub enum PostingState {
 /// overdraft (carries [`AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT`](crate::AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT)).
 ///
 /// A `Posting` is an immutable record: once created it is never updated. Its
-/// lifecycle state is not a field here; it is derived from index-table
-/// membership (see [`PostingState`]).
+/// state is not a field here; it is derived from live-index membership (see
+/// [`PostingState`]).
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Posting {
     /// Unique identifier derived from the creating transfer.
@@ -86,7 +60,7 @@ impl Posting {
 }
 
 /// A posting to be created — carries no id yet because the [`PostingId`] depends
-/// on the [`EnvelopeId`](crate::EnvelopeId), which is computed during validation.
+/// on the [`TransferId`](crate::TransferId), which is computed during validation.
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct NewPosting {
     /// The account (subaccount) that will own the created posting.
@@ -97,7 +71,7 @@ pub struct NewPosting {
     pub value: Cent,
     /// Provenance — who funded this posting. Descriptive only: it is excluded
     /// from the content-address preimage (see [`NewPosting`]'s `ToBytes`), so it
-    /// does not affect the [`EnvelopeId`](crate::EnvelopeId) or the idempotency
+    /// does not affect the [`TransferId`](crate::TransferId) or the idempotency
     /// key. Persisted on the envelope record for audit, not on the stored
     /// [`Posting`].
     pub payer: Option<AccountId>,

+ 42 - 21
crates/kuatia-types/src/transfer.rs

@@ -2,7 +2,7 @@
 //! the [`Receipt`] returned on commit.
 
 use crate::envelope::Metadata;
-use crate::ids::{AccountId, AssetId, BookId, EnvelopeId};
+use crate::ids::{AccountId, AssetId, BookId, TransferId};
 use kuatia_money::{Cent, OverflowError};
 use serde::{Deserialize, Serialize};
 
@@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Receipt {
     /// Content-addressed id of the committed transfer.
-    pub transfer_id: EnvelopeId,
+    pub transfer_id: TransferId,
 }
 
 /// A single movement within a transfer: move value from one account to another.
@@ -30,11 +30,11 @@ pub struct Movement {
     pub amount: Cent,
 }
 
-/// A transfer intent — one or more movements to execute atomically.
+/// A transfer intent: one or more movements to execute atomically.
 ///
-/// The saga pipeline resolves movements into concrete postings
-/// ([`Envelope`](crate::Envelope)) during execution. Callers express *what*
-/// should happen, not *which postings* to consume.
+/// `resolve` turns the movements into the concrete postings of an
+/// [`Envelope`](crate::Envelope) at commit time. Callers express *what* should
+/// happen, not *which postings* to consume.
 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Transfer {
     /// Movements to execute atomically.
@@ -45,6 +45,11 @@ pub struct Transfer {
     pub metadata: Metadata,
 }
 
+/// Metadata key holding a transfer's caller-supplied reference. Reserved, so a
+/// reference set through [`TransferBuilder::reference`] and one written straight
+/// into [`Transfer::metadata`] are the same field.
+pub const REFERENCE_KEY: &str = "reference";
+
 /// Builder for constructing [`Transfer`] values.
 #[derive(Default)]
 pub struct TransferBuilder {
@@ -57,13 +62,9 @@ impl TransferBuilder {
         Self::default()
     }
 
-    /// Add a raw movement between main subaccounts.
-    pub fn movement(self, from: AccountId, to: AccountId, asset: AssetId, amount: Cent) -> Self {
-        self.movement_ref(from, to, asset, amount)
-    }
-
-    /// Add a raw movement between specific subaccounts.
-    pub fn movement_ref(
+    /// Add a movement. The neutral spelling, for a leg that is not a payment:
+    /// each side of an exchange, for instance.
+    pub fn movement(
         mut self,
         from: AccountId,
         to: AccountId,
@@ -79,17 +80,12 @@ impl TransferBuilder {
         self
     }
 
-    /// Add a pay movement between main subaccounts.
+    /// Add a payment. Both endpoints carry their own subaccount, so this spans
+    /// subaccounts as readily as main accounts.
     pub fn pay(self, from: AccountId, to: AccountId, asset: AssetId, amount: Cent) -> Self {
         self.movement(from, to, asset, amount)
     }
 
-    /// Add a pay movement between two specific subaccounts. See
-    /// [`movement_ref`](Self::movement_ref).
-    pub fn pay_ref(self, from: AccountId, to: AccountId, asset: AssetId, amount: Cent) -> Self {
-        self.movement_ref(from, to, asset, amount)
-    }
-
     /// Add a deposit: creates an offset posting on the external account and
     /// credits the target account.  Pushes two movements whose net debit on the
     /// external account is zero.
@@ -123,7 +119,32 @@ impl TransferBuilder {
         self
     }
 
-    /// Set the free-form metadata.
+    /// Attach the caller's own reference for this transfer: a payment reference,
+    /// an order id, whatever identifies the event in the system asking for it.
+    ///
+    /// Give every distinct transfer a distinct reference. A transfer's id is the
+    /// hash of its content, so two transfers that are byte-identical *are* one
+    /// transfer, and the second commit is reported as an already-committed
+    /// replay rather than applied. A payment distinguishes itself, because the
+    /// postings it consumes differ from the previous payment's. A transfer that
+    /// consumes nothing cannot: two deposits of the same amount to the same
+    /// account are identical, and without a reference the second is discarded.
+    ///
+    /// Retry safety is the same mechanism read the other way: repeat the
+    /// reference to make a retry idempotent, and a redelivered request collapses
+    /// onto the transfer it already committed.
+    ///
+    /// Set this before [`metadata`](Self::metadata), which replaces the whole
+    /// map.
+    pub fn reference(mut self, reference: impl Into<String>) -> Self {
+        self.transfer
+            .metadata
+            .insert(REFERENCE_KEY.to_string(), reference.into().into_bytes());
+        self
+    }
+
+    /// Set the free-form metadata, replacing the whole map including any
+    /// [`reference`](Self::reference) already set.
     pub fn metadata(mut self, metadata: Metadata) -> Self {
         self.transfer.metadata = metadata;
         self

+ 1 - 1
crates/kuatia/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "kuatia"
-description = "Append-only, auditable, multi-asset UTXO-style ledger: async resource and saga commit pipeline."
+description = "Append-only, auditable, multi-asset UTXO-style ledger: async resource and atomic commit engine."
 version.workspace = true
 edition.workspace = true
 rust-version.workspace = true

+ 7 - 7
crates/kuatia/README.md

@@ -57,23 +57,23 @@ step.
 
 | Method | Description |
 |--------|-------------|
-| `balance(account, asset)` | Current balance (sum of non-Inactive postings) |
+| `balance(account, asset)` | Current balance (sum of the unspent postings) |
 | `query_transfers(query)` | Paginated, filtered transfer history |
 | `history(account)` | All transfers for an account |
-| `postings(account)` | All postings (any status) |
+| `postings(account)` | All postings (live and spent) |
 | `get_events_since(seq, limit)` | Query ledger event log |
 
 ### Multi-transfer composition
 
-Combine transfers into an all-or-nothing workflow with `run_movements`, which
+Combine transfers into an all-or-nothing workflow with `run_transfers`, which
 commits them in order and reverses the committed ones LIFO on failure:
 
 ```rust
-use kuatia::saga::{DepositInput, Movement, PayInput, run_movements};
+use kuatia::workflow::run_transfers;
 
-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 }),
+let receipts = run_transfers(&ledger, &[
+    TransferBuilder::new().deposit(alice, usd, amount, bank)?.build(),
+    TransferBuilder::new().pay(alice, bob, usd, amount).build(),
 ])
 .await?;
 ```

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

@@ -6,7 +6,6 @@
 //! ```
 
 use std::collections::BTreeMap;
-use std::sync::Arc;
 
 use kuatia::ledger::Ledger;
 use kuatia_core::*;
@@ -53,7 +52,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 /// Open a fresh in-memory SQLite database, run migrations, and wrap it in a
 /// `Ledger`. Point the connection string at a file (e.g.
 /// `"sqlite://ledger.db?mode=rwc"`) or a Postgres URL for a persistent ledger.
-async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
+async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
     kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
@@ -61,6 +60,6 @@ async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
         .await?;
     let store = SqlStore::new(pool);
     store.migrate().await?;
-    let ledger = Arc::new(Ledger::new(store));
+    let ledger = Ledger::new(store);
     Ok(ledger)
 }

+ 3 - 5
crates/kuatia/examples/fund_and_trade.rs

@@ -5,8 +5,6 @@
 //! cargo run -p kuatia --example fund_and_trade
 //! ```
 
-use std::sync::Arc;
-
 use kuatia::ledger::Ledger;
 use kuatia_core::*;
 use kuatia_storage_sql::SqlStore;
@@ -66,7 +64,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 }
 
 async fn print_balances(
-    ledger: &Arc<Ledger>,
+    ledger: &Ledger,
     alice: AccountId,
     bob: AccountId,
     usd: AssetId,
@@ -86,7 +84,7 @@ async fn print_balances(
     Ok(())
 }
 
-async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
+async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
     kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
@@ -94,6 +92,6 @@ async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
         .await?;
     let store = SqlStore::new(pool);
     store.migrate().await?;
-    let ledger = Arc::new(Ledger::new(store));
+    let ledger = Ledger::new(store);
     Ok(ledger)
 }

+ 5 - 6
crates/kuatia/examples/inflight_hold.rs

@@ -11,7 +11,6 @@
 //! cargo run -p kuatia --example inflight_hold
 //! ```
 
-use std::sync::Arc;
 use std::time::Duration;
 
 use kuatia::prelude::*;
@@ -117,7 +116,7 @@ fn confirm_one(from: AccountId, to: AccountId, asset: AssetId, amount: Cent) ->
 }
 
 async fn print_balances(
-    ledger: &Arc<Ledger>,
+    ledger: &Ledger,
     money: &Amount,
     customer: AccountId,
     merchant: AccountId,
@@ -134,9 +133,9 @@ async fn print_balances(
 }
 
 async fn print_status(
-    ledger: &Arc<Ledger>,
+    ledger: &Ledger,
     money: &Amount,
-    inflight: &EnvelopeId,
+    inflight: &TransferId,
 ) -> Result<(), Box<dyn std::error::Error>> {
     let status = ledger.inflight_status(inflight).await?;
     println!("  state: {:?}", status.state);
@@ -156,7 +155,7 @@ async fn print_status(
 /// Open a fresh in-memory SQLite database, run migrations, and wrap it in a
 /// `Ledger`. Point the connection string at a file or a Postgres URL for a
 /// persistent ledger.
-async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
+async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
     kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
@@ -164,6 +163,6 @@ async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
         .await?;
     let store = SqlStore::new(pool);
     store.migrate().await?;
-    let ledger = Arc::new(Ledger::new(store));
+    let ledger = Ledger::new(store);
     Ok(ledger)
 }

+ 3 - 5
crates/kuatia/examples/overdraft.rs

@@ -6,8 +6,6 @@
 //! cargo run -p kuatia --example overdraft
 //! ```
 
-use std::sync::Arc;
-
 use kuatia::error::LedgerError;
 use kuatia::ledger::Ledger;
 use kuatia_core::*;
@@ -95,7 +93,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 /// Prints each posting with its lifecycle state, so a consumed positive and a
 /// created negative are visible side by side rather than inferred from balances.
 async fn print_postings(
-    ledger: &Arc<Ledger>,
+    ledger: &Ledger,
     account: AccountId,
     asset: AssetId,
 ) -> Result<(), Box<dyn std::error::Error>> {
@@ -108,7 +106,7 @@ async fn print_postings(
     Ok(())
 }
 
-async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
+async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
     kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
@@ -116,6 +114,6 @@ async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
         .await?;
     let store = SqlStore::new(pool);
     store.migrate().await?;
-    let ledger = Arc::new(Ledger::new(store));
+    let ledger = Ledger::new(store);
     Ok(ledger)
 }

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

@@ -5,8 +5,6 @@
 //! cargo run -p kuatia --example withdraw
 //! ```
 
-use std::sync::Arc;
-
 use kuatia::ledger::Ledger;
 use kuatia_core::*;
 use kuatia_storage_sql::SqlStore;
@@ -61,7 +59,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     Ok(())
 }
 
-async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
+async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
     kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
@@ -69,6 +67,6 @@ async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
         .await?;
     let store = SqlStore::new(pool);
     store.migrate().await?;
-    let ledger = Arc::new(Ledger::new(store));
+    let ledger = Ledger::new(store);
     Ok(ledger)
 }

+ 11 - 10
crates/kuatia/src/error.rs

@@ -7,17 +7,17 @@ use std::error::Error;
 use std::fmt;
 
 use kuatia_core::{
-    AccountId, AssetId, BookId, EnvelopeId, InsufficientFunds, OverflowError, PostingId,
-    ResolveError, ValidationError,
+    AccountId, AssetId, BookId, InsufficientFunds, OverflowError, PostingId, ResolveError,
+    TransferId, ValidationError,
 };
 use kuatia_storage::error::StoreError;
 
 /// Unified error type for the async ledger API.
 ///
-/// `Clone` so the saga engine can carry a typed error across its step seam and
-/// return the real variant to the caller (an [`OverdraftExceeded`] detected
-/// during commit stays an [`OverdraftExceeded`], not a stringified internal
-/// fault).
+/// `Clone` so a multi-transfer workflow can box the error that triggered its
+/// unwind and still return the real variant to the caller (an
+/// [`OverdraftExceeded`] detected during commit stays an [`OverdraftExceeded`],
+/// not a stringified internal fault).
 ///
 /// [`OverdraftExceeded`]: ValidationError::OverdraftExceeded
 #[derive(Debug, Clone)]
@@ -29,7 +29,7 @@ pub enum LedgerError {
     /// Posting selection failed (e.g. insufficient funds).
     Selection(InsufficientFunds),
     /// The referenced transfer does not exist.
-    TransferNotFound(EnvelopeId),
+    TransferNotFound(TransferId),
     /// The posting cannot be reversed (e.g. already consumed).
     PostingNotReversible(PostingId),
     /// A consumed posting was no longer live at commit time: already spent,
@@ -58,10 +58,10 @@ pub enum LedgerError {
     /// A book with this id already exists.
     BookAlreadyExists(BookId),
     /// The referenced inflight transaction does not exist (no authorize record).
-    InflightNotFound(EnvelopeId),
+    InflightNotFound(TransferId),
     /// The referenced transfer is not an inflight authorize, or its metadata is
     /// malformed.
-    NotInflightTransaction(EnvelopeId),
+    NotInflightTransaction(TransferId),
     /// The destination already has an open inflight hold; only one is allowed at
     /// a time per account.
     InflightAlreadyOpen(AccountId),
@@ -86,7 +86,8 @@ pub enum LedgerError {
         /// Asset whose balance was not loaded.
         asset: AssetId,
     },
-    /// A saga step failed and its compensation also failed.
+    /// A transfer in a multi-transfer workflow failed and reversing an
+    /// earlier one failed too, so the ledger is left part-applied.
     CompensationFailed {
         /// The error that triggered compensation.
         original: Box<LedgerError>,

+ 21 - 32
crates/kuatia/src/inflight.rs

@@ -12,15 +12,13 @@
 //!
 //! See `doc/adr/0014-inflight-holds-via-holding-accounts.md`.
 
-use std::collections::{BTreeMap, BTreeSet};
-use std::sync::Arc;
-
 use kuatia_core::{
-    Account, AccountFlags, AccountId, AssetId, BookId, Cent, EnvelopeId, InsufficientFunds,
-    Receipt, SUB_BITS, Transfer, TransferBuilder, hash::double_sha256,
+    Account, AccountFlags, AccountId, AssetId, BookId, Cent, InsufficientFunds, Receipt, SUB_BITS,
+    Transfer, TransferBuilder, TransferId, hash::double_sha256,
 };
-use kuatia_storage::store::EnvelopeRecord;
+use kuatia_storage::store::TransferRecord;
 use serde::{Deserialize, Serialize};
+use std::collections::{BTreeMap, BTreeSet};
 
 use crate::error::LedgerError;
 use crate::ledger::Ledger;
@@ -51,7 +49,7 @@ pub struct InflightLeg {
 #[derive(Debug, Clone)]
 pub struct Authorization {
     /// Handle for the inflight transaction: the authorize transfer's id.
-    pub inflight: EnvelopeId,
+    pub inflight: TransferId,
     /// The legs, one per original movement.
     pub legs: Vec<InflightLeg>,
 }
@@ -104,7 +102,7 @@ pub struct InflightLegStatus {
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct InflightStatus {
     /// The inflight handle.
-    pub inflight: EnvelopeId,
+    pub inflight: TransferId,
     /// One entry per (destination, asset).
     pub legs: Vec<InflightLegStatus>,
     /// Overall state.
@@ -133,10 +131,7 @@ impl Ledger {
     /// subaccount derived from the trade, so re-authorizing the identical trade is
     /// rejected (its holds already exist), while different trades to the same
     /// destination run concurrently under distinct subaccounts.
-    pub async fn authorize(
-        self: &Arc<Self>,
-        transfer: Transfer,
-    ) -> Result<Authorization, LedgerError> {
+    pub async fn authorize(&self, transfer: Transfer) -> Result<Authorization, LedgerError> {
         // All holds of this inflight share one subaccount, derived from the
         // submitted trade so it is stable and known before the holds are created
         // (the authorize transfer's own id cannot be used: it is a hash of the
@@ -185,7 +180,7 @@ impl Ledger {
                 asset: m.asset,
                 amount: m.amount,
             });
-            builder = builder.movement_ref(m.from, hold, m.asset, m.amount);
+            builder = builder.movement(m.from, hold, m.asset, m.amount);
         }
         let mut md = transfer.metadata.clone();
         md.insert(
@@ -207,10 +202,7 @@ impl Ledger {
 
     /// Confirm the entire inflight transaction: sweep every hold's remaining
     /// balance to its destination and close the drained holds.
-    pub async fn confirm_all(
-        self: &Arc<Self>,
-        inflight: &EnvelopeId,
-    ) -> Result<Vec<Receipt>, LedgerError> {
+    pub async fn confirm_all(&self, inflight: &TransferId) -> Result<Vec<Receipt>, LedgerError> {
         let (record, legs) = self.load_inflight(inflight).await?;
         let book = record.envelope.book();
         let mut receipts = Vec::new();
@@ -252,8 +244,8 @@ impl Ledger {
     /// Movements settle in order, each its own commit, so the batch is not atomic:
     /// a later movement failing leaves earlier confirmations applied.
     pub async fn confirm(
-        self: &Arc<Self>,
-        inflight: &EnvelopeId,
+        &self,
+        inflight: &TransferId,
         confirms: Transfer,
     ) -> Result<Vec<Receipt>, LedgerError> {
         let (record, legs) = self.load_inflight(inflight).await?;
@@ -302,10 +294,7 @@ impl Ledger {
 
     /// Void the entire inflight transaction: return every hold's remaining
     /// balance to the funders recorded in the leg table and close the holds.
-    pub async fn void(
-        self: &Arc<Self>,
-        inflight: &EnvelopeId,
-    ) -> Result<Vec<Receipt>, LedgerError> {
+    pub async fn void(&self, inflight: &TransferId) -> Result<Vec<Receipt>, LedgerError> {
         let (record, legs) = self.load_inflight(inflight).await?;
         let book = record.envelope.book();
         let mut receipts = Vec::new();
@@ -346,14 +335,14 @@ impl Ledger {
     /// from balances and the metadata-tagged settling transfers.
     pub async fn inflight_status(
         &self,
-        inflight: &EnvelopeId,
+        inflight: &TransferId,
     ) -> Result<InflightStatus, LedgerError> {
         let (_record, legs) = self.load_inflight(inflight).await?;
 
         // Load exactly what the projection reads: each hold's settle history and
         // its live per-asset balance. `group_holds` names the holds to fetch;
         // `derive_status` re-derives its own grouping to fold the status.
-        let mut hold_history: Vec<(AccountId, Vec<EnvelopeRecord>)> = Vec::new();
+        let mut hold_history: Vec<(AccountId, Vec<TransferRecord>)> = Vec::new();
         let mut held: BTreeMap<(AccountId, AssetId), Cent> = BTreeMap::new();
         for group in group_holds(&legs, *inflight)? {
             hold_history.push((group.hold, self.history(&group.hold).await?));
@@ -392,8 +381,8 @@ impl Ledger {
     /// Load the authorize transfer and decode its leg table.
     async fn load_inflight(
         &self,
-        inflight: &EnvelopeId,
-    ) -> Result<(EnvelopeRecord, Vec<InflightLeg>), LedgerError> {
+        inflight: &TransferId,
+    ) -> Result<(TransferRecord, Vec<InflightLeg>), LedgerError> {
         let record = self
             .store()
             .get_transfer(inflight)
@@ -409,9 +398,9 @@ impl Ledger {
     /// Commit a `hold -> target` settling transfer tagged with the inflight role.
     #[allow(clippy::too_many_arguments)]
     async fn settle(
-        self: &Arc<Self>,
+        &self,
         book: BookId,
-        inflight: EnvelopeId,
+        inflight: TransferId,
         hold: AccountId,
         target: AccountId,
         destination: AccountId,
@@ -431,14 +420,14 @@ impl Ledger {
         };
         let tx = TransferBuilder::new()
             .book(book)
-            .pay_ref(hold, target, asset, amount)
+            .pay(hold, target, asset, amount)
             .metadata(meta_map(&meta)?)
             .build();
         self.commit(tx).await
     }
 
-    /// Close a holding account once it has no live (active or reserved) postings
-    /// left. No-op if already closed or still holding funds.
+    /// Close a holding account once it has no unspent postings left. No-op if
+    /// already closed or still holding funds.
     async fn close_if_drained(&self, hold: &AccountId) -> Result<(), LedgerError> {
         if self.has_live_postings(hold).await? {
             return Ok(());

+ 17 - 17
crates/kuatia/src/inflight/projection.rs

@@ -7,13 +7,13 @@
 //! `self`, no IO, no async); the async [`Ledger`](crate::ledger::Ledger)
 //! methods in the parent module only load raw records and call these functions.
 //! It stays in the `kuatia` crate rather than moving to `kuatia-core` because it
-//! reads [`EnvelopeRecord`], a `kuatia-storage` type the pure core avoids.
+//! reads [`TransferRecord`], a `kuatia-storage` type the pure core avoids.
 
 use std::collections::{BTreeMap, BTreeSet};
 
-use kuatia_core::{AccountId, AssetId, Cent, EnvelopeId, Metadata, OverflowError};
+use kuatia_core::{AccountId, AssetId, Cent, Metadata, OverflowError, TransferId};
 use kuatia_storage::error::StoreError;
-use kuatia_storage::store::EnvelopeRecord;
+use kuatia_storage::store::TransferRecord;
 use serde::{Deserialize, Serialize};
 
 use super::{InflightLeg, InflightLegStatus, InflightState, InflightStatus};
@@ -37,17 +37,17 @@ pub(super) enum InflightMeta {
     Hold { destination: AccountId },
     /// Tags a settling transfer that delivers to a destination.
     Confirm {
-        tx: EnvelopeId,
+        tx: TransferId,
         destination: AccountId,
     },
     /// Tags a settling transfer that returns to a funder.
     Void {
-        tx: EnvelopeId,
+        tx: TransferId,
         destination: AccountId,
     },
 }
 
-fn malformed(tid: EnvelopeId) -> LedgerError {
+fn malformed(tid: TransferId) -> LedgerError {
     LedgerError::NotInflightTransaction(tid)
 }
 
@@ -92,7 +92,7 @@ pub(super) struct HoldGroup {
 /// leg table and yields holds in sorted order (each with its assets sorted).
 pub(super) fn group_holds(
     legs: &[InflightLeg],
-    inflight: EnvelopeId,
+    inflight: TransferId,
 ) -> Result<Vec<HoldGroup>, LedgerError> {
     holds_of(legs)
         .into_iter()
@@ -120,7 +120,7 @@ fn assets_of(legs: &[InflightLeg], hold: AccountId) -> BTreeSet<AssetId> {
 fn destination_of(
     legs: &[InflightLeg],
     hold: AccountId,
-    inflight: EnvelopeId,
+    inflight: TransferId,
 ) -> Result<AccountId, LedgerError> {
     legs.iter()
         .find(|l| l.hold == hold)
@@ -137,11 +137,11 @@ fn destination_of(
 /// the projection reads.
 pub(super) struct StatusInput<'a> {
     /// The inflight handle.
-    pub(super) inflight: EnvelopeId,
+    pub(super) inflight: TransferId,
     /// The leg table from the authorize transfer.
     pub(super) legs: &'a [InflightLeg],
     /// Settle transfers found in each hold's history, tagged with that hold.
-    pub(super) hold_history: &'a [(AccountId, Vec<EnvelopeRecord>)],
+    pub(super) hold_history: &'a [(AccountId, Vec<TransferRecord>)],
     /// Live held balance per (hold, asset).
     pub(super) held: &'a BTreeMap<(AccountId, AssetId), Cent>,
 }
@@ -170,7 +170,7 @@ pub(super) fn derive_status(input: StatusInput<'_>) -> Result<InflightStatus, Le
 
     // Index history by hold so attribution keys on the fetched-for hold, never
     // on the records' order relative to `groups`.
-    let history_by_hold: BTreeMap<AccountId, &[EnvelopeRecord]> = hold_history
+    let history_by_hold: BTreeMap<AccountId, &[TransferRecord]> = hold_history
         .iter()
         .map(|(hold, recs)| (*hold, recs.as_slice()))
         .collect();
@@ -448,8 +448,8 @@ mod tests {
 
     // -- derive_status end-to-end vectors ----------------------------------
 
-    fn settle_record(meta: InflightMeta, creates: Vec<NewPosting>) -> EnvelopeRecord {
-        EnvelopeRecord {
+    fn settle_record(meta: InflightMeta, creates: Vec<NewPosting>) -> TransferRecord {
+        TransferRecord {
             envelope: Envelope {
                 consumes: vec![],
                 creates,
@@ -458,7 +458,7 @@ mod tests {
                 metadata: meta_map(&meta).unwrap(),
             },
             receipt: Receipt {
-                transfer_id: EnvelopeId([0; 32]),
+                transfer_id: TransferId([0; 32]),
             },
             created_at: 0,
         }
@@ -478,7 +478,7 @@ mod tests {
         // A single leg authorized 100. One confirm settle delivers 60 to the
         // destination and returns 40 change to the hold. The change posting must
         // not count toward `confirmed`.
-        let inflight = EnvelopeId([9; 32]);
+        let inflight = TransferId([9; 32]);
         let hold = AccountId::with_sub(2, 7);
         let dest = AccountId::new(2);
         let legs = [leg(1, 7, 1, 100)];
@@ -515,7 +515,7 @@ mod tests {
     fn derive_status_confirmed_and_voided_bucketing() {
         // Authorized 100, fully settled: 70 confirmed to the destination, 30
         // voided back to the funder, nothing held -> Mixed.
-        let inflight = EnvelopeId([9; 32]);
+        let inflight = TransferId([9; 32]);
         let hold = AccountId::with_sub(2, 7);
         let dest = AccountId::new(2);
         let funder = AccountId::new(1);
@@ -556,7 +556,7 @@ mod tests {
 
     #[test]
     fn derive_status_all_held_when_no_settles() {
-        let inflight = EnvelopeId([9; 32]);
+        let inflight = TransferId([9; 32]);
         let hold = AccountId::with_sub(2, 7);
         let legs = [leg(1, 7, 1, 100)];
         let hold_history = vec![(hold, vec![])];

+ 35 - 18
crates/kuatia/src/ledger.rs

@@ -22,10 +22,12 @@ use crate::error::LedgerError;
 mod balance;
 mod commit;
 mod lifecycle;
+mod projection;
 mod query;
 mod transition;
 
 pub use balance::SubAccountBalance;
+pub use projection::Projection;
 
 /// Default grace window (milliseconds) for the balance projection watermark: how
 /// far behind live a snapshot is allowed to advance, covering commit-to-visibility
@@ -36,6 +38,29 @@ pub const DEFAULT_PROJECTION_GRACE_MS: i64 = 60_000;
 /// since its latest cache point before a read appends a new one. See ADR-0019.
 pub const DEFAULT_SNAPSHOT_INTERVAL: u64 = 128;
 
+/// How the balance projection maintains itself (ADR-0019). Grouped into one type
+/// because these only tune the cache: correctness never depends on them, so a
+/// caller can ignore them entirely.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ProjectionConfig {
+    /// How far behind live (ms) a new cache point's watermark sits, which also
+    /// debounces the background append.
+    pub grace_ms: i64,
+    /// Credits/debits that must accrue since the latest cache point before a
+    /// read appends a new one. Smaller snapshots more often: shorter read tails,
+    /// more rows.
+    pub snapshot_interval: u64,
+}
+
+impl Default for ProjectionConfig {
+    fn default() -> Self {
+        Self {
+            grace_ms: DEFAULT_PROJECTION_GRACE_MS,
+            snapshot_interval: DEFAULT_SNAPSHOT_INTERVAL,
+        }
+    }
+}
+
 /// Return the current time as Unix milliseconds.
 pub(crate) fn now_millis() -> Result<i64, LedgerError> {
     Ok(std::time::SystemTime::now()
@@ -47,12 +72,7 @@ pub(crate) fn now_millis() -> Result<i64, LedgerError> {
 /// Async ledger resource composing the commit pipeline.
 pub struct Ledger {
     store: Arc<dyn Store>,
-    /// Grace window (ms) a cache point keeps behind live when its watermark is
-    /// set (ADR-0019).
-    projection_grace_ms: i64,
-    /// Credits/debits that must accrue since the latest cache point before a read
-    /// appends a new one (ADR-0019).
-    snapshot_interval: u64,
+    projection: ProjectionConfig,
 }
 
 impl Ledger {
@@ -60,24 +80,21 @@ impl Ledger {
     pub fn new(store: impl Store + 'static) -> Self {
         Self {
             store: Arc::new(store),
-            projection_grace_ms: DEFAULT_PROJECTION_GRACE_MS,
-            snapshot_interval: DEFAULT_SNAPSHOT_INTERVAL,
+            projection: ProjectionConfig::default(),
         }
     }
 
-    /// Set the cache-point grace window (ms). Larger is safer against
-    /// commit-to-visibility lag but keeps the read tail longer. See ADR-0019.
-    pub fn with_projection_grace_ms(mut self, grace_ms: i64) -> Self {
-        self.projection_grace_ms = grace_ms;
+    /// Tune how the balance projection maintains itself. Cache behaviour only;
+    /// the defaults suit any ledger that is not measuring its read latency.
+    pub fn with_projection_config(mut self, projection: ProjectionConfig) -> Self {
+        self.projection = projection;
         self
     }
 
-    /// Set how many credits/debits accrue before a read appends a new cache
-    /// point. Smaller snapshots more often (shorter tails, more rows); larger
-    /// snapshots less often. See ADR-0019.
-    pub fn with_snapshot_interval(mut self, interval: u64) -> Self {
-        self.snapshot_interval = interval;
-        self
+    /// The balance projection's maintenance surface, kept off the balance reads
+    /// because nothing here answers what an account holds.
+    pub fn projection(&self) -> Projection<'_> {
+        Projection::new(self)
     }
 
     /// Returns a reference to the underlying store.

+ 15 - 29
crates/kuatia/src/ledger/balance.rs

@@ -3,8 +3,8 @@
 //!
 //! One concept, two computation strategies that must agree:
 //!
-//! - [`compute_balance`](Ledger::compute_balance) is **authoritative**: the sum
-//!   of the live (active or reserved) postings for one `(account, asset)`, always
+//! - [`balance_exact`](Ledger::balance_exact) is **authoritative**: the sum
+//!   of the live (unspent) postings for one `(account, asset)`, always
 //!   recomputed from the source of truth. It is what validation reads, what the
 //!   projector folds into snapshots, and what reconciliation checks against.
 //! - [`balance`](Ledger::balance) is the **everyday read**: the closest cache
@@ -12,7 +12,7 @@
 //!   its watermark.
 //!
 //! The module's core contract: summing every one of an account's transfer deltas
-//! equals its live-posting sum, so **`balance` always equals `compute_balance` at
+//! equals its live-posting sum, so **`balance` always equals `balance_exact` at
 //! rest**. Cache points are a pure optimization that shortens the tail;
 //! correctness never depends on them, and reconciliation re-derives the
 //! authoritative value to check against a cache point.
@@ -26,7 +26,7 @@ use std::sync::Arc;
 use tracing::instrument;
 
 use kuatia_core::{AccountId, AssetId, Cent, PostingId};
-use kuatia_storage::store::{EnvelopeRecord, Store, TransferQuery};
+use kuatia_storage::store::{Store, TransferQuery, TransferRecord};
 
 use super::{Ledger, now_millis};
 use crate::error::LedgerError;
@@ -56,7 +56,7 @@ async fn fold_account_delta(
     store: &dyn Store,
     account: &AccountId,
     asset: &AssetId,
-    records: &[EnvelopeRecord],
+    records: &[TransferRecord],
 ) -> Result<(Cent, u64), LedgerError> {
     let mut delta = Cent::ZERO;
     let mut count: u64 = 0;
@@ -131,7 +131,7 @@ async fn fold_tail(
 /// not in process memory, so it dedups across every ledger instance and survives
 /// a restart, and it needs no lease, lock, or CAS (ADR-0019). `debounce_ms == 0`
 /// disables it (the reconcile path forces an append regardless).
-async fn append_cache_point(
+pub(super) async fn append_cache_point(
     store: &dyn Store,
     grace_ms: i64,
     min_new: u64,
@@ -174,15 +174,15 @@ async fn append_cache_point(
 }
 
 impl Ledger {
-    /// The authoritative balance: the sum of the live (active or reserved)
-    /// postings for one `(account, asset)`. This bypasses the cached projection
+    /// The authoritative balance: the sum of the live (unspent) postings for
+    /// one `(account, asset)`. This bypasses the cached projection
     /// and always recomputes from the source of truth, so it is what validation
     /// reads, what the projector folds into snapshots, and what reconciliation
     /// checks against. Still `O(live postings)`, but the SQL store adds them up
     /// inside the database rather than shipping every row here; prefer
     /// [`balance`](Ledger::balance) for the everyday read.
-    #[instrument(skip(self), name = "ledger.compute_balance")]
-    pub async fn compute_balance(
+    #[instrument(skip(self), name = "ledger.balance_exact")]
+    pub async fn balance_exact(
         &self,
         account: &AccountId,
         asset: &AssetId,
@@ -193,7 +193,7 @@ impl Ledger {
     /// The everyday balance read for one subaccount and asset (ADR-0019): the
     /// closest cache point (at or before now) plus the folded tail of transfers
     /// committed after its watermark. Always equal to
-    /// [`compute_balance`](Ledger::compute_balance) at rest, and faster once a
+    /// [`balance_exact`](Ledger::balance_exact) at rest, and faster once a
     /// cache point keeps the tail short. With no cache point yet it returns the
     /// authoritative live-posting sum directly (rather than folding the whole
     /// history) and bootstraps a cache point in the background. Once enough
@@ -216,7 +216,7 @@ impl Ledger {
                     None,
                 )
                 .await?;
-                if count >= self.snapshot_interval {
+                if count >= self.projection.snapshot_interval {
                     self.spawn_append(*account, *asset);
                 }
                 Ok(p.balance.checked_add(tail)?)
@@ -226,7 +226,7 @@ impl Ledger {
             // the background (the append itself gates on `snapshot_interval`, so a
             // small account never actually appends) so later reads use the tail.
             None => {
-                let balance = self.compute_balance(account, asset).await?;
+                let balance = self.balance_exact(account, asset).await?;
                 self.spawn_append(*account, *asset);
                 Ok(balance)
             }
@@ -297,8 +297,8 @@ impl Ledger {
     /// this process's memory.
     fn spawn_append(&self, account: AccountId, asset: AssetId) {
         let store = Arc::clone(&self.store);
-        let grace = self.projection_grace_ms;
-        let min_new = self.snapshot_interval;
+        let grace = self.projection.grace_ms;
+        let min_new = self.projection.snapshot_interval;
         tokio::spawn(async move {
             if let Err(err) =
                 append_cache_point(store.as_ref(), grace, min_new, grace, &account, &asset).await
@@ -309,18 +309,4 @@ impl Ledger {
             }
         });
     }
-
-    /// Append a cache point for one `(account, asset)` now (folding up to
-    /// `now − grace`), unconditionally. The read path appends lazily in the
-    /// background; this forces one (no debounce), exposed for tests and
-    /// reconciliation. Append-only: a repeat within the same grace-adjusted
-    /// millisecond is a no-op (the watermark is already covered), otherwise it
-    /// adds a fresh row.
-    pub async fn append_cache_point(
-        &self,
-        account: &AccountId,
-        asset: &AssetId,
-    ) -> Result<(), LedgerError> {
-        append_cache_point(self.store(), self.projection_grace_ms, 0, 0, account, asset).await
-    }
 }

+ 11 - 16
crates/kuatia/src/ledger/commit.rs

@@ -10,20 +10,18 @@
 
 use std::collections::HashMap;
 use std::collections::hash_map::Entry;
-use std::sync::Arc;
-
 use tracing::instrument;
 
 use kuatia_core::{
     Account, AccountId, AccountSnapshotId, AssetId, Book, Cent, DEFAULT_BOOK, Envelope,
-    EnvelopeBuilder, EnvelopeId, NewPosting, Plan, PlanInput, Posting, PostingFilter, PostingId,
-    Receipt, ResolveInput, Transfer, ValidationError, account_snapshot_id, draft_movements,
+    EnvelopeBuilder, NewPosting, Plan, PlanInput, Posting, PostingFilter, PostingId, Receipt,
+    ResolveInput, Transfer, TransferId, 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::{CommitOutcome, CommitRejection, CommitRequest, EnvelopeRecord};
+use kuatia_storage::store::{CommitOutcome, CommitRejection, CommitRequest, TransferRecord};
 
 use super::{Ledger, now_millis};
 use crate::error::LedgerError;
@@ -64,7 +62,7 @@ impl Ledger {
 
         let mut balances = HashMap::new();
         for (account_id, asset_id) in &required.balances {
-            let bal = self.compute_balance(account_id, asset_id).await?;
+            let bal = self.balance_exact(account_id, asset_id).await?;
             balances.insert((*account_id, *asset_id), bal);
         }
 
@@ -142,7 +140,7 @@ impl Ledger {
                     debit.account.id,
                     Some(debit.account.sub),
                     Some(&debit.asset),
-                    PostingFilter::Active,
+                    PostingFilter::Live,
                 )
                 .await?;
             available.insert((debit.account, debit.asset), postings);
@@ -173,7 +171,7 @@ impl Ledger {
     /// 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> {
+    pub async fn commit(&self, transfer: Transfer) -> Result<Receipt, LedgerError> {
         let envelope = self.resolve(&transfer).await?;
         self.commit_envelope(envelope).await
     }
@@ -187,10 +185,7 @@ impl Ledger {
     /// 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>,
-        mut envelope: Envelope,
-    ) -> Result<Receipt, LedgerError> {
+    pub async fn commit_envelope(&self, mut envelope: Envelope) -> Result<Receipt, LedgerError> {
         if envelope.account_snapshots().is_empty() {
             let mut ids: Vec<AccountId> = envelope.creates().iter().map(|p| p.owner).collect();
             ids.sort();
@@ -224,7 +219,7 @@ impl Ledger {
         let receipt = Receipt {
             transfer_id: plan.transfer_id,
         };
-        let record = EnvelopeRecord {
+        let record = TransferRecord {
             envelope: envelope.clone(),
             receipt: receipt.clone(),
             created_at: ts,
@@ -260,7 +255,7 @@ impl Ledger {
 
     /// Create and commit a reversal envelope for the given envelope id.
     #[instrument(skip(self), name = "ledger.reverse")]
-    pub async fn reverse(self: &Arc<Self>, id: &EnvelopeId) -> Result<Receipt, LedgerError> {
+    pub async fn reverse(&self, id: &TransferId) -> Result<Receipt, LedgerError> {
         let record = self
             .store
             .get_transfer(id)
@@ -359,8 +354,8 @@ mod tests {
         }
     }
 
-    async fn funded_ledger() -> Arc<Ledger> {
-        let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    async fn funded_ledger() -> Ledger {
+        let ledger = Ledger::new(InMemoryStore::new());
         for (id, p) in [
             (1, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),
             (2, AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT),

+ 3 - 4
crates/kuatia/src/ledger/lifecycle.rs

@@ -86,10 +86,9 @@ impl Ledger {
         .await
     }
 
-    /// Whether `account` (exact base id and subaccount) has any live posting: one
-    /// that is active or reserved by an in-flight saga. Spent postings do not
-    /// count. This is the emptiness test [`close`](Self::close) gates on, and the
-    /// inflight layer uses it to decide when a drained hold can be closed.
+    /// Whether `account` (exact base id and subaccount) holds any unspent
+    /// posting. This is the emptiness test [`close`](Self::close) gates on, and
+    /// the inflight layer uses it to decide when a drained hold can be closed.
     #[instrument(skip(self), name = "ledger.has_live_postings")]
     pub async fn has_live_postings(&self, account: &AccountId) -> Result<bool, LedgerError> {
         Ok(!self

+ 46 - 0
crates/kuatia/src/ledger/projection.rs

@@ -0,0 +1,46 @@
+//! The balance projection's maintenance surface (ADR-0019).
+//!
+//! Kept apart from the balance reads in [`balance`](super::balance) because
+//! nothing here answers what an account holds: these operations manage the
+//! disposable cache that makes those reads fast.
+
+use kuatia_core::{AccountId, AssetId};
+
+use super::Ledger;
+use super::balance::append_cache_point;
+use crate::error::LedgerError;
+
+/// Maintenance operations on the balance projection, from
+/// [`Ledger::projection`](Ledger::projection).
+pub struct Projection<'a> {
+    ledger: &'a Ledger,
+}
+
+impl<'a> Projection<'a> {
+    pub(super) fn new(ledger: &'a Ledger) -> Self {
+        Self { ledger }
+    }
+
+    /// Append a cache point for one `(account, asset)` now, folding up to
+    /// `now - grace`, whether or not one is due.
+    ///
+    /// Reads already append lazily in the background, so a caller needs this
+    /// only to pin a snapshot at a chosen moment, as an audit or a test does.
+    /// Append-only: a repeat inside the same grace-adjusted millisecond adds
+    /// nothing, since that watermark is already covered.
+    pub async fn append_cache_point(
+        &self,
+        account: &AccountId,
+        asset: &AssetId,
+    ) -> Result<(), LedgerError> {
+        append_cache_point(
+            self.ledger.store(),
+            self.ledger.projection.grace_ms,
+            0,
+            0,
+            account,
+            asset,
+        )
+        .await
+    }
+}

+ 4 - 4
crates/kuatia/src/ledger/query.rs

@@ -12,7 +12,7 @@ use kuatia_storage::events::LedgerEvent;
 
 use super::Ledger;
 use crate::error::LedgerError;
-use crate::store::{EnvelopeRecord, Page, PostingQuery, TransferQuery};
+use crate::store::{Page, PostingQuery, TransferQuery, TransferRecord};
 
 impl Ledger {
     /// List all accounts (latest version of each).
@@ -29,7 +29,7 @@ impl Ledger {
     }
 
     /// Return all transfers involving the given account (exact subaccount).
-    pub async fn history(&self, account: &AccountId) -> Result<Vec<EnvelopeRecord>, LedgerError> {
+    pub async fn history(&self, account: &AccountId) -> Result<Vec<TransferRecord>, LedgerError> {
         Ok(self
             .store
             .get_transfers_for_account(account.id, Some(account.sub))
@@ -40,7 +40,7 @@ impl Ledger {
     pub async fn query_transfers(
         &self,
         query: &TransferQuery,
-    ) -> Result<Page<EnvelopeRecord>, LedgerError> {
+    ) -> Result<Page<TransferRecord>, LedgerError> {
         Ok(self.store.query_transfers(query).await?)
     }
 
@@ -53,7 +53,7 @@ impl Ledger {
     }
 
     /// Return all postings for the given account paired with their derived
-    /// lifecycle state (active, reserved, or spent).
+    /// state, which distinguishes an unspent posting from a spent one.
     pub async fn postings_with_state(
         &self,
         account: &AccountId,

+ 6 - 5
crates/kuatia/src/lib.rs

@@ -1,13 +1,14 @@
-//! Kuatia — async ledger resource built on top of [`kuatia_core`].
+//! Kuatia: async ledger resource built on top of [`kuatia_core`].
 //!
-//! This crate adds IO to the pure decision logic: the [`Store`](kuatia_storage::store::Store) trait
-//! abstracts storage, and the [`Ledger`](crate::ledger::Ledger) struct drives the linear
-//! reserve → finalize commit path (validation inside finalize) behind an async API.
+//! This crate adds IO to the pure decision logic: the [`Store`](kuatia_storage::store::Store)
+//! trait abstracts storage, and the [`Ledger`](crate::ledger::Ledger) struct resolves a
+//! transfer and hands it to the store as one atomic commit (ADR-0023) behind an
+//! async API.
 
 pub mod error;
 pub mod inflight;
 pub mod ledger;
-pub mod saga;
+pub mod workflow;
 
 // Re-export storage crate for convenience.
 pub use kuatia_storage::{error as store_error, mem_store, store, store_tests};

+ 0 - 95
crates/kuatia/src/saga.rs

@@ -1,95 +0,0 @@
-//! Multi-transfer composition over the ledger.
-//!
-//! [`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::sync::Arc;
-
-use serde::{Deserialize, Serialize};
-
-use kuatia_core::{AccountId, AssetId, Cent, Receipt, Transfer, TransferBuilder};
-
-use crate::error::LedgerError;
-use crate::ledger::Ledger;
-
-/// A pay movement between two accounts.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct PayInput {
-    /// Source account.
-    pub from: AccountId,
-    /// Destination account.
-    pub to: AccountId,
-    /// Asset to transfer.
-    pub asset: AssetId,
-    /// Amount to transfer.
-    pub amount: Cent,
-}
-
-/// A deposit from an external account.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct DepositInput {
-    /// Account receiving the deposit.
-    pub to: AccountId,
-    /// Asset being deposited.
-    pub asset: AssetId,
-    /// Amount to deposit.
-    pub amount: Cent,
-    /// External account funding the deposit.
-    pub external: AccountId,
-}
-
-/// 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),
-}
-
-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()),
-        }
-    }
-}
-
-/// 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)
-}

+ 41 - 0
crates/kuatia/src/workflow.rs

@@ -0,0 +1,41 @@
+//! Multi-transfer composition over the ledger.
+//!
+//! [`run_transfers`] 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 needs no state of its own.
+
+use kuatia_core::{Receipt, Transfer};
+
+use crate::error::LedgerError;
+use crate::ledger::Ledger;
+
+/// Commit each transfer 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_transfers(
+    ledger: &Ledger,
+    transfers: &[Transfer],
+) -> Result<Vec<Receipt>, LedgerError> {
+    let mut receipts: Vec<Receipt> = Vec::new();
+    for transfer in transfers {
+        match ledger.commit(transfer.clone()).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)
+}

+ 1 - 1
crates/kuatia/tests/inflight.rs

@@ -349,7 +349,7 @@ async fn reauthorize_after_settlement() {
 #[tokio::test]
 async fn unknown_inflight_is_an_error() {
     let ledger = setup().await;
-    let bogus = EnvelopeId([7u8; 32]);
+    let bogus = TransferId([7u8; 32]);
     assert!(matches!(
         ledger.confirm_all(&bogus).await.unwrap_err(),
         LedgerError::InflightNotFound(_)

+ 86 - 22
crates/kuatia/tests/integration.rs

@@ -261,6 +261,78 @@ async fn idempotent_commit() {
     );
 }
 
+/// A deposit consumes nothing, so two of the same amount to the same account
+/// are byte-identical and the second is a replay. This is the case a reference
+/// exists for, and the case that loses money without one.
+#[tokio::test]
+async fn identical_deposits_need_a_reference_to_both_land() {
+    let ledger = setup_ledger().await;
+    let plain = || {
+        TransferBuilder::new()
+            .deposit(account(1), usd(), Cent::from(100), external())
+            .unwrap()
+            .build()
+    };
+
+    let first = ledger.commit(plain()).await.unwrap();
+    let second = ledger.commit(plain()).await.unwrap();
+    assert_eq!(
+        first.transfer_id, second.transfer_id,
+        "identical deposits are one transfer"
+    );
+    assert_eq!(
+        ledger.balance(&account(1), &usd()).await.unwrap(),
+        Cent::from(100),
+        "the second deposit was a replay, not a second credit"
+    );
+
+    let referenced = |r: &str| {
+        TransferBuilder::new()
+            .deposit(account(1), usd(), Cent::from(100), external())
+            .unwrap()
+            .reference(r)
+            .build()
+    };
+    let a = ledger.commit(referenced("top-up-1")).await.unwrap();
+    let b = ledger.commit(referenced("top-up-2")).await.unwrap();
+    assert_ne!(a.transfer_id, b.transfer_id);
+    assert_eq!(
+        ledger.balance(&account(1), &usd()).await.unwrap(),
+        Cent::from(300),
+        "distinct references make distinct transfers"
+    );
+
+    // Repeating a reference is how a retry stays idempotent.
+    let replay = ledger.commit(referenced("top-up-2")).await.unwrap();
+    assert_eq!(replay.transfer_id, b.transfer_id);
+    assert_eq!(
+        ledger.balance(&account(1), &usd()).await.unwrap(),
+        Cent::from(300)
+    );
+}
+
+/// A payment distinguishes itself: the second consumes the change the first
+/// created, so it hashes differently with no reference set.
+#[tokio::test]
+async fn identical_payments_are_distinct_without_a_reference() {
+    let ledger = setup_ledger().await;
+    deposit(&ledger, account(1), usd(), Cent::from(100), external()).await;
+
+    let pay_ten = || {
+        TransferBuilder::new()
+            .pay(account(1), account(2), usd(), Cent::from(10))
+            .build()
+    };
+    let first = ledger.commit(pay_ten()).await.unwrap();
+    let second = ledger.commit(pay_ten()).await.unwrap();
+
+    assert_ne!(first.transfer_id, second.transfer_id);
+    assert_eq!(
+        ledger.balance(&account(2), &usd()).await.unwrap(),
+        Cent::from(20)
+    );
+}
+
 // ---------------------------------------------------------------------------
 // Overdraft prevention
 // ---------------------------------------------------------------------------
@@ -408,12 +480,12 @@ async fn fx_trade_via_market_account() {
     // Build the atomic envelope manually since it spans two assets
     let a1_usd_postings = ledger
         .store()
-        .get_postings_by_account(1, None, Some(&usd()), PostingFilter::Active)
+        .get_postings_by_account(1, None, Some(&usd()), PostingFilter::Live)
         .await
         .unwrap();
     let fx_eur_postings = ledger
         .store()
-        .get_postings_by_account(50, None, Some(&eur()), PostingFilter::Active)
+        .get_postings_by_account(50, None, Some(&eur()), PostingFilter::Live)
         .await
         .unwrap();
 
@@ -528,28 +600,20 @@ async fn close_account_with_balance_rejected() {
     );
 }
 
+/// Paying the whole balance leaves no change posting, so the account holds
+/// nothing live and closing it is allowed: spent postings do not block close.
 #[tokio::test]
-async fn close_rejects_reserved_postings() {
+async fn close_succeeds_once_postings_are_spent() {
     let ledger = setup_ledger().await;
 
     deposit(&ledger, account(1), usd(), Cent::from(100), external()).await;
+    let transfer = TransferBuilder::new()
+        .pay(account(1), account(2), usd(), Cent::from(100))
+        .build();
+    ledger.commit(transfer).await.unwrap();
 
-    // Reserve the account's only posting (a transfer in flight): move it from
-    // the active index into the reserved index.
-    let postings = ledger
-        .store()
-        .get_postings_by_account(1, None, Some(&usd()), PostingFilter::Active)
-        .await
-        .unwrap();
-    ledger
-        .store()
-        .reserve_postings(&[postings[0].id], ReservationId::new(1))
-        .await
-        .unwrap();
-
-    // Close must reject: the posting is live (reserved), not spent.
-    let result = ledger.close(&account(1)).await;
-    assert!(result.is_err());
+    ledger.close(&account(1)).await.unwrap();
+    assert!(ledger.get_account(&account(1)).await.unwrap().is_closed());
 }
 
 #[tokio::test]
@@ -597,7 +661,7 @@ async fn postings_returns_all_postings() {
     let with_state = ledger.postings_with_state(&account(1)).await.unwrap();
     let active: Vec<_> = with_state
         .iter()
-        .filter(|(_, s)| *s == PostingState::Active)
+        .filter(|(_, s)| *s == PostingState::Live)
         .collect();
     assert_eq!(active.len(), 1);
     assert_eq!(active[0].0.value, Cent::from(40));
@@ -776,7 +840,7 @@ async fn overdraft_creates_negative_posting() {
     // A negative posting now backs the overdraft.
     let postings = ledger
         .store()
-        .get_postings_by_account(10, None, Some(&usd()), PostingFilter::Active)
+        .get_postings_by_account(10, None, Some(&usd()), PostingFilter::Live)
         .await
         .unwrap();
     assert!(postings.iter().any(|p| p.value == Cent::from(-50)));
@@ -888,7 +952,7 @@ async fn transfer_in_missing_named_book_is_rejected() {
 // ---------------------------------------------------------------------------
 
 #[tokio::test]
-async fn identical_transfers_share_envelope_id() {
+async fn identical_transfers_share_transfer_id() {
     // Two independently-built default-book transfers must hash identically.
     let a = TransferBuilder::new()
         .pay(account(1), account(2), usd(), Cent::from(10))

+ 33 - 20
crates/kuatia/tests/projection.rs

@@ -6,7 +6,7 @@
 
 use std::sync::Arc;
 
-use kuatia::ledger::Ledger;
+use kuatia::ledger::{Ledger, ProjectionConfig};
 use kuatia::mem_store::InMemoryStore;
 use kuatia_core::*;
 
@@ -66,7 +66,7 @@ async fn pay(ledger: &Arc<Ledger>, from: i64, to: i64, amount: i64) {
 /// for every account, at every asset it might hold.
 async fn assert_projection_matches(ledger: &Arc<Ledger>, ids: &[i64]) {
     for &id in ids {
-        let authoritative = ledger.compute_balance(&account(id), &usd()).await.unwrap();
+        let authoritative = ledger.balance_exact(&account(id), &usd()).await.unwrap();
         let projected = ledger.balance(&account(id), &usd()).await.unwrap();
         assert_eq!(
             projected, authoritative,
@@ -104,7 +104,12 @@ async fn projected_balance_matches_live_sum_without_refresh() {
 /// point with an empty tail.
 #[tokio::test]
 async fn append_cache_point_snapshots_balance_and_preserves_answer() {
-    let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_grace_ms(0));
+    let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_config(
+        ProjectionConfig {
+            grace_ms: 0,
+            ..ProjectionConfig::default()
+        },
+    ));
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -114,6 +119,7 @@ async fn append_cache_point_snapshots_balance_and_preserves_answer() {
     pay(&ledger, 1, 2, 100).await;
 
     ledger
+        .projection()
         .append_cache_point(&account(1), &usd())
         .await
         .unwrap();
@@ -160,11 +166,12 @@ async fn commit_does_not_write_cache_point() {
 /// runtime it runs when we yield).
 #[tokio::test]
 async fn read_appends_cache_point_after_interval() {
-    let ledger = Arc::new(
-        Ledger::new(InMemoryStore::new())
-            .with_projection_grace_ms(0)
-            .with_snapshot_interval(1),
-    );
+    let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_config(
+        ProjectionConfig {
+            grace_ms: 0,
+            snapshot_interval: 1,
+        },
+    ));
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -196,7 +203,7 @@ async fn read_appends_cache_point_after_interval() {
     );
     assert_eq!(
         ledger.balance(&account(1), &usd()).await.unwrap(),
-        ledger.compute_balance(&account(1), &usd()).await.unwrap()
+        ledger.balance_exact(&account(1), &usd()).await.unwrap()
     );
 }
 
@@ -205,11 +212,12 @@ async fn read_appends_cache_point_after_interval() {
 /// is what keeps a hot, frequently-read account from appending near-duplicates).
 #[tokio::test]
 async fn read_below_interval_appends_nothing() {
-    let ledger = Arc::new(
-        Ledger::new(InMemoryStore::new())
-            .with_projection_grace_ms(0)
-            .with_snapshot_interval(1_000),
-    );
+    let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_config(
+        ProjectionConfig {
+            grace_ms: 0,
+            snapshot_interval: 1_000,
+        },
+    ));
     no_overdraft(&ledger, 1).await;
     no_overdraft(&ledger, 2).await;
     overdraft(&ledger, 99).await;
@@ -221,7 +229,7 @@ async fn read_below_interval_appends_nothing() {
     let bal = ledger.balance(&account(1), &usd()).await.unwrap();
     assert_eq!(
         bal,
-        ledger.compute_balance(&account(1), &usd()).await.unwrap()
+        ledger.balance_exact(&account(1), &usd()).await.unwrap()
     );
 
     // Even after the background task has every chance to run, no cache point was
@@ -262,7 +270,7 @@ async fn snapshot_plus_nonempty_tail_matches_live_sum() {
     // authoritative batch-1 sum (folded by the ledger, not by hand); its watermark
     // is a time at or after every batch-1 commit. Appended directly so the
     // watermark is controlled, independent of the lazy read-path grace.
-    let snapshot = ledger.compute_balance(&account(1), &usd()).await.unwrap();
+    let snapshot = ledger.balance_exact(&account(1), &usd()).await.unwrap();
     let watermark = unix_millis_now();
     ledger
         .store()
@@ -282,7 +290,7 @@ async fn snapshot_plus_nonempty_tail_matches_live_sum() {
 
     // The read is snapshot + folded tail, and still equals the live sum.
     let projected = ledger.balance(&account(1), &usd()).await.unwrap();
-    let authoritative = ledger.compute_balance(&account(1), &usd()).await.unwrap();
+    let authoritative = ledger.balance_exact(&account(1), &usd()).await.unwrap();
     assert_eq!(
         projected, authoritative,
         "snapshot + non-empty tail diverged from the live sum"
@@ -329,7 +337,12 @@ async fn projection_matches_live_sum_across_random_utxo_history() {
     // point. The snapshot-plus-non-empty-tail path (a real snapshot with commits
     // folded on top) is covered deterministically by
     // `snapshot_plus_nonempty_tail_matches_live_sum`.
-    let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_snapshot_interval(4));
+    let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_config(
+        ProjectionConfig {
+            snapshot_interval: 4,
+            ..ProjectionConfig::default()
+        },
+    ));
 
     // Accounts under test, including two subaccounts and both overdraft kinds.
     let no_overdraft_ids = [
@@ -372,7 +385,7 @@ async fn projection_matches_live_sum_across_random_utxo_history() {
     let assets = [AssetId::new(1), AssetId::new(2)];
 
     let mut rng = Rng(0x9e3779b97f4a7c15);
-    let mut receipts: Vec<EnvelopeId> = Vec::new();
+    let mut receipts: Vec<TransferId> = Vec::new();
 
     for _ in 0..300 {
         let asset = assets[rng.below(assets.len() as u64) as usize];
@@ -428,7 +441,7 @@ async fn projection_matches_live_sum_across_random_utxo_history() {
         // the authoritative live-posting sum for every (account, asset).
         for account in accounts.iter().chain(std::iter::once(&ext)) {
             for asset in &assets {
-                let authoritative = ledger.compute_balance(account, asset).await.unwrap();
+                let authoritative = ledger.balance_exact(account, asset).await.unwrap();
                 let projected = ledger.balance(account, asset).await.unwrap();
                 assert_eq!(
                     projected, authoritative,

+ 11 - 20
crates/kuatia/tests/saga.rs → crates/kuatia/tests/workflow.rs

@@ -6,7 +6,7 @@ use std::sync::Arc;
 use kuatia::error::LedgerError;
 use kuatia::ledger::Ledger;
 use kuatia::mem_store::InMemoryStore;
-use kuatia::saga::{DepositInput, Movement, PayInput, run_movements};
+use kuatia::workflow::run_transfers;
 use kuatia_core::*;
 
 fn usd() -> AssetId {
@@ -51,22 +51,15 @@ async fn setup_ledger() -> Arc<Ledger> {
     ledger
 }
 
-fn deposit(to: AccountId, amount: Cent) -> Movement {
-    Movement::Deposit(DepositInput {
-        to,
-        asset: usd(),
-        amount,
-        external: external(),
-    })
+fn deposit(to: AccountId, amount: Cent) -> Transfer {
+    TransferBuilder::new()
+        .deposit(to, usd(), amount, external())
+        .unwrap()
+        .build()
 }
 
-fn pay(from: AccountId, to: AccountId, amount: Cent) -> Movement {
-    Movement::Pay(PayInput {
-        from,
-        to,
-        asset: usd(),
-        amount,
-    })
+fn pay(from: AccountId, to: AccountId, amount: Cent) -> Transfer {
+    TransferBuilder::new().pay(from, to, usd(), amount).build()
 }
 
 /// A two-movement workflow (deposit then pay) commits both legs in order.
@@ -74,7 +67,7 @@ fn pay(from: AccountId, to: AccountId, amount: Cent) -> Movement {
 async fn workflow_happy_path() {
     let ledger = setup_ledger().await;
 
-    let receipts = run_movements(
+    let receipts = run_transfers(
         &ledger,
         &[
             deposit(account(1), Cent::from(100)),
@@ -106,9 +99,7 @@ async fn workflow_happy_path() {
 async fn workflow_compensation_on_failure() {
     let ledger = setup_ledger().await;
 
-    // Deposit 50, then try to pay 100 (more than available) -> pay fails ->
-    // deposit is reversed.
-    let err = run_movements(
+    let err = run_transfers(
         &ledger,
         &[
             deposit(account(1), Cent::from(50)),
@@ -138,7 +129,7 @@ async fn workflow_compensation_on_failure() {
 async fn workflow_three_steps_happy() {
     let ledger = setup_ledger().await;
 
-    let receipts = run_movements(
+    let receipts = run_transfers(
         &ledger,
         &[
             deposit(account(1), Cent::from(100)),

+ 2 - 0
doc/SUMMARY.md

@@ -56,4 +56,6 @@
   - [0022: Merge the active/reserved hot indexes into one `live_postings` table](adr/0022-merged-live-postings-hot-index.md)
   - [0023: Atomic storage commit, retiring the write-ahead saga and `legend`](adr/0023-atomic-storage-commit.md)
   - [0024: Native money columns, and exact summation in the database](adr/0024-native-money-columns.md)
+  - [0025: One live set: retire the reservation protocol and the saga-era store primitives](adr/0025-one-live-set-no-reservations.md)
+  - [0026: Let the public API speak the caller's vocabulary](adr/0026-public-api-vocabulary.md)
   - [ADR template](adr/template.md)

+ 12 - 12
doc/accounting-mapping.md

@@ -25,12 +25,12 @@ scope, not the accounting journal.
 
 | Classical accounting | Kuatia | Notes |
 |---|---|---|
-| **Journal** (book of original entry) | **Transfer log**, `TransferStore` of `EnvelopeRecord`s | Append-only, ordered source of truth for committed transfers. |
+| **Journal** (book of original entry) | **Transfer log**, `TransferStore` of `TransferRecord`s | Append-only, ordered source of truth for committed transfers. |
 | **Journal entry** (one balanced event) | Committed **`Transfer`** (intent) → **`Envelope`** (resolved) | One atomic accounting event. |
 | **Compound journal entry** | `Transfer` with multiple `Movement`s | One event touching many accounts/assets. |
 | **Entry line / leg** | **`Posting`** effect (often derived from a `Movement`) | A concrete account-level value fragment. A `Movement` is two-sided intent `{from, to, asset, amount}` that resolves into consumed/created postings, not a 1:1 debit/credit line. |
 | **Σ debits = Σ credits** | **Per-asset conservation** `sum(consumed) == sum(created)` | Enforced in `validate_and_plan`; `ConservationViolation` otherwise. |
-| **Ledger** (accounts + running balances) | **Accounts + active postings** | Balances are projections over `Active` postings, never stored. |
+| **Ledger** (accounts + running balances) | **Accounts + live postings** | Balances are projections over the live (unspent) postings, never stored. |
 | **Posting a transaction** (the verb) | **resolve + commit** (`Transfer` → `Envelope` → apply) | Confusing collision: in Kuatia a *posting* is a noun (a value fragment), not the act of recording. |
 | **Accounting book** | *no direct equivalent unless modeled separately* | Kuatia `Book` is **not** this. |
 | **Transfer policy scope** | **`Book`** | Gates which accounts/assets may participate. See [below](#where-book-fits-and-doesnt). |
@@ -64,7 +64,7 @@ let transfer = TransferBuilder::new()
     .pay(customer, revenue, usd, Cent::from(100))
     .pay(customer, tax_payable, usd, Cent::from(15))
     .build();
-// One Transfer → one Envelope → one EnvelopeRecord in the transfer log.
+// One Transfer → one Envelope → one TransferRecord in the transfer log.
 ```
 
 > Note: this is not a literal debit/credit translation. It shows the business
@@ -89,16 +89,16 @@ These differ in grain: one record vs. the collection of all records.
     Vec<PostingId>, creates: Vec<NewPosting>, account_snapshots, book, … }`.
     It names the concrete postings to spend and create.
   - Committing one (`commit` / `commit_envelope`) returns a `Receipt {
-    transfer_id }` identifying the committed envelope, the `EnvelopeId`, which
+    transfer_id }` identifying the committed envelope, the `TransferId`, which
     is content-addressed (the double-SHA-256 of the canonical envelope bytes).
 - Transfer log = the accounting journal. The append-only, ordered sequence of
-  every committed envelope, persisted by `TransferStore` as `EnvelopeRecord {
+  every committed envelope, persisted by `TransferStore` as `TransferRecord {
   envelope, receipt, created_at }`. Each transfer is one entry in it.
 
 > Transfer/Envelope : transfer log :: one journal entry : the journal.
 
 "The system is trivially auditable by replaying the transfer log" means:
-re-apply every `EnvelopeRecord` in order and you reconstruct all balances.
+re-apply every `TransferRecord` in order and you reconstruct all balances.
 There is no stored balance that can drift.
 
 ## Two append-only logs: don't conflate "log"
@@ -108,7 +108,7 @@ accounting journal.
 
 | Log | Type | Records | Role |
 |---|---|---|---|
-| **Transfer log** | `TransferStore` → `EnvelopeRecord` | Full posting-level detail of each committed transfer | The accounting **journal**, the source of truth for balances. |
+| **Transfer log** | `TransferStore` → `TransferRecord` | Full posting-level detail of each committed transfer | The accounting **journal**, the source of truth for balances. |
 | **Event log** | `EventStore` → `LedgerEvent` | High-level lifecycle notifications | Projections / subscribers; *not* the journal. |
 
 `LedgerEvent { seq, timestamp, kind }` carries a monotonic `seq` and a `kind`
@@ -124,13 +124,13 @@ event grain is identical. Because postings are signed, debit/credit is not the
 native primitive; resolution works in terms of consuming and creating
 postings:
 
-- In a simple movement, the source side is resolved by consuming `Active`
+- In a simple movement, the source side is resolved by consuming `Live`
   postings from the source account, creating a change posting if the selected
   postings exceed the amount.
 - The destination side is represented by newly created postings on the
   destination account.
-- An account's balance is the sum of its `Active` postings, computed on
-  demand, never stored.
+- An account's balance is the sum of its `Live` postings, computed on demand,
+  never stored.
 
 So an entry line maps to a `Posting` effect, usually derived from a `Movement`
 (two-sided intent) that resolves into one or more postings (a created posting,
@@ -158,7 +158,7 @@ See the [glossary](glossary.md#book) for the Book model and worked examples.
 
 | Classical accounting | Kuatia | Notes |
 |---|---|---|
-| Journal | Transfer log / `TransferStore<EnvelopeRecord>` | Append-only source of truth for committed transfers. |
+| Journal | Transfer log / `TransferStore<TransferRecord>` | Append-only source of truth for committed transfers. |
 | Journal entry | Committed `Transfer` / `Envelope` | One atomic accounting event. |
 | Entry line / leg | `Posting` effect | A concrete account-level value fragment; movements are intent that resolve into postings. |
 | Compound journal entry | `Transfer` with multiple movements | One event touching many accounts/assets. |
@@ -167,7 +167,7 @@ See the [glossary](glossary.md#book) for the Book model and worked examples.
 | Posting a transaction (verb) | Resolve + commit | Avoid confusion: Kuatia `Posting` is a noun. |
 | Accounting book | No direct equivalent unless modeled separately | Kuatia `Book` is not this. |
 | Transfer policy scope | `Book` | Gates allowed accounts/assets. |
-| Proof a txn was recorded | `Receipt { transfer_id }` | Content-addressed `EnvelopeId`. |
+| Proof a txn was recorded | `Receipt { transfer_id }` | Content-addressed `TransferId`. |
 | Lifecycle notifications | Event log (`LedgerEvent`) | Separate from the transfer log. |
 
 In one line: Kuatia's transfer log is the accounting journal; each committed

+ 9 - 11
doc/accounts.md

@@ -4,9 +4,8 @@
 
 An account is a versioned entity that owns postings. Balance is never
 stored: it is always computed from postings for a given (account, asset)
-pair. `balance()` sums the live postings, meaning those in the active or
-reserved index (`Active ∪ Reserved`); spent postings, which remain only in
-the immutable table, are excluded.
+pair. `balance()` sums the live postings, meaning those in the live index;
+spent postings, which remain only in the immutable table, are excluded.
 
 ## Structure
 
@@ -83,13 +82,12 @@ directly, and `Account::forbids_overdraft()` reports it. There is no bounded
 "credit line" floor between the two: a credit-line limit, if needed, is enforced
 by the application above the ledger.
 
-The zero-floor check is re-validated as the last step before finalize writes
-(the finalize step re-loads balances and account versions and re-runs validation
-just before deactivating). Double-spend safety is exact regardless: the
-reservation protocol (an atomic conditional `reserve_postings`) guarantees a
-posting cannot be consumed twice. See
+The zero floor is re-checked inside the commit transaction, over the live rows
+that survive the spend, so it is strict rather than best-effort. Double-spend
+safety comes from the same transaction: deleting a consumed live row is the
+atomic single-winner claim, so a posting cannot be consumed twice. See
 [accounting-mapping.md](accounting-mapping.md) and the ADR at
-[adr/0003-dumb-storage-saga-recovery.md](adr/0003-dumb-storage-saga-recovery.md).
+[adr/0023-atomic-storage-commit.md](adr/0023-atomic-storage-commit.md).
 
 ## Lifecycle
 
@@ -134,7 +132,7 @@ During validation, if snapshots are present, the current account state is
 hashed and compared. A mismatch produces `AccountVersionMismatch`,
 preventing TOCTOU races where an account is mutated between load and apply.
 
-The saga `commit()` path auto-populates snapshots when none are provided.
+`commit()` auto-populates snapshots when none are provided.
 
 ## Subaccounts and balances
 
@@ -163,7 +161,7 @@ Balance for an (account reference, asset) pair is computed as:
 balance(account, asset) = sum(p.value for p in postings
                               where p.owner == account
                               and   p.asset == asset
-                              and   p.status != Inactive)
+                              and   p.is_live)
 ```
 
 There is no stored balance field. This eliminates drift between the balance

+ 1 - 1
doc/adr/0006-reservation-protocol-posting-lifecycle.md

@@ -1,6 +1,6 @@
 # Reservation protocol and the posting lifecycle
 
-* Status: accepted
+* Status: superseded by ADR-0025
 * Authors: Cesar Rodas
 * Date: 2026-06-29
 * Targeted modules: `kuatia-types` (`PostingStatus`, `ReservationId`),

+ 1 - 1
doc/adr/0008-conformance-tested-storage.md

@@ -1,6 +1,6 @@
 # Conformance-tested storage with an in-memory reference
 
-* Status: accepted
+* Status: accepted (amended by ADR-0025)
 * Authors: Cesar Rodas
 * Date: 2026-06-29
 * Targeted modules: `kuatia-storage` (`store_tests!`, `InMemoryStore`), `kuatia-storage-sql`

+ 1 - 1
doc/adr/0012-subaccounts.md

@@ -1,6 +1,6 @@
 # Extend account identity with a subaccount dimension
 
-* Status: accepted
+* Status: accepted (`TransferBuilder` clause superseded by ADR-0026)
 * Authors: Cesar Rodas
 * Date: 2026-07-05
 * Targeted modules: `kuatia-types`, `kuatia-core`, `kuatia-storage`,

+ 1 - 1
doc/adr/0022-merged-live-postings-hot-index.md

@@ -1,6 +1,6 @@
 # Merge the active/reserved hot indexes into one `live_postings` table
 
-* Status: accepted
+* Status: accepted (`reservation` column superseded by ADR-0025)
 * Authors: Cesar Rodas
 * Date: 2026-08-01
 * Targeted modules: `kuatia-storage-sql` (schema, migration 008,

+ 94 - 0
doc/adr/0025-one-live-set-no-reservations.md

@@ -0,0 +1,94 @@
+# One live set: retire the reservation protocol and the saga-era store primitives
+
+* Status: accepted
+* Authors: Cesar Rodas
+* Date: 2026-11-21
+* Targeted modules: `kuatia-types` (`PostingState`, `PostingFilter`, `ids`),
+  `kuatia-storage` (`Store`, `InMemoryStore`), `kuatia-storage-sql`,
+  `kuatia` (`workflow`)
+* Associated tickets/PRs: N/A
+
+## Context and Problem Statement
+
+ADR-0023 made a commit one store transaction and deleted the write-ahead saga, but left the data model that saga had needed. A posting could be `Active`, `Reserved` by a `ReservationId`, or `Spent`, and six `Store` methods (`reserve_postings`, `release_postings`, `deactivate_postings`, `insert_postings`, `append_account_version`, `store_transfer`) remained as single-update primitives whose work the commit transaction now does inline.
+
+Nothing called them. Both backends hard-coded the unreserved side of the column in every commit statement, so `Reserved` was unreachable: the only way to observe one was for a test to reach through `Ledger::store()` and create it. ADR-0023 said as much and deferred the removal to a follow-up.
+
+That leftover had three costs. `Ledger::store()` returns the whole trait, so the primitives were a public route to spend a posting or append an account version while skipping the double-spend, freeze/close and overdraft guards the commit transaction enforces. Each cost two backend implementations plus a block of conformance tests that pinned a contract with no caller. And `Live` (`Active ∪ Reserved`) and `Active` had become two names for the same rows, so code chose between them by habit rather than meaning.
+
+## Decision Drivers
+
+* A guard that can be bypassed by a public API is not a guard.
+* One concept should have one name. The `live_postings` table, the `live_balance` aggregate and `has_live_postings` all already said "live".
+* A backend author should have to implement only what the ledger calls.
+* Conformance tests are worth more when they exercise the path production takes.
+
+## Considered Options
+
+#### Keep the reservation vocabulary as dead but harmless
+
+Leave the types and primitives in place and only fix the documentation.
+
+**Pros:**
+
+* No API break, no migration.
+
+**Cons:**
+
+* Bad, because the bypass through `Ledger::store()` stays open.
+* Bad, because the next reader has to discover empirically that `Reserved` cannot happen, and the schema keeps a column that nothing writes.
+
+#### Keep `PostingState::Reserved` for a future hold feature
+
+Retain the state on the theory that durable holds will want it.
+
+**Pros:**
+
+* Good, because a later hold feature would not need a new migration.
+
+**Cons:**
+
+* Bad, because holds already exist and do not use it. ADR-0014 implements them as per-destination holding subaccounts, precisely so a hold is an ordinary balance rather than a lifecycle state.
+* Bad, because it keeps an unreachable variant in a public enum that every backend and every reader must account for.
+
+#### Retire the reservation protocol entirely (chosen)
+
+Collapse `PostingState` to `Live | Spent | Missing` and `PostingFilter` to `Live | All`, delete `ReservationId`, `TransitionId` and the id generator behind them, delete the six primitives, drop `live_postings.reservation`, and seed the conformance suite through `commit_envelope`.
+
+**Pros:**
+
+* Good, because a posting's liveness becomes one fact: it is in `live_postings` or it is spent.
+* Good, because the atomic commit is the only posting write a backend has, so no caller can leave half a transfer applied.
+* Good, because the conformance suite now proves the commit path rather than a hand-rolled imitation of it.
+
+**Cons:**
+
+* Bad, because it breaks `Store` for any out-of-tree backend, and changes the serde representation of `PostingState`.
+* Bad, because the suite's seeds now require the accounts they reference to exist, which the removed `insert_postings` did not.
+
+## Decision Outcome
+
+Chosen option: retire the reservation protocol entirely. The middle state had no producer, no consumer and no feature waiting on it, and keeping it left a documented bypass of the commit guards.
+
+`TransitionId` went with it, having never been referenced outside its own definition.
+
+The `kuatia::saga` module is renamed to `kuatia::workflow` and `run_movements` to `run_transfers`, taking the transfers themselves. The cross-transfer LIFO unwind it performs is real behaviour that single-transfer atomicity does not provide, so only the name and the inputs change; its own `Movement` type had shadowed `kuatia_types::Movement`, which means something else.
+
+### Positive Consequences
+
+* `PostingState` has no unreachable variant, and the SQL state probe reads one column fewer.
+* The in-memory backend holds one live map instead of two, so its commit has no cross-map claim to keep atomic.
+* Migration `012_drop_reservation` releases any row that still carried a token. That row was never consumed, so it always counted toward the balance, and the saga that owned the token no longer exists to finalize or release it.
+
+### Negative Consequences
+
+* Breaking for out-of-tree `Store` implementors and for anyone matching on `PostingState::Active` or persisting its serde form.
+* `close_rejects_reserved_postings` asserted a state that is no longer representable and is gone. It is replaced by the half of the close guard that was untested: an account whose postings have all been spent can be closed.
+
+## Links
+
+* Follows [ADR-0023](0023-atomic-storage-commit.md), which made the commit atomic and deferred this removal.
+* Supersedes [ADR-0006](0006-reservation-protocol-posting-lifecycle.md), the reservation protocol itself.
+* Supersedes the `reservation` column of [ADR-0022](0022-merged-live-postings-hot-index.md).
+* Amends [ADR-0008](0008-conformance-tested-storage.md): the suite seeds through the commit path, not through write primitives.
+* Holds are unaffected: [ADR-0014](0014-inflight-holds-via-holding-accounts.md) uses holding subaccounts, never reserved postings.

+ 94 - 0
doc/adr/0026-public-api-vocabulary.md

@@ -0,0 +1,94 @@
+# Let the public API speak the caller's vocabulary
+
+* Status: accepted
+* Authors: Cesar Rodas
+* Date: 2026-11-22
+* Targeted modules: `kuatia` (`ledger`, `inflight`, `workflow`),
+  `kuatia-types` (`ids`, `transfer`), `kuatia-storage` (`store`)
+* Associated tickets/PRs: N/A
+
+## Context and Problem Statement
+
+ADR-0025 finished removing the saga-era data model, which left the surface a caller actually touches as the last place still shaped by decisions that no longer hold. Four things in particular made the library read like its own internals:
+
+`commit`, `commit_envelope`, `reverse`, the five inflight entry points and the multi-transfer runner all took the ledger as `&Arc<Self>`, so the first line of every program using the library wrapped one. No body touched the `Arc`: the commit path spawned work under the saga, and the spawning left with it.
+
+`TransferBuilder` had `movement`, `movement_ref`, `pay` and `pay_ref` pushing the same `Movement`. ADR-0012 introduced the `_ref` pair to move "between specific subaccounts" while the plain spellings moved "between main accounts", but both take a full `AccountId` and `AccountId::new(id)` is `with_sub(id, 0)`, so the distinction had no referent.
+
+The API said transfer while its types said envelope: `Receipt.transfer_id` was an `EnvelopeId`, `history()` returned `EnvelopeRecord`s, and `get_transfer` took an `&EnvelopeId`.
+
+Four public methods answered "what is the balance" with nothing to tell a caller which to reach for, one of them (`append_cache_point`) being cache maintenance and two of them (`with_snapshot_interval`, `with_projection_grace_ms`) knobs no caller outside the tests had ever set.
+
+## Decision Drivers
+
+* Ceremony a caller cannot skip is worse than ceremony they opt into.
+* One concept, one name. Two names for one thing cost every reader the work of learning they are the same.
+* A name should say which of two similar operations a call site got.
+* Removing a published name is cheap now and expensive after 0.4.0 ships.
+
+## Considered Options
+
+#### Leave the surface and document it better
+
+Write the distinctions down instead of removing them.
+
+**Pros:**
+
+* Good, because nothing breaks for anyone.
+
+**Cons:**
+
+* Bad, because the `Arc` and the `_ref` pair have nothing true to document: one is unused, the other names a difference that does not exist.
+* Bad, because documentation that exists to explain an avoidable choice is a cost paid on every read.
+
+#### Rename `Envelope` to `Transfer` throughout, collapsing the pair
+
+Make the resolved form and the intent share one word.
+
+**Pros:**
+
+* Good, because one word would cover the whole pipeline.
+
+**Cons:**
+
+* Bad, because the two are genuinely different: one is movements a caller wrote, the other is the postings to consume and create. Collapsing them would hide the resolve step that ADR-0005 deliberately exposes.
+
+#### Collapse `balance` and `compute_balance` into one method
+
+One way to ask for a balance.
+
+**Cons:**
+
+* Bad, because the whole of `tests/projection.rs` is a differential test between two independent derivations of the same number, and `compute_balance` is the oracle. With one method there is nothing left to compare against, and a dropped tail or an off-by-one in the fold stops being observable.
+* Bad, because the commit path must read the authoritative sum to enforce the overdraft floor, never the cache (ADR-0019 item 6).
+
+#### Fix the four separately, keeping every distinction that is real (chosen)
+
+## Decision Outcome
+
+Chosen option: remove what was unused or duplicated, rename what was misleading, and keep every distinction with something behind it.
+
+* Every method takes `&self`. A caller who wants to share a ledger still wraps it in an `Arc`, which derefs; the signature no longer decides for them.
+* `movement_ref` and `pay_ref` are gone. `movement` and `pay` both stay, the same call under two names, because an exchange commits two legs that are not payments and most callers are paying someone.
+* `EnvelopeId` is `TransferId` and `EnvelopeRecord` is `TransferRecord`. `Envelope` and `EnvelopeBuilder` keep their names, so the everyday surface says transfer and the resolved interior that `resolve` and `commit_envelope` expose says envelope.
+* `compute_balance` is `balance_exact`, beside `balance`. `append_cache_point` moves to a `Projection` handle from `Ledger::projection()`, and the two knobs become one `ProjectionConfig`.
+
+### Positive Consequences
+
+* The README example lost its first line, and none of the five examples mentions `Arc`.
+* A call site says whether it took the cached read or the exact one.
+* The rename changes nothing stored. `TransferId` is a newtype over `[u8; 32]` whose `ToBytes` is a byte passthrough, serde discards a newtype's struct name, the event dedup key hexes the inner bytes, and `TransferRecord` is decomposed into columns rather than serialized. No migration, and the schema already said transfer throughout.
+* `Ledger::projection()` gives the as-of and rebuild reads on the roadmap somewhere to land.
+
+### Negative Consequences
+
+* Breaking on every one of the four counts for anyone already calling the library: the `_ref` methods, both type names, `compute_balance`, `append_cache_point` and the two knobs.
+* `movement` and `pay` remain two names for one call, which is a deliberate exception to the rule this record argues for.
+* The accepted ADRs still say `EnvelopeId` and `compute_balance`. A record is not edited to match later code, so the old spelling stays wherever it was written.
+
+## Links
+
+* Follows [ADR-0025](0025-one-live-set-no-reservations.md), which removed the data model these shapes served.
+* Supersedes the `TransferBuilder` clause of [ADR-0012](0012-subaccounts.md): the `_ref` methods it introduced are gone, and subaccount movement needs no separate spelling.
+* Keeps [ADR-0019](0019-cached-balance-projection.md) item 5 intact under a new name, and moves the maintenance call it describes onto `Ledger::projection()`.
+* Leaves [ADR-0005](0005-intent-api-movements-vs-envelopes.md)'s intent/envelope split in place; only the id and record types stop borrowing the internal word.

+ 6 - 4
doc/adr/README.md

@@ -15,9 +15,9 @@ to reverse a decision. Instead, a new ADR supersedes it.
 | [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. |
+| [0006](0006-reservation-protocol-posting-lifecycle.md) | Reservation protocol & posting lifecycle | superseded by 0025 | `Active → PendingInactive → Inactive` + a durable `ReservationId` give lock-free, recoverable, exclusive ownership of inputs. The primitive behind 0002/0003. Storage representation superseded by 0016; retired entirely by 0025, once the atomic commit left the middle state with no producer. |
 | [0007](0007-reversal-via-compensating-transfers.md) | Reversal via compensating transfers | accepted | Undo is an inverse envelope committed through the normal path (never deletion/mutation), preserving the append-only audit log. |
-| [0008](0008-conformance-tested-storage.md) | Conformance-tested storage | accepted | One `store_tests!` suite every backend must pass, with `InMemoryStore` as the executable reference; enforces the equal count semantics 0003 relies on. |
+| [0008](0008-conformance-tested-storage.md) | Conformance-tested storage | accepted (amended by 0025) | One `store_tests!` suite every backend must pass, with `InMemoryStore` as the executable reference. Amended by 0025: the suite seeds its state through the atomic commit, so a backend's run exercises the path production takes. |
 | [0009](0009-monetary-representation-integer-minor-units.md) | Monetary amounts as integer minor units | accepted | `Cent` is an `i64` newtype of minor units with only checked arithmetic; scale lives in the presentation-only `Amount`, not on the stored value or asset. Makes 0001's conservation exact. |
 | [0010](0010-event-stream-vs-transfer-log.md) | Derived event stream vs. transfer log | accepted | A secondary append-only `EventStore` feed (outbox-style) for transfer + account-lifecycle events; transfer log stays authoritative. `append_event` is idempotent on a content key, a scoped exception to 0003. |
 | [0011](0011-swappable-money-backing.md) | Swappable integer backing for money, default i64 | accepted (storage clause superseded by 0024) | `Cent` moves to a `kuatia-money` crate over a `CentBacking` trait; the i64↔i128 width is a cargo feature, hidden from the API. Refines 0009. Text storage superseded by 0024, which makes the amount columns backend-native. |
@@ -31,9 +31,11 @@ to reverse a decision. Instead, a new ADR supersedes it.
 | [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 | 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. |
+| [0022](0022-merged-live-postings-hot-index.md) | Merge the active/reserved hot indexes into one `live_postings` table | accepted (`reservation` column superseded by 0025) | 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. The column itself is dropped by 0025; the merged table stands. |
 | [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. |
 | [0024](0024-native-money-columns.md) | Native money columns, and exact summation in the database | accepted | Amount columns become `NUMERIC(39,0)` on PostgreSQL and a 16-byte order-preserving `BLOB` on SQLite, stored at full i128 width whatever the backing. The database may now sum them, exactly: plain `SUM()` on Postgres, a registered `kuatia_i128_sum` aggregate on SQLite. Supersedes 0011's text storage; amends 0009 and 0023. |
+| [0025](0025-one-live-set-no-reservations.md) | One live set: retire the reservation protocol and the saga-era store primitives | accepted | A posting is live or spent, with nothing in between: `PostingState` loses `Reserved`, `PostingFilter` loses `Active`, and `ReservationId`/`TransitionId` go. The six single-update write primitives are removed, leaving the atomic commit as the store's only posting write, and migration 012 drops `live_postings.reservation`. Follows 0023; supersedes 0006; amends 0008. |
+| [0026](0026-public-api-vocabulary.md) | Let the public API speak the caller's vocabulary | accepted | Four shapes left over from earlier designs leave the surface: the `Arc<Ledger>` every commit required and never used, `TransferBuilder`'s duplicate `_ref` methods, the `Envelope` spelling in `EnvelopeId`/`EnvelopeRecord` (now `TransferId`/`TransferRecord`), and the four-way balance surface (`compute_balance` becomes `balance_exact`; cache maintenance moves to `Ledger::projection()`). Nothing stored changes. Follows 0025; supersedes 0012's builder clause. |
 
 ## Recommended future ADRs
 
@@ -41,7 +43,7 @@ Real decisions whose rationale lives in the code/docs but is not yet
 captured as an ADR, roughly in priority order:
 
 1. **Content-addressed transfer ids, and rejecting a sequential hash
-   chain**: `EnvelopeId = double-SHA-256(canonical bytes)` for idempotency
+   chain**: `TransferId = double-SHA-256(canonical bytes)` for idempotency
    + tamper evidence, and why a per-transfer hash chain was rejected (a
    concurrency bottleneck). See the "No Sequential Hash Chain" section of
    `architecture.md`.

+ 35 - 53
doc/architecture.md

@@ -7,7 +7,7 @@ exactly one account. A positive posting is value controlled by the account; a
 negative posting is an offset position (issuance, external flow, or system
 balancing).
 
-Account balance = sum of non-`Inactive` postings (`Active + PendingInactive`)
+Account balance = sum of the live (unspent) postings
 for that (account, asset) pair. There is no mutable balance field to drift out
 of sync.
 
@@ -27,13 +27,12 @@ graph LR
     subgraph "kuatia (async, IO)"
         L[Ledger]
         ST[Store sub-traits]
-        SG[Saga steps]
+        W[workflow::run_transfers]
     end
     L --> V
     L --> S
     L --> ST
-    SG --> L
-    SG --> ST
+    W --> L
 ```
 
 **kuatia-core** contains all validation logic with no IO, no async runtime, and
@@ -62,21 +61,18 @@ classDiagram
         +get_account(id)
         +get_accounts(ids)
         +create_account(account)
-        +append_account_version(account)
         +get_account_history(id)
         +list_accounts()
     }
     class PostingStore {
         +get_postings(ids)
-        +get_postings_by_account(account, asset?, status?)
-        +reserve_postings(ids, reservation) u64
-        +release_postings(ids, reservation) u64
-        +deactivate_postings(ids, reservation?) u64
-        +insert_postings(postings) u64
+        +get_postings_by_account(account, sub?, asset?, filter)
+        +get_posting_states(ids)
+        +live_balance(account, asset)
+        +query_postings(query)
     }
     class TransferStore {
         +get_transfer(id)
-        +store_transfer(record, involved) u64
         +get_transfers_for_account(account)
         +query_transfers(query)
     }
@@ -93,6 +89,10 @@ classDiagram
         +get_book(id)
         +list_books()
     }
+    class BalanceProjectionStore {
+        +append_balance_projection(account, asset, balance, watermark)
+        +get_closest_balance_projection(account, asset, as_of)
+    }
     class Store {
         <<composite>>
     }
@@ -102,6 +102,7 @@ classDiagram
     Store --|> CommitStore
     Store --|> EventStore
     Store --|> BookStore
+    Store --|> BalanceProjectionStore
 ```
 
 A whole transfer is committed atomically by `CommitStore::commit_envelope`, so
@@ -156,12 +157,12 @@ ledger core. See
 
 `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
+`workflow::run_transfers`, which commits them in order and reverses the committed
 ones LIFO on failure.
 
 ## Content-Addressed Transfers
 
-`EnvelopeId` is the double-SHA-256 of a transfer's canonical binary
+`TransferId` is the double-SHA-256 of a transfer's canonical binary
 serialization. This serves two purposes:
 
 - **Idempotency**: committing the same transfer twice returns the cached
@@ -284,61 +285,42 @@ share one selection pass, avoiding double-selection of the same postings.
 
 ## Posting Lifecycle
 
-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:
+A posting is live while the live index holds it and spent once the atomic commit
+deletes it, so its state is derived from one membership question and never stored
+on the posting:
 
 ```mermaid
 stateDiagram-v2
-    [*] --> Active: insert_postings
-    Active --> PendingInactive: reserve_postings
-    PendingInactive --> Active: release_postings (compensation)
-    PendingInactive --> Inactive: deactivate_postings(reservation)
-    Active --> Inactive: deactivate_postings(None)
+    [*] --> Live: commit creates it
+    Live --> Spent: commit consumes it
 ```
 
-| State | Available | In balance | Description |
+| State | Spendable | In balance | Description |
 |-------|-----------|------------|-------------|
-| **Active** | Yes | Yes | Available for consumption |
-| **PendingInactive** | No | Yes | Reserved for a transfer. Reverts to Active on compensation |
-| **Inactive** | No | No | Consumed. Kept for audit trail (void) |
-
-### Batch semantics
-
-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 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
-  update; a posting that is not Active is skipped. Returns the number flipped.
-- **`release_postings(ids, rid)`**: reverts each `PendingInactive` posting owned
-  by `rid` to `Active`. Others are skipped. Returns the number reverted.
+| **Live** | Yes | Yes | Available for consumption |
+| **Spent** | No | No | Consumed. Kept for audit trail (void) |
 
-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.
+A consumed posting is deleted from the live index, never from the immutable
+record, so history stays complete. There is no intermediate reserved state: the
+commit transaction's own delete is the single-winner claim, which is why nothing
+needs to hold a posting between a check and a write. See
+[ADR-0025](adr/0025-one-live-set-no-reservations.md).
 
 ## Multi-Transfer Composition
 
 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(..)`:
+a thin runner, not a saga VM. `workflow::run_transfers` commits the transfers in
+order and, on the first failure, reverses the already-committed receipts LIFO via
+`ledger.reverse(..)`:
 
 ```rust
-use std::sync::Arc;
-use kuatia::saga::{DepositInput, Movement, PayInput, run_movements};
+use kuatia::workflow::run_transfers;
 
-let ledger: Arc<Ledger> = /* ... */;
-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 }),
+let ledger: Ledger = /* ... */;
+let receipts = run_transfers(&ledger, &[
+    TransferBuilder::new().deposit(alice, usd, amount, bank)?.build(),
+    TransferBuilder::new().pay(alice, bob, usd, amount).build(),
 ])
 .await?;
 ```

+ 62 - 80
doc/crates.md

@@ -20,19 +20,19 @@ dependencies (`sha2`, `serde`, `bitflags`).
 |------|-------------|
 | `AccountId(i64)` | Stable account identity (snowflake-style, generated in Rust) |
 | `AssetId(u32)` | Asset identifier (USD, BTC, etc.). Conservation boundary |
-| `EnvelopeId([u8; 32])` | Content-addressed double-SHA-256 of transfer bytes |
+| `TransferId([u8; 32])` | Content-addressed double-SHA-256 of transfer bytes |
 | `PostingId { transfer, index }` | Identifies a posting by its creating transfer + position |
 | `AccountSnapshotId { account, snapshot_id }` | Account state hash for version pinning |
 | `Cent` | Smallest monetary unit (private field, backing integer hidden). Backing is `i64` by default, `i128` under the `i128` feature. Checked arithmetic via `checked_add`, `checked_sub`, `checked_neg`, `checked_sum` returning `Result<Cent, OverflowError>` |
 | `OverflowError` | Returned when a `Cent` operation would overflow or underflow |
-| `PostingState` | Derived posting lifecycle (from index-table membership, not stored): `Active`, `Reserved(ReservationId)`, `Spent`, `Missing` |
-| `PostingFilter` | Read filter over derived posting state: `Active`, `Reserved`, `Live` (Active ∪ Reserved), `All` |
+| `PostingState` | Derived posting state (from live-index membership, not stored): `Live`, `Spent`, `Missing` |
+| `PostingFilter` | Read filter over derived posting state: `Live`, `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 by the `reserve_postings`/`release_postings` primitives (unused by the atomic commit path) |
+| `Posting` | Immutable signed amount of one asset owned by one account. Carries no state field; its state is derived from live-index membership (see `PostingState`) |
 | `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 |
+| `EnvelopeBuilder` | Fluent builder for `Envelope` construction (the resolved form; `TransferBuilder` builds the intent) |
+| `REFERENCE_KEY` | Reserved metadata key for a caller's transfer reference, set via `TransferBuilder::reference` |
 | `Account` | Versioned entity with flags, book, metadata. `Account::new(id)` allows overdraft by default; `Account::debit_must_not_exceed_credit(id)` forbids it; `Account::forbids_overdraft()` queries the constraint |
 | `AccountFlags` | Bitflags: `FROZEN`, `CLOSED`, `DEBIT_MUST_NOT_EXCEED_CREDIT` (when set, the account's debits may not exceed its credits: balance stays `>= 0`, no negative postings) |
 | `Metadata` | `BTreeMap<String, Vec<u8>>` for free-form key-value data |
@@ -48,12 +48,12 @@ in order:
 graph TD
     A[1. Non-empty] --> B[2. No duplicate consumes]
     B --> C[3. Posting existence]
-    C --> E[5. Account existence & lifecycle]
-    E --> F[6. Snapshot pinning]
-    F --> BP[7. Book policy]
-    BP --> G[8. Per-asset conservation]
-    G --> H[9. Negative posting restriction]
-    H --> J[10. Balance-constraint enforcement]
+    C --> E[4. Account existence & lifecycle]
+    E --> F[5. Snapshot pinning]
+    F --> BP[6. Book policy]
+    BP --> G[7. Per-asset conservation]
+    G --> H[8. Negative posting restriction]
+    H --> J[9. Balance-constraint enforcement]
     J --> I[Plan]
     style I fill:#e8f5e9
 ```
@@ -61,19 +61,19 @@ graph TD
 1. **Non-empty**: transfer must consume or create at least one posting
 2. **No duplicate consumes**: each posting consumed at most once
 3. **Posting existence**: every consumed posting exists in the immutable table
-   (a `Posting` carries no lifecycle state; double-spend safety is enforced by
-   the reserve claim and the finalize "all spent" guard, not here)
-5. **Account existence & lifecycle**: all referenced accounts exist, not
+   (a `Posting` carries no state, so double-spend safety is enforced by the
+   commit transaction's own delete, not here)
+4. **Account existence & lifecycle**: all referenced accounts exist, not
    frozen, not closed
-6. **Snapshot pinning**: account snapshots (if provided) must match current
+5. **Snapshot pinning**: account snapshots (if provided) must match current
    state
-7. **Book policy**: when a book is loaded, referenced assets/accounts/flags
+6. **Book policy**: when a book is loaded, referenced assets/accounts/flags
    must be allowed by the book
-8. **Per-asset conservation**: `sum(consumed) == sum(created)` for each asset
-9. **Negative posting restriction**: negative postings forbidden only on
+7. **Per-asset conservation**: `sum(consumed) == sum(created)` for each asset
+8. **Negative posting restriction**: negative postings forbidden only on
    accounts that forbid overdraft (the `DEBIT_MUST_NOT_EXCEED_CREDIT` flag is
    set); allowed on overdraft-permitting accounts
-10. **Balance-constraint enforcement**: for an account that forbids overdraft,
+9. **Balance-constraint enforcement**: for an account that forbids overdraft,
     the projected balance stays `>= 0`
 
 Output is a `Plan` containing `transfer_id`, `postings_to_deactivate`, and
@@ -91,10 +91,10 @@ Async resource layer. Depends on `kuatia-core`, `tokio`, `async-trait`,
 | Module | Purpose |
 |--------|---------|
 | `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`) |
+| `store` | `Store` composite trait + sub-traits (`AccountStore`, `PostingStore`, `TransferStore`, `CommitStore`, `EventStore`, `BookStore`, `BalanceProjectionStore`) |
 | `error` | `StoreError`, `LedgerError`: unified error hierarchy |
 | `mem_store` | `InMemoryStore`: in-memory `Store` implementation for tests |
-| `saga` | `run_movements`: multi-transfer LIFO composition over `commit`/`reverse` |
+| `workflow` | `run_transfers`: multi-transfer LIFO composition over `commit`/`reverse` |
 
 ### Ledger API
 
@@ -112,14 +112,13 @@ graph LR
     style E fill:#e8f5e9
 ```
 
-Note: `commit`/`commit_envelope`/`reverse` require `Arc<Ledger>`. A crash leaves
-no half-applied state, so there is no recovery step.
+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(transfer)` | Resolve intent, validate, then one atomic store commit |
 | `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` |
 
@@ -148,7 +147,9 @@ Transfers are built via `TransferBuilder` and committed with
 
 | Method | Description |
 |--------|-------------|
-| `balance(account, asset)` | Sum of live (Active or Reserved) postings (computed by Ledger) |
+| `balance(account, asset)` | The everyday read: closest cache point plus the folded tail since its watermark |
+| `balance_exact(account, asset)` | The authoritative sum of the live (unspent) postings, uncached. What the commit path reads |
+| `balances(account, asset, sub?)` | One entry per non-closed subaccount; never summed across them (ADR-0012) |
 | `list_accounts()` | All current account snapshots |
 | `get_account(id)` | Latest account snapshot |
 | `query_transfers(query)` | Paginated, filtered transfer history (by date range, book) |
@@ -176,17 +177,14 @@ graph TB
 ```
 
 - **`AccountStore`**: `get_account`, `get_accounts`, `create_account`,
-  `append_account_version`, `get_account_history`, `list_accounts`
+  `get_account_history`, `list_accounts`; a version is appended only by
+  `CommitStore::commit_transition`
 - **`PostingStore`**: `get_postings`, `get_posting_states`,
   `get_postings_by_account(account, sub?, asset?, filter)`, `query_postings(query)`,
   `live_balance(account, asset) -> Cent` (the one read a backend may compute
-  itself, because it can do so exactly — ADR-0024), and the dumb write
-  primitives `reserve_postings(ids, reservation) -> u64`,
-  `release_postings(ids, reservation) -> u64`,
-  `deactivate_postings(ids, reservation?) -> u64`,
-  `insert_postings(postings) -> u64`
-- **`TransferStore`**: `get_transfer`,
-  `store_transfer(record, involved) -> u64`, `get_transfers_for_account`,
+  itself, because it can do so exactly, ADR-0024). All reads: a posting is
+  written only by `CommitStore`
+- **`TransferStore`**: `get_transfer`, `get_transfers_for_account`,
   `query_transfers`
 - **`CommitStore`**: `commit_envelope(request) -> CommitOutcome`,
   `commit_transition(next, event) -> TransitionOutcome`: the atomic write
@@ -196,46 +194,31 @@ graph TB
 - **`BookStore`**: `create_book`, `get_book`, `list_books`
 
 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.
+crash-safety comes from the transaction rather than write-ahead recovery, and it
+is the only way a posting is ever written.
 
-#### Batch posting operations
+#### Derived posting state
 
-`reserve_postings`/`release_postings`/`deactivate_postings` apply each id's
-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`,
-reserved index → `Reserved(rid)`, neither (only the immutable table) → `Spent`.
-Every transition is an insert/delete on an index table; the posting row never
-changes.
+State is live-index membership: in it, the posting is `Live`; in the immutable
+table only, `Spent`; in neither, `Missing`. The posting row itself never
+changes, and only a commit moves one between the two tables.
 
 ```mermaid
 stateDiagram-v2
-    [*] --> Active: insert_postings
-    Active --> Reserved: reserve_postings
-    Reserved --> Active: release_postings
-    Reserved --> Spent: deactivate_postings(reservation)
-    Active --> Spent: deactivate_postings(None)
+    [*] --> Live: commit creates it
+    Live --> Spent: commit consumes it
 ```
 
-Each cell is the count a primitive returns (1 = moved, 0 = no-op / not
-applicable). The saga interprets a 0:
-
-| Operation | Active | Reserved (this rid) | Spent |
-|-----------|--------|---------------------|-------|
-| `reserve_postings(rid)` | → Reserved (1) | 0 | 0 |
-| `release_postings(rid)` | 0 | → Active (1) | 0 |
-| `deactivate_postings(Some rid)` | 0 | → Spent (1) | 0 |
-| `deactivate_postings(None)` | → Spent (1) | 0 | 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 caller reads the count and decides what to do.
+Deleting the consumed live row inside the commit transaction is the atomic
+single-winner claim, so two commits cannot both spend a posting: the one whose
+delete affects no row is refused with `CommitRejection::DoubleSpend`. See
+[ADR-0025](adr/0025-one-live-set-no-reservations.md).
 
-Balance computation lives in the Ledger (`compute_balance`), not the Store.
+Balance computation lives in the Ledger, not the Store: `balance_exact` asks the
+store for one exact aggregate (`PostingStore::live_balance`, ADR-0024) and
+`balance` folds a tail on top of a cache point. Cache maintenance sits apart on
+`ledger.projection()`, and `ProjectionConfig` tunes it; neither affects what a
+balance says, only how fast it is read (ADR-0019).
 
 ### Error Hierarchy
 
@@ -258,33 +241,32 @@ LedgerError
 ```
 StoreError
 ├── NotFound(String)
-├── AlreadyExists(String)
-├── VersionConflict { account, expected, actual }  // append_account_version: stale version
-└── Internal(String)
+├── Internal(String)
+└── Misconfigured(String)   // backend setup missing, retrying will not fix it
 ```
 
 `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.
+`LedgerError`; the remaining count-returning writes (`create_account`,
+`create_book`) report a count and the caller derives meaning from it.
 
 ### Multi-Transfer Composition
 
-`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.
+`workflow::run_transfers(ledger, transfers)` commits the transfers 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
-use kuatia::saga::{DepositInput, Movement, PayInput, run_movements};
+use kuatia::workflow::run_transfers;
 
-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 }),
+let receipts = run_transfers(&ledger, &[
+    TransferBuilder::new().deposit(alice, usd, amount, bank)?.build(),
+    TransferBuilder::new().pay(alice, bob, usd, amount).build(),
 ])
 .await?;
 ```
 
-If a movement fails, the committed ones are reversed and the original error is
+If a transfer fails, the committed ones are reversed and the original error is
 returned; a failing reversal surfaces as `LedgerError::CompensationFailed`.

+ 7 - 7
doc/glossary.md

@@ -9,8 +9,8 @@
 ### Posting
 
 A signed amount of one asset owned by one account. The fundamental unit of
-value in the ledger. Postings are immutable once created. Consumed postings
-are marked `Inactive` but never deleted.
+value in the ledger. Postings are immutable once created. A consumed posting
+leaves the live index but is never deleted from the record.
 
 - **Positive posting**: value controlled by the account.
 - **Negative posting**: an offset position, allowed on any account that permits
@@ -18,15 +18,15 @@ are marked `Inactive` but never deleted.
   issuance, external flow, boundary/system balancing, or an overdraft. An
   account that forbids overdraft may not hold one.
 
-Lifecycle: `Active` → `PendingInactive` (reserved by a saga, stamped with its
-`ReservationId`) → `Inactive` (consumed). **Ledger balance** sums
-`Active + PendingInactive` postings; **available balance** sums only `Active`
-(postings reserved for an in-flight transfer are not available to spend).
+State: `Live` (unspent) → `Spent` (consumed by a committed transfer), derived
+from live-index membership rather than stored. **Balance** sums the live
+postings; there is nothing between the two states, so what an account holds and
+what it can spend are the same set.
 
 ### Account
 
 A versioned entity that owns postings. Balance is never stored. It is always
-the sum of non-inactive postings for a given (account, asset) pair.
+the sum of the live postings for a given (account, asset) pair.
 
 Accounts have **flags** (lifecycle, the `DEBIT_MUST_NOT_EXCEED_CREDIT` balance
 constraint, and user-defined bits) and a **book** assignment.

+ 5 - 4
doc/inflight.md

@@ -28,7 +28,7 @@ A hold is keyed by destination, so `hold(fee)` collects EUR from B and BTC from
 A. Each holding posting's funder is recorded in the authorize transfer's leg
 table, so a void returns each posting to the account that paid it.
 
-Nothing new is stored. The authorize transfer is the record: its `EnvelopeId` is
+Nothing new is stored. The authorize transfer is the record: its `TransferId` is
 the inflight handle, and its metadata carries the leg table. Every artifact
 (holding accounts, authorize, confirm, void) is tagged with a CBOR-encoded
 payload under a single `inflight` metadata key, so the lifecycle is read from
@@ -86,7 +86,7 @@ let open = ledger.list_open_inflights().await?;
 ```
 
 `authorize` returns an `Authorization { inflight, receipt, legs }`. The
-`inflight` field (an `EnvelopeId`) is the handle passed to every other call.
+`inflight` field (an `TransferId`) is the handle passed to every other call.
 
 ## Guarantees
 
@@ -95,8 +95,9 @@ let open = ledger.list_open_inflights().await?;
   fails validation. The sum of confirmations can never exceed the authorized
   amount.
 - **No double-spend under concurrency.** Concurrent confirmations serialize on
-  the shared holding posting via the reservation protocol. On contention, one
-  wins and the caller retries the other against the new remaining balance.
+  the shared holding posting: the commit transaction's delete is the atomic
+  single-winner claim, so one wins and the caller retries the other against the
+  new remaining balance.
 - **State is derived.** The amount still held on a leg is `balance(hold, asset)`.
   Confirmed and voided amounts are summed from the metadata-tagged settling
   transfers. Nothing mutable is stored.

+ 5 - 5
doc/journaling.md

@@ -26,7 +26,7 @@ Kuatia provides the same guarantees over a UTXO-style, posting-based model:
 
 | Classical accounting | Kuatia |
 |---|---|
-| Journal (book of original entry) | Transfer log (`TransferStore` of `EnvelopeRecord`s) |
+| Journal (book of original entry) | Transfer log (`TransferStore` of `TransferRecord`s) |
 | Journal entry (one balanced event) | Committed `Transfer` resolved into an `Envelope` |
 | Compound journal entry | `Transfer` with multiple `Movement`s |
 | `Σ debits = Σ credits` | Per-asset conservation `sum(consumed) == sum(created)` |
@@ -76,7 +76,7 @@ let transfer = TransferBuilder::new()
     .pay(customer, revenue, usd, Cent::from(100))
     .pay(customer, tax_payable, usd, Cent::from(15))
     .build();
-// One Transfer -> one Envelope -> one EnvelopeRecord in the transfer log.
+// One Transfer -> one Envelope -> one TransferRecord in the transfer log.
 ```
 
 Both are a single balanced event. In the classical entry `Σ Dr (115) = Σ Cr
@@ -108,11 +108,11 @@ One entry and the journal differ only in grain:
 
 - A `Transfer` / `Envelope` is one record: one journal entry.
 - The transfer log is the collection of all records: the accounting journal.
-  `TransferStore` persists each committed envelope as `EnvelopeRecord {
+  `TransferStore` persists each committed envelope as `TransferRecord {
   envelope, receipt, created_at }` in append-only order.
 
 Committing an entry returns a `Receipt { transfer_id }` naming the committed
-envelope. The `EnvelopeId` is content-addressed (the double-SHA-256 of the
+envelope. The `TransferId` is content-addressed (the double-SHA-256 of the
 canonical envelope bytes), which gives idempotency (re-committing the same
 envelope returns the cached receipt) and tamper evidence (any edit changes the
 id).
@@ -126,7 +126,7 @@ which postings moved. See
 ## Auditability by replay
 
 There are no stored balances to drift. An account's balance is the sum of its
-`Active` postings, computed on demand. Re-applying every `EnvelopeRecord` in
+`Live` postings, computed on demand. Re-applying every `TransferRecord` in
 order reconstructs all balances exactly. Because each entry is balanced per
 asset and the log is append-only and content-addressed, the journal is both
 verifiable (recompute any balance) and tamper-evident (any change to a past

+ 16 - 26
doc/storage-schema.md

@@ -3,7 +3,7 @@
 Reference for the tables `kuatia-storage-sql` creates. This is the composed
 end-state after replaying every migration in
 `crates/kuatia-storage-sql/src/migrations/` (`001_init` through
-`011_native_amounts`) plus the `_migrations` bookkeeping table created in
+`012_drop_reservation`) plus the `_migrations` bookkeeping table created in
 `crates/kuatia-storage-sql/src/migrate.rs`. It is a living reference: update it
 when a migration lands. For *why* the schema looks this way, see the ADRs it
 links to, not this file.
@@ -74,7 +74,6 @@ erDiagram
         BIGINT subaccount
         INTEGER asset
         AMOUNT value
-        BIGINT reservation
     }
     transfers {
         TEXT id PK
@@ -101,10 +100,6 @@ erDiagram
         AMOUNT balance
         BIGINT watermark
     }
-    sagas {
-        BIGINT id PK
-        TEXT data
-    }
     events {
         BIGINT seq PK
         BIGINT timestamp
@@ -168,30 +163,29 @@ never `UPDATE`.
 
 A posting is a signed amount of one asset owned by one (sub)account, identified
 by `(transfer_id, idx)`. The immutable `postings` record is the historical source
-of truth; one `live_postings` hot table carries a full row copy of the live set
-(spendable + reserved), so spendable reads never merge back to history. Lifecycle
-state is *derived* from `live_postings` membership plus its `reservation` column:
-present with `reservation` NULL = Active, present with a reservation = Reserved,
-in `postings` only = Spent, absent = Missing. Owned by `posting.rs`
-(`PostingStore`). See
+of truth; one `live_postings` hot table carries a full row copy of the unspent
+set, so spendable reads never merge back to history. State is *derived* from
+`live_postings` membership: present = Live, in `postings` only = Spent, absent =
+Missing. Owned by `posting.rs` (`PostingStore`). See
 [ADR-0016 (immutable postings + index tables)](adr/0016-immutable-postings-index-tables.md),
 [ADR-0017 (full-row hot copies)](adr/0017-correctness-first-append-only-hot-indexes.md),
 [ADR-0022 (merged hot index)](adr/0022-merged-live-postings-hot-index.md),
-[ADR-0006 (reservation protocol)](adr/0006-reservation-protocol-posting-lifecycle.md).
+[ADR-0025 (one live set)](adr/0025-one-live-set-no-reservations.md).
 
 **Why one hot table with full-row copies?** The index originally held only ids in
 two tables ([ADR-0016](adr/0016-immutable-postings-index-tables.md));
 [ADR-0017](adr/0017-correctness-first-append-only-hot-indexes.md) switched to
-full-row copies, and [ADR-0022](adr/0022-merged-live-postings-hot-index.md) merged
-the active and reserved tables into one `live_postings` (a nullable `reservation`
-replaces the two-table split). The hot read is "what can this account spend in
+full-row copies, [ADR-0022](adr/0022-merged-live-postings-hot-index.md) merged the
+active and reserved tables into one `live_postings`, and
+[ADR-0025](adr/0025-one-live-set-no-reservations.md) dropped the `reservation`
+column that had distinguished them. The hot read is "what can this account spend in
 this asset" (`get_postings_by_account`, `query_postings`, and the balance sum):
 carrying the data columns lets `live_postings` hold `idx_live_owner(owner,
 subaccount, asset)`, so a live read is one index scan on a small table with no
 join back to history and no `UNION` (the index *is* the table). The duplication
-is safe because the copied columns are immutable: `postings` rows never change and
-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
+is safe because the copied columns are immutable: a `live_postings` row is
+inserted and deleted but never updated, and `postings` rows never change, 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` and the transfer log, so a corrupt hot table is a drop-and-rebuild,
 not data loss.
@@ -214,12 +208,9 @@ The immutable record. A row here that is absent from `live_postings` is Spent.
 
 ### `live_postings`
 
-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 (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.
+The live-set hot copy. A posting is here while it is spendable, and an atomic
+commit deletes the consumed row directly (→ Spent), so membership is the whole of
+its state. Rebuildable from `postings` and the transfer log.
 
 | Column | Type | Key | Purpose |
 |---|---|---|---|
@@ -229,7 +220,6 @@ log.
 | `subaccount` | `BIGINT` | | Owning subaccount code. |
 | `asset` | `INTEGER` | | Asset id. |
 | `value` | `NUMERIC(39,0)` / `BLOB` | | Signed `Cent`, stored natively: `NUMERIC(39,0)` on PostgreSQL, the 16-byte order-preserving encoding on SQLite. Read a SQLite one with `kuatia_i128_to_text(value)`. |
-| `reservation` | `BIGINT` | | Nullable: NULL = Active, set = the `ReservationId` holding this posting (Reserved). |
 
 - **Primary key**: `(transfer_id, idx)`.
 - **Index**: `idx_live_owner (owner, subaccount, asset)`.

+ 45 - 19
doc/transfers.md

@@ -159,10 +159,41 @@ struct Envelope {
 }
 ```
 
-The envelope is content-addressed: its `EnvelopeId` is the double-SHA-256 of
+The envelope is content-addressed: its `TransferId` is the double-SHA-256 of
 its canonical binary serialization. This provides idempotency (committing the
 same envelope twice returns the cached receipt) and tamper evidence.
 
+## Transfer identity: give every distinct transfer a reference
+
+Because the id is the hash of the content, two transfers with identical content
+**are one transfer**: the second commit returns the first one's receipt and
+applies nothing.
+
+A payment distinguishes itself. The postings it consumes are part of the
+content, and the second payment consumes what the first left behind, so paying
+the same amount to the same account twice produces two transfers with no effort
+from the caller.
+
+A transfer that consumes nothing cannot distinguish itself. A deposit creates
+value at the boundary, so two deposits of the same amount to the same account
+are byte-identical, and the second is discarded as a replay. The same holds for
+any issuance.
+
+Set `reference` on anything that may legitimately repeat:
+
+```rust
+let top_up = TransferBuilder::new()
+    .deposit(alice, usd, Cent::from(5_000), bank)?
+    .reference("top-up-8f21c4")   // this payment, not the last identical one
+    .build();
+```
+
+Read the other way, this is retry safety: repeat the same reference and a
+redelivered request collapses onto the transfer it already committed, which is
+the behaviour you want from a retry. One rule covers both. The reference is
+stored under the reserved `REFERENCE_KEY` metadata key, so it is part of the
+content address and part of the audit record.
+
 ## Transfer Builder
 
 The `TransferBuilder` provides a fluent API for constructing transfers:
@@ -180,27 +211,22 @@ A single transfer can contain multiple movements of different types. All
 movements execute atomically. A transfer with multiple movements is a compound
 journal entry; see [journaling.md](journaling.md).
 
-## Commit Paths
-
-### Saga commit (default)
+## Commit Path
 
 ```
-Transfer → resolve → Envelope → reserve → finalize(validate → write) → Receipt
+Transfer → resolve → Envelope → validate → atomic store commit → Receipt
 ```
 
-Resolution is read-only; `commit(transfer)` resolves then runs the two-step
-envelope saga (reserve → finalize) with automatic retry and LIFO compensation.
-Validation runs inside the finalize step, immediately before the writes.
-
-### Committing a pre-built envelope
-
-```
-Envelope → reserve → finalize(validate → write) → Receipt
-```
+Resolution is read-only. `commit(transfer)` resolves, validates in the pure
+core, then hands the result to `CommitStore::commit_envelope`, one transaction
+that spends the consumed postings, inserts the created ones, stores the transfer
+and appends the event. The transaction re-checks double-spend, freeze/close and
+the overdraft floor inside itself, so those guards are strict rather than
+best-effort (ADR-0023).
 
-`ledger.commit_envelope(envelope)` runs the same saga for an envelope you
-already hold (e.g. a hand-built multi-asset/FX envelope, or a reversal).
-`reverse()` uses it. There is no separate single-pass "atomic" path.
+`ledger.commit_envelope(envelope)` takes the same path for an envelope you
+already hold (a hand-built multi-asset or FX envelope, or a reversal), and
+`reverse()` uses it. There is one commit path.
 
 ## Reversal
 
@@ -219,8 +245,8 @@ validation steps are:
 1. Non-empty (must consume or create at least one posting)
 2. No duplicate consumed PostingIds
 3. All consumed postings exist in the immutable table (a `Posting` carries no
-   lifecycle state; double-spend safety is enforced by the reserve claim and the
-   finalize "all spent" guard, not by validation)
+   state, so double-spend safety is enforced by the commit transaction's own
+   delete, not by validation)
 5. All referenced accounts exist, not frozen, not closed
 6. Account snapshot pinning (if provided)
 7. Book policy (if a book is loaded): referenced assets/accounts/flags allowed

Некоторые файлы не были показаны из-за большого количества измененных файлов