Pārlūkot izejas kodu

Store amounts in a form the database can add up exactly

Every monetary column was decimal TEXT, so the database could not order,
range-filter or aggregate an amount. The in-transaction overdraft floor
paid for that on the hot path: it fetched every live posting row for an
(owner, asset) pair, parsed each 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.

Make the stored form backend-native and always 128 bits wide, whatever
the Backing feature selects: NUMERIC(39,0) on PostgreSQL, a fixed 16-byte
BLOB on SQLite. The blob is offset-binary (two's complement big-endian
with the sign bit flipped), so byte-wise comparison is numeric comparison
and ORDER BY and range predicates come for free. It is deliberately not
byte-identical to the frozen canonical hash preimage, so cross-using the
two fails immediately instead of silently working.

Summation stays exact on both backends: NUMERIC is arbitrary precision,
and SQLite gets a registered kuatia_i128_sum aggregate that folds with
i128::checked_add and raises on overflow. PostingStore::live_balance
becomes a Store method, so the floor check and the ledger's balance read
are each one aggregate row, with the in-memory backend summing via
Cent::checked_sum as the conformance oracle.

sqlx::Any stays, and the divergence lands in the Dialect seam. Registering
the SQLite functions needs sqlite3_auto_extension, because Any never
exposes the driver handle: that brings the first unsafe in the repository
and the requirement that install_drivers() run before any pool connects.
Migration 011 converts existing rows per backend.

Recorded in ADR-0024, superseding the storage clause of ADR-0011 and
retiring its accepted cost that amounts could not be ordered.
C 2 mēneši atpakaļ
vecāks
revīzija
db22dc4cd6
35 mainītis faili ar 1688 papildinājumiem un 188 dzēšanām
  1. 2 2
      CLAUDE.md
  2. 1 0
      Cargo.lock
  3. 1 1
      crates/kuatia-dashboard/src/seed.rs
  4. 14 0
      crates/kuatia-money/README.md
  5. 124 0
      crates/kuatia-money/src/lib.rs
  6. 5 1
      crates/kuatia-storage-sql/Cargo.toml
  7. 22 12
      crates/kuatia-storage-sql/README.md
  8. 48 44
      crates/kuatia-storage-sql/src/commit.rs
  9. 52 0
      crates/kuatia-storage-sql/src/dialect.rs
  10. 32 2
      crates/kuatia-storage-sql/src/lib.rs
  11. 72 19
      crates/kuatia-storage-sql/src/migrate.rs
  12. 10 0
      crates/kuatia-storage-sql/src/migrations/011_native_amounts.postgres.sql
  13. 64 0
      crates/kuatia-storage-sql/src/migrations/011_native_amounts.sqlite.sql
  14. 67 24
      crates/kuatia-storage-sql/src/posting.rs
  15. 21 21
      crates/kuatia-storage-sql/src/projection.rs
  16. 57 10
      crates/kuatia-storage-sql/src/row.rs
  17. 319 0
      crates/kuatia-storage-sql/src/sqlite_ext.rs
  18. 102 4
      crates/kuatia-storage-sql/tests/postgres.rs
  19. 280 7
      crates/kuatia-storage-sql/tests/sqlite.rs
  20. 7 1
      crates/kuatia-storage/src/error.rs
  21. 13 0
      crates/kuatia-storage/src/mem_store.rs
  22. 9 0
      crates/kuatia-storage/src/store.rs
  23. 67 0
      crates/kuatia-storage/src/store_tests.rs
  24. 3 1
      crates/kuatia-types/src/lib.rs
  25. 1 1
      crates/kuatia/examples/create_accounts.rs
  26. 1 1
      crates/kuatia/examples/fund_and_trade.rs
  27. 1 1
      crates/kuatia/examples/inflight_hold.rs
  28. 1 1
      crates/kuatia/examples/withdraw.rs
  29. 7 15
      crates/kuatia/src/ledger/balance.rs
  30. 220 0
      doc/adr/0024-native-money-columns.md
  31. 6 3
      doc/adr/README.md
  32. 4 2
      doc/architecture.md
  33. 3 1
      doc/crates.md
  34. 51 13
      doc/storage-schema.md
  35. 1 1
      doc/transfers.md

+ 2 - 2
CLAUDE.md

@@ -37,7 +37,7 @@ doc/
 
 - **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 (summed in Rust from live rows, never in SQL) inside the commit transaction. A domain rejection is a typed `CommitRejection` the ledger maps back to a `LedgerError`.
+- **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.
 - **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.
@@ -75,7 +75,7 @@ cargo test -p kuatia        # integration + commit/concurrency tests
 ## Conventions
 
 - Clarity over cleverness
-- **All arithmetic in Rust only** — the storage layer is a dumb record keeper. No SQL `SUM`, `MAX`, `MIN`, `AVG`, or any computation on monetary amounts or domain values in queries. `COUNT(*)` for pagination row totals is allowed (it counts rows, not domain values). Balances are always computed in Rust with checked arithmetic (`checked_add`, `checked_sub`, `checked_neg`) — no silent overflow
+- **Money arithmetic must be exact, wherever it runs** (ADR-0024). Amount columns are native: `NUMERIC(39,0)` on PostgreSQL, a 16-byte order-preserving `BLOB` on SQLite. Over *those* columns the database may add up and compare: `SUM()` on Postgres, the registered `kuatia_i128_sum` aggregate on SQLite, plus `MIN`/`MAX`/`ORDER BY`/range predicates. Both are exact and raise on overflow rather than wrapping. `COUNT(*)` for pagination row totals is still fine (it counts rows, not domain values). Everything else stays banned: no floating-point anywhere near an amount (no `AVG`, no `REAL`/`DOUBLE`), no implicit coercion into or out of an amount column (Postgres binds and reads through an explicit `CAST`, SQLite through the 16-byte codec), no arithmetic on an amount stored as text, no aggregate mixing assets or subaccounts, and no aggregate that wraps on overflow. Everything that is not an exact aggregate over a native amount column is still computed in Rust with `checked_add`/`checked_sub`/`checked_neg`
 - No `unwrap()`/`expect()` in production code — all errors bubble up via `Result`
 - Domain types for all identifiers — never raw integers or byte arrays in public APIs
 - Use "Posting" not "Coin" for accounting clarity

+ 1 - 0
Cargo.lock

@@ -1089,6 +1089,7 @@ dependencies = [
  "async-trait",
  "kuatia-storage",
  "kuatia-types",
+ "libsqlite3-sys",
  "paste",
  "serde",
  "serde_json",

+ 1 - 1
crates/kuatia-dashboard/src/seed.rs

@@ -47,7 +47,7 @@ pub fn account_label(id: AccountId) -> Option<&'static str> {
 /// ledger; one connection is also fine for a low-traffic dashboard on a file or
 /// Postgres backend.
 pub async fn connect(db_url: &str) -> Result<Arc<Ledger>, Box<dyn Error>> {
-    sqlx::any::install_default_drivers();
+    kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
         .connect(&sqlite_creatable(db_url))

+ 14 - 0
crates/kuatia-money/README.md

@@ -20,6 +20,20 @@ can never silently round or overflow.
 | `Backing` | The integer type behind every `Cent` (`i64`, or `i128` via feature) |
 | `CentBacking` | Trait an integer must satisfy to back a `Cent` |
 | `OverflowError` | Returned when a checked operation would overflow |
+| `encode_storage_i128` / `decode_storage_i128` | The 16-byte order-preserving storage encoding |
+
+## Encodings
+
+A `Cent` has two fixed-width byte forms, both 128 bits wide whatever the
+backing, and they are deliberately different:
+
+- `to_canonical_bytes` / `from_canonical_bytes` — two's-complement big-endian.
+  The content-addressed hash preimage, frozen by `CANONICAL_VERSION`, so the
+  same amount hashes identically under any backing.
+- `to_storage_bytes` / `from_storage_bytes` — the same bytes with the sign bit
+  flipped. What the SQLite backend stores: byte-wise comparison of two of these
+  matches the numeric ordering of the amounts, so an amount column can be
+  ordered and range-filtered. See ADR-0024.
 
 ## Features
 

+ 124 - 0
crates/kuatia-money/src/lib.rs

@@ -11,6 +11,12 @@
 //! All arithmetic is checked: addition, subtraction and negation return
 //! [`OverflowError`] rather than wrapping, so the ledger's conservation sum can
 //! never silently round or overflow.
+//!
+//! A `Cent` has two fixed 16-byte forms, both independent of the backing and
+//! deliberately different from each other:
+//! [`to_canonical_bytes`](Cent::to_canonical_bytes) is the content-addressed
+//! hash preimage, and [`to_storage_bytes`](Cent::to_storage_bytes) is what a
+//! database stores, ordered so a byte-wise comparison matches the numeric one.
 
 use serde::{Deserialize, Deserializer, Serialize, Serializer};
 use std::error::Error;
@@ -125,6 +131,34 @@ impl CentBacking for i128 {
 }
 
 // ---------------------------------------------------------------------------
+// Storage encoding
+// ---------------------------------------------------------------------------
+
+/// Encode a raw `i128` in the order-preserving 16-byte storage form:
+/// two's-complement big-endian with the sign bit flipped, so a byte-wise
+/// (`memcmp`) comparison of two encodings matches the numeric ordering of the
+/// values.
+///
+/// The width is fixed at 128 bits regardless of the active [`Backing`], so a
+/// stored amount does not change shape when the `i128` feature is toggled, and
+/// a backend that folds these encodings (the SQLite `kuatia_i128_sum`
+/// aggregate) can do so at full width. Distinct from the canonical hash
+/// encoding: see [`Cent::to_storage_bytes`].
+pub fn encode_storage_i128(value: i128) -> [u8; 16] {
+    let mut bytes = value.to_be_bytes();
+    bytes[0] ^= 0x80;
+    bytes
+}
+
+/// Decode a raw `i128` from the 16-byte storage form produced by
+/// [`encode_storage_i128`]. Total: every 16-byte sequence is a valid encoding.
+pub fn decode_storage_i128(bytes: &[u8; 16]) -> i128 {
+    let mut bytes = *bytes;
+    bytes[0] ^= 0x80;
+    i128::from_be_bytes(bytes)
+}
+
+// ---------------------------------------------------------------------------
 // Cent — stored monetary amount
 // ---------------------------------------------------------------------------
 
@@ -220,6 +254,31 @@ impl Cent {
             .map(Cent)
             .ok_or(OverflowError)
     }
+
+    /// The 16-byte order-preserving storage encoding: two's-complement
+    /// big-endian with the sign bit flipped, so a byte-wise (`memcmp`)
+    /// comparison of two encodings matches the numeric ordering of the amounts.
+    /// SQLite compares `BLOB`s that way, which is what lets a stored amount be
+    /// ordered and range-filtered.
+    ///
+    /// This is a storage format only, deliberately distinct from
+    /// [`to_canonical_bytes`](Self::to_canonical_bytes), which owns the hash
+    /// preimage and is frozen by the canonical version. The width is 16 bytes
+    /// whatever the active backing, so the column type does not depend on the
+    /// `i128` feature.
+    pub fn to_storage_bytes(self) -> [u8; 16] {
+        encode_storage_i128(self.0.to_i128())
+    }
+
+    /// Decode a [`Cent`] from its 16-byte storage encoding, returning
+    /// [`OverflowError`] if the value does not fit the active backing. A
+    /// database written under the `i128` backing therefore fails loudly when
+    /// read under the default `i64` one instead of truncating.
+    pub fn from_storage_bytes(bytes: &[u8; 16]) -> Result<Self, OverflowError> {
+        Backing::try_from_i128(decode_storage_i128(bytes))
+            .map(Cent)
+            .ok_or(OverflowError)
+    }
 }
 
 impl From<i64> for Cent {
@@ -484,4 +543,69 @@ mod tests {
         assert_eq!(amt.format(Cent::from(-5)), "-0.05");
         assert_eq!(Amount::new(0).format(Cent::from(700)), "700");
     }
+
+    #[test]
+    fn storage_bytes_round_trip() {
+        let extremes = [
+            Cent::from_str(&Backing::MIN.to_string()).unwrap(),
+            Cent::from_str(&Backing::MAX.to_string()).unwrap(),
+        ];
+        for c in [
+            Cent::from(0),
+            Cent::from(1),
+            Cent::from(-1),
+            Cent::from(1234),
+        ]
+        .into_iter()
+        .chain(extremes)
+        {
+            assert_eq!(Cent::from_storage_bytes(&c.to_storage_bytes()), Ok(c));
+        }
+    }
+
+    #[test]
+    fn storage_bytes_are_16_and_zero_is_midpoint() {
+        let zero = Cent::ZERO.to_storage_bytes();
+        assert_eq!(zero.len(), 16);
+        let mut expected = [0u8; 16];
+        expected[0] = 0x80;
+        assert_eq!(zero, expected);
+    }
+
+    #[test]
+    fn storage_bytes_preserve_order() {
+        let mut values = [
+            Cent::from_str(&Backing::MIN.to_string()).unwrap(),
+            Cent::from(-1000),
+            Cent::from(-1),
+            Cent::ZERO,
+            Cent::from(1),
+            Cent::from(1000),
+            Cent::from_str(&Backing::MAX.to_string()).unwrap(),
+        ];
+        values.sort();
+        let encoded: Vec<[u8; 16]> = values.iter().map(|c| c.to_storage_bytes()).collect();
+        let mut sorted = encoded.clone();
+        sorted.sort();
+        assert_eq!(encoded, sorted);
+    }
+
+    #[test]
+    fn storage_encoding_differs_from_canonical_encoding() {
+        for v in [0i32, 1, -1, 500] {
+            let c = Cent::from(v);
+            assert_ne!(c.to_storage_bytes(), c.to_canonical_bytes());
+        }
+    }
+
+    #[test]
+    fn from_storage_bytes_rejects_out_of_range() {
+        let big = i128::from(i64::MAX) + 1;
+        let decoded = Cent::from_storage_bytes(&encode_storage_i128(big));
+        if cfg!(feature = "i128") {
+            assert!(decoded.is_ok());
+        } else {
+            assert_eq!(decoded, Err(OverflowError));
+        }
+    }
 }

+ 5 - 1
crates/kuatia-storage-sql/Cargo.toml

@@ -20,6 +20,10 @@ sqlx = { workspace = true, features = ["macros"] }
 async-trait.workspace = true
 serde.workspace = true
 serde_json.workspace = true
+# Pinned to the exact version sqlx-sqlite depends on, with default features off
+# to match: it is a `links = "sqlite3"` crate, so the whole graph must resolve to
+# one instance. Only needed to register the money functions (see `sqlite_ext`).
+libsqlite3-sys = { version = "0.30.1", default-features = false, optional = true }
 
 [dev-dependencies]
 tokio = { workspace = true, features = ["full"] }
@@ -31,7 +35,7 @@ serde_json.workspace = true
 
 [features]
 default = ["sqlite"]
-sqlite = ["sqlx/sqlite"]
+sqlite = ["sqlx/sqlite", "dep:libsqlite3-sys"]
 postgres = ["sqlx/postgres"]
 # Opt-in gate for the Postgres conformance suite (`tests/postgres.rs`), which
 # needs a live `DATABASE_URL`. Kept distinct from `postgres` so that a plain

+ 22 - 12
crates/kuatia-storage-sql/README.md

@@ -17,21 +17,30 @@ kuatia-storage-sql = { features = ["sqlite"] }   # or "postgres"
 | `sqlite` (default) | SQLite via sqlx | Conformance tests pass |
 | `postgres` | PostgreSQL via sqlx | Portable DDL/queries; needs a running instance to test |
 
-A single portable schema in `src/migrations/001_init.sql` serves both backends.
-Applied migrations are tracked in a `_migrations` table, so `migrate()` is
-idempotent. Upserts use portable `ON CONFLICT … DO UPDATE`, and all ids are
-generated in Rust (no `AUTOINCREMENT`/`SERIAL`).
-
-Every column is a text type: no opaque binary is stored. Content-addressed ids
-(and the opaque saga blob) are kept as lower-case hex `TEXT`, and structured
-payloads as their JSON `TEXT` serialization, so any row is readable in a plain
-SQL client for auditing. The JSON is never queried into.
+The migrations in `src/migrations/` serve both backends. Applied migrations are
+tracked in a `_migrations` table, so `migrate()` is idempotent. Upserts use
+portable `ON CONFLICT … DO UPDATE`, and all ids are generated in Rust (no
+`AUTOINCREMENT`/`SERIAL`).
+
+Identifier and payload columns are text, so any row is readable in a plain SQL
+client for auditing: content-addressed ids as lower-case hex `TEXT`, structured
+payloads as their JSON `TEXT` serialization (never queried into). Amounts are
+the exception, stored natively so the database can sum and order them:
+`NUMERIC(39,0)` on PostgreSQL, a 16-byte order-preserving `BLOB` on SQLite. A
+SQLite amount reads back as a decimal string through `kuatia_i128_to_text(value)`
+in any process that called `install_drivers()`; a plain `sqlite3` CLI has no such
+function and sees the blob. See ADR-0024.
 
 ## Usage
 
+`install_drivers()` replaces `sqlx::any::install_default_drivers()` and must run
+**before** the pool connects: it registers the SQLite money functions as an
+auto-extension, so a connection opened earlier would not have them.
+
 ```rust
-use kuatia_storage_sql::SqlStore;
+use kuatia_storage_sql::{SqlStore, install_drivers};
 
+install_drivers()?;
 let pool = sqlx::any::AnyPoolOptions::new()
     .connect("sqlite::memory:").await?;
 let store = SqlStore::new(pool);
@@ -40,5 +49,6 @@ store.migrate().await?;
 
 ## Schema
 
-Tables: `accounts`, `postings`, `transfers`, `transfer_accounts`, `sagas`,
-`events`, `books`. Migrations run via `store.migrate()`.
+Tables: `accounts`, `account_head`, `postings`, `live_postings`, `transfers`,
+`transfer_accounts`, `events`, `books`, `balance_projection`. Migrations run via
+`store.migrate()`; the full catalog is in `doc/storage-schema.md`.

+ 48 - 44
crates/kuatia-storage-sql/src/commit.rs

@@ -9,7 +9,6 @@
 //! serializes writers and the delete-affected-count is the double-spend backstop.
 
 use std::collections::HashSet;
-use std::str::FromStr;
 
 use async_trait::async_trait;
 use sqlx::{Row, Transaction};
@@ -23,8 +22,10 @@ use kuatia_storage::store::{
 use kuatia_types::*;
 
 use crate::SqlStore;
-use crate::posting::{MAX_IDS_PER_QUERY, id_predicate};
-use crate::row::{deserialize_json, envelope_id_to_hex, row_to_account, serialize_json};
+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,
+};
 
 fn internal(e: impl std::fmt::Display) -> StoreError {
     StoreError::Internal(e.to_string())
@@ -56,29 +57,28 @@ impl SqlStore {
         }
     }
 
-    /// Sum the live-posting values for one `(owner, asset)` inside `tx`. All
-    /// arithmetic is done in Rust with checked addition; the query never sums.
+    /// Sum the live-posting values for one `(owner, asset)` inside `tx`.
+    ///
+    /// The database does the addition, in one row rather than one row per
+    /// posting, and it is exact either way: PostgreSQL sums arbitrary-precision
+    /// `NUMERIC`, SQLite folds with `i128::checked_add` and raises on overflow
+    /// (ADR-0024). Deliberately unlocked: an aggregate cannot carry `FOR UPDATE`
+    /// on PostgreSQL, and it does not need to, because the caller already holds
+    /// the account-head lock that serializes the floor check.
     async fn live_balance(
         &self,
         tx: &mut Transaction<'_, sqlx::Any>,
         owner: &AccountId,
         asset: &AssetId,
     ) -> Result<Cent, StoreError> {
-        let rows = sqlx::query(
-            "SELECT value FROM live_postings WHERE owner = $1 AND subaccount = $2 AND asset = $3",
-        )
-        .bind(owner.id)
-        .bind(owner.sub)
-        .bind(asset.0 as i32)
-        .fetch_all(&mut **tx)
-        .await
-        .map_err(internal)?;
-        let mut values = Vec::with_capacity(rows.len());
-        for row in &rows {
-            let v: String = row.try_get("value").map_err(internal)?;
-            values.push(Cent::from_str(&v).map_err(internal)?);
-        }
-        Cent::checked_sum(values).map_err(internal)
+        let row = sqlx::query(&live_balance_sql(self.dialect))
+            .bind(owner.id)
+            .bind(owner.sub)
+            .bind(asset.0 as i32)
+            .fetch_one(&mut **tx)
+            .await
+            .map_err(internal)?;
+        row_to_cent(self.dialect, &row, "total")
     }
 }
 
@@ -224,30 +224,34 @@ impl CommitStore for SqlStore {
         // Insert and activate the created postings.
         for p in req.create {
             let hex = envelope_id_to_hex(&p.id.transfer);
-            sqlx::query(
-                "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (transfer_id, idx) DO NOTHING",
-            )
-            .bind(&hex)
-            .bind(p.id.index as i16)
-            .bind(p.owner.id)
-            .bind(p.owner.sub)
-            .bind(p.asset.0 as i32)
-            .bind(p.value.to_string())
-            .execute(&mut *tx)
-            .await
-            .map_err(internal)?;
-            sqlx::query(
-                "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ($1, $2, $3, $4, $5, $6, NULL) ON CONFLICT (transfer_id, idx) DO NOTHING",
-            )
-            .bind(&hex)
-            .bind(p.id.index as i16)
-            .bind(p.owner.id)
-            .bind(p.owner.sub)
-            .bind(p.asset.0 as i32)
-            .bind(p.value.to_string())
-            .execute(&mut *tx)
-            .await
-            .map_err(internal)?;
+            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(p.id.index as i16)
+                .bind(p.owner.id)
+                .bind(p.owner.sub)
+                .bind(p.asset.0 as i32);
+            bind_money(q, self.dialect, p.value)
+                .execute(&mut *tx)
+                .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",
+                self.dialect.money_bind(6)
+            );
+            let q = sqlx::query(&sql)
+                .bind(hex.clone())
+                .bind(p.id.index as i16)
+                .bind(p.owner.id)
+                .bind(p.owner.sub)
+                .bind(p.asset.0 as i32);
+            bind_money(q, self.dialect, p.value)
+                .execute(&mut *tx)
+                .await
+                .map_err(internal)?;
             touched.insert((p.owner, p.asset));
         }
 

+ 52 - 0
crates/kuatia-storage-sql/src/dialect.rs

@@ -27,6 +27,58 @@ impl Dialect {
         }
     }
 
+    /// The placeholder for binding an amount, as it must appear in the SQL.
+    ///
+    /// PostgreSQL stores amounts as `NUMERIC(39,0)` and the value arrives as
+    /// text (the `Any` driver has no numeric kind), so the cast is required
+    /// rather than cosmetic: `text` to `numeric` is explicit-only in `pg_cast`,
+    /// and a bare placeholder is rejected. SQLite binds the 16-byte encoding
+    /// straight into a `BLOB`.
+    pub(crate) fn money_bind(self, n: u32) -> String {
+        match self {
+            Self::Postgres => format!("CAST(${n} AS NUMERIC)"),
+            Self::Sqlite => format!("${n}"),
+        }
+    }
+
+    /// How an amount column must be named in a `SELECT` list.
+    ///
+    /// The cast is mandatory on PostgreSQL, and not only so the value can be
+    /// parsed: `AnyRow` converts every column's type before any of them is
+    /// read, and it has no mapping for `NUMERIC`, so one uncast amount fails
+    /// the whole row even when nothing reads it.
+    pub(crate) fn money_read(self, col: &str) -> String {
+        match self {
+            Self::Postgres => format!("CAST({col} AS TEXT) AS {col}"),
+            Self::Sqlite => col.to_string(),
+        }
+    }
+
+    /// An exact sum over an amount column, as a `SELECT` list entry.
+    ///
+    /// Both sides are exact and neither wraps: `NUMERIC` is arbitrary
+    /// precision, and `kuatia_i128_sum` accumulates with `i128::checked_add`
+    /// and raises rather than overflowing. `COALESCE` and the aggregate's
+    /// zero-for-no-rows make an empty group a real row, so callers never have
+    /// to special-case `NULL`.
+    pub(crate) fn money_sum(self, col: &str) -> String {
+        match self {
+            Self::Postgres => format!("CAST(COALESCE(SUM({col}), 0) AS TEXT)"),
+            Self::Sqlite => format!("kuatia_i128_sum({col})"),
+        }
+    }
+
+    /// The `SELECT` list [`row_to_posting`](crate::row::row_to_posting) reads.
+    /// Spelled out rather than `*` because the amount column needs
+    /// [`money_read`](Self::money_read); the six columns are shared by
+    /// `postings` and `live_postings`.
+    pub(crate) fn posting_columns(self) -> String {
+        format!(
+            "transfer_id, idx, owner, subaccount, asset, {}",
+            self.money_read("value")
+        )
+    }
+
     /// Row-locking clause appended to a `SELECT` that takes a pessimistic lock:
     /// ` FOR UPDATE` on Postgres, empty on SQLite (which has no such clause and
     /// serializes writers itself).

+ 32 - 2
crates/kuatia-storage-sql/src/lib.rs

@@ -4,20 +4,25 @@
 //! `sqlite` or `postgres` to select the backend.
 //!
 //! ```text
+//! kuatia_storage_sql::install_drivers()?;
 //! let pool = sqlx::any::AnyPoolOptions::new()
 //!     .connect("sqlite::memory:").await?;
 //! let store = SqlStore::new(pool);
 //! store.migrate().await?;
 //! ```
 //!
+//! [`install_drivers`] replaces `sqlx::any::install_default_drivers` and has to
+//! run before the pool connects; see its docs for why.
+//!
 //! The [`Store`](kuatia_storage::store::Store) sub-traits are each implemented in
 //! their own module (`account`, `posting`, `transfer`, `commit`, `event`,
 //! `book`, `projection`); shared row mappers and codecs live in `row`, the schema
-//! migrations in `migrate`, and the one SQLite/PostgreSQL divergence behind the
-//! `Dialect` seam in `dialect`.
+//! migrations in `migrate`, the SQLite/PostgreSQL divergence behind the
+//! `Dialect` seam in `dialect`, and the SQLite money functions in `sqlite_ext`.
 
 use sqlx::{Any, Pool};
 
+use kuatia_storage::error::StoreError;
 use kuatia_types::autoid::AutoId;
 
 use crate::dialect::Dialect;
@@ -31,8 +36,33 @@ mod migrate;
 mod posting;
 mod projection;
 mod row;
+#[cfg(feature = "sqlite")]
+mod sqlite_ext;
 mod transfer;
 
+/// Install the `sqlx::Any` drivers and, when the `sqlite` feature is on, the
+/// SQLite money functions.
+///
+/// Call this instead of [`sqlx::any::install_default_drivers`], and call it
+/// **before** connecting any pool: the SQLite functions are registered as an
+/// auto-extension, so a connection opened earlier will not have them and every
+/// statement naming one fails to prepare.
+pub fn install_drivers() -> Result<(), StoreError> {
+    sqlx::any::install_default_drivers();
+    install_sqlite_extensions()
+}
+
+/// Install just the SQLite money functions, for callers that install the
+/// `sqlx::Any` drivers themselves. Idempotent; a no-op without the `sqlite`
+/// feature. See [`install_drivers`] for the ordering requirement.
+pub fn install_sqlite_extensions() -> Result<(), StoreError> {
+    #[cfg(feature = "sqlite")]
+    {
+        sqlite_ext::install()?;
+    }
+    Ok(())
+}
+
 /// SQL-backed [`Store`](kuatia_storage::store::Store) implementation.
 pub struct SqlStore {
     pool: Pool<Any>,

+ 72 - 19
crates/kuatia-storage-sql/src/migrate.rs

@@ -1,64 +1,117 @@
 //! Schema migrations. Idempotent: a `_migrations` ledger records what has been
-//! applied, so re-running is a no-op. The DDL is identical for both backends.
+//! applied, so re-running is a no-op.
 
 use kuatia_storage::error::StoreError;
 
 use crate::SqlStore;
+use crate::dialect::Dialect;
+
+/// One migration's body. Most are the same DDL on both backends; the ones that
+/// touch a money column cannot be, because the native types differ (ADR-0024).
+enum Migration {
+    /// The same statements on every backend.
+    Shared(&'static str),
+    /// One body per backend.
+    PerDialect {
+        /// Applied against PostgreSQL.
+        postgres: &'static str,
+        /// Applied against SQLite.
+        sqlite: &'static str,
+    },
+}
+
+impl Migration {
+    fn body(&self, dialect: Dialect) -> &'static str {
+        match self {
+            Self::Shared(sql) => sql,
+            Self::PerDialect { postgres, sqlite } => match dialect {
+                Dialect::Postgres => postgres,
+                Dialect::Sqlite => sqlite,
+            },
+        }
+    }
+}
 
 impl SqlStore {
     /// Run database migrations. Idempotent: a `_migrations` ledger records what
-    /// has been applied, so re-running is a no-op. Every column is a text type,
-    /// so the store holds no opaque binary and the DDL is identical for both
-    /// backends. Content-addressed ids and opaque saga bytes are stored as hex
-    /// `TEXT`, and JSON payloads as their `TEXT` serialization, keeping every
-    /// row legible for auditing.
+    /// has been applied, so re-running is a no-op. Identifier and payload
+    /// columns are text, keeping a row legible for auditing: content-addressed
+    /// ids as hex `TEXT`, JSON payloads as their `TEXT` serialization. Amounts
+    /// are stored natively instead, so their DDL differs by backend (ADR-0024).
+    ///
+    /// On SQLite this first checks that the money functions are installed,
+    /// since [`install_drivers`](crate::install_drivers) has to run before the
+    /// pool connects and a pool built without it would otherwise fail with a
+    /// bare "no such function" partway through a migration.
     pub async fn migrate(&self) -> Result<(), StoreError> {
+        if self.dialect == Dialect::Sqlite {
+            sqlx::query("SELECT kuatia_i128_to_text(kuatia_i128_from_text('1'))")
+                .fetch_one(&self.pool)
+                .await
+                .map_err(|e| {
+                    StoreError::Misconfigured(format!(
+                        "the SQLite money functions are missing on this connection ({e}); call \
+                         kuatia_storage_sql::install_drivers() before connecting the pool"
+                    ))
+                })?;
+        }
+
         sqlx::query("CREATE TABLE IF NOT EXISTS _migrations (name TEXT PRIMARY KEY)")
             .execute(&self.pool)
             .await
             .map_err(|e| StoreError::Internal(e.to_string()))?;
 
-        let migrations: &[(&str, &str)] = &[
-            ("001_init", include_str!("migrations/001_init.sql")),
+        let migrations: &[(&str, Migration)] = &[
+            (
+                "001_init",
+                Migration::Shared(include_str!("migrations/001_init.sql")),
+            ),
             (
                 "002_subaccounts",
-                include_str!("migrations/002_subaccounts.sql"),
+                Migration::Shared(include_str!("migrations/002_subaccounts.sql")),
             ),
             (
                 "003_drop_user_data",
-                include_str!("migrations/003_drop_user_data.sql"),
+                Migration::Shared(include_str!("migrations/003_drop_user_data.sql")),
             ),
             (
                 "004_index_tables",
-                include_str!("migrations/004_index_tables.sql"),
+                Migration::Shared(include_str!("migrations/004_index_tables.sql")),
             ),
             (
                 "005_account_head",
-                include_str!("migrations/005_account_head.sql"),
+                Migration::Shared(include_str!("migrations/005_account_head.sql")),
             ),
             (
                 "006_drop_policy",
-                include_str!("migrations/006_drop_policy.sql"),
+                Migration::Shared(include_str!("migrations/006_drop_policy.sql")),
             ),
             (
                 "007_balance_projection",
-                include_str!("migrations/007_balance_projection.sql"),
+                Migration::Shared(include_str!("migrations/007_balance_projection.sql")),
             ),
             (
                 "008_live_postings",
-                include_str!("migrations/008_live_postings.sql"),
+                Migration::Shared(include_str!("migrations/008_live_postings.sql")),
             ),
             (
                 "009_saga_kind",
-                include_str!("migrations/009_saga_kind.sql"),
+                Migration::Shared(include_str!("migrations/009_saga_kind.sql")),
             ),
             (
                 "010_drop_sagas",
-                include_str!("migrations/010_drop_sagas.sql"),
+                Migration::Shared(include_str!("migrations/010_drop_sagas.sql")),
+            ),
+            (
+                "011_native_amounts",
+                Migration::PerDialect {
+                    postgres: include_str!("migrations/011_native_amounts.postgres.sql"),
+                    sqlite: include_str!("migrations/011_native_amounts.sqlite.sql"),
+                },
             ),
         ];
 
-        for (name, sql) in migrations {
+        for (name, migration) in migrations {
             let applied = sqlx::query("SELECT 1 FROM _migrations WHERE name = $1")
                 .bind(*name)
                 .fetch_optional(&self.pool)
@@ -80,7 +133,7 @@ impl SqlStore {
                 .await
                 .map_err(|e| StoreError::Internal(e.to_string()))?;
 
-            for statement in sql.split(';') {
+            for statement in migration.body(self.dialect).split(';') {
                 let trimmed = statement.trim();
                 if !trimmed.is_empty() {
                     sqlx::query(trimmed)

+ 10 - 0
crates/kuatia-storage-sql/src/migrations/011_native_amounts.postgres.sql

@@ -0,0 +1,10 @@
+-- Money columns become native NUMERIC(39,0) so the database can sum, order and
+-- range-filter an amount exactly (ADR-0024, superseding ADR-0011's text
+-- storage). 39 digits is the width of i128, so the column holds the full range
+-- whatever the `i128` cargo feature selects. ALTER ... TYPE rewrites the table
+-- and keeps the existing indexes.
+ALTER TABLE postings ALTER COLUMN value TYPE NUMERIC(39,0) USING value::numeric;
+
+ALTER TABLE live_postings ALTER COLUMN value TYPE NUMERIC(39,0) USING value::numeric;
+
+ALTER TABLE balance_projection ALTER COLUMN balance TYPE NUMERIC(39,0) USING balance::numeric;

+ 64 - 0
crates/kuatia-storage-sql/src/migrations/011_native_amounts.sqlite.sql

@@ -0,0 +1,64 @@
+-- Money columns become a 16-byte BLOB holding the order-preserving encoding, so
+-- the database can sum them with kuatia_i128_sum and order them with a plain
+-- byte comparison (ADR-0024, superseding ADR-0011's text storage). The width is
+-- fixed at i128 whatever the `i128` cargo feature selects.
+--
+-- SQLite cannot change a column's type in place, so each table is rebuilt, in
+-- the same shape migrations 004 and 008 already use. The conversion is
+-- kuatia_i128_from_text, registered by kuatia_storage_sql install_drivers.
+-- SQLite resolves function names when it prepares a statement, so a missing
+-- installation fails here rather than later.
+CREATE TABLE postings_new (
+    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)
+);
+
+INSERT INTO postings_new (transfer_id, idx, owner, subaccount, asset, value) SELECT transfer_id, idx, owner, subaccount, asset, kuatia_i128_from_text(value) FROM postings;
+
+DROP TABLE postings;
+
+ALTER TABLE postings_new RENAME TO postings;
+
+CREATE INDEX IF NOT EXISTS idx_postings_owner ON postings(owner, subaccount, asset);
+
+CREATE TABLE live_postings_new (
+    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)
+);
+
+INSERT INTO live_postings_new (transfer_id, idx, owner, subaccount, asset, value, reservation) SELECT transfer_id, idx, owner, subaccount, asset, kuatia_i128_from_text(value), reservation FROM live_postings;
+
+DROP TABLE live_postings;
+
+ALTER TABLE live_postings_new RENAME TO live_postings;
+
+CREATE INDEX IF NOT EXISTS idx_live_owner ON live_postings(owner, subaccount, asset);
+
+CREATE TABLE balance_projection_new (
+    id         BIGINT  NOT NULL,
+    account    BIGINT  NOT NULL,
+    subaccount BIGINT  NOT NULL DEFAULT 0,
+    asset      INTEGER NOT NULL,
+    balance    BLOB    NOT NULL,
+    watermark  BIGINT  NOT NULL,
+    PRIMARY KEY (id)
+);
+
+INSERT INTO balance_projection_new (id, account, subaccount, asset, balance, watermark) SELECT id, account, subaccount, asset, kuatia_i128_from_text(balance), watermark FROM balance_projection;
+
+DROP TABLE balance_projection;
+
+ALTER TABLE balance_projection_new RENAME TO balance_projection;
+
+CREATE INDEX IF NOT EXISTS idx_balance_projection_closest ON balance_projection (account, subaccount, asset, watermark, id);

+ 67 - 24
crates/kuatia-storage-sql/src/posting.rs

@@ -17,7 +17,20 @@ use kuatia_storage::store::*;
 use kuatia_types::*;
 
 use crate::SqlStore;
-use crate::row::{envelope_id_to_hex, row_to_posting};
+use crate::dialect::Dialect;
+use crate::row::{bind_money, envelope_id_to_hex, row_to_cent, row_to_posting};
+
+/// The live-balance aggregate, shared by [`PostingStore::live_balance`] and the
+/// in-transaction overdraft floor in `commit`, so both read the balance the same
+/// way. The sum happens in the database and is exact on both backends
+/// (ADR-0024).
+pub(crate) fn live_balance_sql(dialect: Dialect) -> String {
+    format!(
+        "SELECT {} AS total FROM live_postings \
+         WHERE owner = $1 AND subaccount = $2 AND asset = $3",
+        dialect.money_sum("value")
+    )
+}
 
 /// The `(source_table, state_predicate)` a posting read of the given filter
 /// targets. Live/Active/Reserved read the single `live_postings` hot table,
@@ -73,7 +86,8 @@ impl PostingStore for SqlStore {
         let mut found: HashMap<(String, i16), Posting> = HashMap::with_capacity(ids.len());
         for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
             let sql = format!(
-                "SELECT * FROM postings WHERE {}",
+                "SELECT {} FROM postings WHERE {}",
+                self.dialect.posting_columns(),
                 id_predicate(chunk.len(), 1)
             );
             let mut q = sqlx::query(&sql);
@@ -89,7 +103,7 @@ impl PostingStore for SqlStore {
 
             // Index the fetched postings by the same `(hex, idx)` key that was bound.
             for row in &rows {
-                let posting = row_to_posting(row)?;
+                let posting = row_to_posting(self.dialect, row)?;
                 let key = (
                     envelope_id_to_hex(&posting.id.transfer),
                     posting.id.index as i16,
@@ -123,7 +137,10 @@ impl PostingStore for SqlStore {
         // 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);
-        let mut sql = format!("SELECT * FROM {source} WHERE owner = $1");
+        let mut sql = format!(
+            "SELECT {} FROM {source} WHERE owner = $1",
+            self.dialect.posting_columns()
+        );
         let mut placeholder = 2u32;
         if sub.is_some() {
             sql.push_str(&format!(" AND subaccount = ${placeholder}"));
@@ -150,7 +167,20 @@ impl PostingStore for SqlStore {
             .fetch_all(&self.pool)
             .await
             .map_err(|e| StoreError::Internal(e.to_string()))?;
-        rows.iter().map(row_to_posting).collect()
+        rows.iter()
+            .map(|row| row_to_posting(self.dialect, row))
+            .collect()
+    }
+
+    async fn live_balance(&self, account: &AccountId, asset: &AssetId) -> Result<Cent, StoreError> {
+        let row = sqlx::query(&live_balance_sql(self.dialect))
+            .bind(account.id)
+            .bind(account.sub)
+            .bind(asset.0 as i32)
+            .fetch_one(&self.pool)
+            .await
+            .map_err(|e| StoreError::Internal(e.to_string()))?;
+        row_to_cent(self.dialect, &row, "total")
     }
 
     async fn get_posting_states(&self, ids: &[PostingId]) -> Result<Vec<PostingState>, StoreError> {
@@ -259,7 +289,13 @@ impl PostingStore for SqlStore {
             w.push_str(&format!(
                 " ORDER BY transfer_id, idx LIMIT {limit} OFFSET {offset}"
             ));
-            (format!("SELECT * FROM {source} {w}"), c)
+            (
+                format!(
+                    "SELECT {} FROM {source} {w}",
+                    self.dialect.posting_columns()
+                ),
+                c,
+            )
         };
 
         // Build count query
@@ -291,7 +327,10 @@ impl PostingStore for SqlStore {
             .await
             .map_err(|e| StoreError::Internal(e.to_string()))?;
 
-        let items: Vec<Posting> = rows.iter().map(row_to_posting).collect::<Result<_, _>>()?;
+        let items: Vec<Posting> = rows
+            .iter()
+            .map(|row| row_to_posting(self.dialect, row))
+            .collect::<Result<_, _>>()?;
         Ok(Page {
             items,
             total: total as u64,
@@ -463,32 +502,36 @@ impl PostingStore for SqlStore {
         let mut inserted: u64 = 0;
         for posting in postings {
             let hex = envelope_id_to_hex(&posting.id.transfer);
-            let res = sqlx::query(
-                "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (transfer_id, idx) DO NOTHING"
-            )
+            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)
-                .bind(posting.value.to_string())
+                .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.
-                sqlx::query(
-                    "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ($1, $2, $3, $4, $5, $6, NULL) ON CONFLICT (transfer_id, idx) DO NOTHING",
-                )
-                .bind(hex)
-                .bind(posting.id.index as i16)
-                .bind(posting.owner.id)
-                .bind(posting.owner.sub)
-                .bind(posting.asset.0 as i32)
-                .bind(posting.value.to_string())
-                .execute(&mut *tx)
-                .await
-                .map_err(|e| StoreError::Internal(e.to_string()))?;
+                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;
             }
         }

+ 21 - 21
crates/kuatia-storage-sql/src/projection.rs

@@ -1,7 +1,5 @@
 //! [`BalanceProjectionStore`]: append-only balance cache points (ADR-0019).
 
-use std::str::FromStr;
-
 use async_trait::async_trait;
 use sqlx::Row;
 
@@ -10,6 +8,7 @@ use kuatia_storage::store::*;
 use kuatia_types::*;
 
 use crate::SqlStore;
+use crate::row::{bind_money, row_to_cent};
 
 #[async_trait]
 impl BalanceProjectionStore for SqlStore {
@@ -22,19 +21,21 @@ impl BalanceProjectionStore for SqlStore {
     ) -> Result<(), StoreError> {
         // Append-only: mint a fresh monotonic id and insert a new cache point.
         let id = self.autoid.next();
-        sqlx::query(
+        let sql = format!(
             "INSERT INTO balance_projection (id, account, subaccount, asset, balance, watermark) \
-             VALUES ($1, $2, $3, $4, $5, $6)",
-        )
-        .bind(id)
-        .bind(account.id)
-        .bind(account.sub)
-        .bind(asset.0 as i32)
-        .bind(balance.to_string())
-        .bind(watermark)
-        .execute(&self.pool)
-        .await
-        .map_err(|e| StoreError::Internal(e.to_string()))?;
+             VALUES ($1, $2, $3, $4, {}, $6)",
+            self.dialect.money_bind(5)
+        );
+        let q = sqlx::query(&sql)
+            .bind(id)
+            .bind(account.id)
+            .bind(account.sub)
+            .bind(asset.0 as i32);
+        bind_money(q, self.dialect, balance)
+            .bind(watermark)
+            .execute(&self.pool)
+            .await
+            .map_err(|e| StoreError::Internal(e.to_string()))?;
         Ok(())
     }
 
@@ -46,11 +47,12 @@ impl BalanceProjectionStore for SqlStore {
     ) -> Result<Option<BalanceProjection>, StoreError> {
         // Closest at or before `as_of`: the largest watermark not exceeding it,
         // tie-broken by highest id. Row selection, not an aggregate over values.
-        let row = sqlx::query(
-            "SELECT id, balance, watermark FROM balance_projection \
+        let row = sqlx::query(&format!(
+            "SELECT id, {}, watermark FROM balance_projection \
              WHERE account = $1 AND subaccount = $2 AND asset = $3 AND watermark <= $4 \
              ORDER BY watermark DESC, id DESC LIMIT 1",
-        )
+            self.dialect.money_read("balance")
+        ))
         .bind(account.id)
         .bind(account.sub)
         .bind(asset.0 as i32)
@@ -64,9 +66,7 @@ impl BalanceProjectionStore for SqlStore {
         let id: i64 = row
             .try_get("id")
             .map_err(|e| StoreError::Internal(e.to_string()))?;
-        let balance: String = row
-            .try_get("balance")
-            .map_err(|e| StoreError::Internal(e.to_string()))?;
+        let balance = row_to_cent(self.dialect, &row, "balance")?;
         let watermark: i64 = row
             .try_get("watermark")
             .map_err(|e| StoreError::Internal(e.to_string()))?;
@@ -74,7 +74,7 @@ impl BalanceProjectionStore for SqlStore {
             id,
             account: *account,
             asset: *asset,
-            balance: Cent::from_str(&balance).map_err(|e| StoreError::Internal(e.to_string()))?,
+            balance,
             watermark,
         }))
     }

+ 57 - 10
crates/kuatia-storage-sql/src/row.rs

@@ -1,18 +1,68 @@
 //! Shared row mappers and codecs: how the store turns domain values into the
-//! text columns it stores, and rows back into domain types.
+//! columns it stores, and rows back into domain types.
 //!
-//! Every column is a text type, so the database holds no opaque binary and a row
-//! is legible in any SQL client. Content-addressed ids and opaque saga bytes are
-//! stored as hex `TEXT`, JSON payloads as their `TEXT` serialization.
+//! Identifier and payload columns are text, so a row stays legible in any SQL
+//! client: content-addressed ids as hex `TEXT`, JSON payloads as their `TEXT`
+//! serialization. Amounts are the exception. They are stored natively so the
+//! database can sum and order them (ADR-0024), which means their wire form
+//! depends on the backend, and every amount crosses this module through
+//! [`bind_money`] and [`row_to_cent`] rather than through `Display`/`FromStr`.
 
 use std::str::FromStr;
 
 use sqlx::Row;
-use sqlx::any::AnyRow;
+use sqlx::any::{AnyArguments, AnyRow};
+use sqlx::query::Query;
 
 use kuatia_storage::error::StoreError;
 use kuatia_types::*;
 
+use crate::dialect::Dialect;
+
+/// Bind one amount, in whichever form the backend's column takes: the decimal
+/// string for a PostgreSQL `NUMERIC` (the SQL must wrap the placeholder in
+/// [`Dialect::money_bind`]), the 16-byte order-preserving encoding for a SQLite
+/// `BLOB`. `.bind` is typed, so the two arms cannot be collapsed.
+pub(crate) fn bind_money<'q>(
+    q: Query<'q, sqlx::Any, AnyArguments<'q>>,
+    dialect: Dialect,
+    value: Cent,
+) -> Query<'q, sqlx::Any, AnyArguments<'q>> {
+    match dialect {
+        Dialect::Postgres => q.bind(value.to_string()),
+        Dialect::Sqlite => q.bind(value.to_storage_bytes().to_vec()),
+    }
+}
+
+/// Read one amount back. The column must have been selected through
+/// [`Dialect::money_read`] or [`Dialect::money_sum`].
+pub(crate) fn row_to_cent(
+    dialect: Dialect,
+    row: &AnyRow,
+    column: &str,
+) -> Result<Cent, StoreError> {
+    match dialect {
+        Dialect::Postgres => {
+            let text: String = row
+                .try_get(column)
+                .map_err(|e| StoreError::Internal(e.to_string()))?;
+            Cent::from_str(&text).map_err(|e| StoreError::Internal(e.to_string()))
+        }
+        Dialect::Sqlite => {
+            let bytes: Vec<u8> = row
+                .try_get(column)
+                .map_err(|e| StoreError::Internal(e.to_string()))?;
+            let bytes: [u8; 16] = bytes.as_slice().try_into().map_err(|_| {
+                StoreError::Internal(format!(
+                    "expected a 16-byte amount in {column}, got {} bytes",
+                    bytes.len()
+                ))
+            })?;
+            Cent::from_storage_bytes(&bytes).map_err(|e| StoreError::Internal(e.to_string()))
+        }
+    }
+}
+
 /// Serialize a value to a JSON string. Payload columns store JSON as `TEXT` so
 /// the database is directly readable for auditing; the ledger never queries into
 /// the JSON, so no binary or indexed representation is needed.
@@ -91,7 +141,7 @@ pub(crate) fn row_to_account(row: &AnyRow) -> Result<Account, StoreError> {
     })
 }
 
-pub(crate) fn row_to_posting(row: &AnyRow) -> Result<Posting, StoreError> {
+pub(crate) fn row_to_posting(dialect: Dialect, row: &AnyRow) -> Result<Posting, StoreError> {
     let transfer_id: String = row
         .try_get("transfer_id")
         .map_err(|e| StoreError::Internal(e.to_string()))?;
@@ -107,10 +157,7 @@ pub(crate) fn row_to_posting(row: &AnyRow) -> Result<Posting, StoreError> {
     let asset: i32 = row
         .try_get("asset")
         .map_err(|e| StoreError::Internal(e.to_string()))?;
-    let value: String = row
-        .try_get("value")
-        .map_err(|e| StoreError::Internal(e.to_string()))?;
-    let value = Cent::from_str(&value).map_err(|e| StoreError::Internal(e.to_string()))?;
+    let value = row_to_cent(dialect, row, "value")?;
 
     Ok(Posting {
         id: PostingId {

+ 319 - 0
crates/kuatia-storage-sql/src/sqlite_ext.rs

@@ -0,0 +1,319 @@
+//! The SQLite money functions, registered as an auto-extension.
+//!
+//! SQLite has no 128-bit integer, so a money column stores the 16-byte
+//! order-preserving encoding from `kuatia-money` and this module teaches the
+//! engine to fold and print it. `kuatia_i128_sum` is what lets the overdraft
+//! floor be one aggregate row instead of one row per posting, and it is exact:
+//! it accumulates with `i128::checked_add` and raises rather than wrapping.
+//!
+//! Registration goes through `sqlite3_auto_extension` because `sqlx::Any` never
+//! exposes the underlying `sqlite3*` handle, so there is nowhere to hook a
+//! per-connection callback. That makes it process-global and one-way: every
+//! SQLite connection opened afterwards, by anyone in the process, sees these
+//! functions, which is why the names are prefixed. It also has to happen before
+//! the first connection is opened; [`SqlStore::migrate`](crate::SqlStore::migrate)
+//! probes for the functions and reports a typed error if it did not.
+
+use std::ffi::{CStr, c_char, c_int, c_void};
+use std::sync::Once;
+use std::sync::atomic::{AtomicI32, Ordering};
+
+use libsqlite3_sys as ffi;
+
+use kuatia_storage::error::StoreError;
+use kuatia_types::{decode_storage_i128, encode_storage_i128};
+
+/// Width of a stored amount, in bytes.
+const WIDTH: usize = 16;
+
+static INSTALL: Once = Once::new();
+static INSTALL_RC: AtomicI32 = AtomicI32::new(ffi::SQLITE_OK);
+
+/// Register the money functions with every SQLite connection this process opens
+/// from now on. Idempotent, and cheap to call again.
+///
+/// Must run before the first connection is opened: a connection established
+/// earlier does not get the functions, and any statement naming one fails to
+/// prepare.
+pub fn install() -> Result<(), StoreError> {
+    INSTALL.call_once(|| {
+        let rc = unsafe { ffi::sqlite3_auto_extension(Some(entry_point)) };
+        INSTALL_RC.store(rc, Ordering::SeqCst);
+    });
+    match INSTALL_RC.load(Ordering::SeqCst) {
+        ffi::SQLITE_OK => Ok(()),
+        rc => Err(StoreError::Misconfigured(format!(
+            "sqlite3_auto_extension failed with code {rc}"
+        ))),
+    }
+}
+
+/// The auto-extension entry point SQLite calls for each new connection.
+///
+/// # Safety
+///
+/// Called by SQLite with a live connection handle. Every argument is used only
+/// for the duration of the call.
+unsafe extern "C" fn entry_point(
+    db: *mut ffi::sqlite3,
+    _err_msg: *mut *mut c_char,
+    _api: *const ffi::sqlite3_api_routines,
+) -> c_int {
+    let deterministic = ffi::SQLITE_UTF8 | ffi::SQLITE_DETERMINISTIC;
+
+    let rc = unsafe {
+        ffi::sqlite3_create_function_v2(
+            db,
+            c"kuatia_i128_sum".as_ptr(),
+            1,
+            ffi::SQLITE_UTF8,
+            std::ptr::null_mut(),
+            None,
+            Some(sum_step),
+            Some(sum_final),
+            None,
+        )
+    };
+    if rc != ffi::SQLITE_OK {
+        return rc;
+    }
+
+    let rc = unsafe {
+        ffi::sqlite3_create_function_v2(
+            db,
+            c"kuatia_i128_from_text".as_ptr(),
+            1,
+            deterministic,
+            std::ptr::null_mut(),
+            Some(from_text),
+            None,
+            None,
+            None,
+        )
+    };
+    if rc != ffi::SQLITE_OK {
+        return rc;
+    }
+
+    unsafe {
+        ffi::sqlite3_create_function_v2(
+            db,
+            c"kuatia_i128_to_text".as_ptr(),
+            1,
+            deterministic,
+            std::ptr::null_mut(),
+            Some(to_text),
+            None,
+            None,
+            None,
+        )
+    }
+}
+
+/// The `kuatia_i128_sum` accumulator.
+///
+/// The sum is held as raw bytes rather than an `i128` field on purpose:
+/// `sqlite3_aggregate_context` returns memory aligned for 8 bytes, not the 16 an
+/// `i128` wants, so a struct carrying one could not be read through the returned
+/// pointer on every target. They are *native* bytes, not the storage encoding,
+/// because SQLite hands back the allocation zeroed and zeroed native bytes are
+/// the zero this fold has to start from. The same 16 zero bytes read as a
+/// storage encoding would be `i128::MIN`.
+#[repr(C)]
+#[derive(Clone, Copy)]
+struct Accumulator {
+    sum: [u8; WIDTH],
+    failed: c_int,
+}
+
+/// Report `message` as the failure of the running SQL statement.
+///
+/// # Safety
+///
+/// `ctx` must be the context SQLite passed to the enclosing callback.
+unsafe fn fail(ctx: *mut ffi::sqlite3_context, message: &CStr) {
+    unsafe { ffi::sqlite3_result_error(ctx, message.as_ptr(), -1) }
+}
+
+/// Read the 16-byte amount out of one argument, or `None` if it is not a blob
+/// of exactly that width.
+///
+/// # Safety
+///
+/// `value` must be an argument SQLite passed to the enclosing callback.
+unsafe fn amount_arg(value: *mut ffi::sqlite3_value) -> Option<i128> {
+    if unsafe { ffi::sqlite3_value_type(value) } != ffi::SQLITE_BLOB {
+        return None;
+    }
+    if unsafe { ffi::sqlite3_value_bytes(value) } != WIDTH as c_int {
+        return None;
+    }
+    let ptr = unsafe { ffi::sqlite3_value_blob(value) };
+    if ptr.is_null() {
+        return None;
+    }
+    let mut bytes = [0u8; WIDTH];
+    unsafe { std::ptr::copy_nonoverlapping(ptr.cast::<u8>(), bytes.as_mut_ptr(), WIDTH) };
+    Some(decode_storage_i128(&bytes))
+}
+
+/// Return a 16-byte amount as the result of the current call. `SQLITE_TRANSIENT`
+/// makes SQLite copy the buffer before this frame goes away.
+///
+/// # Safety
+///
+/// `ctx` must be the context SQLite passed to the enclosing callback.
+unsafe fn result_amount(ctx: *mut ffi::sqlite3_context, value: i128) {
+    let bytes = encode_storage_i128(value);
+    unsafe {
+        ffi::sqlite3_result_blob(
+            ctx,
+            bytes.as_ptr().cast::<c_void>(),
+            WIDTH as c_int,
+            ffi::SQLITE_TRANSIENT(),
+        )
+    }
+}
+
+/// Fold one row into the running sum.
+///
+/// # Safety
+///
+/// Called by SQLite with its own context and argument array.
+unsafe extern "C" fn sum_step(
+    ctx: *mut ffi::sqlite3_context,
+    argc: c_int,
+    argv: *mut *mut ffi::sqlite3_value,
+) {
+    let raw = unsafe {
+        ffi::sqlite3_aggregate_context(ctx, size_of::<Accumulator>() as c_int).cast::<Accumulator>()
+    };
+    if raw.is_null() {
+        unsafe { ffi::sqlite3_result_error_nomem(ctx) };
+        return;
+    }
+    let mut acc = unsafe { std::ptr::read_unaligned(raw) };
+    if acc.failed != 0 {
+        return;
+    }
+
+    let stepped = if argc != 1 {
+        None
+    } else {
+        unsafe { amount_arg(*argv) }
+            .and_then(|v| i128::from_ne_bytes(acc.sum).checked_add(v))
+            .map(i128::to_ne_bytes)
+    };
+
+    match stepped {
+        Some(sum) => acc.sum = sum,
+        None => acc.failed = 1,
+    }
+    unsafe { std::ptr::write_unaligned(raw, acc) };
+}
+
+/// Produce the aggregate's result: the summed amount, or an error if any row
+/// was not a 16-byte amount or the running total left the `i128` range. An
+/// empty group sums to zero rather than to SQL `NULL`, so a caller can decode
+/// the result unconditionally.
+///
+/// # Safety
+///
+/// Called by SQLite with its own context.
+unsafe extern "C" fn sum_final(ctx: *mut ffi::sqlite3_context) {
+    let raw = unsafe { ffi::sqlite3_aggregate_context(ctx, 0).cast::<Accumulator>() };
+    if raw.is_null() {
+        unsafe { result_amount(ctx, 0) };
+        return;
+    }
+    let acc = unsafe { std::ptr::read_unaligned(raw) };
+    if acc.failed != 0 {
+        unsafe {
+            fail(
+                ctx,
+                c"kuatia_i128_sum: argument is not a 16-byte amount, or the sum left the i128 range",
+            )
+        };
+        return;
+    }
+    unsafe { result_amount(ctx, i128::from_ne_bytes(acc.sum)) };
+}
+
+/// `kuatia_i128_from_text(TEXT) -> BLOB`: the decimal form of an amount to its
+/// stored encoding. Used by the migration that converts the old text columns,
+/// which is also what makes a missing installation fail at prepare time.
+///
+/// # Safety
+///
+/// Called by SQLite with its own context and argument array.
+unsafe extern "C" fn from_text(
+    ctx: *mut ffi::sqlite3_context,
+    argc: c_int,
+    argv: *mut *mut ffi::sqlite3_value,
+) {
+    if argc != 1 {
+        unsafe { fail(ctx, c"kuatia_i128_from_text: expected one argument") };
+        return;
+    }
+    let value = unsafe { *argv };
+    if unsafe { ffi::sqlite3_value_type(value) } != ffi::SQLITE_TEXT {
+        unsafe { fail(ctx, c"kuatia_i128_from_text: argument is not text") };
+        return;
+    }
+    let ptr = unsafe { ffi::sqlite3_value_text(value) };
+    if ptr.is_null() {
+        unsafe { fail(ctx, c"kuatia_i128_from_text: argument is not text") };
+        return;
+    }
+    let len = unsafe { ffi::sqlite3_value_bytes(value) };
+    if len < 0 {
+        unsafe { fail(ctx, c"kuatia_i128_from_text: argument is not text") };
+        return;
+    }
+    let bytes = unsafe { std::slice::from_raw_parts(ptr, len as usize) };
+    let parsed = std::str::from_utf8(bytes)
+        .ok()
+        .and_then(|s| s.trim().parse::<i128>().ok());
+    match parsed {
+        Some(v) => unsafe { result_amount(ctx, v) },
+        None => unsafe { fail(ctx, c"kuatia_i128_from_text: not a decimal i128") },
+    }
+}
+
+/// `kuatia_i128_to_text(BLOB) -> TEXT`: an amount's stored encoding back to its
+/// decimal form. The amount columns are not human-readable any more, so this is
+/// how a client that registered these functions reads one. A plain `sqlite3`
+/// CLI has no access to it and sees the blob.
+///
+/// # Safety
+///
+/// Called by SQLite with its own context and argument array.
+unsafe extern "C" fn to_text(
+    ctx: *mut ffi::sqlite3_context,
+    argc: c_int,
+    argv: *mut *mut ffi::sqlite3_value,
+) {
+    let amount = if argc == 1 {
+        unsafe { amount_arg(*argv) }
+    } else {
+        None
+    };
+    let Some(amount) = amount else {
+        unsafe {
+            fail(
+                ctx,
+                c"kuatia_i128_to_text: argument is not a 16-byte amount",
+            )
+        };
+        return;
+    };
+    let text = amount.to_string();
+    unsafe {
+        ffi::sqlite3_result_text(
+            ctx,
+            text.as_ptr().cast::<c_char>(),
+            text.len() as c_int,
+            ffi::SQLITE_TRANSIENT(),
+        )
+    };
+}

+ 102 - 4
crates/kuatia-storage-sql/tests/postgres.rs

@@ -17,13 +17,19 @@
 
 use std::sync::atomic::{AtomicU64, Ordering};
 
+use kuatia_storage::store::PostingStore;
 use kuatia_storage_sql::SqlStore;
-use sqlx::{Any, Pool};
+use kuatia_types::*;
+use sqlx::{Any, Pool, Row};
 
 static SCHEMA_SEQ: AtomicU64 = AtomicU64::new(0);
 
 async fn new_store() -> SqlStore {
-    sqlx::any::install_default_drivers();
+    new_store_with_pool().await.0
+}
+
+async fn new_store_with_pool() -> (SqlStore, Pool<Any>) {
+    kuatia_storage_sql::install_drivers().expect("install drivers");
     let url = std::env::var("DATABASE_URL")
         .expect("DATABASE_URL must point at a PostgreSQL instance for this suite");
 
@@ -47,9 +53,101 @@ async fn new_store() -> SqlStore {
         sqlx::query(&stmt).execute(&pool).await.unwrap();
     }
 
-    let store = SqlStore::new(pool);
+    let store = SqlStore::new(pool.clone());
     store.migrate().await.unwrap();
-    store
+    (store, pool)
 }
 
 kuatia_storage::store_tests!(new_store);
+
+/// Amounts are stored as native `NUMERIC`, not text, and round-trip through the
+/// store. The type assertion is the point: under `sqlx::Any` an uncast
+/// `NUMERIC` fails the whole row, so this also proves every money `SELECT`
+/// goes through `Dialect::money_read` (ADR-0024).
+#[tokio::test]
+async fn amount_columns_are_numeric() {
+    let (store, pool) = new_store_with_pool().await;
+    let posting = Posting::new(
+        PostingId {
+            transfer: EnvelopeId([0x3f; 32]),
+            index: 0,
+        },
+        AccountId::new(1),
+        AssetId::new(1),
+        Cent::from(-4321),
+    );
+    store
+        .insert_postings(std::slice::from_ref(&posting))
+        .await
+        .unwrap();
+
+    let got = store.get_postings(&[posting.id]).await.unwrap();
+    assert_eq!(got[0].value, Cent::from(-4321));
+    assert_eq!(
+        store
+            .live_balance(&AccountId::new(1), &AssetId::new(1))
+            .await
+            .unwrap(),
+        Cent::from(-4321)
+    );
+
+    for (table, column) in [
+        ("postings", "value"),
+        ("live_postings", "value"),
+        ("balance_projection", "balance"),
+    ] {
+        let row = sqlx::query(
+            "SELECT data_type FROM information_schema.columns \
+             WHERE table_schema = current_schema() AND table_name = $1 AND column_name = $2",
+        )
+        .bind(table)
+        .bind(column)
+        .fetch_one(&pool)
+        .await
+        .unwrap();
+        assert_eq!(
+            row.try_get::<String, _>("data_type").unwrap(),
+            "numeric",
+            "{table}.{column}"
+        );
+    }
+}
+
+/// The 011 migration rewrites the existing text amounts into `NUMERIC`, keeping
+/// their values (including negatives).
+#[tokio::test]
+async fn migration_011_converts_text_amounts() {
+    let (_store, pool) = new_store_with_pool().await;
+
+    // Roll the money columns back to their pre-011 text form, with rows in
+    // them, then replay 011 alone.
+    for stmt in [
+        "ALTER TABLE postings ALTER COLUMN value TYPE TEXT USING value::text",
+        "ALTER TABLE live_postings ALTER COLUMN value TYPE TEXT USING value::text",
+        "ALTER TABLE balance_projection ALTER COLUMN balance TYPE TEXT USING balance::text",
+        "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')",
+        "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')",
+        "DELETE FROM _migrations WHERE name = '011_native_amounts'",
+    ] {
+        sqlx::query(stmt).execute(&pool).await.unwrap();
+    }
+
+    let store = SqlStore::new(pool.clone());
+    store.migrate().await.unwrap();
+
+    let rows = sqlx::query("SELECT CAST(value AS TEXT) AS v FROM postings ORDER BY transfer_id")
+        .fetch_all(&pool)
+        .await
+        .unwrap();
+    let got: Vec<String> = rows.iter().map(|r| r.try_get("v").unwrap()).collect();
+    assert_eq!(got, vec!["100".to_string(), "-250".to_string()]);
+
+    let row = sqlx::query(
+        "SELECT data_type FROM information_schema.columns \
+         WHERE table_schema = current_schema() AND table_name = 'postings' AND column_name = 'value'",
+    )
+    .fetch_one(&pool)
+    .await
+    .unwrap();
+    assert_eq!(row.try_get::<String, _>("data_type").unwrap(), "numeric");
+}

+ 280 - 7
crates/kuatia-storage-sql/tests/sqlite.rs

@@ -7,7 +7,7 @@ use kuatia_types::*;
 use sqlx::{Any, Pool, Row};
 
 async fn new_pool() -> Pool<Any> {
-    sqlx::any::install_default_drivers();
+    kuatia_storage_sql::install_drivers().expect("install sqlite money functions");
     sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
         .connect("sqlite::memory:")
@@ -23,9 +23,12 @@ async fn new_store() -> SqlStore {
 
 kuatia_storage::store_tests!(new_store);
 
-/// The point of the schema: no column holds opaque binary. A content-addressed
-/// id is stored as lower-case hex text, and a structured payload as readable
-/// JSON text, so a row can be audited in a plain SQL client.
+/// The point of the schema: no identifier or payload column holds opaque
+/// binary. A content-addressed id is stored as lower-case hex text, and a
+/// structured payload as readable JSON text, so a row can be audited in a plain
+/// SQL client. Amounts are the one exception, stored natively so the database
+/// can sum and order them (ADR-0024); `kuatia_i128_to_text` is how a client that
+/// registered the money functions reads one back.
 #[tokio::test]
 async fn columns_store_hex_ids_and_json_text() {
     let pool = new_pool().await;
@@ -71,6 +74,15 @@ async fn columns_store_hex_ids_and_json_text() {
         serde_json::from_str::<serde_json::Value>(&metadata).is_ok(),
         "metadata should be JSON text, got: {metadata}"
     );
+
+    // The amount is a 16-byte blob, and still legible through the helper.
+    let row =
+        sqlx::query("SELECT typeof(value) AS t, kuatia_i128_to_text(value) AS v FROM postings")
+            .fetch_one(&pool)
+            .await
+            .unwrap();
+    assert_eq!(row.try_get::<String, _>("t").unwrap(), "blob");
+    assert_eq!(row.try_get::<String, _>("v").unwrap(), "100");
 }
 
 /// The 002 migration adds the subaccount column and a subaccount account/posting
@@ -241,6 +253,7 @@ async fn migration_004_backfills_index_tables() {
         "008_live_postings",
         "009_saga_kind",
         "010_drop_sagas",
+        "011_native_amounts",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -317,8 +330,8 @@ async fn migration_005_backfills_account_head() {
     }
 
     // Record every migration except 005 as applied so migrate() runs only 005.
-    // 008 is pinned as applied so it does not run against a DB whose 004 index
-    // tables were never created.
+    // 008 and 011 are pinned as applied so they do not run against a DB whose
+    // 004 index tables were never created.
     sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
         .execute(&pool)
         .await
@@ -333,6 +346,7 @@ async fn migration_005_backfills_account_head() {
         "008_live_postings",
         "009_saga_kind",
         "010_drop_sagas",
+        "011_native_amounts",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -405,6 +419,7 @@ async fn migration_008_merges_live_postings() {
         "007_balance_projection",
         "009_saga_kind",
         "010_drop_sagas",
+        "011_native_amounts",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -454,7 +469,7 @@ async fn migration_008_merges_live_postings() {
 /// migrate() is idempotent: running it repeatedly on the same DB is a no-op.
 #[tokio::test]
 async fn migrate_is_idempotent() {
-    sqlx::any::install_default_drivers();
+    kuatia_storage_sql::install_drivers().expect("install sqlite money functions");
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
         .connect("sqlite::memory:")
@@ -519,3 +534,261 @@ async fn id_batch_primitives_chunk_large_batches() {
     let after = store.get_posting_states(&ids).await.unwrap();
     assert!(after.iter().all(|s| *s == PostingState::Spent));
 }
+
+fn encoded(value: i128) -> Vec<u8> {
+    encode_storage_i128(value).to_vec()
+}
+
+fn decoded(bytes: &[u8]) -> i128 {
+    let bytes: [u8; 16] = bytes.try_into().expect("a 16-byte amount");
+    decode_storage_i128(&bytes)
+}
+
+/// The money scalars round-trip the full i128 range, which is what the 011
+/// migration relies on to convert the old text columns.
+#[tokio::test]
+async fn money_scalars_round_trip() {
+    let pool = new_pool().await;
+    for v in [
+        "0",
+        "1",
+        "-1",
+        "170141183460469231731687303715884105727",
+        "-170141183460469231731687303715884105728",
+    ] {
+        let row = sqlx::query("SELECT kuatia_i128_to_text(kuatia_i128_from_text($1)) AS t")
+            .bind(v)
+            .fetch_one(&pool)
+            .await
+            .unwrap();
+        assert_eq!(row.try_get::<String, _>("t").unwrap(), v);
+    }
+}
+
+/// The aggregate folds mixed signs exactly, and an empty group sums to zero
+/// rather than to SQL NULL, so a caller can decode the result unconditionally.
+#[tokio::test]
+async fn i128_sum_folds_and_handles_empty_group() {
+    let pool = new_pool().await;
+    sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)")
+        .execute(&pool)
+        .await
+        .unwrap();
+    let values: Vec<i128> = vec![5, -3, 1_000_000_000_000_000_000_000, -7];
+    for v in &values {
+        sqlx::query("INSERT INTO amounts (v) VALUES ($1)")
+            .bind(encoded(*v))
+            .execute(&pool)
+            .await
+            .unwrap();
+    }
+
+    let row = sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts")
+        .fetch_one(&pool)
+        .await
+        .unwrap();
+    assert_eq!(
+        decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()),
+        values.iter().sum::<i128>()
+    );
+
+    let row = sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts WHERE 1 = 0")
+        .fetch_one(&pool)
+        .await
+        .unwrap();
+    assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 0);
+}
+
+/// The aggregate raises rather than wrapping. This is the property that makes
+/// summing in SQL as safe as `Cent::checked_sum`.
+#[tokio::test]
+async fn i128_sum_overflows_loudly() {
+    let pool = new_pool().await;
+    sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)")
+        .execute(&pool)
+        .await
+        .unwrap();
+    for _ in 0..2 {
+        sqlx::query("INSERT INTO amounts (v) VALUES ($1)")
+            .bind(encoded(i128::MAX))
+            .execute(&pool)
+            .await
+            .unwrap();
+    }
+    let err = match sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts")
+        .fetch_one(&pool)
+        .await
+    {
+        Ok(_) => panic!("summing past i128::MAX should fail"),
+        Err(e) => e.to_string(),
+    };
+    assert!(err.contains("i128"), "{err}");
+}
+
+/// A value that is not a 16-byte amount fails the statement instead of being
+/// skipped, so a corrupt row can never silently change a balance.
+#[tokio::test]
+async fn i128_sum_rejects_non_amount() {
+    let pool = new_pool().await;
+    let err = match sqlx::query("SELECT kuatia_i128_sum(x) AS s FROM (SELECT 'abc' AS x)")
+        .fetch_one(&pool)
+        .await
+    {
+        Ok(_) => panic!("a text argument should fail"),
+        Err(e) => e.to_string(),
+    };
+    assert!(err.contains("16-byte"), "{err}");
+}
+
+/// The storage encoding is order-preserving, so SQLite's byte-wise BLOB
+/// comparison orders amounts numerically. This is what the text columns could
+/// not do (ADR-0011) and the reason the encoding flips the sign bit.
+#[tokio::test]
+async fn blob_order_matches_numeric_order() {
+    let pool = new_pool().await;
+    sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)")
+        .execute(&pool)
+        .await
+        .unwrap();
+    for v in [7i128, -9, 0, i128::MAX, i128::MIN, -1, 1] {
+        sqlx::query("INSERT INTO amounts (v) VALUES ($1)")
+            .bind(encoded(v))
+            .execute(&pool)
+            .await
+            .unwrap();
+    }
+    let ordered: Vec<i128> =
+        sqlx::query("SELECT kuatia_i128_to_text(v) AS t FROM amounts ORDER BY v")
+            .fetch_all(&pool)
+            .await
+            .unwrap()
+            .iter()
+            .map(|r| r.try_get::<String, _>("t").unwrap().parse().unwrap())
+            .collect();
+    let mut expected = ordered.clone();
+    expected.sort();
+    assert_eq!(ordered, expected);
+    assert_eq!(ordered.first(), Some(&i128::MIN));
+    assert_eq!(ordered.last(), Some(&i128::MAX));
+}
+
+/// Amounts are stored at full i128 width, so a value past the i64 backing
+/// round-trips through the store under the `i128` feature.
+#[cfg(feature = "i128")]
+#[tokio::test]
+async fn value_beyond_i64_round_trips() {
+    use std::str::FromStr;
+
+    let store = new_store().await;
+    let value = Cent::from_str("170141183460469231731687303715884105727").unwrap();
+    let posting = Posting::new(
+        PostingId {
+            transfer: EnvelopeId([0x5c; 32]),
+            index: 0,
+        },
+        AccountId::new(1),
+        AssetId::new(1),
+        value,
+    );
+    store
+        .insert_postings(std::slice::from_ref(&posting))
+        .await
+        .unwrap();
+
+    let got = store.get_postings(&[posting.id]).await.unwrap();
+    assert_eq!(got[0].value, value);
+    assert_eq!(
+        store
+            .live_balance(&AccountId::new(1), &AssetId::new(1))
+            .await
+            .unwrap(),
+        value
+    );
+}
+
+/// 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]
+async fn migration_011_converts_text_amounts() {
+    let pool = new_pool().await;
+
+    // Post-010 shape: money columns are still TEXT.
+    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 TEXT 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 TEXT NOT NULL, reservation BIGINT, PRIMARY KEY (transfer_id, idx))",
+        "CREATE TABLE balance_projection (id BIGINT NOT NULL, account BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, balance TEXT NOT NULL, watermark BIGINT NOT NULL, PRIMARY KEY (id))",
+        "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')",
+        "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')",
+        "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, '100', 77)",
+        "INSERT INTO balance_projection (id, account, subaccount, asset, balance, watermark) VALUES (1, 1, 0, 1, '-150', 5)",
+    ] {
+        sqlx::query(ddl).execute(&pool).await.unwrap();
+    }
+
+    // Record every migration except 011 as applied so migrate() runs only 011.
+    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",
+    ] {
+        sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
+            .bind(m)
+            .execute(&pool)
+            .await
+            .unwrap();
+    }
+
+    let store = SqlStore::new(pool.clone());
+    store.migrate().await.unwrap();
+
+    let rows = sqlx::query(
+        "SELECT transfer_id, typeof(value) AS t, kuatia_i128_to_text(value) AS v FROM postings ORDER BY transfer_id",
+    )
+    .fetch_all(&pool)
+    .await
+    .unwrap();
+    let got: Vec<(String, String, String)> = rows
+        .iter()
+        .map(|r| {
+            (
+                r.try_get("transfer_id").unwrap(),
+                r.try_get("t").unwrap(),
+                r.try_get("v").unwrap(),
+            )
+        })
+        .collect();
+    assert_eq!(
+        got,
+        vec![
+            ("aa".to_string(), "blob".to_string(), "100".to_string()),
+            ("bb".to_string(), "blob".to_string(), "-250".to_string()),
+        ]
+    );
+
+    // The rest of the row survives, and the summing path reads the new column.
+    let row = sqlx::query("SELECT reservation, kuatia_i128_sum(value) AS s FROM live_postings")
+        .fetch_one(&pool)
+        .await
+        .unwrap();
+    assert_eq!(row.try_get::<i64, _>("reservation").unwrap(), 77);
+    assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 100);
+
+    let row =
+        sqlx::query("SELECT kuatia_i128_to_text(balance) AS b, watermark FROM balance_projection")
+            .fetch_one(&pool)
+            .await
+            .unwrap();
+    assert_eq!(row.try_get::<String, _>("b").unwrap(), "-150");
+    assert_eq!(row.try_get::<i64, _>("watermark").unwrap(), 5);
+}

+ 7 - 1
crates/kuatia-storage/src/error.rs

@@ -9,13 +9,18 @@ use std::fmt;
 /// 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.
+/// count and an I/O fault. [`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)]
 pub enum StoreError {
     /// The requested entity was not found.
     NotFound(String),
     /// Catch-all for unexpected internal errors.
     Internal(String),
+    /// The backend is missing setup the store requires, such as the SQLite
+    /// functions that must be installed before any connection is opened.
+    Misconfigured(String),
 }
 
 impl fmt::Display for StoreError {
@@ -23,6 +28,7 @@ impl fmt::Display for StoreError {
         match self {
             Self::NotFound(msg) => write!(f, "not found: {msg}"),
             Self::Internal(msg) => write!(f, "internal error: {msg}"),
+            Self::Misconfigured(msg) => write!(f, "misconfigured: {msg}"),
         }
     }
 }

+ 13 - 0
crates/kuatia-storage/src/mem_store.rs

@@ -254,6 +254,19 @@ impl PostingStore for InMemoryStore {
         Ok(result)
     }
 
+    async fn live_balance(&self, account: &AccountId, asset: &AssetId) -> Result<Cent, StoreError> {
+        let live = self
+            .get_postings_by_account(
+                account.id,
+                Some(account.sub),
+                Some(asset),
+                PostingFilter::Live,
+            )
+            .await?;
+        Cent::checked_sum(live.iter().map(|p| p.value))
+            .map_err(|e| StoreError::Internal(e.to_string()))
+    }
+
     async fn get_posting_states(&self, ids: &[PostingId]) -> Result<Vec<PostingState>, StoreError> {
         let postings = self.postings.read().await;
         Ok(ids

+ 9 - 0
crates/kuatia-storage/src/store.rs

@@ -183,6 +183,15 @@ pub trait PostingStore: Send + Sync {
     /// 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.
+    ///
+    /// The one place a backend is allowed to add up money itself, and only
+    /// because it can do so exactly (ADR-0024): the SQL store folds native
+    /// amount columns inside the database rather than shipping one row per
+    /// posting to the caller. An overflow is an error, never a wrap.
+    async fn live_balance(&self, account: &AccountId, asset: &AssetId) -> Result<Cent, StoreError>;
+
     /// Query postings with filtering and pagination.
     async fn query_postings(&self, query: &PostingQuery) -> Result<Page<Posting>, StoreError> {
         // `get_postings_by_account` returns a deterministic id-ordered sequence,

+ 67 - 0
crates/kuatia-storage/src/store_tests.rs

@@ -791,6 +791,72 @@ pub async fn get_postings_by_account_live_filter(store: &(impl Store + 'static))
     assert_eq!(ids, vec![active.id, reserved.id]);
 }
 
+/// `live_balance` agrees with summing the same live postings in Rust, and keeps
+/// assets and subaccounts apart. This is the differential check on the backends
+/// that push the sum into the database (ADR-0024): the oracle is the
+/// `get_postings_by_account` + `Cent::checked_sum` path the ledger used before.
+pub async fn live_balance_matches_rust_sum(store: &(impl Store + 'static)) {
+    let account = AccountId::new(70);
+    let asset = AssetId::new(1);
+
+    assert_eq!(
+        store.live_balance(&account, &asset).await.unwrap(),
+        Cent::ZERO
+    );
+
+    let active = make_posting([0xC7; 32], 0, 70, 1, 900);
+    let negative = make_posting([0xC7; 32], 1, 70, 1, -250);
+    let reserved = make_posting([0xC7; 32], 2, 70, 1, 40);
+    let spent = make_posting([0xC7; 32], 3, 70, 1, 10_000);
+    let other_asset = make_posting([0xC7; 32], 4, 70, 2, 77);
+    let other_sub = make_posting_sub([0xC7; 32], 5, 70, 9, 1, 500);
+    store
+        .insert_postings(&[
+            active.clone(),
+            negative.clone(),
+            reserved.clone(),
+            spent.clone(),
+            other_asset.clone(),
+            other_sub.clone(),
+        ])
+        .await
+        .unwrap();
+    store
+        .reserve_postings(&[reserved.id], ReservationId::new(7))
+        .await
+        .unwrap();
+    store.deactivate_postings(&[spent.id], None).await.unwrap();
+
+    for (account, asset) in [
+        (account, asset),
+        (account, AssetId::new(2)),
+        (AccountId::with_sub(70, 9), asset),
+    ] {
+        let live = store
+            .get_postings_by_account(
+                account.id,
+                Some(account.sub),
+                Some(&asset),
+                PostingFilter::Live,
+            )
+            .await
+            .unwrap();
+        let expected = Cent::checked_sum(live.iter().map(|p| p.value)).unwrap();
+        assert_eq!(
+            store.live_balance(&account, &asset).await.unwrap(),
+            expected,
+            "live_balance disagreed for {account:?} / {asset:?}"
+        );
+    }
+
+    // Reserved postings are still live, the spent one is not, and the negative
+    // one is subtracted rather than dropped.
+    assert_eq!(
+        store.live_balance(&account, &asset).await.unwrap(),
+        Cent::from(690)
+    );
+}
+
 /// `store_transfer` returns 1 when the record is newly inserted, 0 on replay,
 /// and indexes the involved accounts.
 pub async fn store_transfer_counts(store: &(impl Store + 'static)) {
@@ -1728,6 +1794,7 @@ macro_rules! store_tests {
             get_posting_states_batch_preserves_order,
             spent_posting_remains_in_immutable_table,
             get_postings_by_account_live_filter,
+            live_balance_matches_rust_sum,
             store_transfer_counts,
             store_transfer_indexes_involved,
             // Reservation / double-spend regressions

+ 3 - 1
crates/kuatia-types/src/lib.rs

@@ -28,7 +28,9 @@ pub use canonical::{
 };
 
 // Cent — re-exported from kuatia-money (swappable integer backing).
-pub use kuatia_money::{Amount, Cent, OverflowError, ParseAmountError};
+pub use kuatia_money::{
+    Amount, Cent, OverflowError, ParseAmountError, decode_storage_i128, encode_storage_i128,
+};
 
 pub use account::{Account, AccountFlags};
 pub use book::{Book, BookBuilder, BookPolicy};

+ 1 - 1
crates/kuatia/examples/create_accounts.rs

@@ -54,7 +54,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 /// `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>> {
-    sqlx::any::install_default_drivers();
+    kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
         .connect("sqlite::memory:")

+ 1 - 1
crates/kuatia/examples/fund_and_trade.rs

@@ -87,7 +87,7 @@ async fn print_balances(
 }
 
 async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
-    sqlx::any::install_default_drivers();
+    kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
         .connect("sqlite::memory:")

+ 1 - 1
crates/kuatia/examples/inflight_hold.rs

@@ -157,7 +157,7 @@ async fn print_status(
 /// `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>> {
-    sqlx::any::install_default_drivers();
+    kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
         .connect("sqlite::memory:")

+ 1 - 1
crates/kuatia/examples/withdraw.rs

@@ -62,7 +62,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 }
 
 async fn connect() -> Result<Arc<Ledger>, Box<dyn std::error::Error>> {
-    sqlx::any::install_default_drivers();
+    kuatia_storage_sql::install_drivers()?;
     let pool = sqlx::any::AnyPoolOptions::new()
         .max_connections(1)
         .connect("sqlite::memory:")

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

@@ -25,7 +25,7 @@ use std::sync::Arc;
 
 use tracing::instrument;
 
-use kuatia_core::{AccountId, AssetId, Cent, PostingFilter, PostingId};
+use kuatia_core::{AccountId, AssetId, Cent, PostingId};
 use kuatia_storage::store::{EnvelopeRecord, Store, TransferQuery};
 
 use super::{Ledger, now_millis};
@@ -175,10 +175,11 @@ async fn append_cache_point(
 
 impl Ledger {
     /// The authoritative balance: the sum of the live (active or reserved)
-    /// postings for one `(account, asset)`, computed in Rust. 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. Cost is `O(live postings)`; prefer
+    /// 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(
@@ -186,16 +187,7 @@ impl Ledger {
         account: &AccountId,
         asset: &AssetId,
     ) -> Result<Cent, LedgerError> {
-        let postings = self
-            .store
-            .get_postings_by_account(
-                account.id,
-                Some(account.sub),
-                Some(asset),
-                PostingFilter::Live,
-            )
-            .await?;
-        Ok(Cent::checked_sum(postings.iter().map(|p| p.value))?)
+        Ok(self.store.live_balance(account, asset).await?)
     }
 
     /// The everyday balance read for one subaccount and asset (ADR-0019): the

+ 220 - 0
doc/adr/0024-native-money-columns.md

@@ -0,0 +1,220 @@
+# 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](0011-swappable-money-backing.md) 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](0011-swappable-money-backing.md) ("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](0009-monetary-representation-integer-minor-units.md): the
+  persisted form has now gone `BIGINT` → text → backend-native.
+* Amends [ADR-0023](0023-atomic-storage-commit.md): the overdraft floor is still
+  re-checked inside the commit transaction, but the sum is now one aggregate.
+* Touches [ADR-0019](0019-cached-balance-projection.md)
+  (`balance_projection.balance`) and
+  [ADR-0022](0022-merged-live-postings-hot-index.md) (`live_postings.value`).

+ 6 - 3
doc/adr/README.md

@@ -20,7 +20,7 @@ to reverse a decision. Instead, a new ADR supersedes it.
 | [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. |
 | [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 | `Cent` moves to a `kuatia-money` crate over a `CentBacking` trait; the i64↔i128 width is a cargo feature, hidden from the API, stored as text. Refines 0009. |
+| [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. |
@@ -33,6 +33,7 @@ to reverse a decision. Instead, a new ADR supersedes it.
 | [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. |
 | [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. |
 
 ## Recommended future ADRs
 
@@ -53,8 +54,10 @@ captured as an ADR, roughly in priority order:
 4. **Append-only, versioned accounts + snapshot pinning**: accounts are
    never modified in place; snapshot hashes guard against TOCTOU between
    load and apply.
-5. **All arithmetic in Rust, never in SQL**: no `SUM`/`MAX`/etc. on
-   monetary values; the storage layer stays a dumb record keeper.
+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

+ 4 - 2
doc/architecture.md

@@ -107,8 +107,10 @@ classDiagram
 A whole transfer is committed atomically by `CommitStore::commit_envelope`, so
 there is a single atomic commit boundary. The store enforces the stateful guards
 (double-spend, freeze/close, overdraft floor) inside that transaction; the pure
-core validates everything else first. Balance computation, validation, and the
-resolve decision live in the Ledger and `kuatia-core`.
+core validates everything else first. Validation and the resolve decision live
+in the Ledger and `kuatia-core`. Summing an account's live postings is the one
+thing a backend may do itself, through `PostingStore::live_balance`, because the
+amount columns are native and the sum is exact either way (ADR-0024).
 
 ## Atomic Commit
 

+ 3 - 1
doc/crates.md

@@ -179,7 +179,9 @@ graph TB
   `append_account_version`, `get_account_history`, `list_accounts`
 - **`PostingStore`**: `get_postings`, `get_posting_states`,
   `get_postings_by_account(account, sub?, asset?, filter)`, `query_postings(query)`,
-  and the dumb write primitives `reserve_postings(ids, reservation) -> u64`,
+  `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`

+ 51 - 13
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
-`007_balance_projection`) plus the `_migrations` bookkeeping table created in
+`011_native_amounts`) 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.
@@ -15,13 +15,22 @@ Ground rules that keep the catalog terse:
   database. A posting's identity is `transfer_id + idx`; `account_head` points at
   the current `accounts` version; the account/transfer link is an explicit index
   table. See [ADR-0003](adr/0003-dumb-storage-saga-recovery.md).
-- **Every payload, money, and hash column is `TEXT`.** Content-addressed ids and
-  opaque saga bytes are lower-case hex; JSON payloads are their `TEXT`
-  serialization; a `Cent` is its decimal string. The store never does arithmetic
-  or `SUM`/`MAX` on these; balances are computed in Rust.
+- **Every payload and hash column is `TEXT`.** Content-addressed ids and opaque
+  saga bytes are lower-case hex; JSON payloads are their `TEXT` serialization.
+  The store never does arithmetic on these.
+- **Money columns are backend-native, and only they may be summed in SQL.** An
+  amount is `NUMERIC(39,0)` on PostgreSQL and a 16-byte `BLOB` on SQLite, always
+  at full `i128` width whatever the `i128` cargo feature selects. Both forms are
+  ordered and compared numerically, and both sum exactly: plain `SUM()` on
+  Postgres, the registered `kuatia_i128_sum` aggregate on SQLite, which raises
+  rather than wrapping. Everything else is still computed in Rust. `AMOUNT` in
+  the diagram below stands for this pair of types. See
+  [ADR-0024](adr/0024-native-money-columns.md).
 - **All ids are Rust-minted `BIGINT`.** No `AUTOINCREMENT` / `SERIAL`; snowflake
   ids come from `AutoId`. See [ADR-0015](adr/0015-fixed-width-account-code.md).
-- The identical DDL runs on both SQLite and PostgreSQL (`sqlx::Any`).
+- The DDL is identical on SQLite and PostgreSQL (`sqlx::Any`) except for the
+  money columns, whose native types differ; that divergence lives in the
+  `Dialect` seam and in the per-backend halves of `011_native_amounts`.
 
 Design rationale lives in [ADR-0016 (immutable postings + index
 tables)](adr/0016-immutable-postings-index-tables.md), [ADR-0017 (append-only
@@ -56,7 +65,7 @@ erDiagram
         BIGINT owner
         BIGINT subaccount
         INTEGER asset
-        TEXT value
+        AMOUNT value
     }
     live_postings {
         TEXT transfer_id PK
@@ -64,7 +73,7 @@ erDiagram
         BIGINT owner
         BIGINT subaccount
         INTEGER asset
-        TEXT value
+        AMOUNT value
         BIGINT reservation
     }
     transfers {
@@ -89,7 +98,7 @@ erDiagram
         BIGINT account
         BIGINT subaccount
         INTEGER asset
-        TEXT balance
+        AMOUNT balance
         BIGINT watermark
     }
     sagas {
@@ -198,7 +207,7 @@ The immutable record. A row here that is absent from `live_postings` is Spent.
 | `owner` | `BIGINT` | | Owning base account id. |
 | `subaccount` | `BIGINT` | | Owning subaccount code. |
 | `asset` | `INTEGER` | | Asset id. |
-| `value` | `TEXT` | | Signed `Cent` as a decimal string. |
+| `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)`. |
 
 - **Primary key**: `(transfer_id, idx)`.
 - **Index**: `idx_postings_owner (owner, subaccount, asset)`.
@@ -219,7 +228,7 @@ log.
 | `owner` | `BIGINT` | | Owning base account id. |
 | `subaccount` | `BIGINT` | | Owning subaccount code. |
 | `asset` | `INTEGER` | | Asset id. |
-| `value` | `TEXT` | | Signed `Cent` as a decimal string. |
+| `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)`.
@@ -307,7 +316,7 @@ never authoritative. Owned by `projection.rs` (`BalanceProjectionStore`). See
 | `account` | `BIGINT` | | Base account id. |
 | `subaccount` | `BIGINT` | | Subaccount code. |
 | `asset` | `INTEGER` | | Asset id. |
-| `balance` | `TEXT` | | The cached `Cent` as a decimal string. |
+| `balance` | `NUMERIC(39,0)` / `BLOB` | | The cached `Cent`, stored natively (see `postings.value`). |
 | `watermark` | `BIGINT` | | Commit-time watermark (unix millis) this snapshot covers. |
 
 - **Primary key**: `id`.
@@ -320,6 +329,35 @@ migration whose `name` is present is skipped, making `migrate()` idempotent.
 
 | Column | Type | Key | Purpose |
 |---|---|---|---|
-| `name` | `TEXT` | PK | The migration name (e.g. `007_balance_projection`). |
+| `name` | `TEXT` | PK | The migration name (e.g. `011_native_amounts`). |
 
 - **Primary key**: `name`.
+
+## SQLite money functions
+
+SQLite has no 128-bit integer, so an amount is a 16-byte `BLOB` and three
+registered functions do the work the type system would otherwise do. They are
+installed by `kuatia_storage_sql::install_drivers()`, which callers use in place
+of `sqlx::any::install_default_drivers()` and **must call before connecting a
+pool**: registration goes through `sqlite3_auto_extension`, so a connection
+opened earlier does not have them. `migrate()` checks for them on SQLite and
+returns `StoreError::Misconfigured` rather than a bare "no such function".
+
+| Function | Signature | Purpose |
+|---|---|---|
+| `kuatia_i128_sum` | `BLOB` → `BLOB` (aggregate) | Exact sum of an amount column. Folds with `i128::checked_add` and raises on overflow or on an argument that is not a 16-byte amount; an empty group sums to zero, not `NULL`. The PostgreSQL equivalent is plain `SUM()`. |
+| `kuatia_i128_from_text` | `TEXT` → `BLOB` | Decimal string to the stored encoding. Used by `011_native_amounts` to convert the old text columns. |
+| `kuatia_i128_to_text` | `BLOB` → `TEXT` | The stored encoding back to a decimal string, for tooling built on this crate. |
+
+The encoding is two's-complement big-endian with the sign bit flipped, so
+SQLite's byte-wise `BLOB` comparison orders amounts numerically: `i128::MIN` is
+all zeros, `0` is `0x80` followed by zeros, `i128::MAX` is all `0xFF`. It is
+deliberately not the content-addressed hash encoding
+(`Cent::to_canonical_bytes`), so the two cannot be confused.
+
+These functions live in the process that registers them, so a **plain `sqlite3`
+CLI does not have them**: it sees a blob. To read one by hand there, take
+`hex(value)`, subtract `0x80` from the leading byte, and read the result as a
+128-bit big-endian two's-complement integer. This is the one place the schema
+gives up on being legible without tooling, and it is the price of an amount
+column the database can sum and order (ADR-0024).

+ 1 - 1
doc/transfers.md

@@ -236,7 +236,7 @@ Steps 1-8 run in the pure core before the write. The effects are then applied by
 `store.commit_envelope(..)` in one transaction, which re-checks the stateful
 guards inside it: double-spend (deleting a consumed live posting is the atomic
 single-winner claim), freeze/close, and the zero floor of an account that forbids
-overdraft (steps 9-10, summed in Rust from the post-commit live rows). Because
+overdraft (steps 9-10, one exact aggregate over the post-commit live rows). Because
 the checks and the writes share the transaction, the floor is **strict**, not
 best-effort: two transfers cannot both pass and jointly push an account below
 zero (ADR-0023, superseding the best-effort floor of ADR-0003). A crash leaves no