Quellcode durchsuchen

Answer the tenancy and account-class questions, and add an as-of balance

A review asked whether a book is a tenant boundary and whether an account
carries an accounting class. Both answers were inferable from the code and
stated nowhere, and the docs disagreed with themselves on the first: the
glossary recommended a book per tenant while four other pages said a book
partitions nothing.

A book cannot isolate a tenant. Balances are global, no read is restricted by
book, and a transfer naming the default book when no such book is stored
commits with no policy applied, so a caller is never held inside one.
Isolation is a store per tenant instead.

An account has no asset, liability, equity, income or expense dimension. That
blocks the balance sheet and the profit-and-loss statement, and nothing else:
a trial balance is a flat per-account list, so it waits on a read across
accounts rather than on a class.

A past balance cannot come from the postings, which carry no timestamp, so
balance_as_of folds the transfers committed up to its cutoff onto the newest
cache point at or before it. It stays a separate method because the everyday
read must keep its open upper bound. A commit stamped slightly ahead by a
skewed clock would otherwise drop out of the cached read while the live sum
still counted it, which is the disagreement the projection tests exist to
catch. The cutoff is commit time, because the cache points a read folds
against are watermarked by the commit clock.
C vor 1 Woche
Ursprung
Commit
7a4a906ce9

+ 9 - 0
CHANGELOG.md

@@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ### Added
 
+- `Ledger::balance_as_of(account, asset, as_of)`, the balance as it stood at a
+  past commit instant: the newest cache point at or before `as_of` plus the
+  transfers committed up to it. `as_of` is commit time in unix milliseconds and
+  never a value date, because the cache points a read folds against are
+  watermarked by the commit clock. A past balance cannot be taken from the
+  postings, which carry no timestamp, so the read folds transfers; with no cache
+  point below `as_of` it folds the whole history up to it. An as-of read appends
+  no cache point. No new storage method and no decision of its own: the storage
+  lookup already took an `as_of` (ADR-0019).
 - `TransferBuilder::value_date(..)` and the `ValueDate` calendar-day type, for an
   entry booked on a different day than it belongs to: a correction, a late
   settlement, a future-dated order. `TransferQuery` gains `from_value_date` and

+ 5 - 3
crates/kuatia-types/src/book.rs

@@ -5,9 +5,11 @@ use crate::ids::{AccountId, AssetId, BookId};
 use serde::{Deserialize, Serialize};
 
 /// A Book is a transfer policy scope: it gates which accounts and assets may
-/// participate in a transfer. It is **not** the chronological entry log (the
-/// transfer log plays that role), and it does **not** partition balances —
-/// balances are global; a Book only gates participation.
+/// participate in a transfer. It is not the chronological entry log (the
+/// transfer log plays that role), it does not partition balances, and it is not
+/// a tenancy boundary: balances are global, no read is restricted by book, and a
+/// transfer naming [`DEFAULT_BOOK`](crate::DEFAULT_BOOK) with no such book
+/// stored commits with no policy applied.
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct Book {
     /// Stable identity for this book.

+ 43 - 1
crates/kuatia/src/ledger/balance.rs

@@ -9,7 +9,9 @@
 //!   projector folds into snapshots, and what reconciliation checks against.
 //! - [`balance`](Ledger::balance) is the **everyday read**: the closest cache
 //!   point (at or before now) plus the folded tail of transfers committed after
-//!   its watermark.
+//!   its watermark. [`balance_as_of`](Ledger::balance_as_of) is that same read
+//!   bounded above by a past commit instant, which no live-posting sum can
+//!   answer because a posting carries no timestamp.
 //!
 //! The module's core contract: summing every one of an account's transfer deltas
 //! equals its live-posting sum, so **`balance` always equals `balance_exact` at
@@ -233,6 +235,46 @@ impl Ledger {
         }
     }
 
+    /// The balance as it stood at `as_of`, a commit instant in unix
+    /// milliseconds: the closest cache point at or before `as_of`, plus the tail
+    /// of transfers committed after that point's watermark and up to `as_of`
+    /// (ADR-0019).
+    ///
+    /// `as_of` is commit time and never the value date, because the cache points
+    /// a read folds against are watermarked by the commit clock.
+    ///
+    /// With no cache point at or before `as_of`, this folds the whole history up
+    /// to it instead of taking the live-posting sum that
+    /// [`balance`](Ledger::balance) falls back on: a posting carries no
+    /// timestamp, so that sum is always "now". It also appends no cache point,
+    /// since a new one's watermark comes from the current clock and would
+    /// describe a window this read never looked at.
+    #[instrument(skip(self), name = "ledger.balance_as_of")]
+    pub async fn balance_as_of(
+        &self,
+        account: &AccountId,
+        asset: &AssetId,
+        as_of: i64,
+    ) -> Result<Cent, LedgerError> {
+        let closest = self
+            .store
+            .get_closest_balance_projection(account, asset, as_of)
+            .await?;
+        let from_ts = closest.as_ref().map(|p| p.watermark.saturating_add(1));
+        let (tail, _) = fold_tail(
+            self.store(),
+            account,
+            asset,
+            from_ts,
+            Some(as_of.saturating_add(1)),
+        )
+        .await?;
+        match closest {
+            Some(p) => Ok(p.balance.checked_add(tail)?),
+            None => Ok(tail),
+        }
+    }
+
     /// Report the per-subaccount balances of a base account for one asset.
     ///
     /// One entry per non-closed subaccount, each read through the everyday cached

+ 183 - 0
crates/kuatia/tests/projection.rs

@@ -480,3 +480,186 @@ async fn projection_matches_under_concurrent_commits() {
 
     assert_projection_matches(&ledger, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 99]).await;
 }
+
+/// An as-of read is bounded above by `as_of`: with no cache point anywhere, it
+/// folds the history up to that instant and the later commits are simply absent.
+/// Each batch is separated by a real millisecond, since two commits inside one
+/// millisecond share a stamp and would make the boundary ambiguous.
+#[tokio::test]
+async fn balance_as_of_excludes_later_commits() {
+    let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    no_overdraft(&ledger, 1).await;
+    no_overdraft(&ledger, 2).await;
+    overdraft(&ledger, 99).await;
+
+    deposit(&ledger, 1, 1000).await;
+    pay(&ledger, 1, 2, 250).await;
+
+    let as_of = unix_millis_now();
+    tokio::time::sleep(std::time::Duration::from_millis(3)).await;
+    deposit(&ledger, 1, 500).await;
+
+    assert_eq!(
+        ledger
+            .balance_as_of(&account(1), &usd(), as_of)
+            .await
+            .unwrap(),
+        Cent::from(750),
+        "the as-of read picked up a transfer committed after it"
+    );
+    assert_eq!(
+        ledger.balance(&account(1), &usd()).await.unwrap(),
+        Cent::from(1250)
+    );
+}
+
+/// The as-of read takes the closest cache point at or before `as_of` and folds
+/// only the window between that point's watermark and `as_of`, so the two
+/// derivations (pinned snapshot plus bounded tail, and the hand-computed total)
+/// agree while later commits stay out. The `assert_ne!` guards the test itself:
+/// a snapshot that already held the as-of balance would leave the tail empty and
+/// quietly degrade this to a case the other tests cover.
+#[tokio::test]
+async fn balance_as_of_folds_a_bounded_tail_onto_its_cache_point() {
+    let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    no_overdraft(&ledger, 1).await;
+    no_overdraft(&ledger, 2).await;
+    overdraft(&ledger, 99).await;
+
+    deposit(&ledger, 1, 1000).await;
+    pay(&ledger, 1, 2, 250).await;
+
+    let snapshot = ledger.balance_exact(&account(1), &usd()).await.unwrap();
+    let watermark = unix_millis_now();
+    ledger
+        .store()
+        .append_balance_projection(&account(1), &usd(), snapshot, watermark)
+        .await
+        .unwrap();
+
+    tokio::time::sleep(std::time::Duration::from_millis(3)).await;
+    deposit(&ledger, 1, 500).await;
+
+    let as_of = unix_millis_now();
+    tokio::time::sleep(std::time::Duration::from_millis(3)).await;
+    deposit(&ledger, 1, 300).await;
+
+    assert_eq!(
+        ledger
+            .balance_as_of(&account(1), &usd(), as_of)
+            .await
+            .unwrap(),
+        Cent::from(1250),
+        "snapshot plus bounded tail diverged from the total at as_of"
+    );
+    assert_eq!(
+        ledger.balance(&account(1), &usd()).await.unwrap(),
+        Cent::from(1550)
+    );
+    assert_ne!(
+        snapshot,
+        Cent::from(1250),
+        "the snapshot already held the as-of balance; the tail was empty"
+    );
+}
+
+/// A cache point whose watermark is above `as_of` covers transfers the read must
+/// not see, so the read falls back to the history below `as_of` instead.
+#[tokio::test]
+async fn balance_as_of_ignores_a_cache_point_above_it() {
+    let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    no_overdraft(&ledger, 1).await;
+    no_overdraft(&ledger, 2).await;
+    overdraft(&ledger, 99).await;
+
+    deposit(&ledger, 1, 1000).await;
+    pay(&ledger, 1, 2, 250).await;
+
+    let as_of = unix_millis_now();
+    tokio::time::sleep(std::time::Duration::from_millis(3)).await;
+    deposit(&ledger, 1, 500).await;
+
+    let full = ledger.balance_exact(&account(1), &usd()).await.unwrap();
+    ledger
+        .store()
+        .append_balance_projection(&account(1), &usd(), full, unix_millis_now())
+        .await
+        .unwrap();
+
+    assert_eq!(
+        ledger
+            .balance_as_of(&account(1), &usd(), as_of)
+            .await
+            .unwrap(),
+        Cent::from(750),
+        "the as-of read used a cache point covering later commits"
+    );
+    assert_eq!(ledger.balance(&account(1), &usd()).await.unwrap(), full);
+}
+
+/// An as-of read appends no cache point, even past the interval that makes the
+/// everyday read append one: a new point's watermark comes from the current
+/// clock, so it would describe a window the as-of read never looked at.
+#[tokio::test]
+async fn balance_as_of_appends_no_cache_point() {
+    let ledger = Arc::new(Ledger::new(InMemoryStore::new()).with_projection_config(
+        ProjectionConfig {
+            grace_ms: 0,
+            snapshot_interval: 1,
+        },
+    ));
+    no_overdraft(&ledger, 1).await;
+    no_overdraft(&ledger, 2).await;
+    overdraft(&ledger, 99).await;
+
+    deposit(&ledger, 1, 1000).await;
+    pay(&ledger, 1, 2, 250).await;
+
+    let _ = ledger
+        .balance_as_of(&account(1), &usd(), unix_millis_now())
+        .await
+        .unwrap();
+
+    for _ in 0..1000 {
+        tokio::task::yield_now().await;
+    }
+    assert!(
+        ledger
+            .store()
+            .get_closest_balance_projection(&account(1), &usd(), i64::MAX)
+            .await
+            .unwrap()
+            .is_none(),
+        "an as-of read appended a cache point"
+    );
+}
+
+/// Both ends of the history: before the first commit an account holds nothing,
+/// and an `as_of` past every commit is the everyday balance.
+#[tokio::test]
+async fn balance_as_of_outside_the_committed_history() {
+    let ledger = Arc::new(Ledger::new(InMemoryStore::new()));
+    no_overdraft(&ledger, 1).await;
+    no_overdraft(&ledger, 2).await;
+    overdraft(&ledger, 99).await;
+
+    let before = unix_millis_now();
+    tokio::time::sleep(std::time::Duration::from_millis(3)).await;
+    deposit(&ledger, 1, 1000).await;
+    pay(&ledger, 1, 2, 250).await;
+
+    assert_eq!(
+        ledger
+            .balance_as_of(&account(1), &usd(), before)
+            .await
+            .unwrap(),
+        Cent::from(0)
+    );
+    assert_eq!(
+        ledger
+            .balance_as_of(&account(1), &usd(), i64::MAX)
+            .await
+            .unwrap(),
+        ledger.balance(&account(1), &usd()).await.unwrap()
+    );
+}

+ 4 - 1
doc/accounting-mapping.md

@@ -34,6 +34,7 @@ scope, not the accounting journal.
 | **Posting a transaction** (the verb) | **resolve + commit** (`Transfer` → `Envelope` → apply) | Confusing collision: in Kuatia a *posting* is a noun (a value fragment), not the act of recording. |
 | **Accounting book** | *no direct equivalent unless modeled separately* | Kuatia `Book` is **not** this. |
 | **Transfer policy scope** | **`Book`** | Gates which accounts/assets may participate. See [below](#where-book-fits-and-doesnt). |
+| **Chart of accounts** (accounts grouped by class) | *no equivalent* | An account carries no asset/liability/equity/income/expense dimension. See [accounts carry no accounting class](accounts.md#accounts-carry-no-accounting-class). |
 
 > A journal entry is one committed accounting event. In many accounting
 > texts this event is also called a transaction, a word that is overloaded
@@ -146,7 +147,8 @@ transfer (`BookPolicy { allowed_assets, allowed_flags, allowed_accounts }`).
 It is explicitly not:
 - the journal (that is the transfer log),
 - a journal entry (that is a `Transfer`/`Envelope`),
-- a balance partition (balances are global; a Book only gates participation).
+- a balance partition (balances are global; a Book only gates participation),
+- a tenant boundary (see [books are not a tenancy boundary](glossary.md#books-are-not-a-tenancy-boundary)).
 
 > Despite the name, a Kuatia `Book` must not be confused with an accounting
 > book. The accounting journal is the transfer log; `Book` is purely a policy
@@ -167,6 +169,7 @@ See the [glossary](glossary.md#book) for the Book model and worked examples.
 | Posting a transaction (verb) | Resolve + commit | Avoid confusion: Kuatia `Posting` is a noun. |
 | Accounting book | No direct equivalent unless modeled separately | Kuatia `Book` is not this. |
 | Transfer policy scope | `Book` | Gates allowed accounts/assets. |
+| Chart of accounts | No equivalent | An account carries no class; a class lives in metadata or a user flag bit. |
 | Proof a txn was recorded | `Receipt { transfer_id }` | Content-addressed `TransferId`. |
 | Lifecycle notifications | Event log (`LedgerEvent`) | Separate from the transfer log. |
 

+ 10 - 0
doc/accounts.md

@@ -167,6 +167,8 @@ balance(account, asset) = sum(p.value for p in postings
 There is no stored balance field. This eliminates drift between the balance
 and the underlying postings.
 
+`balance_as_of(account, asset, as_of)` answers the same question at a past instant, by folding only the transfers committed up to `as_of` onto the newest cache point at or before it (ADR-0019). `as_of` is a commit instant in unix milliseconds, not a value date: the cache points a read folds against are watermarked by the commit clock, so an entry backdated with a [value date](transfers.md#booking-date-and-value-date) still lands at the instant it was committed. A past balance cannot come from the postings themselves, because a posting carries no timestamp.
+
 ## Account Types in Practice
 
 The single flag divides accounts into two kinds. Intent (wallet vs. boundary
@@ -193,3 +195,11 @@ An ordinary `Account::new(id)` may go negative without bound. This covers:
 
 When such an account's positive postings are insufficient for a debit, a negative
 posting covers the shortfall.
+
+## Accounts carry no accounting class
+
+There is no asset, liability, equity, income or expense dimension on an account. The [structure table](#structure) above is the whole record, and no field classifies it, so the ledger cannot group accounts the way a balance sheet or a profit-and-loss statement does. Those are the reports this blocks, and the only ones: a trial balance is a flat list of every account's balance, so it needs a read across accounts rather than a class.
+
+A class that is only reported on fits in `metadata`, which the ledger stores and never interprets. A class that has to be enforced fits better in one of the user-defined `AccountFlags` bits, because a book policy can gate participation on a flag and cannot gate on metadata. The [retail example](examples/retail.md) marks its revenue and warehouse accounts that way.
+
+> Classical accounting's "asset" names a class of account. Kuatia's [`Asset`](glossary.md#asset) names a currency or a commodity. The two senses are unrelated.

+ 10 - 0
doc/adr/README.md

@@ -75,3 +75,13 @@ captured as an ADR, roughly in priority order:
    sum over the live (active or reserved) postings, so a read concurrent
    with a commit is eventually consistent; the read-side guarantee is
    implied but never stated.
+9. **An accounting class on an account**: an account has no
+   asset/liability/equity/income/expense dimension, so a balance sheet or
+   a P&L cannot be grouped from the ledger; whether that class belongs on
+   the account, in metadata, or outside the ledger entirely is undecided.
+   See [accounts.md](../accounts.md#accounts-carry-no-accounting-class).
+10. **Whether tenancy belongs in the ledger**: `Book` gates participation
+    and isolates nothing, so today a tenant is a separate `Store`;
+    whether the ledger should own a tenant dimension instead is
+    undecided. See
+    [glossary.md](../glossary.md#books-are-not-a-tenancy-boundary).

+ 3 - 2
doc/architecture.md

@@ -205,8 +205,9 @@ values must equal the sum of created posting values.
 
 Conservation boundaries are **per-asset only**. The `book` field on transfers
 and accounts is a transfer policy scope (which accounts/assets may
-participate). It does not affect conservation enforcement, and it does not
-partition balances.
+participate). It does not affect conservation enforcement, it does not
+partition balances, and it is not a tenancy boundary
+([glossary](glossary.md#books-are-not-a-tenancy-boundary)).
 
 ## Account Balance Constraint
 

+ 1 - 0
doc/crates.md

@@ -149,6 +149,7 @@ Transfers are built via `TransferBuilder` and committed with
 | Method | Description |
 |--------|-------------|
 | `balance(account, asset)` | The everyday read: closest cache point plus the folded tail since its watermark |
+| `balance_as_of(account, asset, as_of)` | The balance at a past commit instant (unix ms), bounded above by `as_of`; commit time, never the value date |
 | `balance_exact(account, asset)` | The authoritative sum of the live (unspent) postings, uncached. What the commit path reads |
 | `balances(account, asset, sub?)` | One entry per non-closed subaccount; never summed across them (ADR-0012) |
 | `list_accounts()` | All current account snapshots |

+ 17 - 7
doc/glossary.md

@@ -29,7 +29,9 @@ A versioned entity that owns postings. Balance is never stored. It is always
 the sum of the live postings for a given (account, asset) pair.
 
 Accounts have **flags** (lifecycle, the `DEBIT_MUST_NOT_EXCEED_CREDIT` balance
-constraint, and user-defined bits) and a **book** assignment.
+constraint, and user-defined bits) and a **book** assignment. They carry no
+accounting class, so a class lives in metadata or a user flag bit: see
+[accounts carry no accounting class](accounts.md#accounts-carry-no-accounting-class).
 
 An account is identified by `AccountId { id: i64, sub: i64 }`: a base `id` plus a
 **subaccount**. `sub = 0` is the main account; a non-zero `sub` is a subaccount
@@ -148,8 +150,7 @@ and the [runnable programs](examples/runnable.md).
   assets and accounts are expected.
 - **Multiple flows**: separate books for sales, payments, inventory, banking.
   Prevents cross-contamination.
-- **Multi-tenant**: one book per tenant with `allowed_accounts` restricting to
-  that tenant's accounts.
+- **Multi-tenant**: one book per tenant, with `allowed_accounts` naming that tenant's accounts, records and gates which accounts may transact together. It does not isolate one tenant from another: see [books are not a tenancy boundary](#books-are-not-a-tenancy-boundary).
 
 ### Book scoping rules
 
@@ -166,9 +167,18 @@ An account passes the book check if:
 
 ### Books do NOT partition balances
 
-An account's balance is the sum of all its non-inactive postings across ALL
-books. If Alice receives 100 USD via the `deposits` book and spends 50 USD via
-the `trading` book, her balance is 50 USD, not 100 in one book and -50 in
-another.
+An account's balance is the sum of all its live postings across ALL books. If
+Alice receives 100 USD via the `deposits` book and spends 50 USD via the
+`trading` book, her balance is 50 USD, not 100 in one book and -50 in another.
 
 This is intentional: books scope *access*, not *state*.
+
+### Books are not a tenancy boundary
+
+A book gates which accounts and assets may appear in one transfer. It is not an isolation boundary, and what follows from that is not obvious from the name:
+
+- Balances are global, as above.
+- No read is restricted by book. `TransferQuery::book` is a filter a caller may pass, and `list_accounts`, `history` and the posting reads take no book at all, so nothing stops a query from returning another tenant's rows.
+- The gate is per transfer and the caller picks it. A transfer naming the default book when no such book is stored commits with no policy applied at all, so a book cannot be relied on to hold a caller in.
+
+Isolation is a deployment choice instead: give each tenant its own `Store`, meaning its own database or schema. A ledger over that store needs no cross-tenant check, because the store holds nothing belonging to another tenant.

+ 2 - 2
doc/journaling.md

@@ -137,8 +137,8 @@ entry breaks its id).
 Two Kuatia concepts are easy to mistake for the journal and are not:
 
 - `Book` is a transfer policy scope. It gates which accounts and assets may
-  participate in a transfer. It is not the journal, not a journal entry, and not
-  a balance partition. See
+  participate in a transfer. It is not the journal, not a journal entry, not a
+  balance partition, and not a tenancy boundary. See
   [accounting-mapping.md](accounting-mapping.md#where-book-fits-and-doesnt).
 - The event log records lifecycle notifications for subscribers. The transfer
   log is the source of truth for balances.