# Architecture Decisions ## UTXO (Unspent Transaction Output)-Style Postings The ledger stores value as **postings**, which are signed amounts of a single asset. Exactly one account owns each posting. A positive posting is value that the account controls. A negative posting is an offset position, and it covers issuance, an external flow, or a system balance. An account balance is the sum of the live, unspent postings for that (account, asset) pair. There is no mutable balance field, so nothing can drift out of step. The ledger marks a consumed posting as inactive and never deletes it. So the audit trail stays complete. ## Pure Core / Async Layer Separation ```mermaid graph LR subgraph "kuatia-core (pure, sync, no IO)" V[validate_and_plan] S[select_postings] H[hash / transfer_id] T[Types & ToBytes] end subgraph "kuatia (async, IO)" L[Ledger] ST[Store sub-traits] W[workflow::run_transfers] end L --> V L --> S L --> ST W --> L ``` **kuatia-core** holds all the validation logic. It has no IO, no async runtime and almost no dependency. Golden vectors can test it, a replay is deterministic, and it embeds in a `no_std` environment. **kuatia** adds the async `Store` trait, which it uses as `dyn Store` through a trait object, and the commit engine. The `Ledger` struct is non-generic and holds an `Arc`. This separation keeps the auditable heart of the system deterministic, and a test can reach it on its own. ## Store Sub-Trait Architecture The `Store` trait is a composite of focused sub-traits, and each one owns a single domain. A transfer commits atomically through `CommitStore`, by `commit_envelope` or `commit_transition`. The other posting and account write methods are **simple instructions** that a read or a setup step uses. Each one applies one update and returns the number of affected rows, or an IO error. No method interprets that count. ```mermaid classDiagram class AccountStore { +get_account(id) +get_accounts(ids) +create_account(account) +get_account_history(id) +list_accounts() } class PostingStore { +get_postings(ids) +get_postings_by_account(account, sub?, asset?, filter) +get_posting_states(ids) +live_balance(account, asset) +query_postings(query) } class TransferStore { +get_transfer(id) +get_transfers_for_account(account) +query_transfers(query) } class CommitStore { +commit_envelope(request) CommitOutcome +commit_transition(next, event) TransitionOutcome } class EventStore { +append_event(event) +get_events_since(after_seq, limit) } class BookStore { +create_book(book) +get_book(id) +list_books() } class BalanceProjectionStore { +append_balance_projection(account, asset, balance, watermark) +get_closest_balance_projection(account, asset, as_of) } class Store { <> } Store --|> AccountStore Store --|> PostingStore Store --|> TransferStore Store --|> CommitStore Store --|> EventStore Store --|> BookStore Store --|> BalanceProjectionStore ``` `CommitStore::commit_envelope` commits a whole transfer atomically, so there is one atomic commit boundary. The store enforces the stateful guards inside that transaction, which are double-spend, freeze and close, and the overdraft floor. The pure core validates everything else first. Validation and the resolve decision live in the Ledger and in `kuatia-core`. A sum of an account's live postings is the one thing a backend can do itself, through `PostingStore::live_balance`. The amount columns are native, so the sum is exact either way (ADR-0024). ## Atomic Commit `commit(transfer)` resolves the intent into a concrete envelope, and that step is read-only. It validates the envelope against the loaded state in the pure core. It then hands the validated effects to `store.commit_envelope(..)`, which applies them in one transaction. ```mermaid sequenceDiagram participant C as Caller participant L as Ledger participant S as Store C->>L: commit(transfer) L->>L: resolve(transfer) → envelope [read-only] L->>L: load + validate_and_plan() [pure core] L->>S: commit_envelope(consume, create, record, involved, event) Note over S: one transaction —
idempotency check, freeze/close,
double-spend (delete-affected-count),
overdraft floor, then apply S-->>L: Committed | AlreadyCommitted | Rejected L-->>C: Receipt (or mapped error) ``` Inside the transaction the store first checks idempotency, and a transfer that is already stored returns its receipt. The store then re-checks the three stateful guards strictly: - The consumed postings must still be live. The delete-affected-count is the atomic single-winner claim. - The involved accounts must not be frozen and must not be closed. - The projected balance of an account that forbids overdraft must stay at zero or above. Rust sums it from the live rows. A domain rejection is a typed `CommitRejection`, and the ledger maps it to a `LedgerError`. The store applies nothing on a rejection. The write is all-or-nothing, so a crash either applied the whole commit or none of it. There is no write-ahead record and no `recover()` step. An account transition has the same shape, whether it is a freeze, an unfreeze or a close. `commit_transition` appends the new version and its lifecycle event in one transaction. This design replaced an earlier saga pipeline. A saga is the right tool for a workflow that spans resources which cannot share a transaction, such as several services or a sharded store. Here every step sat behind one transactional store, so one ACID transaction was the simpler and stricter primitive. If a backend ever shards its data, the saga returns *inside* that backend's `commit_envelope` and not in the ledger core. See [ADR-0023](adr/0023-atomic-storage-commit.md), under "When a saga is the right tool". `reverse()` builds a reversal envelope and runs the same `commit_envelope` path. Several transfers compose into an all-or-nothing workflow through `workflow::run_transfers`. That runner commits them in order, and on a failure it reverses the committed ones in last-in-first-out order. ## Content-Addressed Transfers `TransferId` is the double-SHA-256 of a transfer's canonical binary serialization. This serves two purposes: - **Idempotency**: a second commit of the same transfer returns the cached receipt rather than a second apply. - **Tamper evidence**: any change to a transfer's data changes its ID. Every domain type implements deterministic binary serialization through the `ToBytes` trait. The encoding is big-endian with a version prefix, `CANONICAL_VERSION = 6`. ## Append-Only Account Versioning The ledger never modifies an account in place. Each account mutation appends a new snapshot with a `version` field one higher than the last, and the version starts at 1 on creation. A freeze, an unfreeze, a close and a flags change are all such mutations. Note that a transfer does **not** bump an account version. The ledger derives a balance from the postings and does not store it on the account. The store enforces that each new version is exactly `current + 1`, which prevents a gap and prevents an overwrite. `account_history()` queries the full version history. ## Account Snapshot Pinning A transfer can carry `AccountSnapshotId` values. Each one is a pair of `(AccountId, snapshot_hash)`, and it records the account version that the transfer validated against. During validation, when a caller provides snapshots, the ledger hashes the current account state and compares the two. A mismatch produces `AccountVersionMismatch`. This prevents a TOCTOU race, which is Time-Of-Check to Time-Of-Use, where something mutates an account between the load and the apply. The `commit()` convenience method fills in the snapshots when a caller provides none. ## Per-Asset Conservation Here is the conservation invariant. For each asset, the sum of the consumed posting values must equal the sum of the created posting values. A conservation boundary is **per asset only**. The `book` field on a transfer and on an account is a transfer policy scope, and it names which accounts and assets can participate. It does not affect conservation enforcement. It does not partition balances. It is not a tenancy boundary ([glossary](glossary.md#books-are-not-a-tenancy-boundary)). ## Account Balance Constraint The single per-account balance constraint is the `AccountFlags` bit `DEBIT_MUST_NOT_EXCEED_CREDIT`: | Flag | Balance | Negative postings | |------|---------|-------------------| | unset (default) | can go negative, unbounded | Yes (unbounded) | | `DEBIT_MUST_NOT_EXCEED_CREDIT` | `>= 0` | No | By default the ledger allows overdraft. An overdraft is a **negative posting** that the ledger assigns to the account to cover a shortfall. A debit short of the account's positive postings takes a negative offset posting to cover it. The ledger then records the transfer, if it conserves value per asset. A credit-line limit is an application concern, and the ledger does not enforce one. With the flag set, the account's debits must not exceed its credits. Its balance must not go negative, and it must not hold a negative posting. Validation rejects a negative posting on such an account. Use `Account::debit_must_not_exceed_credit(id)` to set the flag and `Account::forbids_overdraft()` to query it. ## The Debit-Must-Not-Exceed-Credit Constraint Under Concurrency An account that forbids overdraft has a balance floor at zero, and the UTXO model alone does not back that floor. Two concurrent transfers could each pass a snapshot validation and together push the balance negative, which is write-skew. Under the atomic-commit model (ADR-0023) the transaction re-runs the floor check and the freeze and close checks **inside itself**. It runs them after the delete of the consumed postings and the insert of the created ones, so they see the true post-commit state. A projected negative balance on an account that forbids overdraft aborts the whole transaction. On PostgreSQL the transaction takes the involved account-head rows `FOR UPDATE` before the live-posting writes. That serializes concurrent commits which touch the same account. On SQLite the single write transaction serializes the writers. So the floor is **strict** and not best-effort. Double-spend safety comes from the same transaction. The delete of a consumed live row is the atomic single-winner claim, so two commits cannot both spend it. This supersedes the best-effort tradeoff that [doc/adr/0003-dumb-storage-saga-recovery.md](adr/0003-dumb-storage-saga-recovery.md) records. See [doc/adr/0023-atomic-storage-commit.md](adr/0023-atomic-storage-commit.md). An account that permits overdraft has no floor to violate. ## No Sequential Hash Chain An earlier design linked each transfer to the one before it through a hash chain, which enforced a total order. The design dropped the chain for these reasons: - UTXO double-spend prevention already stops a reorder attack, because nothing can consume a posting twice. - A content-addressed transfer ID gives tamper evidence and needs no chain. - Append-only account versioning stops the manipulation of an account state. - The chain was a **concurrency bottleneck**, because every transfer had to wait for the hash of the one before it. ## Posting Selection The intent layer hides the UTXO complexity from a caller. Every operation is one or more movements, and each one is an [`Amount`](glossary.md#amount) that moves from one account to another. The builder splits each movement into the `Movement { from, to, asset, amount }` that the resolve step reads. The resolve step aggregates the net debit per (account, asset) pair across all the movements. Then, for each pair with a positive net debit, the `select_postings` function runs a **greedy largest-first** algorithm: 1. Filter to the live, positive postings of the target asset. 2. Sort by value, highest first. 3. Add values until the sum meets or passes the target. If the selected sum passes the target, the resolve step creates a **change posting** that returns the remainder to the sender. This is exactly like a change output in Bitcoin. Aggregation before selection means that several movements which debit the same account share one selection pass. So the resolver cannot select the same posting twice. ## Posting Lifecycle A posting is live while the live index holds it. It is spent once the atomic commit deletes it from that index. So its state follows from one membership question, and the posting never stores it: ```mermaid stateDiagram-v2 [*] --> Live: commit creates it Live --> Spent: commit consumes it ``` | State | Spendable | In balance | Description | |-------|-----------|------------|-------------| | **Live** | Yes | Yes | Available for consumption | | **Spent** | No | No | Consumed. Kept for audit trail (void) | The ledger deletes a consumed posting from the live index and never from the immutable record, so the history stays complete. There is no intermediate reserved state. The commit transaction's own delete is the single-winner claim, which is the reason 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 One commit is already atomic in the store. So a composition of several transfers into one all-or-nothing workflow needs only a thin runner, and not a saga machine. An FX trade and a multi-leg settlement are both such a workflow. `workflow::run_transfers` commits the transfers in order. On the first failure it reverses the receipts it already committed, in last-in-first-out order, through `ledger.reverse(..)`: ```rust use kuatia::workflow::run_transfers; let ledger: Ledger = /* ... */; let receipts = run_transfers(&ledger, &[ TransferBuilder::new().deposit(alice, ("100.00", &usd), bank).build()?, TransferBuilder::new().pay(alice, bob, ("40.00", &usd)).build()?, ]) .await?; ``` If the pay fails, the runner reverses the deposit and returns the original error. A reversal that fails surfaces as `LedgerError::CompensationFailed`. ### Reversal `reverse()` creates a compensating transfer. It consumes the postings that the original created and recreates the postings that the original consumed. So it undoes the operation and keeps the full audit trail.