README.md 12 KB

Architecture Decision Records

Significant, hard-to-reverse design decisions for Kuatia, captured so the why survives. New ADRs follow template.md (MADR-style: context → drivers → considered options with pros/cons → decision outcome → consequences → links). Numbering is sequential; an ADR is never edited to reverse a decision. Instead, a new ADR supersedes it.

Index

ADR Title Status Summary
0001 Modified UTXO: value as signed postings accepted Value is signed postings (negative = "offset positions"), not mutable balances; conservation is structural; balances are projections.
0002 Saga commit pipeline accepted Commit is a compensating saga (reserve → finalize), not a single/distributed transaction: composable, coordinator-free, crash-recoverable.
0003 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 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 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 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 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 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 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 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 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 Subaccount dimension on account identity accepted Account identity gains a subaccount dimension (used for per-destination inflight holding subaccounts).
0013 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 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 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 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 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 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 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 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 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 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 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 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 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 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

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: 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.
  2. Pure core / async layer split: a zero-IO, deterministic kuatia-core (validation, selection, hashing; golden-vector testable) vs. the async storage + saga layer.
  3. Rust-generated ids (AutoId), no AUTOINCREMENT/SERIAL: the application owns identity (snowflake-style i64), enabling future sharding without DB coordination.
  4. Append-only, versioned accounts + snapshot pinning: accounts are never modified in place; snapshot hashes guard against TOCTOU between load and apply.
  5. Pushing posting selection into SQL: now that amount columns are orderable (ADR-0024), greedy largest-first selection could run as a query instead of fetching every live posting; whether the resolve decision should move into the store at all is undecided.
  6. Posting proliferation & consolidation: greedy largest-first selection (ADR-0001/0005) fragments balances into ever-smaller change postings; whether and how to consolidate, and what to do with dust, is undecided.
  7. Retention / pruning of spent postings and the append-only logs: the immutable postings table (ADR-0016), the transfer log, and the derived event stream (ADR-0010) all grow without bound; archival/retention is deferred and currently a conscious omission. ADR-0016 makes the spent history physically separable from the live working set, which is where pruning would apply.
  8. Read/projection consistency model: a balance is a non-transactional sum over the live (active or reserved) postings, so a read concurrent with a commit is eventually consistent; the read-side guarantee is implied but never stated.