0024-native-money-columns.md 11 KB

Native money columns, and exact summation in the database

  • Status: accepted
  • Authors: Cesar Rodas
  • Date: 2026-09-08
  • Targeted modules: kuatia-money, kuatia-storage, kuatia-storage-sql
  • Associated tickets/PRs: —

Context and Problem Statement

ADR-0011 made the Cent backing a compile-time choice between i64 and i128, and stored every amount as a decimal TEXT column. That hid the width and sidestepped the fact that neither backend has a native 128-bit integer. It also accepted a cost, recorded there: "the database cannot order or range-filter on the amount."

That cost is now on the hot path. The in-transaction overdraft floor (commit.rs::live_balance) fetched every live posting row for an (owner, asset) pair, parsed each decimal string and folded them in Rust, inside the commit transaction, once per overdraft-forbidding account a transfer touches. Ledger::compute_balance did the same through the Store trait. The schema could not index, order or aggregate an amount at all.

Can amounts be stored in a form the database understands, without reintroducing the two things text was protecting against: a width that leaks into the API, and inexact or wrapping money arithmetic?

Decision Drivers

  • An amount must survive the i128 cargo feature being toggled without a migration, so the stored width cannot be the backing's width.
  • Summation must be exact and must fail loudly, never wrap and never round. Whatever does the addition, the guarantee has to match Cent::checked_sum.
  • The Cent API must keep the backing width out of public signatures, and the content-addressed hash preimage (to_canonical_bytes, frozen by CANONICAL_VERSION) must not change: switching backings must not rehash the ledger.
  • sqlx::Any is the whole SQL backend. Its value universe is Bool/Int/Real/Text/Blob, and it never exposes the underlying driver handle.
  • A row should stay auditable. Amounts are where this is conceded, knowingly: see the negative consequences.

Considered Options

Option 1: Keep TEXT, keep summing in Rust

Change nothing.

Pros:

  • Zero risk, zero new dependencies, no unsafe.

Cons:

  • Bad, because the overdraft floor keeps shipping one row per posting into the commit transaction, which is the cost that motivated this ADR.
  • Bad, because no amount column can ever be indexed, ordered or range-filtered, which also blocks pushing greedy largest-first posting selection (ADR-0001/0005) into SQL later.

Option 2: Native columns, keeping sqlx::Any, with casts at the dialect seam

NUMERIC(39,0) on PostgreSQL, a fixed 16-byte BLOB on SQLite. Amounts cross the Any boundary as String (Postgres) or Vec<u8> (SQLite), with the SQL carrying CAST($n AS NUMERIC) / CAST(col AS TEXT) on Postgres. SQLite gets a registered kuatia_i128_sum aggregate; Postgres uses plain SUM().

Pros:

  • Good, because storage, indexing, ordering and aggregation are all native on both backends.
  • Good, because both aggregates are exact: NUMERIC is arbitrary precision, and kuatia_i128_sum folds with i128::checked_add and raises on overflow.
  • Good, because the whole divergence lands in the existing Dialect seam instead of spreading through the query code.

Cons:

  • Bad, because PostgreSQL money still travels as decimal text, so a read pays a numeric → text → parse round trip.
  • Bad, because AnyRow converts every column's type before any column is read and has no mapping for NUMERIC, so one forgotten cast fails the whole row. SELECT * over a money table is therefore no longer allowed.
  • Bad, because SQLite function registration has to be process-global (see below), which brings an ordering requirement and the first unsafe in the repository.

Option 3: Drop sqlx::Any for concrete Pool<Sqlite> / Pool<Postgres>

Write real Type/Encode/Decode impls per driver, so Cent binds as binary NUMERIC on Postgres and as a blob on SQLite.

Pros:

  • Good, because money is native end to end, with no casts and no text hop.
  • Good, because SqliteConnectOptions can register the aggregate per connection, with no global state and no ordering trap.
  • Good, because SELECT * keeps working and compile-time-checked queries become possible.

Cons:

  • Bad, because every query in account/posting/transfer/commit/event/ book/projection must be duplicated per backend or made generic over a Database bound, whose where-clauses fight "clarity over cleverness".
  • Bad, because it is a rewrite of the storage crate for a change whose payload is three columns.

Option 4: Native columns, but implement Type/Encode/Decode<Any> for a Cent wrapper

Instead of binding String/Vec<u8> and converting by hand, teach Any about Cent directly.

Pros:

  • Good, because call sites would read .bind(cent) and row.try_get::<Cent, _>().

Cons:

  • Bad, because AnyValueKind and AnyArgumentBuffer are not re-exported from the sqlx facade and are #[doc(hidden)] in sqlx-core, so this needs a direct dependency on a crate whose own description says "not for direct use".
  • Bad, because it buys nothing: AnyValueKind has no numeric variant either, so the Postgres cast is still required.

Decision Outcome

Chosen option: Option 2. It gets the whole payload (native storage, exact in-database summation, orderable amounts) for a diff confined to the Dialect seam, two row helpers and one new module, where Option 3 is a rewrite of the storage crate and Option 4 buys nothing for a #[doc(hidden)] dependency.

Concretely:

  • The stored form is always 128 bits wide, whatever Backing is. Postgres uses NUMERIC(39,0), which is exactly the decimal width of i128. SQLite uses a 16-byte BLOB. Toggling the i128 feature needs no migration, and a database written under i128 fails loudly when read under i64 rather than truncating.
  • The SQLite encoding is offset-binary: two's-complement big-endian with the sign bit flipped (encode_storage_i128 in kuatia-money). SQLite compares blobs byte-wise, and all amounts are exactly 16 bytes, so unsigned lexicographic order is numeric order: i128::MIN is all zeros, 0 is 0x80 00…, i128::MAX is all 0xFF. ORDER BY value and WHERE value > ? are correct for free, which is what Postgres NUMERIC gives natively — so both backends gain the same capability rather than diverging.
  • It is deliberately not the canonical hash encoding. Two's-complement would have made to_storage_bytes byte-identical to to_canonical_bytes, and a cross-use of the frozen hash preimage would then have silently worked until either encoding was touched. The flipped bit makes that mistake fail immediately.
  • SQLite gets three registered functions: kuatia_i128_sum (an aggregate folding with i128::checked_add, raising on overflow or on any argument that is not a 16-byte amount, and summing an empty group to zero rather than to NULL), plus kuatia_i128_from_text and kuatia_i128_to_text. The scalars do the 011 migration's conversion and let tooling built on this crate read a column that is no longer human-readable.
  • Registration is process-global, via sqlite3_auto_extension, because sqlx::Any never exposes the sqlite3* handle (AnyConnection.backend is private, so there is nothing to downcast). Callers use kuatia_storage_sql::install_drivers() in place of sqlx::any::install_default_drivers(), before connecting a pool.
  • PostingStore::live_balance is a Store method, so the ledger's authoritative balance read goes through it too, with the in-memory backend summing in Rust as the conformance oracle.

Positive Consequences

  • The in-transaction overdraft floor is one aggregate row instead of one row per live posting, and so is Ledger::compute_balance.
  • Amount columns can be ordered, compared and indexed on both backends. This retires ADR-0011's accepted negative consequence and unblocks pushing posting selection into SQL.
  • The conformance suite cross-checks the database's sum against Cent::checked_sum over the same rows on every backend, so the two paths cannot drift apart silently.

Negative Consequences

  • PostgreSQL amounts still travel as decimal text under sqlx::Any, so a read costs a numeric → text → parse hop. Only the storage is native, not the wire.
  • Every Postgres SELECT touching money must go through Dialect::money_read. A missed cast fails the entire row, and only the Postgres CI job catches it, never the default SQLite run. SELECT * over a money table is banned, so a future column added to postings will not be picked up automatically.
  • install_drivers() must run before the first connection is opened. migrate() probes for the functions on SQLite and returns StoreError::Misconfigured rather than a bare "no such function", but the ordering requirement is real.
  • Registration affects every SQLite connection in the process, including ones opened by unrelated libraries. The function names are prefixed accordingly.
  • A SQLite amount is no longer legible in a plain sqlite3 CLI, which does not have kuatia_i128_to_text and shows a blob. Reading one by hand there means taking hex(value), subtracting 0x80 from the leading byte and decoding a 128-bit big-endian two's-complement integer. Identifier and payload columns are unaffected, and PostgreSQL NUMERIC stays fully legible.
  • kuatia-storage-sql now depends directly on libsqlite3-sys, a links = "sqlite3" crate. Only one version can exist in the graph, so the pin must be kept in step with whatever sqlx-sqlite depends on; a sqlx bump is now a deliberate event rather than a routine one.
  • This introduces the first unsafe in the repository. It is confined to crates/kuatia-storage-sql/src/sqlite_ext.rs. The one non-obvious hazard there: sqlite3_aggregate_context returns memory aligned for 8 bytes, not the 16 an i128 needs, so the accumulator holds raw bytes rather than an i128 field.

Links

  • Supersedes the storage clause of ADR-0011 ("Storage serializes to string"), and retires its negative consequence that the database cannot order or range-filter on the amount. The CentBacking / cargo-feature decision itself stands.
  • Amends ADR-0009: the persisted form has now gone BIGINT → text → backend-native.
  • Amends ADR-0023: the overdraft floor is still re-checked inside the commit transaction, but the sum is now one aggregate.
  • Touches ADR-0019 (balance_projection.balance) and ADR-0022 (live_postings.value).