فهرست منبع

Cut 0.4.0, with a deadline on held funds and no cross-account read

The cycle since 0.3.0 is breaking throughout and none of it was released, so
the version still read 0.3.0 and the changelog was missing the three largest
changes in it: the atomic storage commit, the amount columns the database can
add up exactly, and the payer field leaving the content address. Somebody
upgrading had no way to learn any of those from the file that exists to tell
them. The upgrade hazards were scattered through individual entries, where they
are met in the order the features were written rather than the order the steps
have to be taken, so they are now one numbered section.

An authorization with nobody to settle it held its funders' money forever: a
hold waited for a confirm or a void, and no caller was obliged to come back.
A deadline now rides on the holding account, which is create-only and so cannot
drift after the authorization is recorded, and the sweep reads only the accounts
list_open_inflights already returns. Expiring runs the existing void path, so an
expired authorization returns what a void returns: each posting to the account
that funded it, only the remainder when some legs were confirmed, and the
confirmations left alone. The clock is a parameter, so nothing starts a timer.

A trial balance was built on top of the asset registry and then taken out
again, because it asked the store a question no account bounds. A read without
an account cannot be routed to the shard holding the data, its cost grows with
the ledger rather than with one account, and the work it does is reporting,
which an application can cache off the event stream. ADR-0031 records the rule
so the next proposal of that shape has an answer to read. What stays is the
same question from the side an account bounds: what one account holds, across
every asset it holds anything in.

The minted asset id is masked to 31 bits as well. The asset columns are a
4-byte signed integer, and an unmasked fold stored about half of all ids as
negative numbers. They round-tripped, since the bind and the read cast the same
way, but nothing should have to know that to read the column.
C 4 روز پیش
والد
کامیت
b401e9833d

+ 77 - 6
CHANGELOG.md

@@ -7,8 +7,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ## [Unreleased]
 
+## [0.4.0] - 2026-12-02
+
+### Upgrading to 0.4.0
+
+In this order, before the first commit against an upgraded database:
+
+1. **Register every asset already in use**, with the precision it was always
+   recorded at. A posting now rebuilds its amount by joining the registry, so a
+   posting in an unregistered asset fails its read loudly rather than coming
+   back at the wrong scale.
+2. **Settle any two assets sharing a code** before migration `015` adds its
+   unique index, or the migration fails on them. Two assets under one code
+   split every balance held in it, which is the condition the index exists to
+   prevent, and only a human knows which row is the real one.
+3. **Drain inflight authorizations.** An authorization opened before the
+   upgrade cannot be confirmed after it: the leg table is CBOR inside a
+   transfer's metadata and its shape moved twice this cycle.
+
+Stored transfer ids from 0.3.0 do not reproduce. The content-address preimage
+moved twice: `payer` left it and `value_date` joined it, and
+`CANONICAL_VERSION` is now 6. The recorded ids are untouched and still verify
+against the bytes that produced them, so the audit trail is intact; recomputing
+one from its transfer under this version gives a different id.
+
 ### Added
 
+- `Ledger::authorize_until(transfer, expires_at)`, an authorization with a
+  deadline, plus `expire(inflight, now)` and `expire_due(now)` to return its
+  funds once that deadline has passed. An authorize with nobody to settle it
+  used to park its funders' money indefinitely. The deadline is written onto
+  the holding account at creation, where it cannot drift, and expiring runs the
+  existing void path, so an expired authorization returns exactly what a void
+  returns: each posting to the account that funded it, only the remainder when
+  some legs were confirmed, and confirmations left alone. Nothing expires on
+  its own: `expire_due` takes the clock and is a method a caller schedules.
+  `authorize` is unchanged and records no deadline. See
+  [doc/inflight.md](doc/inflight.md#expiry).
+- `Ledger::holdings(account)`, every asset one account holds, with what it
+  holds of each. A balance read answered for one account and one asset, so
+  asking what an account held at all meant the caller keeping its own list of
+  the assets to ask about. Assets the account has no live posting of are
+  absent rather than reported as zero.
+
+  No read aggregates across accounts, so a trial balance, a balance sheet and
+  a P&L are the application's to build, off the event stream where they can be
+  cached (ADR-0031). `holdings` and `balances` are bounded by one account,
+  which is what lets the store be sharded on it later.
 - Amounts are what the ledger stores and what it hands back. `Movement`,
   `Posting`, `NewPosting` and `BalanceProjection` each hold one `Amount`
   instead of an `AssetId` beside a value, and an amount serializes with its
@@ -22,11 +67,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
   refuses two assets, and `minor_units() -> i128`, and the other crates reach
   the integer through `kuatia_types::internals`. `AssetId` stays public as the
   name of an asset. *(breaking throughout)* (ADR-0029)
-
-  Two notes for an upgrade. Register every asset already in use first, or
-  reads of postings in unregistered assets fail. And an inflight
-  authorization opened before this cannot be confirmed after it: the leg table
-  is CBOR inside a transfer's metadata and its shape moved.
 - An asset registry, and an `Amount` that carries its asset. `Asset { id, code,
   symbol, decimals }` is a row written once and never updated; `AssetStore`
   adds `create_asset`/`get_asset`/`list_assets` and migration `014_assets`.
@@ -74,6 +114,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ### Changed
 
+- A transfer commits in one store transaction. `CommitStore::commit_envelope`
+  spends the consumed postings, inserts the created ones, records the transfer
+  and appends its event together, so a crash leaves nothing half applied and
+  there is nothing to recover: the write-ahead record and its machinery
+  (`SagaStore`, `PendingSaga`, `Ledger::recover`, the reserve/finalize phases)
+  are gone and migration `010_drop_sagas` drops the table. The guards that used
+  to be checked before the write are re-checked inside that transaction and are
+  now strict rather than best-effort: double-spend (the delete's affected count
+  is the atomic single-winner claim), freeze and close, and the no-overdraft
+  floor. Multi-transfer composition is a plain LIFO runner over `commit` and
+  `reverse` instead of a saga interpreter. *(breaking for `Store`
+  implementors, and `Ledger::recover` is gone)* (ADR-0023)
+- Amount columns are native integers the database can add up exactly:
+  `NUMERIC(39,0)` on PostgreSQL and a 16-byte order-preserving `BLOB` on
+  SQLite, through migrations `011`. An amount used to be stored in a form only
+  Rust could interpret, so every aggregate had to be folded in the process that
+  asked, and the commit transaction could not check a balance without shipping
+  the rows out of the database. The floor check and the live-balance read are
+  now one exact aggregate inside the transaction, `SUM()` on Postgres and a
+  registered `kuatia_i128_sum` on SQLite, both of which raise on overflow
+  instead of wrapping. Ordering and range predicates work on the column
+  directly. No floating point goes near an amount, and everything that is not
+  an exact aggregate over one of these columns is still computed in Rust with
+  checked arithmetic. *(on-disk format change)* (ADR-0024)
+- `payer` is provenance and no longer part of a transfer's identity, so it left
+  the content-address preimage. Two transfers that differ only in who paid are
+  now one transfer and the second commit is reported as a replay, which is the
+  point: the payer is a record of where the funds came from, not a way to make
+  an otherwise identical transfer distinct. *(breaking: a transfer id computed
+  under 0.3.0 does not reproduce)*
 - `Ledger::asset(code, symbol, decimals)` registers an asset on first sight and
   returns its handle, so naming money takes one line and no invented id:
   `ledger.asset("EUR", "\u{20ac}", 2)`. Idempotent, so setup code calls it
@@ -271,8 +341,9 @@ Initial release.
 - `kuatia-core` — pure, sans-IO logic: validation, hashing, posting selection.
 - `kuatia-storage` — storage abstraction and conformance suite.
 - `kuatia-storage-sql` — SQLite/PostgreSQL backend.
-- `kuatia` — async `Ledger` resource and saga commit pipeline.
+- `kuatia` — async `Ledger` resource and the atomic commit path.
 
+[0.4.0]: https://github.com/crodas/kuatia/releases/tag/v0.4.0
 [0.3.0]: https://github.com/crodas/kuatia/releases/tag/v0.3.0
 [0.2.0]: https://github.com/crodas/kuatia/releases/tag/v0.2.0
 [0.1.0]: https://github.com/crodas/kuatia/releases/tag/v0.1.0

+ 1 - 0
CLAUDE.md

@@ -75,6 +75,7 @@ cargo test -p kuatia        # integration + commit/concurrency tests
 ## Conventions
 
 - Clarity over cleverness
+- **Every read is account scoped** (ADR-0031). No read folds value across accounts: an aggregate keyed by asset, book, flag or time has no shard key and its cost grows with the ledger, so it is not the library's to answer. `balance`, `balance_exact`, `balance_as_of`, `balances` and `holdings` are the balance surface, each bounded by one account. A trial balance, a balance sheet or a P&L belongs in the application or a read model off the event stream (ADR-0010). Enumerations that return rows without folding value (`list_accounts`, the paginated `query_transfers`) and registry reads (`list_assets`, `list_books`) are not aggregates and stay. A cross-account aggregate was built and removed before 0.4.0; do not propose another.
 - **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

+ 7 - 7
Cargo.lock

@@ -1019,7 +1019,7 @@ dependencies = [
 
 [[package]]
 name = "kuatia"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
  "async-trait",
  "ciborium",
@@ -1036,7 +1036,7 @@ dependencies = [
 
 [[package]]
 name = "kuatia-core"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
  "kuatia-types",
  "serde",
@@ -1045,7 +1045,7 @@ dependencies = [
 
 [[package]]
 name = "kuatia-dashboard"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
  "axum",
  "clap",
@@ -1065,7 +1065,7 @@ dependencies = [
 
 [[package]]
 name = "kuatia-money"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
  "serde",
  "serde_json",
@@ -1073,7 +1073,7 @@ dependencies = [
 
 [[package]]
 name = "kuatia-storage"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
  "async-trait",
  "kuatia-types",
@@ -1084,7 +1084,7 @@ dependencies = [
 
 [[package]]
 name = "kuatia-storage-sql"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
  "async-trait",
  "kuatia-storage",
@@ -1099,7 +1099,7 @@ dependencies = [
 
 [[package]]
 name = "kuatia-types"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
  "bitflags",
  "kuatia-money",

+ 6 - 6
Cargo.toml

@@ -3,7 +3,7 @@ resolver = "2"
 members = ["crates/kuatia-money", "crates/kuatia-types", "crates/kuatia-core", "crates/kuatia-storage", "crates/kuatia-storage-sql", "crates/kuatia", "crates/kuatia-dashboard"]
 
 [workspace.package]
-version = "0.3.0"
+version = "0.4.0"
 edition = "2024"
 rust-version = "1.85"
 license = "Apache-2.0"
@@ -14,11 +14,11 @@ categories = ["finance", "database-implementations"]
 
 [workspace.dependencies]
 # Internal crates
-kuatia-money = { path = "crates/kuatia-money", version = "0.3.0" }
-kuatia-types = { path = "crates/kuatia-types", version = "0.3.0" }
-kuatia-core = { path = "crates/kuatia-core", version = "0.3.0" }
-kuatia-storage = { path = "crates/kuatia-storage", version = "0.3.0" }
-kuatia-storage-sql = { path = "crates/kuatia-storage-sql", version = "0.3.0" }
+kuatia-money = { path = "crates/kuatia-money", version = "0.4.0" }
+kuatia-types = { path = "crates/kuatia-types", version = "0.4.0" }
+kuatia-core = { path = "crates/kuatia-core", version = "0.4.0" }
+kuatia-storage = { path = "crates/kuatia-storage", version = "0.4.0" }
+kuatia-storage-sql = { path = "crates/kuatia-storage-sql", version = "0.4.0" }
 
 # External crates
 serde = { version = "1", features = ["derive"] }

+ 5 - 5
crates/kuatia-dashboard/Cargo.toml

@@ -1,9 +1,9 @@
 [package]
 name = "kuatia-dashboard"
-version = "0.3.0"
-edition = "2024"
-rust-version = "1.85"
-license = "Apache-2.0"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+license.workspace = true
 publish = false
 description = "Server-rendered dashboard and REST API for exploring a Kuatia ledger"
 
@@ -12,7 +12,7 @@ name = "kuatia-dashboard"
 path = "src/main.rs"
 
 [dependencies]
-kuatia = { path = "../kuatia", version = "0.3.0" }
+kuatia = { path = "../kuatia", version = "0.4.0" }
 kuatia-core = { workspace = true }
 kuatia-storage = { workspace = true }
 kuatia-storage-sql = { workspace = true, features = ["postgres"] }

+ 109 - 1
crates/kuatia/src/inflight.rs

@@ -19,6 +19,7 @@ use kuatia_core::{
 use kuatia_storage::store::TransferRecord;
 use serde::{Deserialize, Serialize};
 use std::collections::{BTreeMap, BTreeSet};
+use tracing::instrument;
 
 use crate::error::LedgerError;
 use crate::ledger::Ledger;
@@ -128,6 +129,30 @@ impl Ledger {
     /// rejected (its holds already exist), while different trades to the same
     /// destination run concurrently under distinct subaccounts.
     pub async fn authorize(&self, transfer: Transfer) -> Result<Authorization, LedgerError> {
+        self.authorize_inner(transfer, None).await
+    }
+
+    /// Authorize with an expiry: a commit instant in unix milliseconds after
+    /// which [`expire_due`](Self::expire_due) may sweep the holds back to their
+    /// funders.
+    ///
+    /// The expiry is a permission to sweep, not a schedule. Nothing in the
+    /// ledger runs a timer, for the same reason the balance cache does not
+    /// (ADR-0019): a caller decides when to sweep, and an expired hold keeps
+    /// its funds parked until something asks.
+    pub async fn authorize_until(
+        &self,
+        transfer: Transfer,
+        expires_at: i64,
+    ) -> Result<Authorization, LedgerError> {
+        self.authorize_inner(transfer, Some(expires_at)).await
+    }
+
+    async fn authorize_inner(
+        &self,
+        transfer: Transfer,
+        expires_at: Option<i64>,
+    ) -> Result<Authorization, LedgerError> {
         // All holds of this inflight share one subaccount, derived from the
         // submitted trade so it is stable and known before the holds are created
         // (the authorize transfer's own id cannot be used: it is a hash of the
@@ -154,7 +179,10 @@ impl Ledger {
             // overdraft so it can never go negative.
             acct.flags = AccountFlags::INFLIGHT | AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT;
             acct.book = transfer.book;
-            acct.metadata = meta_map(&InflightMeta::Hold { destination: *dest })?;
+            acct.metadata = meta_map(&InflightMeta::Hold {
+                destination: *dest,
+                expires_at,
+            })?;
             match self.create_account(acct).await {
                 Ok(()) => {}
                 Err(LedgerError::AccountAlreadyExists(_)) => {
@@ -371,6 +399,86 @@ impl Ledger {
     }
 
     // -----------------------------------------------------------------------
+    // Expiry
+    // -----------------------------------------------------------------------
+
+    /// Void one inflight if its holds have expired by `now`, a commit instant
+    /// in unix milliseconds.
+    ///
+    /// Settles through [`void`](Self::void), so an expiry returns funds by
+    /// exactly the route a caller's own void would, including the partial case:
+    /// what was confirmed stays, what is still held goes back to its funders.
+    /// Returns no receipts when the inflight has no expiry, has not reached it,
+    /// or is already drained, so a sweep can call it without checking first.
+    #[instrument(skip(self), name = "ledger.expire")]
+    pub async fn expire(
+        &self,
+        inflight: &TransferId,
+        now: i64,
+    ) -> Result<Vec<Receipt>, LedgerError> {
+        let (_, legs) = self.load_inflight(inflight).await?;
+        let mut due = false;
+        for hold in legs.iter().map(|l| l.hold) {
+            if self.hold_expiry(&hold).await?.is_some_and(|at| at <= now) {
+                due = true;
+                break;
+            }
+        }
+        if !due {
+            return Ok(Vec::new());
+        }
+        self.void(inflight).await
+    }
+
+    /// Sweep every open hold whose expiry has passed, voiding the inflights
+    /// they belong to, and report which ones were voided.
+    ///
+    /// Reads the expiry off the holding accounts, which is why it lives there:
+    /// the filter costs one account read per open hold and no transfer parsing.
+    /// Only the holds that are actually due pay for the history read that finds
+    /// their inflight.
+    #[instrument(skip(self), name = "ledger.expire_due")]
+    pub async fn expire_due(&self, now: i64) -> Result<Vec<TransferId>, LedgerError> {
+        let mut voided = Vec::new();
+        for hold in self.list_open_inflights().await? {
+            if !self.hold_expiry(&hold).await?.is_some_and(|at| at <= now) {
+                continue;
+            }
+            let Some(inflight) = self.inflight_of_hold(&hold).await? else {
+                continue;
+            };
+            if voided.contains(&inflight) {
+                continue; // another hold of the same inflight already swept it
+            }
+            self.void(&inflight).await?;
+            voided.push(inflight);
+        }
+        Ok(voided)
+    }
+
+    /// The expiry stamped on a holding account, if it has one.
+    async fn hold_expiry(&self, hold: &AccountId) -> Result<Option<i64>, LedgerError> {
+        let account = self.get_account(hold).await?;
+        match read_meta(&account.metadata) {
+            Some(InflightMeta::Hold { expires_at, .. }) => Ok(expires_at),
+            _ => Ok(None),
+        }
+    }
+
+    /// The inflight a holding account belongs to, found by the authorize
+    /// transfer in its history. The hold is created before that transfer is
+    /// committed, so its id cannot be stamped on the account and has to be read
+    /// back from the one record that carries the leg table.
+    async fn inflight_of_hold(&self, hold: &AccountId) -> Result<Option<TransferId>, LedgerError> {
+        for record in self.history(hold).await? {
+            if let Some(InflightMeta::Authorize { .. }) = read_meta(record.envelope.metadata()) {
+                return Ok(Some(record.receipt.transfer_id));
+            }
+        }
+        Ok(None)
+    }
+
+    // -----------------------------------------------------------------------
     // Internal helpers
     // -----------------------------------------------------------------------
 

+ 8 - 2
crates/kuatia/src/inflight/projection.rs

@@ -37,8 +37,14 @@ pub(super) const K_INFLIGHT: &str = "inflight";
 pub(super) enum InflightMeta {
     /// Tags the authorize transfer and carries its leg table.
     Authorize { legs: Vec<InflightLeg> },
-    /// Tags a per-destination holding subaccount.
-    Hold { destination: AccountId },
+    /// Tags a per-destination holding subaccount, with the instant after which
+    /// the hold may be swept. The expiry lives here rather than on the
+    /// authorize transfer because a sweep starts from the open holds, and
+    /// because account metadata is written once and never drifts.
+    Hold {
+        destination: AccountId,
+        expires_at: Option<i64>,
+    },
     /// Tags a settling transfer that delivers to a destination.
     Confirm {
         tx: TransferId,

+ 9 - 4
crates/kuatia/src/ledger/asset.rs

@@ -16,12 +16,17 @@ use crate::error::LedgerError;
 const MINT_ATTEMPTS: usize = 8;
 
 /// Ids for assets come from the same generator accounts and books use, folded
-/// into the `u32` an [`AssetId`] carries. The high bit is cleared by the
-/// generator, so the fold keeps the counter and the low timestamp bits, which
-/// is what makes two registrations in one process differ.
+/// into the `u32` an [`AssetId`] carries. The fold keeps the counter and the
+/// low timestamp bits, which is what makes two registrations in one process
+/// differ.
+///
+/// Masked to 31 bits because the `asset` columns are a 4-byte signed integer:
+/// an id above that range still round-trips, since the bind and the read cast
+/// the same way, but it sits in the table as a negative number, which is a trap
+/// for anything that later reads the column as a magnitude.
 fn next_asset_id() -> u32 {
     static IDS: AutoId = AutoId::new();
-    IDS.next() as u32
+    (IDS.next() as u32) & 0x7fff_ffff
 }
 
 impl Ledger {

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

@@ -351,6 +351,21 @@ impl Ledger {
         Ok(result)
     }
 
+    /// Everything one account holds, one entry per asset it has a live posting
+    /// of. Reads the registry for the asset list, so an asset nobody holds does
+    /// not appear.
+    #[instrument(skip(self), name = "ledger.holdings")]
+    pub async fn holdings(&self, account: &AccountId) -> Result<Vec<Amount>, LedgerError> {
+        let mut out = Vec::new();
+        for asset in self.list_assets().await? {
+            let amount = self.balance_exact_of(account, &asset.id).await?;
+            if !amount.is_zero() {
+                out.push(amount);
+            }
+        }
+        Ok(out)
+    }
+
     /// List the non-closed subaccounts of a base account.
     ///
     /// This scans every account row and filters in memory, so it pays for

+ 84 - 0
crates/kuatia/tests/inflight.rs

@@ -409,3 +409,87 @@ async fn balances_are_segregated_by_subaccount() {
     assert_eq!(only_main.len(), 1);
     assert_eq!(only_main[0].account.sub, 0);
 }
+
+// ---------------------------------------------------------------------------
+// Expiry
+// ---------------------------------------------------------------------------
+
+/// An authorization with no expiry is never swept, however late the sweep runs.
+#[tokio::test]
+async fn a_hold_without_an_expiry_is_never_swept() {
+    let ledger = setup().await;
+    let auth = ledger.authorize(trade()).await.unwrap();
+
+    assert!(ledger.expire_due(i64::MAX).await.unwrap().is_empty());
+    assert!(
+        ledger
+            .expire(&auth.inflight, i64::MAX)
+            .await
+            .unwrap()
+            .is_empty()
+    );
+    assert_eq!(bal(&ledger, a(), eur()).await, 0, "funds are still held");
+}
+
+/// An expiry in the future is a permission, not a schedule: nothing moves until
+/// the sweep runs with a clock past it.
+#[tokio::test]
+async fn a_hold_is_swept_only_once_its_expiry_has_passed() {
+    let ledger = setup().await;
+    let auth = ledger.authorize_until(trade(), 5_000).await.unwrap();
+
+    assert!(ledger.expire_due(4_999).await.unwrap().is_empty());
+    assert_eq!(bal(&ledger, a(), eur()).await, 0);
+
+    let swept = ledger.expire_due(5_000).await.unwrap();
+    assert_eq!(swept, vec![auth.inflight], "the inflight is reported once");
+
+    // The funders have their money back, exactly as a void returns it.
+    assert_eq!(bal(&ledger, a(), eur()).await, 100);
+    assert_eq!(bal(&ledger, b(), btc()).await, 10);
+    assert_eq!(bal(&ledger, a(), btc()).await, 1);
+    assert_eq!(bal(&ledger, b(), eur()).await, 1);
+}
+
+/// A partially confirmed authorization expires only what is still held. What
+/// was delivered stays delivered.
+#[tokio::test]
+async fn expiry_returns_the_remainder_and_leaves_confirmations() {
+    let ledger = setup().await;
+    let auth = ledger.authorize_until(trade(), 1_000).await.unwrap();
+
+    let part = TransferBuilder::new()
+        .pay(a(), b(), money(eur(), 40))
+        .build()
+        .unwrap();
+    ledger.confirm(&auth.inflight, part).await.unwrap();
+
+    assert_eq!(ledger.expire_due(1_000).await.unwrap(), vec![auth.inflight]);
+
+    // B put its own 1 EUR into the fee hold at authorize and that leg was never
+    // confirmed, so the sweep returns it: 40 delivered plus the 1 back.
+    assert_eq!(bal(&ledger, b(), eur()).await, 41);
+    assert_eq!(
+        bal(&ledger, a(), eur()).await,
+        60,
+        "the remainder came back"
+    );
+    assert_eq!(
+        bal(&ledger, fee(), eur()).await,
+        0,
+        "nothing settled to the fee"
+    );
+}
+
+/// Sweeping twice is not an error and moves nothing the second time: the holds
+/// are drained and closed, so there is no inflight left to find.
+#[tokio::test]
+async fn sweeping_twice_moves_nothing_the_second_time() {
+    let ledger = setup().await;
+    ledger.authorize_until(trade(), 1).await.unwrap();
+
+    assert_eq!(ledger.expire_due(10).await.unwrap().len(), 1);
+    let before = bal(&ledger, a(), eur()).await;
+    assert!(ledger.expire_due(10).await.unwrap().is_empty());
+    assert_eq!(bal(&ledger, a(), eur()).await, before);
+}

+ 75 - 0
crates/kuatia/tests/integration.rs

@@ -1614,3 +1614,78 @@ async fn redefining_an_asset_is_refused() {
         2
     );
 }
+
+/// A minted asset id fits a signed 4-byte column, which is what the `asset`
+/// columns are. An unmasked fold would store half of them as negative numbers.
+#[tokio::test]
+async fn minted_asset_ids_are_positive() {
+    let ledger = bare_ledger();
+    for n in 0..256 {
+        let asset = ledger.asset(format!("A{n}"), "?", 2).await.unwrap();
+        assert!(
+            asset.id.0 <= i32::MAX as u32,
+            "minted id {} does not fit a signed 4-byte column",
+            asset.id.0
+        );
+    }
+    assert_eq!(ledger.list_assets().await.unwrap().len(), 256);
+}
+
+/// Conservation nets to zero in each asset, read one account at a time.
+///
+/// Value inside the ledger is mirrored by the offset postings that brought it
+/// in, so the accounts in play net to zero. Summed from per-account reads
+/// because that is the only balance read there is (ADR-0031), which also means
+/// a missing account makes the total non-zero rather than quietly shrinking it.
+#[tokio::test]
+async fn conservation_nets_to_zero_across_the_accounts_in_play() {
+    let ledger = setup_ledger().await;
+
+    deposit(&ledger, account(1), usd(), 1000, external()).await;
+    deposit(&ledger, account(2), eur(), 500, external()).await;
+    pay(&ledger, account(1), account(2), usd(), 250).await;
+    pay(&ledger, account(2), account(3), usd(), 50).await;
+
+    let involved = [account(1), account(2), account(3), external()];
+    for asset in [usd(), eur()] {
+        let mut total = 0i128;
+        for id in &involved {
+            total += ledger.balance_exact(id, asset).await.unwrap().minor_units();
+        }
+        assert_eq!(total, 0, "{asset:?} did not net to zero");
+    }
+
+    // The external boundary holds the negative side of the USD deposit.
+    assert_eq!(
+        ledger
+            .balance_exact(&external(), usd())
+            .await
+            .unwrap()
+            .minor_units(),
+        -1000
+    );
+}
+
+/// What one account holds, across every registered asset, skipping the assets
+/// it has no live posting of.
+#[tokio::test]
+async fn holdings_lists_every_asset_an_account_holds() {
+    let ledger = setup_ledger().await;
+    deposit(&ledger, account(1), usd(), 1000, external()).await;
+
+    let one = ledger.holdings(&account(1)).await.unwrap();
+    assert_eq!(one.len(), 1, "account 1 holds only USD");
+    assert_eq!(one[0].asset_id(), usd());
+    assert_eq!(one[0].minor_units(), 1000);
+
+    deposit(&ledger, account(1), eur(), 25, external()).await;
+    let two = ledger.holdings(&account(1)).await.unwrap();
+    assert_eq!(two.len(), 2);
+    assert_eq!(
+        two.iter().map(|a| a.minor_units()).sum::<i128>(),
+        1025,
+        "both holdings are reported"
+    );
+
+    assert!(ledger.holdings(&account(3)).await.unwrap().is_empty());
+}

+ 1 - 0
doc/SUMMARY.md

@@ -63,4 +63,5 @@
   - [0028: An amount carries its asset, and the ledger owns the asset registry](adr/0028-amount-carries-its-asset.md)
   - [0029: Stored amounts, and a public surface that never names `Cent`](adr/0029-stored-amounts-and-a-closed-money-surface.md)
   - [0030: An asset is named by its code, and the ledger mints its id](adr/0030-assets-named-by-code.md)
+  - [0031: Every read is account scoped: no aggregate crosses accounts](adr/0031-every-read-is-account-scoped.md)
   - [ADR template](adr/template.md)

+ 106 - 0
doc/adr/0031-every-read-is-account-scoped.md

@@ -0,0 +1,106 @@
+# Every read is account scoped: no aggregate crosses accounts
+
+* Status: accepted
+* Authors: Cesar Rodas
+* Date: 2026-12-02
+* Targeted modules: `kuatia-storage` (`PostingStore`), `kuatia-storage-sql`
+  (`posting`), `kuatia` (`ledger::balance`)
+* Associated tickets/PRs: N/A
+
+## Context and Problem Statement
+
+The asset registry (ADR-0030) gave a caller the asset list a trial balance needs to iterate, and the roadmap had wanted one since 0.2.0. It was built: `Ledger::trial_balance(asset)` over a new `PostingStore::live_balances(asset)`, one grouped aggregate per asset over the live set, returning every account holding it.
+
+The read is keyed by an asset. Every other read on the ledger is keyed by an account: `live_balance(account, asset)`, `get_postings_by_account(id, sub, ..)`, and `PostingQuery.account`, which is a plain `i64` and not an option. The trial balance was the first read that asked the store a question no account bounds.
+
+Its cost shows why that matters. The only index on the live table is `idx_live_owner(owner, subaccount, asset)`, so a filter on `asset` alone cannot seek it. Measured on a populated SQLite database:
+
+```
+SCAN live_postings USING COVERING INDEX idx_live_owner      -- live_balances(asset)
+SEARCH live_postings USING COVERING INDEX idx_live_owner    -- live_balance(account, asset)
+        (owner=? AND subaccount=? AND asset=?)
+```
+
+One read reads the whole live set, including the postings of every other asset. The other seeks. An index starting with `asset` would fix the second half of that, which is what made the question worth asking rather than answering with a migration.
+
+## Decision Drivers
+
+* An account-scoped read can be routed to the shard that holds the account. A cross-account aggregate has to fan out to every shard, so having one in the public API forecloses splitting the store later.
+* A read's cost should be bounded by one account's data. A cross-account aggregate has no bound: it gets slower every day the ledger runs, in the hot path of whatever asked for it.
+* Aggregating across accounts is reporting, and reporting can be cached, scheduled and denormalized off the event stream (ADR-0010). Inside the ledger it can do none of those things and runs against the write path's tables.
+* An exact aggregate in the database is permitted (ADR-0024), so the rule cannot come from arithmetic safety. This is about which questions the store answers, not how it adds up.
+
+## Considered Options
+
+#### Keep it, and add an asset-first index
+
+A migration adding `(asset, owner, subaccount)` turns the scan into a range seek.
+
+**Pros:**
+
+* Good, because the measured cost problem goes away, and the trial balance is a feature a ledger is expected to have.
+
+**Cons:**
+
+* Bad, because it fixes only the cost. The fan-out across shards and the coupling to the write path's tables are unchanged.
+* Bad, because it adds an index to the hottest table in the system to serve a read nothing on the commit path makes.
+
+#### Keep it behind a feature flag or a documented warning
+
+**Pros:**
+
+* Good, because a caller who has measured their own ledger can opt in.
+
+**Cons:**
+
+* Bad, because a published method is a published method: it will be called, and the cost lands on whoever called it rather than whoever enabled it.
+
+#### No read aggregates value across accounts (chosen)
+
+**Pros:**
+
+* Good, because every read keeps a shard key, so the store can be split by account without changing the API.
+* Good, because a read's cost stays proportional to one account, which is the only bound that does not grow with the ledger.
+* Good, because it is one rule that answers the next proposal of this shape without re-deriving the argument.
+
+**Cons:**
+
+* Bad, because a trial balance, a balance sheet and a P&L are the reports an accounting system is asked for, and the library now answers none of them.
+* Bad, because an application that wants one has to enumerate its own accounts, and only it knows that list.
+
+## Decision Outcome
+
+Chosen option: **no read aggregates value across accounts**. `Ledger::trial_balance` and `PostingStore::live_balances` are removed before 0.4.0 is tagged, so neither was ever published.
+
+The line is about aggregating value, not about touching more than one row:
+
+| Shape | Allowed | Why |
+|---|---|---|
+| `balance`, `balance_exact`, `balance_as_of`, `balances`, `holdings` | yes | Each is bounded by one account. `holdings` loops the asset registry, which is small and bounded, for one account. |
+| `live_balance(account, asset)` | yes | The one aggregate in the store, bounded by an account and seeking its index. |
+| An aggregate keyed by asset, book, flag or time | no | No shard key, and the cost grows with the ledger. |
+| `list_accounts`, `query_transfers` with `account: None` | yes, as they are | They enumerate rows without folding value, and the transfer query is paginated. Pre-existing; this ADR does not widen them. |
+| `list_assets`, `list_books`, `get_asset_by_code` | yes | Definitions, not value. |
+| `expire_due(now)` | yes | It walks holds the ledger created as subaccounts of their destinations (ADR-0014), settling each through `void`. It reads no aggregate. |
+
+Per-asset conservation is still tested, from per-account reads over the accounts a test creates, which is the same invariant and fails the same way if a row goes missing.
+
+### Positive Consequences
+
+* Every read in the public API carries an account, so the store can be sharded on it.
+* The hot live table needs no second index, and no read scans it.
+* The next cross-account report has an answer to point at instead of an argument to repeat.
+
+### Negative Consequences
+
+* The library answers no cross-account question, so a trial balance, a balance sheet and a P&L are all the application's to build.
+* An application building one enumerates accounts itself and pays a read per account. That is the cost this ADR moves rather than removes, and it moves it somewhere it can be cached.
+* The roadmap item that asked for a trial balance is closed as ruled out rather than done, after the feature was built and removed.
+
+## Links
+
+* The asset registry that unblocked the trial balance: [ADR-0030](0030-assets-named-by-code.md).
+* Exact aggregation is permitted and is not what this restricts: [ADR-0024](0024-native-money-columns.md).
+* Where a cross-account report belongs instead: the derived event stream, [ADR-0010](0010-event-stream-vs-transfer-log.md).
+* Holds as subaccounts, which is why the expiry sweep is account scoped: [ADR-0014](0014-inflight-holds-via-holding-accounts.md).
+* Conservation per asset, the invariant the removed test checked: [ADR-0001](0001-modified-utxo-signed-postings.md).

+ 1 - 0
doc/adr/README.md

@@ -40,6 +40,7 @@ to reverse a decision. Instead, a new ADR supersedes it.
 | [0028](0028-amount-carries-its-asset.md) | An amount carries its asset, and the ledger owns the asset registry | accepted | `Amount { asset: Arc<Asset>, value: Cent }` is what the public API takes and returns, so two assets cannot be added by a caller holding two balances. A registered `Asset` carries the precision a written amount parses at, which retires ADR-0009's accepted gap; its old presentation-only `Amount` becomes `Scale`. `Arc<Asset>` stops at the public surface, so nothing stored and no content address moves. Refines 0009; follows 0026. |
 | [0029](0029-stored-amounts-and-a-closed-money-surface.md) | Stored amounts, and a public surface that never names `Cent` | accepted | An amount's serialized form carries its asset, so `Movement`, `Posting`, `NewPosting` and `BalanceProjection` each hold one amount and decode with no registry. The content address still hashes the asset id and the value, proved by a golden vector. The column tables keep the integer and the id for ADR-0024's sums and left-join the registry to rebuild an amount. `Cent` leaves the public surface entirely, reachable only through `kuatia_types::internals`. Supersedes 0028's point 3. |
 | [0030](0030-assets-named-by-code.md) | An asset is named by its code, and the ledger mints its id | accepted | `ledger.asset("EUR", "€", 2)` registers on first sight and returns the handle, so a caller states the code, symbol and precision and never invents an id. A code is unique (migration 015) and one registered at another precision is refused rather than resolved. Supersedes ADR-0028's caller-supplied-id clause. |
+| [0031](0031-every-read-is-account-scoped.md) | Every read is account scoped: no aggregate crosses accounts | accepted | No read folds value across accounts, so every read keeps a shard key and a cost bounded by one account. `Ledger::trial_balance` and `PostingStore::live_balances` are removed before they were ever published; cross-account reporting belongs off the event stream. Row enumerations and registry reads are unaffected. |
 
 ## Recommended future ADRs
 

+ 22 - 1
doc/inflight.md

@@ -48,6 +48,7 @@ stateDiagram-v2
     Held --> Held: confirm (partial)
     Held --> Confirmed: confirm_all / drained
     Held --> Voided: void
+    Held --> Voided: expire (past its expiry)
     Confirmed --> [*]
     Voided --> [*]
 ```
@@ -89,6 +90,15 @@ let status = ledger.inflight_status(&auth.inflight).await?;
 
 // The holding accounts of every open inflight.
 let open = ledger.list_open_inflights().await?;
+
+// Authorize with a deadline, as unix milliseconds.
+let auth = ledger.authorize_until(trade, 1_767_225_600_000).await?;
+
+// Void one inflight if its expiry has passed. Nothing happens if it has not.
+ledger.expire(&auth.inflight, now_ms).await?;
+
+// Sweep every open hold whose expiry has passed, and report what was voided.
+let voided = ledger.expire_due(now_ms).await?;
 ```
 
 `authorize` returns an `Authorization { inflight, receipt, legs }`. The
@@ -134,10 +144,21 @@ summed.
   restricts participation by flag or account, it must admit the holds (for
   example by allowing the `INFLIGHT` flag).
 
+## Expiry
+
+An authorization with no expiry holds its funds until a caller settles it, which parks money indefinitely if the caller never comes back. `authorize_until` records a deadline on each holding account at creation, as unix milliseconds, and `authorize` is the same call with none.
+
+- **The deadline is on the hold, not in a timer.** It is written into the holding account's metadata, which is create-only, so it cannot drift after the fact. `list_open_inflights` already returns exactly those accounts, so a sweep reads no transfer bodies.
+- **Nothing expires on its own.** `expire_due(now)` is a method a caller schedules, the same way the balance projection refuses to own a timer ([adr/0019-cached-balance-projection.md](adr/0019-cached-balance-projection.md)). Passing the clock in also makes the behaviour testable without waiting.
+- **Expiry is a void.** It runs the existing `void` path, so there is one settlement route: funds return to the recorded funders, a partially confirmed hold returns only its remainder, and what was confirmed stays delivered.
+- **A sweep is idempotent.** Voiding drains and closes the holds, so the inflight is no longer open and a second sweep finds nothing. `expire` on an inflight that is already settled returns no receipts rather than an error.
+
+An expired hold is reported once per inflight, not once per leg, even when several legs of one authorization share the deadline.
+
 ## Where it lives
 
 - `crates/kuatia/src/inflight.rs` — the API and metadata schema.
 - `crates/kuatia/tests/inflight.rs` — authorize, confirm, partial confirm, void,
   over-confirm rejection, concurrent inflights per account, segregated balances,
-  and status tests.
+  status, and expiry tests.
 - `AccountFlags::INFLIGHT` — `crates/kuatia-types/src/lib.rs`.