Forráskód Böngészése

Say that a pending state is an account, not a flag

The book showed this once, as the mechanism behind inflight holds, and
never stated it. A reader who needed escrow, a clearing account or a
chargeback reserve had to recognise the construction in the inflight source
and generalise it themselves, and the ones who do not go looking conclude
that an append-only ledger cannot express a workflow state at all.

The new Concepts page gives the rule first, that the ledger has one
committed state and anything pending is value parked in an account whose
balance is its status, then derives what follows: the amount and the state
are one read and cannot disagree, partial settlement needs no new concept,
and a drained account closes so that finished is provable rather than
asserted.

Escrow is the worked example because it is not a hold, so the pattern has
to carry it rather than the inflight API. It runs, and the page includes it
from source, so it cannot drift from the API the way a prose snippet can.

The page also says where the pattern stops. A state with no value behind it
yet is not an account, and modelling it as one means inventing the status
field this design does without.
C 4 napja
szülő
commit
0cdc8a859a

+ 168 - 0
crates/kuatia/examples/escrow.rs

@@ -0,0 +1,168 @@
+//! Hold a buyer's money until a deal closes, then release it or refund it.
+//!
+//! Escrow is a pending state, and this ledger has no pending state: every
+//! transfer is final the moment it commits. So the state lives in an account.
+//! Value sits in an escrow account per agreement, and "in escrow" is not a flag
+//! anyone set, it is the balance of that account being non-zero.
+//!
+//! See `doc/pending-states.md`.
+//!
+//! Run with:
+//! ```sh
+//! cargo run -p kuatia --example escrow
+//! ```
+
+use kuatia::ledger::Ledger;
+use kuatia_core::*;
+use kuatia_storage_sql::SqlStore;
+
+/// Top-level account every agreement's escrow hangs off as a subaccount, so one
+/// agreement's money can never be spent by another and each closes on its own.
+const ESCROW: i64 = 50;
+
+fn escrow_for(agreement: i64) -> AccountId {
+    AccountId::with_sub(ESCROW, agreement)
+}
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+    let ledger = connect().await?;
+
+    let buyer = AccountId::new(1);
+    let seller = AccountId::new(2);
+    let bank = AccountId::new(99);
+    let usd = AssetId::new(1);
+    let money = Amount::new(2);
+
+    ledger
+        .create_account(Account::debit_must_not_exceed_credit(buyer))
+        .await?;
+    ledger
+        .create_account(Account::debit_must_not_exceed_credit(seller))
+        .await?;
+    ledger.create_account(Account::new(bank)).await?;
+
+    ledger
+        .commit(
+            TransferBuilder::new()
+                .deposit(buyer, usd, money.parse("500.00")?, bank)?
+                .reference("funding-buyer")
+                .build(),
+        )
+        .await?;
+
+    // Two agreements, so both endings are visible: one releases, one refunds.
+    let sale = 7001;
+    let cancelled = 7002;
+
+    for agreement in [sale, cancelled] {
+        // An escrow account forbids overdraft. That is what makes releasing
+        // more than was deposited impossible rather than merely wrong.
+        ledger
+            .create_account(Account::debit_must_not_exceed_credit(escrow_for(agreement)))
+            .await?;
+    }
+
+    // Enter escrow. An ordinary payment, final on commit.
+    ledger
+        .commit(
+            TransferBuilder::new()
+                .pay(buyer, escrow_for(sale), usd, money.parse("120.00")?)
+                .reference("escrow-in-7001")
+                .build(),
+        )
+        .await?;
+    ledger
+        .commit(
+            TransferBuilder::new()
+                .pay(buyer, escrow_for(cancelled), usd, money.parse("80.00")?)
+                .reference("escrow-in-7002")
+                .build(),
+        )
+        .await?;
+
+    let watched = [
+        ("buyer", buyer),
+        ("seller", seller),
+        ("escrow(7001)", escrow_for(sale)),
+        ("escrow(7002)", escrow_for(cancelled)),
+    ];
+    report(&ledger, &money, usd, &watched).await?;
+
+    // Nothing recorded that these are pending. Reading the escrow balance is
+    // what tells you, and it is the same read that tells you how much.
+    for agreement in [sale, cancelled] {
+        let held = ledger.balance(&escrow_for(agreement), &usd).await?;
+        println!(
+            "agreement {agreement}: {} USD in escrow",
+            money.format(held)
+        );
+    }
+
+    // The sale closes: release to the seller.
+    let held = ledger.balance(&escrow_for(sale), &usd).await?;
+    ledger
+        .commit(
+            TransferBuilder::new()
+                .pay(escrow_for(sale), seller, usd, held)
+                .reference("escrow-release-7001")
+                .build(),
+        )
+        .await?;
+
+    // The other falls through: refund the buyer, from the same account, by the
+    // same kind of transfer. Only the destination differs.
+    let held = ledger.balance(&escrow_for(cancelled), &usd).await?;
+    ledger
+        .commit(
+            TransferBuilder::new()
+                .pay(escrow_for(cancelled), buyer, usd, held)
+                .reference("escrow-refund-7002")
+                .build(),
+        )
+        .await?;
+
+    report(&ledger, &money, usd, &watched).await?;
+
+    // A drained escrow account holds no live postings, so it can be closed and
+    // the agreement is provably finished rather than marked finished.
+    for agreement in [sale, cancelled] {
+        ledger.close(&escrow_for(agreement)).await?;
+        println!(
+            "agreement {agreement}: escrow closed = {}",
+            ledger
+                .get_account(&escrow_for(agreement))
+                .await?
+                .is_closed()
+        );
+    }
+
+    Ok(())
+}
+
+async fn report(
+    ledger: &Ledger,
+    money: &Amount,
+    asset: AssetId,
+    accounts: &[(&str, AccountId)],
+) -> Result<(), Box<dyn std::error::Error>> {
+    let mut line = String::new();
+    for (label, account) in accounts {
+        let balance = ledger.balance(account, &asset).await?;
+        line.push_str(&format!("{label} {}  ", money.format(balance)));
+    }
+    println!("{}", line.trim_end());
+    Ok(())
+}
+
+async fn connect() -> Result<Ledger, Box<dyn std::error::Error>> {
+    kuatia_storage_sql::install_drivers()?;
+    let pool = sqlx::any::AnyPoolOptions::new()
+        .max_connections(1)
+        .connect("sqlite::memory:")
+        .await?;
+    let store = SqlStore::new(pool);
+    store.migrate().await?;
+    let ledger = Ledger::new(store);
+    Ok(ledger)
+}

+ 1 - 0
doc/SUMMARY.md

@@ -8,6 +8,7 @@
 - [Architecture](architecture.md)
 - [Accounts](accounts.md)
 - [Transfers](transfers.md)
+- [Pending states](pending-states.md)
 - [Inflight holds](inflight.md)
 
 # Examples

+ 2 - 1
doc/examples/README.md

@@ -5,7 +5,8 @@
 | [Overdraft and the shortfall posting](overdraft.md) | A debit larger than the balance: a negative posting on an account that permits it, `InsufficientFunds` on one that does not |
 | [Currency exchange](exchange.md) | Deposit, a two-leg cross-asset trade, withdrawal, and books scoping the two flows |
 | [Retail point of sale](retail.md) | Inventory as assets, a sale recording COGS, cash deposited to bank |
-| [Runnable programs](runnable.md) | The four programs in `crates/kuatia/examples/`, included from source |
+| [Escrow](../pending-states.md) | A workflow state held in an account: pay in, then release or refund, then close the drained account |
+| [Runnable programs](runnable.md) | The programs in `crates/kuatia/examples/`, included from source |
 
 The exchange and retail chapters are walkthroughs: the code is real but the
 accounts are declared inline rather than built into a program you can run. The

+ 10 - 1
doc/examples/runnable.md

@@ -1,6 +1,6 @@
 # Runnable programs
 
-Four programs in `crates/kuatia/examples/` drive a real ledger over SQLite in
+The programs in `crates/kuatia/examples/` drive a real ledger over SQLite in
 memory, so each one runs with no setup:
 
 ```sh
@@ -8,6 +8,7 @@ cargo run -p kuatia --example create_accounts
 cargo run -p kuatia --example fund_and_trade
 cargo run -p kuatia --example withdraw
 cargo run -p kuatia --example inflight_hold
+cargo run -p kuatia --example escrow
 ```
 
 They are included below from source, so what the book shows is the code `cargo
@@ -42,3 +43,11 @@ Authorize, confirm and void through a per-destination holding subaccount; see
 ```rust
 {{#include ../../crates/kuatia/examples/inflight_hold.rs}}
 ```
+
+## Escrow
+
+Explained in [Pending states](../pending-states.md).
+
+```rust
+{{#include ../../crates/kuatia/examples/escrow.rs}}
+```

+ 6 - 0
doc/inflight.md

@@ -8,6 +8,12 @@ The design and its rationale are in
 [adr/0014-inflight-holds-via-holding-accounts.md](adr/0014-inflight-holds-via-holding-accounts.md).
 This page is the usage guide.
 
+Holds are one instance of a general pattern: this ledger has no pending state,
+so a workflow state is value parked in an account you control.
+[pending-states.md](pending-states.md) states that rule and works escrow
+through as a second instance, which is where to start when the shape you need
+is not authorise then capture.
+
 ## Model
 
 An inflight transaction is an ordinary trade whose every destination is

+ 92 - 0
doc/pending-states.md

@@ -0,0 +1,92 @@
+# Pending states
+
+The ledger has one state: committed. Anything that looks pending, reserved, authorised or unsettled is value parked in an account you control, and its status is the balance of that account. To add a workflow state, add an account, not a flag.
+
+## Why there is nothing else to use
+
+Postings are immutable and a balance is a projection over them, so no row exists that a status could be written on. That is the whole of the constraint, and it is also the mechanism: because position is the only thing that can carry a state, every state change is a transfer, and every transfer is already conserved, content-addressed and in the log. A status modelled this way cannot drift from the money, because it *is* the money. A status column can.
+
+This is why there is no `Transfer::status` and no pending flag on an account. Asking for one is usually asking for an account.
+
+## Escrow, end to end
+
+`crates/kuatia/examples/escrow.rs` is this page in runnable form. Run it with `cargo run -p kuatia --example escrow`.
+
+An agreement's money sits in its own escrow account, a subaccount of one top-level escrow account, so one agreement's funds can never be spent by another and each closes independently.
+
+```rust
+const ESCROW: i64 = 50;
+
+fn escrow_for(agreement: i64) -> AccountId {
+    AccountId::with_sub(ESCROW, agreement)
+}
+```
+
+The account forbids overdraft, which is what makes releasing more than was deposited impossible rather than merely incorrect:
+
+```rust
+ledger
+    .create_account(Account::debit_must_not_exceed_credit(escrow_for(agreement)))
+    .await?;
+```
+
+Entering escrow is an ordinary payment, final the moment it commits:
+
+```rust
+ledger.commit(
+    TransferBuilder::new()
+        .pay(buyer, escrow_for(agreement), usd, amount)
+        .reference("escrow-in-7001")
+        .build(),
+).await?;
+```
+
+Leaving it is the same transfer with a different destination. Release pays the seller, refund pays the buyer, and nothing distinguishes them to the ledger:
+
+```rust
+let held = ledger.balance(&escrow_for(agreement), &usd).await?;
+ledger.commit(
+    TransferBuilder::new()
+        .pay(escrow_for(agreement), seller, usd, held)   // or back to buyer
+        .reference("escrow-release-7001")
+        .build(),
+).await?;
+```
+
+```mermaid
+stateDiagram-v2
+    [*] --> InEscrow: pay buyer to escrow(7001)
+    InEscrow --> Released: pay escrow(7001) to seller
+    InEscrow --> Refunded: pay escrow(7001) to buyer
+    Released --> [*]: close the drained account
+    Refunded --> [*]: close the drained account
+```
+
+Three properties come free, and are the reason to model it this way rather than with a status field:
+
+- **The amount and the state are one read.** `balance(escrow_for(agreement), usd)` answers both "is this pending" and "how much", and cannot disagree with itself.
+- **Partial settlement needs no new concept.** Release part of the balance and the rest stays in escrow, still readable the same way.
+- **Finished is provable.** A drained escrow account holds no live postings, so `close` succeeds, and a closed account rejects further transfers. The agreement is finished rather than marked finished.
+
+## The same shape, elsewhere
+
+| Business state | The account that holds it | What ends it |
+|---|---|---|
+| Card authorisation | Per-destination hold (implemented, see [inflight.md](inflight.md)) | Capture, or void on expiry |
+| Escrow | Escrow account per agreement | Release to seller, or refund to buyer |
+| Unsettled card batch | Clearing account per settlement cycle | Settlement file, netted to the bank account |
+| Chargeback reserve | Reserve account per merchant | Dispute resolved either way |
+| Unapplied receipt | Suspense account | Matched to an invoice |
+| Accrued but unbilled revenue | Accrual account per period | Invoice issued |
+
+Classical accounting calls the general shape a control account with a subsidiary ledger; payments systems call it a sub-ledger or virtual accounts under a master account. Subaccounts exist to make it cheap: an account is a base id plus a subaccount, so a per-agreement or per-cycle account is addressable without minting unrelated top-level accounts (ADR-0012).
+
+## Inflight holds are the implemented instance
+
+[Inflight holds](inflight.md) apply this to authorisation and capture, with the per-destination holding account created for you. `authorize` rewrites every destination of a trade to a holding subaccount, `confirm` sweeps a hold to its destination, and `void` returns it to the funders recorded in the authorize transfer's leg table. All three are ordinary commits. Reach for them when the shape is authorise then capture, and build your own account when it is not.
+
+## When the state holds no value
+
+Not every workflow state is money sitting somewhere. An authorisation you have accepted but not funded, a payment awaiting compliance review before any value moves, a quote: none of these park value, so none of them is an account. Those live outside the ledger, or as metadata on the transfer that eventually commits.
+
+The test is whether value has moved. If it has, the state is an account. If it has not, the ledger has nothing to record yet, and recording it anyway means inventing the status field this model does without.