Cotton code
398 lines · 19.3 KB · RustRaw
//! The phone's money run: each money row's balance before and after it, and//! each account's balance, worked out on this device by the object's own rule//! (`cotton_core::rules::money::balances`) for the rows the object has not//! stamped — a local copy before Backup, or a write the object has not//! answered yet (owner, 27 Oct 2026; coordinator, 2 Nov 2026: one rule, run on//! the phone too).//!//! - **The object's figures win.** A row the object has written (a receipt//!   of the object's) is the object's: its balances are what the pull laid,//!   and this pass never writes them. Every other row and account is filled.//! - **Filled after every fold that moves a run** (a money row, an account,//!   a statement, a line, evidence), inside that fold's transaction//!   (`cotton_store::derived::Derive::fill`): a fold resets a column no//!   receipt names, so the pass fills it again before anyone reads it. The//!   numbers are the engine's bookkeeping: written in place, minted as no//!   change, never sent — the object works its own.//! - **Only into the columns the copy keeps** for the definitions//!   ([`cotton_store::schema::package_shape::served_on`]): a copy that keeps//!   no balance column is filled with nothing.//! - **A sealed money row is the phone's alone** (e2e rulings R3, 16 Nov//!   2026): when the copy's `transaction` definition carries a seal block,//!   the object cannot read an amount and works no run, so no row or account//!   is the object's to figure and this pass fills every one.//! - **Today** is the workspace's day, as the phone's other money reader//!   takes it (`tables::money_runway`): the zone the workspace names, UTC//!   when it names none.//! - **A write works out only the runs it moved** (coordinator, 7 Nov 2026://!   every money write re-worked every account over the whole book). A fold//!   of money rows alone works out the accounts of the windows its rows were//!   in and are in now ([`run_window`]: the account a row runs on and the row//!   it settles), each over its own window of the book. Each row's window is//!   kept beside it in `_computed` (`~run`), and the day the windows were//!   kept for (`@run`); a fold of anything else, a new day, or windows not//!   kept (a rebuild clears them) works every account out, as before.use std::collections::{BTreeSet, HashMap, HashSet};use cotton_core::rules::money::balances::{run_window, usual_account, work_book, Book, BookRow};use cotton_store::{Driver, Result};use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::clock::{Clock, SystemClock};use crate::mcp::handlers::common::{is_known_zone, today_in};/// The store table each table of the run keeps its rows in.const TRANSACTIONS: &str = "cotton_money_transactions";const ACCOUNTS: &str = "cotton_money_accounts";const STATEMENTS: &str = "cotton_money_statements";const LINES: &str = "cotton_money_statement_lines";const EVIDENCE: &str = "cotton_money_evidence";/// The store tables whose rows can move a run.pub const MOVES_A_RUN: [&str; 5] = [TRANSACTIONS, ACCOUNTS, STATEMENTS, LINES, EVIDENCE];/// The author the object writes under (`cotton_client::transport::object`).const OBJECT_AUTHOR: &str = "object";/// The columns a money row's run fills, and an account's.const ROW_COLUMNS: [&str; 3] = ["balance_before_minor", "balance_after_minor", "balance_state"];const ACCOUNT_COLUMNS: [&str; 2] = ["balance_minor", "balance_as_of"];/// Fill the run after `rows` folded, when one of them can move it.pub fn after_fold(db: &Driver, rows: &[(String, String)]) -> Result<()> {    if !rows.iter().any(|(table, _)| MOVES_A_RUN.contains(&table.as_str())) {        return Ok(());    }    let today = today(db, &SystemClock)?;    match moved_accounts(db, rows, &today)? {        Some((written, accounts)) => refill_accounts(db, &today, &written, &accounts),        None => refill(db, &today),    }}/// Where each money row's window is kept, and the day the windows are kept for.const WINDOW_KEY: &str = "~run";const KEPT_ROW: &str = "@run";const KEPT_DAY: &str = "~day";/// Between a window's account and the row it settles, as kept.const SEP: char = '\u{1f}';/// The rows a fold of money rows alone wrote, and the accounts whose runs/// they moved — where they ran and what they settled before, and now — or/// `None` when every account is worked out again.fn moved_accounts(db: &Driver, rows: &[(String, String)], today: &str) -> Result<Option<(BTreeSet<String>, BTreeSet<String>)>> {    if rows.iter().any(|(table, _)| table != TRANSACTIONS) || kept(db, KEPT_ROW, KEPT_DAY)?.as_deref() != Some(today) {        return Ok(None);    }    let accounts_of = rows_of(db, ACCOUNTS, "")?;    let usual = usual_account(&accounts_of);    let written: BTreeSet<String> = rows.iter().map(|(_, id)| id.clone()).collect();    let mut moved = BTreeSet::new();    let mut settled = BTreeSet::new();    for id in &written {        if let Some(window) = kept(db, id, WINDOW_KEY)? {            let (account, settles) = window.split_once(SEP).unwrap_or((window.as_str(), ""));            moved.extend(Some(account).filter(|a| !a.is_empty()).map(str::to_owned));            settled.extend(Some(settles).filter(|s| !s.is_empty()).map(str::to_owned));        }        for row in rows_of(db, TRANSACTIONS, &where_ids(&[id.clone()]))? {            let (account, settles) = run_window(&row, usual);            moved.extend(account.map(str::to_owned));            settled.extend(settles.map(str::to_owned));        }    }    // A row settled, or no longer settled, leaves or rejoins its own account's run.    let settled: Vec<String> = settled.into_iter().collect();    for row in rows_of(db, TRANSACTIONS, &where_ids(&settled))? {        moved.extend(run_window(&row, usual).0.map(str::to_owned));    }    Ok(Some((written, moved)))}/// `WHERE id IN (…)` over quoted ids (row ids are uuids; a quote is doubled).fn where_ids(ids: &[String]) -> String {    if ids.is_empty() {        return "WHERE 0".to_owned();    }    let quoted: Vec<String> = ids.iter().map(|id| format!("'{}'", id.replace('\'', "''"))).collect();    format!("WHERE id IN ({})", quoted.join(","))}/// The runs of `accounts` worked out again over their window of the book —/// their rows, every row that settles another, their read statements, and/// the lines and evidence their rows were booked from ([`run_window`]) — and/// filled into those rows, `written` and those accounts.fn refill_accounts(db: &Driver, today: &str, written: &BTreeSet<String>, accounts: &BTreeSet<String>) -> Result<()> {    let row_columns = held(db, TRANSACTIONS, &ROW_COLUMNS)?;    let account_columns = held(db, ACCOUNTS, &ACCOUNT_COLUMNS)?;    if !row_columns && !account_columns {        return Ok(());    }    let money_account = rows_of(db, ACCOUNTS, "")?;    let usual = usual_account(&money_account).map(str::to_owned);    let mine: Vec<String> = accounts.iter().cloned().collect();    let list = |ids: &[String]| ids.iter().map(|id| format!("'{}'", id.replace('\'', "''"))).collect::<Vec<_>>().join(",");    // Each part by its own index: the accounts' rows, every row that settles    // another, the rows written (wherever they run now), and — the usual    // account among them — the rows that name no account.    let mut parts = vec![format!("SELECT id FROM {TRANSACTIONS} WHERE id IN ({})", list(&written.iter().cloned().collect::<Vec<_>>()))];    if !mine.is_empty() {        parts.push(format!("SELECT id FROM {TRANSACTIONS} WHERE account_id IN ({})", list(&mine)));        parts.push(format!("SELECT id FROM {TRANSACTIONS} WHERE settles_transaction_id IS NOT NULL AND settles_transaction_id <> ''"));    }    if usual.as_ref().is_some_and(|usual| accounts.contains(usual)) {        parts.push(format!("SELECT id FROM {TRANSACTIONS} WHERE account_id IS NULL OR account_id = ''"));    }    let selected = parts.join(" UNION ");    let ours = format!("id IN ({selected})");    let book = Book {        money_account,        transaction: rows_of(db, TRANSACTIONS, &format!("WHERE {ours}"))?,        statement: rows_of(db, STATEMENTS, &format!("WHERE account_id IN ({})", list(&mine)))?,        statement_line: rows_of(db, LINES, &format!(            "WHERE id IN (SELECT ref_id FROM {EVIDENCE} WHERE transaction_id IN ({selected})){}",            // A line names its row itself only where the copy keeps it (the object's).            if has_column(db, LINES, "transaction_id")? { format!(" OR transaction_id IN ({selected})") } else { String::new() },        ))?,        evidence: rows_of(db, EVIDENCE, &format!("WHERE transaction_id IN ({selected})"))?,    };    let worked = work_book(&book, today);    if row_columns {        let stamped = stamped_among(db, TRANSACTIONS, &selected)?;        for row in &book.transaction {            let ran_here = run_window(row, usual.as_deref()).0.is_some_and(|account| accounts.contains(account));            if !(ran_here || written.contains(&row.id)) || stamped.contains(&row.id) {                continue;            }            let balance = worked.transactions.get(&row.id).copied().unwrap_or_default();            let values = [                balance.balance_before_minor.map_or(Value::Null, Value::from),                balance.balance_after_minor.map_or(Value::Null, Value::from),                balance.balance_state.map_or(Value::Null, |state| Value::from(state.as_str())),            ];            write(db, TRANSACTIONS, row, &ROW_COLUMNS, &values)?;        }    }    if account_columns {        let stamped = stamped_among(db, ACCOUNTS, &format!("SELECT id FROM {ACCOUNTS} WHERE id IN ({})", list(&mine)))?;        for row in book.money_account.iter().filter(|row| accounts.contains(&row.id) && !stamped.contains(&row.id)) {            let Some(Some(balance)) = worked.accounts.get(&row.id) else { continue };            write(db, ACCOUNTS, row, &ACCOUNT_COLUMNS, &[Value::from(*balance), Value::from(today)])?;        }    }    let now = rows_of(db, TRANSACTIONS, &where_ids(&written.iter().cloned().collect::<Vec<_>>()))?;    let mut windows: HashMap<String, Option<String>> = written.iter().map(|id| (id.clone(), None)).collect();    for row in &now {        windows.insert(row.id.clone(), window_of(row, usual.as_deref()));    }    for (id, window) in windows {        keep(db, &id, WINDOW_KEY, window)?;    }    Ok(())}/// Whether `table` has `column` in this copy.fn has_column(db: &Driver, table: &str, column: &str) -> Result<bool> {    Ok(db.all(&format!("PRAGMA table_info({table})"), &[])?.iter().any(|row| row.text("name") == Some(column)))}/// What a row's window is kept as: nothing when it runs on no account and settles nothing.fn window_of(row: &BookRow, usual: Option<&str>) -> Option<String> {    let (account, settles) = run_window(row, usual);    (account.is_some() || settles.is_some()).then(|| format!("{}{SEP}{}", account.unwrap_or(""), settles.unwrap_or("")))}/// One kept value of the run's bookkeeping.fn kept(db: &Driver, row: &str, key: &str) -> Result<Option<String>> {    Ok(db        .get("SELECT value FROM _computed WHERE table_id = ? AND record_id = ? AND key = ?", &[SqlValue::Text(TRANSACTIONS.to_owned()), SqlValue::Text(row.to_owned()), SqlValue::Text(key.to_owned())])?        .and_then(|found| found.text("value").map(str::to_owned)))}/// Keep `value` (nothing for none) under the run's bookkeeping.fn keep(db: &Driver, row: &str, key: &str, value: Option<String>) -> Result<()> {    let place = [SqlValue::Text(TRANSACTIONS.to_owned()), SqlValue::Text(row.to_owned()), SqlValue::Text(key.to_owned())];    match value {        None => db.run("DELETE FROM _computed WHERE table_id = ? AND record_id = ? AND key = ?", &place).map(drop),        Some(value) => {            let mut params = place.to_vec();            params.push(SqlValue::Text(value));            db.run(                "INSERT INTO _computed (table_id, record_id, key, value) VALUES (?, ?, ?, ?) ON CONFLICT (table_id, record_id, key) DO UPDATE SET value = excluded.value",                &params,            )            .map(drop)        }    }}/// Every row's window kept as the whole book has it, and the day: from here/// a fold of money rows works out only the runs it moved.fn keep_windows(db: &Driver, book: &Book, today: &str) -> Result<()> {    let usual = usual_account(&book.money_account);    let mut held: HashMap<String, String> = db        .all("SELECT record_id, value FROM _computed WHERE table_id = ? AND key = ?", &[SqlValue::Text(TRANSACTIONS.to_owned()), SqlValue::Text(WINDOW_KEY.to_owned())])?        .iter()        .filter_map(|row| Some((row.text("record_id")?.to_owned(), row.text("value")?.to_owned())))        .collect();    for row in &book.transaction {        let window = window_of(row, usual);        if held.remove(&row.id) != window {            keep(db, &row.id, WINDOW_KEY, window)?;        }    }    for gone in held.into_keys() {        keep(db, &gone, WINDOW_KEY, None)?;    }    keep(db, KEPT_ROW, KEPT_DAY, Some(today.to_owned()))}/// The workspace's day by `clock`.pub fn today(db: &Driver, clock: &dyn Clock) -> Result<String> {    let zone = db        .get("SELECT timezone FROM cotton_news_settings LIMIT 1", &[])        .ok()        .flatten()        .and_then(|row| row.text("timezone").map(str::to_owned))        .filter(|zone| !zone.trim().is_empty() && is_known_zone(zone))        .unwrap_or_else(|| "UTC".to_owned());    today_in(&zone, clock.now().timestamp_millis()).map_err(|failure| cotton_store::error::StoreError::Refused(failure.to_string()))}/// Every account's run worked out again on `today`; a row the object has not/// stamped takes its numbers where they moved.pub fn refill(db: &Driver, today: &str) -> Result<()> {    let row_columns = held(db, TRANSACTIONS, &ROW_COLUMNS)?;    let account_columns = held(db, ACCOUNTS, &ACCOUNT_COLUMNS)?;    if !row_columns && !account_columns {        return Ok(());    }    let book = Book {        money_account: rows_of(db, ACCOUNTS, "")?,        transaction: rows_of(db, TRANSACTIONS, "")?,        statement: rows_of(db, STATEMENTS, "")?,        statement_line: rows_of(db, LINES, "")?,        evidence: rows_of(db, EVIDENCE, "")?,    };    let worked = work_book(&book, today);    if row_columns {        let stamped = stamped(db, TRANSACTIONS)?;        for row in book.transaction.iter().filter(|row| !stamped.contains(&row.id)) {            let balance = worked.transactions.get(&row.id).copied().unwrap_or_default();            let values = [                balance.balance_before_minor.map_or(Value::Null, Value::from),                balance.balance_after_minor.map_or(Value::Null, Value::from),                balance.balance_state.map_or(Value::Null, |state| Value::from(state.as_str())),            ];            write(db, TRANSACTIONS, row, &ROW_COLUMNS, &values)?;        }    }    if account_columns {        let stamped = stamped(db, ACCOUNTS)?;        for row in book.money_account.iter().filter(|row| !stamped.contains(&row.id)) {            // An account with no anchor keeps what it held, as the object's does.            let Some(Some(balance)) = worked.accounts.get(&row.id) else { continue };            write(db, ACCOUNTS, row, &ACCOUNT_COLUMNS, &[Value::from(*balance), Value::from(today)])?;        }    }    keep_windows(db, &book, today)}/// Whether the copy keeps every one of `columns` on `table`.fn held(db: &Driver, table: &str, columns: &[&str]) -> Result<bool> {    let served = cotton_store::schema::package_shape::served_on(db, table)?;    Ok(columns.iter().all(|column| served.iter().any(|held| held == column)))}/// Whether the object works the run: not when the copy's money row is/// sealed (its definition, as the object serves it, carries a seal block),/// since then the object cannot read an amount (e2e rulings R3).pub(crate) fn object_works_the_run(db: &Driver) -> Result<bool> {    let held = db.get(&format!("SELECT definition FROM {} WHERE id = 'transaction'", crate::definitions::TABLE_DEFINITIONS), &[])?;    let sealed = held        .and_then(|row| row.text("definition").map(str::to_owned))        .and_then(|text| serde_json::from_str::<Value>(&text).ok())        .is_some_and(|definition| definition.get("seal").is_some_and(|seal| !seal.is_null()));    Ok(!sealed)}/// The rows of `table` the object has written: theirs, not this pass's.fn stamped(db: &Driver, table: &str) -> Result<HashSet<String>> {    if !object_works_the_run(db)? {        return Ok(HashSet::new());    }    Ok(db        .all(            "SELECT DISTINCT row_id FROM _writes WHERE tbl = ? AND author = ?",            &[SqlValue::Text(table.to_owned()), SqlValue::Text(OBJECT_AUTHOR.to_owned())],        )?        .iter()        .filter_map(|row| row.text("row_id").map(str::to_owned))        .collect())}/// The rows of `table` among `selected` (a `SELECT id …`) the object has written.fn stamped_among(db: &Driver, table: &str, selected: &str) -> Result<HashSet<String>> {    if !object_works_the_run(db)? {        return Ok(HashSet::new());    }    Ok(db        .all(            &format!("SELECT DISTINCT row_id FROM _writes WHERE tbl = ? AND author = ? AND row_id IN ({selected})"),            &[SqlValue::Text(table.to_owned()), SqlValue::Text(OBJECT_AUTHOR.to_owned())],        )?        .iter()        .filter_map(|row| row.text("row_id").map(str::to_owned))        .collect())}/// The rows of `table` that `filter` (a `WHERE …`, or nothing for all of/// them) keeps, in the object's row shape: its columns by name (the run's/// tables keep the object's keys), an empty value left out. In the table's/// own order, so a window of the book meets its rows as the whole book does.fn rows_of(db: &Driver, table: &str, filter: &str) -> Result<Vec<BookRow>> {    let mut out = Vec::new();    for row in db.all(&format!("SELECT * FROM {table} {filter} ORDER BY rowid"), &[])? {        let Some(id) = row.text("id").map(str::to_owned) else { continue };        let created_at = row.text("created_at").unwrap_or_default().to_owned();        let mut data = Map::new();        for (column, value) in row.columns() {            let value = match value {                SqlValue::Integer(n) => Value::from(*n),                SqlValue::Real(x) => Value::from(*x),                SqlValue::Text(text) => Value::from(text.clone()),                SqlValue::Null | SqlValue::Blob(_) => continue,            };            data.insert(column.clone(), value);        }        out.push(BookRow { id, created_at, data });    }    Ok(out)}/// `columns` of `row` take `values` where they differ from what it holds.fn write(db: &Driver, table: &str, row: &BookRow, columns: &[&str], values: &[Value]) -> Result<()> {    let moved = columns.iter().zip(values).any(|(column, value)| row.data.get(*column).unwrap_or(&Value::Null) != value);    if !moved {        return Ok(());    }    let assignments: Vec<String> = columns.iter().map(|column| format!("\"{column}\" = ?")).collect();    let mut params: Vec<SqlValue> = values        .iter()        .map(|value| match value {            Value::Number(n) => n.as_i64().map_or(SqlValue::Null, SqlValue::Integer),            Value::String(text) => SqlValue::Text(text.clone()),            _ => SqlValue::Null,        })        .collect();    params.push(SqlValue::Text(row.id.clone()));    db.run(&format!("UPDATE {table} SET {} WHERE id = ?", assignments.join(", ")), &params)?;    Ok(())}#[cfg(test)]#[path = "money_run_tests.rs"]mod tests;