# Architecture Decision Records The significant, hard-to-reverse design decisions for Kuatia. They are here so that the *why* survives. A new record follows [`template.md`](template.md), in the MADR style. The sections are context, then drivers, then the considered options with their pros and cons, then the decision outcome, then the consequences, then the links. The numbers run in sequence. Nobody edits a record to reverse a decision. Instead a new record supersedes it. ## Index | ADR | Title | Status | Summary | |-----|-------|--------|---------| | [0001](0001-modified-utxo-signed-postings.md) | Modified UTXO: value as signed postings | accepted | Value is signed postings (negative = "offset positions"), not mutable balances; conservation is structural; balances are projections. | | [0002](0002-saga-commit-pipeline.md) | Saga commit pipeline | accepted | Commit is a compensating saga (`reserve → finalize`), not a single/distributed transaction: composable, coordinator-free, crash-recoverable. | | [0003](0003-dumb-storage-saga-recovery.md) | Dumb storage + durable saga recovery | 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 | 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 (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. | | [0012](0012-subaccounts.md) | Subaccount dimension on account identity | accepted | Account identity gains a subaccount dimension (used for per-destination inflight holding subaccounts). | | [0013](0013-journaling-model.md) | Journaling model: transfer as journal entry | accepted | A committed `Transfer`/`Envelope` is a (compound) journal entry; the transfer log is the accounting journal; `Book` is a policy scope, not the journal. Frames 0001/0005/0010 in accounting terms. | | [0014](0014-inflight-holds-via-holding-accounts.md) | Inflight holds via per-destination holding accounts | accepted | A hold is a subaccount of its destination; committing routes funds through the holding subaccount so pending value stays visible and reconcilable until settle or cancel. | | [0015](0015-fixed-width-account-code.md) | Fixed-width 20-character account code | accepted | The IBAN-style code becomes a fixed 20 chars (18-char body + 2 trailing check digits, five groups of four) by packing id (63 bits) and subaccount (30 bits) into one permuted value. Presentation-only; caps the subaccount at `SUB_BITS`. Supersedes the code section of 0012. | | [0016](0016-immutable-postings-index-tables.md) | Immutable postings with active/reserved index tables | accepted (hot-table representation refined by 0017) | Postings become an insert-only immutable table; lifecycle state moves to two index tables (`active_postings`, `reserved_postings`). Append-only integrity + least privilege (no `UPDATE`) + hot working set by segregation. Supersedes the storage representation of 0006. | | [0017](0017-correctness-first-append-only-hot-indexes.md) | Correctness-first storage: append-only value tables, disposable hot indexes | accepted | The guiding principle: value/audit tables (`postings`, `accounts`) are strictly append-only source of truth; disposable hot tables (`active_postings`, `reserved_postings`, `account_head`) index the live subset by `INSERT`/`DELETE` only and are rebuildable. Correctness first; no `UPDATE` anywhere, enforceable by DB grants. Generalizes 0016 (hot tables now hold full row copies). | | [0018](0018-single-debit-must-not-exceed-credit-flag.md) | Collapse account policy into a single debit-must-not-exceed-credit flag | accepted | The `AccountPolicy` enum is removed; the only per-account balance constraint is the `AccountFlags` bit `DEBIT_MUST_NOT_EXCEED_CREDIT`. Overdraft is allowed by default (unbounded); the flag forbids a negative balance and negative postings. Credit-line floors become an application concern. Supersedes 0004. | | [0019](0019-cached-balance-projection.md) | Cached balance projection via append-only cache points | accepted | Append-only `balance_projection` cache points (id, watermark, balance); a read takes the closest one at or before `now` and folds the tail of committed movements since its commit-time watermark (grace Δ). Correctness never depends on the cache (equals the live sum at rest). Cache points are appended lazily on read once N credits/debits accrue (configurable); no per-commit hook, no lease, no background loop. | | [0020](0020-account-transition-recovery.md) | Crash-safe account-version transitions | 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 (`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 can 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` 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. | | [0027](0027-value-date-separate-from-commit-time.md) | Value date, separate from commit time and inside the content address | accepted | An entry can be booked one day and take effect another. `ValueDate` is a calendar day on `Transfer` and `Envelope`, inside the content address, so two entries differing only in the day they take effect are two transfers. `created_at` keeps its single meaning as the commit clock the balance cache folds against; migration 013 adds a filterable column and `TransferQuery` gains its own window. Bumps `CANONICAL_VERSION`. Follows 0026; constrained by 0019. | | [0028](0028-amount-carries-its-asset.md) | An amount carries its asset, and the ledger owns the asset registry | accepted | `Amount { asset: Arc, value: Cent }` is what the public API takes and returns, so two assets cannot be added by a caller holding two balances. A registered `Asset` carries the precision a written amount parses at, which retires ADR-0009's accepted gap; its old presentation-only `Amount` becomes `Scale`. `Arc` stops at the public surface, so nothing stored and no content address moves. Refines 0009; follows 0026. | | [0029](0029-stored-amounts-and-a-closed-money-surface.md) | Stored amounts, and a public surface that never names `Cent` | accepted | An amount's serialized form carries its asset, so `Movement`, `Posting`, `NewPosting` and `BalanceProjection` each hold one amount and decode with no registry. The content address still hashes the asset id and the value, proved by a golden vector. The column tables keep the integer and the id for ADR-0024's sums and left-join the registry to rebuild an amount. `Cent` leaves the public surface entirely, reachable only through `kuatia_types::internals`. Supersedes 0028's point 3. | | [0030](0030-assets-named-by-code.md) | An asset is named by its code, and the ledger mints its id | accepted | `ledger.asset("EUR", "€", 2)` registers on first sight and returns the handle, so a caller states the code, symbol and precision and never invents an id. A code is unique (migration 015) and one registered at another precision is refused rather than resolved. Supersedes ADR-0028's caller-supplied-id clause. | | [0031](0031-every-read-is-account-scoped.md) | Every read is account scoped: no aggregate crosses accounts | accepted | No read folds value across accounts, so every read keeps a shard key and a cost bounded by one account. `Ledger::trial_balance` and `PostingStore::live_balances` are removed before they were ever published; cross-account reporting belongs off the event stream. Row enumerations and registry reads are unaffected. | ## Recommended future ADRs These are real decisions. Their rationale lives in the code and the documents, and no record captures it yet. They are in rough order of priority: 1. **A content-addressed transfer id, and the rejection of a sequential hash chain**: `TransferId = double-SHA-256(canonical bytes)` gives idempotency and tamper evidence. The record must also say why the design turned down a hash chain per transfer, which was a concurrency bottleneck. See the "No Sequential Hash Chain" section of `architecture.md`. 2. **The split between the pure core and the async layer**: `kuatia-core` is deterministic and does no IO. It holds the validation, the selection and the hash, and a golden vector can test it. The async layer holds the storage and the saga. 3. **An id that Rust generates through `AutoId`, with no `AUTOINCREMENT` and no `SERIAL`**: the application owns the identity, as a snowflake-style `i64`. That allows a later sharding with no coordination by the database. 4. **An append-only, versioned account, plus snapshot pinning**: nothing modifies an account in place. A snapshot hash guards against a TOCTOU race between the load and the apply. 5. **A move of the posting selection into SQL**: an amount column orders numerically now (ADR-0024), so a greedy largest-first selection can run as a query. Today the ledger fetches every live posting instead. Nobody has decided whether the resolve decision belongs in the store at all. 6. **The growth in the number of postings, and their consolidation**: the greedy largest-first selection of ADR-0001 and ADR-0005 breaks a balance into change postings. Those get smaller and smaller. Nobody has decided whether to consolidate them, how to do it, or what to do with dust. 7. **Retention for the spent postings and the append-only logs**: three things grow without bound. Those are the immutable postings table (ADR-0016), the transfer log, and the derived event stream (ADR-0010). An archive and a retention policy are both deferred, and that omission is deliberate today. ADR-0016 keeps the spent history physically apart from the live set, which is where a retention policy applies. 8. **The consistency model for a read and a projection**: a balance is a sum over the live postings. Those are the active postings and the reserved ones. That sum takes no transaction. So a read that runs beside a commit is eventually consistent. The documents imply the guarantee on the read side and never state it. 9. **An accounting class on an account**: an account has no dimension for an asset, a liability, equity, income or an expense. So the ledger cannot group a balance sheet or a profit-and-loss statement. Nobody has decided where that class belongs: on the account, in metadata, or outside the ledger. See [accounts.md](../accounts.md#accounts-carry-no-accounting-class). 10. **Whether tenancy belongs in the ledger**: `Book` gates participation and isolates nothing, so a tenant is a separate `Store` today. Nobody has decided whether the ledger must own a tenant dimension instead. See [glossary.md](../glossary.md#books-are-not-a-tenancy-boundary).