//! The derive pass: what every computed column holds, worked out by the one//! implementation on each device and kept in the device-local `_computed`//! (`cotton_store::derived`).//!//! A computed column — a lookup, a rollup or a formula//! (`cotton_core::definitions::computed`) — is stored in no synced column. After//! every fold the store hands this pass the rows that fold changed, inside//! the fold's own transaction, and the pass works out again exactly what//! those rows can have moved: the record's own computed columns, the records//! that look a value up through a link to it, and the records whose rollups//! gather it — now, and where its link pointed before. A change of any//! table's definition, or a build with another derivation, rebuilds the//! whole index instead ([`rebuild`], [`ensure_current`]).//!//! Made tables supply their typed stored rows. Built-ins supply their live//! logical rows through the generic reader's stable projection, including//! canonical Money balances. Ordered columns always see the whole table,//! independently of the page or single record a reader asks for.use std::collections::{BTreeMap, BTreeSet, VecDeque};use cotton_store::derived::{self, Derive};use cotton_store::{Driver, Result};use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};use cotton_core::definitions::computed::{HANDLE_KIND, HANDLE_VALUE, dangling, derive_order, validate_across, Activity, ActivityOp, Computed, Formula, FormulaOp, RollupRead, RollupOp, Running, RunningOpening};use cotton_core::definitions::{ builtin_store_table, builtin_table_definitions, is_computed_column, ColumnType, TableDefinition, ValueMatch, RESOLVED_COLUMNS,};use cotton_core::records::{compare_values, sum_numbers, Data};usecrate::mcp::handlers::tables::{made_table, stored_from_row};/// The evaluator's own version: bump it when what a computed column holds/// changes for the same records, so every device rebuilds its index.const EVALUATOR: u32 = 5;/// The most records one fold's pass visits. A fold that would move more is a/// rebuild's work: the pass gives up, which marks the index stale.const MOST_VISITS: usize = 20_000;/// What `_computed` must say it was rebuilt by: the evaluator and every/// table's stamp ([`table_stamps`]), over the file's own definitions — what/// the index is worked out FROM, never how a table looks. A change to a/// page, a card, a word or the slips table moves no stamp, so it rebuilds/// nothing (phone 296, 17 Oct 2026: a presentation change rebuilt every/// computed value on every database).pubfn derivation_of(db: &Driver) -> Result<String> {Ok(Catalogue::load(db)?.map_or_else(|| stamp_over(&BTreeMap::new()), |catalogue| catalogue.derivation.clone()))}fn stamp_over(stamps: &BTreeMap<String, String>) -> String {use sha2::Digest;let bytes = serde_json::to_vec(stamps).expect("stamps serialize"); format!("{EVALUATOR}:tables:sha256:{}", hex::encode(sha2::Sha256::digest(bytes)))}/// ONLY WHAT CHANGED IS WORKED OUT AGAIN. Each table with a computed column/// has its own stamp: its computed columns' specs, a view's source, and/// every column those read — through links, lookups and rollups, to the end/// — with the evaluator. A rebuild works out the tables whose stamp moved/// and keeps every other table's values (Mac 165, 21 Oct 2026: a birthday/// that stopped being computed, and two new tables with no computed column,/// rebuilt every table's index on every database for eighteen minutes).pubfn table_stamps(tables: &[TableDefinition]) -> BTreeMap<String, String> {use sha2::Digest;let all: Vec<&TableDefinition> = tables.iter().collect();letmut known = BTreeMap::new(); tables .iter() .filter(|table| table.has_computed()) .map(|table| {let columns: Vec<Value> = table .columns .iter() .filter(|column| column.computed.is_some()) .map(|column| column_inputs(&all, table, &column.key, &mutVec::new(), &mut known)) .collect();let source = table.source.as_ref().map(|source| { json!([source, all.iter().find(|other| other.id == source.table).map(|other| &other.columns)]) });let bytes = serde_json::to_vec(&json!([EVALUATOR, table.id, source, columns])).expect("definitions serialize"); (table.id.clone(), hex::encode(sha2::Sha256::digest(bytes))) }) .collect()}/// One column as what it is worked out from: its definition and, for a/// computed column, every column it reads, to the end.fn column_inputs( all: &[&TableDefinition], table: &TableDefinition, key: &str, path: &mutVec<(String, String)>, known: &mut BTreeMap<(String, String), Value>,) -> Value {letSome(column) = table.column(key) else { return json!([table.id, key, null]) };letSome(computed) = &column.computed else { return json!([table.id, column]) };let node = (table.id.clone(), key.to_string());ifletSome(inputs) = known.get(&node) {return inputs.clone(); }if path.contains(&node) {return json!([table.id, key, "cycle"]); } path.push(node.clone());let reads: Vec<Value> = computed .reads(table, all) .into_iter() .map(|(other, read)| match all.iter().copied().find(|candidate| candidate.id == other) {Some(other) => column_inputs(all, other, read, path, known),None => json!([other, read, null]), }) .collect(); path.pop();let inputs = json!([table.id, column, reads]); known.insert(node, inputs.clone()); inputs}/// The derive pass a process installs ([`install`]).pubstructCoreDerive;implDeriveforCoreDerive {fn fill(&self, db: &Driver, rows: &[(String, String)]) -> Result<()> {crate::money_run::after_fold(db, rows) }fn reads(&self, table: &str) -> bool { READ.contains(&table) || made_of(table).is_some() || kind_store(table) || crate::activity::reads(table) }fn derive(&self, db: &Driver, rows: &[(String, String)]) -> Result<()> {// A redefinition moves the file's derivation by itself: the index is// stale from this fold on, its kept stamps saying which tables the// rebuild has to work out again.let redefined = rows.iter().any(|(table, _)| table == "cotton_table_definitions");// ON A DEVICE a stale index, or a fold that redefines a table, is// left to the background rebuild with the rows this fold changed:// a rebuild here would run inside the sync pass, holding the copy's// mutex and its write lock for minutes ([`Driver::index_beside`]).// A redefinition is asked first: whether the index is current costs// a stamp over every definition the file holds, which a fresh copy's// 21 tool installs paid once each (copy-installer-cpu, 7 Nov 2026).if db.indexes_beside() && redefined {return note_pending(db, rows); }let stale = !is_current(db)?;if db.indexes_beside() && stale {return note_pending(db, rows); }// A stale index is not patched: it is rebuilt, here, by the first// fold that would have patched it.if stale && rework_in_place(db)? {returnOk(()); } derive_rows(db, rows) }}/// The store tables whose rows a computed column of a made table always/// reads; a made table's own rows are read too ([`made_of`]), and a/// built-in's own table by the lookups that point into it.const READ: &[&str] = &["cotton_table_definitions"];/// The made table whose records are rows of store table `table`: a table no/// compiled spec owns, named `cotton_<id>` (`tables::made_table`).fn made_of(table: &str) -> Option<&str> {if !cotton_store::schema::package_shape::may_arrive(table) {returnNone; } table.strip_prefix("cotton_").filter(|id| !id.is_empty())}/// The built-in tables whose records are rows of store table `table`.fn builtins_stored_in(table: &str) -> Vec<&'static str> {static STORED: std::sync::OnceLock<Vec<(String, String, String)>> = std::sync::OnceLock::new(); STORED .get_or_init(|| { builtin_table_definitions() .iter() .filter_map(|definition| Some((definition.store_table()?.to_string(), definition.id.clone(), definition.rows_table().to_string()))) .collect() }) .iter() .filter(|(store, _, rows)| holds_rows_of(store, rows, table)) .map(|(_, id, _)| id.as_str()) .collect()}/// Whether a table whose rows live in `store` (and are `rows`' rows) has/// records that are rows of store table `table`. A view over a store is/// queued with the table it reads; a Money projection with every store it/// reads.fn holds_rows_of(store: &str, rows: &str, table: &str) -> bool { store == table || crate::mcp::handlers::money_views::projection_tables(rows).contains(&table)}/// Whether store table `table` holds the rows of a kind with a built-in/// store — compiled in or not. A kit's table over one (Money's `transaction`/// and its view Owed, which arrive with the money tool) is a definition of/// the file's, not of this build, so its store is read whatever the/// compiled definitions name; the pass then finds the file's tables in it/// ([`Catalogue::stored_in`]).fn kind_store(table: &str) -> bool {static STORES: std::sync::OnceLock<BTreeSet<&'static str>> = std::sync::OnceLock::new(); STORES .get_or_init(|| { cotton_core::constants::PrimitiveKind::ALL .iter() .map(|kind| kind.as_str()) .chain(cotton_core::definitions::SUPPORTING_BUILTINS.iter().map(|(id, _)| *id)) .flat_map(|id| builtin_store_table(id).into_iter().chain(crate::mcp::handlers::money_views::projection_tables(id).iter().copied())) .collect() }) .contains(table)}/// One column of a built-in's record, as its row stores it: nothing for a/// column its engine works out or keeps as a list, or one its row has not.fn builtin_value(db: &Driver, table: &str, id: &str, key: &str) -> Result<Value> {let stored = builtin_store_table(table).filter(|store| { !is_computed_column(table, key) && !RESOLVED_COLUMNS.contains(&(table, key)) && cotton_store::schema::specs::columns_of(store).is_some_and(|columns| columns.iter().any(|(name, _)| *name == key)) });letSome(store) = stored else {returnOk(Value::Null); };let row = db.get(&format!("SELECT \"{key}\" AS value FROM {store} WHERE id = ?"), &[SqlValue::Text(id.to_string())])?;Ok(stored_value(row.as_ref().and_then(|row| row.get("value")), ColumnType::Text))}/// Give this process the derive pass, so every fold on every handle keeps/// `_computed` in step. Called once by whatever starts a process that folds.pubfn install() {static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| derived::install(std::sync::Arc::new(CoreDerive)));}/// Rebuild `_computed` unless this build's derivation/// already rebuilt it and nothing has marked it stale since.pubfn ensure_current(db: &Driver) -> Result<()> {if is_current(db)? {returnOk(()); } rebuild(db)}/// Whether `_computed` holds what this build works out: rebuilt whole by this/// build's derivation and marked stale by nothing since. A read that orders,/// filters or searches on a computed column asks first — a stale index would/// answer a wrong list, and a read may not rebuild it.pubfn is_current(db: &Driver) -> Result<bool> {Ok(derived::derivation(db)?.as_deref() == Some(derivation_of(db)?.as_str()))}/// Observable boundaries of a background index pass, outside application locks.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumIndexProgress {Started,Finished { ms: u64, success: bool },}/// Work on an existing file through a dedicated WAL connection. The caller/// keeps the file alive, but holds neither its writer nor replica mutex./// The atomic transaction leaves stale-dependent reads refusing until commit.pubfn ensure_file_current( path: &std::path::Path, workspace_id: &str, report: implFn(IndexProgress),) -> Result<Option<Vec<String>>> {let connection = rusqlite::Connection::open_with_flags( path, rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, )?;// Closing this temporary writer must not checkpoint and delete the WAL. connection.set_db_config(rusqlite::config::DbConfig::SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, true)?;let db = Driver::from_connection(connection, true)?;if is_current(&db)? {returnOk(None); }let started = std::time::Instant::now(); tracing::info!(workspace_id, ms = 0u64, "computed index rebuild started"); report(IndexProgress::Started);let result = rebuild_beside(&db);let ms = started.elapsed().as_millis() as u64;let success = result.is_ok(); tracing::info!(workspace_id, ms, success, "computed index rebuild finished"); report(IndexProgress::Finished { ms, success }); result}/// How many times a rebuild beside the folds is worked out again because a/// table was redefined while it ran, before it gives the index up to the/// next open.const BESIDE_ROUNDS: usize = 3;/// THE REBUILD HOLDS NO WRITE LOCK WHILE IT WORKS. The new index is worked/// out on this connection's own TEMP `_computed` — an unqualified name finds/// the temp table first, so every read and write of the derive pass lands/// there — inside a READ transaction on the copy, which no writer waits for./// Then one short write swaps it in: the rows folds changed meanwhile (left/// pending by [`CoreDerive::derive`]) are patched, and the marker says/// current, in the same transaction. Before, the whole rebuild was one write/// transaction, and every sync pass and every screen write waited out/// SQLite's thirty-second busy timeout behind it — for minutes, on a phone/// that iOS suspended before it ever committed (20 Oct 2026).fn rebuild_beside(db: &Driver) -> Result<Option<Vec<String>>> {for _ in0..BESIDE_ROUNDS {if is_current(db)? {returnOk(None); } db.exec("DROP TABLE IF EXISTS temp._computed; \ CREATE TEMP TABLE _computed (table_id TEXT NOT NULL, record_id TEXT NOT NULL, \ key TEXT NOT NULL, value, PRIMARY KEY (table_id, record_id, key))", )?;let worked_out = db.read_transaction(|db| {let _rows = RebuildRows::begin();let catalogue = Catalogue::load(db)?;let rework = Rework::of(db, catalogue.as_deref())?; rework.copy_inputs(db)?; rework.work_out(db, catalogue.as_deref())?;Ok(rework) });let swapped = worked_out.and_then(|rework| db.transaction(|db| swap_in(db, &rework)));let _ = db.exec("DROP TABLE IF EXISTS temp._computed");match swapped? {Swap::Done(moved) => returnOk(Some(moved)),Swap::Redefined => continue,Swap::Overtaken => returnOk(None), } }Ok(None)}enumSwap {Done(Vec<String>),/// A table was redefined while the index was worked out: it is worked/// out again.Redefined,/// Another rebuild swapped its index in while this one worked: that one/// is the newer, and this one's work is thrown away.Overtaken,}/// The pending marker's key: a row a fold changed while the index was stale,/// `record_id` its `<store table>\u{1f}<row id>`.const PENDING: &str = "pending";const PENDING_SEPARATOR: char = '\u{1f}';/// Leave `rows` for the background rebuild to patch.fn note_pending(db: &Driver, rows: &[(String, String)]) -> Result<()> {for (table, id) in rows { db.run("INSERT OR IGNORE INTO main._computed (table_id, record_id, key, value) VALUES ('', ?, ?, NULL)", &[SqlValue::Text(format!("{table}{PENDING_SEPARATOR}{id}")), SqlValue::Text(PENDING.to_string())], )?; }Ok(())}fn swap_in(db: &Driver, rework: &Rework) -> Result<Swap> {// TWO REBUILDS MAY RUN AT ONCE, each on its own connection (the open's// and the one a sync pass starts). The first to swap patches and clears// the pending rows and marks the index current; a second swapping after// it would put an index worked out from an older read over those rows// and mark it current, and the rows folds changed in between would be// lost until the next redefinition (20 Oct 2026: a summary's rollup read// empty after its source tool was removed).if derived::main_derivation(db)?.as_deref() == Some(rework.derivation.as_str()) {returnOk(Swap::Overtaken); }let pending = pending_rows(db)?;// The redefinition is worked out again by the next round; the rows// other folds changed stay pending for the swap that ends it.if pending.iter().any(|(table, _)| table == "cotton_table_definitions") {for (table, id) in pending.iter().filter(|(table, _)| table == "cotton_table_definitions") { db.run("DELETE FROM main._computed WHERE table_id = '' AND record_id = ? AND key = ?", &[SqlValue::Text(format!("{table}{PENDING_SEPARATOR}{id}")), SqlValue::Text(PENDING.to_string())], )?; }returnOk(Swap::Redefined); } rework.clear(db, "main")?; db.run("DELETE FROM main._computed WHERE table_id = '' AND key = ?", &[SqlValue::Text(PENDING.to_string())])?; rework.carry(db)?; db.exec("DROP TABLE temp._computed")?;if !pending.is_empty() { derive_rows(db, &pending)?; } moved_tables(db).map(Swap::Done)}/// The store tables a rebuild of `_computed` moves — every table holding a/// computed column, as a `data` event names it (a built-in's store, else/// `cotton_<id>`), and `_computed` itself — what the done signal of the/// background rebuild names so the lists it stalled read again by/// themselves (passivemove rule 3).pubfn moved_tables(db: &Driver) -> Result<Vec<String>> {letmut tables = BTreeSet::new();ifletSome(catalogue) = Catalogue::load(db)? {for (table, _) in &catalogue.order {letSome(definition) = catalogue.table(table) else { continue }; tables.insert(definition.store_table().map_or_else(|| format!("cotton_{}", definition.rows_table()), str::to_string)); } } tables.insert("_computed".to_string());Ok(tables.into_iter().collect())}typeOpening = (Value, BTreeSet<String>);typeCurrencyOpenings = (BTreeMap<String, Opening>, Opening, Opening);/// One ordered column's state, shared by persisted and virtual row reads.structOrderedValues<'a> { table: &'a TableDefinition, key: &'a str, computed: &'a Computed, partitions: BTreeMap<String, (Value, BTreeSet<String>)>, openings: BTreeMap<Option<String>, (Value, BTreeSet<String>)>,/// The window of the row [`OrderedValues::step`] last walked. last_window: String,}impl<'a> OrderedValues<'a> {fn new(table: &'a TableDefinition, key: &'a str, computed: &'a Computed) -> Self {Self { table, key, computed, partitions: BTreeMap::new(), openings: BTreeMap::new(), last_window: String::new() } }/// The window a row's ordered value is worked out in: its partition's/// values (and an amount's currency) as one JSON tuple, which keeps type/// and field boundaries, absent values too; with the currency and whether/// the amount's unit is known.fn window(&self, catalogue: &Catalogue, db: &Driver, id: &str, data: &Data, from_read: bool) -> Result<(String, Option<String>, bool)> {let (column, partition) = ordered_shape(self.computed);let currency = catalogue.resolved_currency_in(db,self.table,id,data,column,from_read)?;let source = self.table.column(column);let known = source.is_none_or(|source| source.currency.is_none()) || currency.is_some();letmut tuple = Vec::new();for key in partition { tuple.push(catalogue.value_in(db,self.table,id,data,key,from_read)?); }if source.is_some_and(|source| source.column_type == ColumnType::Amount) { tuple.push(currency.clone().map_or(Value::Null,Value::String)); }Ok((Value::Array(tuple).to_string(), currency, known)) }fn step(&mutself, catalogue: &Catalogue, db: &Driver, id: &str, data: &Data, from_read: bool) -> Result<Value> {let (partition, currency, known) = self.window(catalogue, db, id, data, from_read)?;self.last_window.clone_from(&partition);let (column, _) = ordered_shape(self.computed);let amount = catalogue.value_in(db,self.table,id,data,column,from_read)?;matchself.computed {Computed::Previous(_) => {let before = self.partitions.insert(partition,(if known { amount } else { Value::Null },BTreeSet::new()));Ok(before.map_or(Value::Null,|(value,_)|value)) }Computed::Running(shape) => {if !self.openings.contains_key(¤cy) {let opening = catalogue.running_opening(db,self.table,self.key,shape,from_read,currency.as_deref())?;self.openings.insert(currency.clone(),opening); }let initial = self.openings[¤cy].clone();let (total,currencies) = self.partitions.entry(partition).or_insert(initial); *total = running_step(total.clone(),currencies,amount,currency,known);Ok(total.clone()) } _ => unreachable!("only ordered columns have ordered state"), } }}/// The column an ordered shape walks and the columns its windows split by.fn ordered_shape(computed: &Computed) -> (&String, &Vec<String>) {match computed {Computed::Running(shape) => (&shape.column, &shape.partition),Computed::Previous(shape) => (&shape.column, &shape.partition), _ => unreachable!("only ordered columns have ordered state"), }}/// A stale index's refusal where only the file is at hand: the file's own/// database's `refusal.tables.being_worked_out` (the kit's where it has no/// rows), noted typed for the app's boundary/// ([`crate::mcp::handlers::tables::take_being_worked_out`]).fn being_worked_out(db: &Driver) -> cotton_store::StoreError {crate::mcp::handlers::tables::note_being_worked_out();let workspace = cotton_store::meta::read_meta(db).ok().flatten().map(|meta| meta.workspace_id).unwrap_or_default();let lines = crate::presentation::line_rows(db, &workspace); cotton_store::StoreError::refused(crate::mcp::handlers::tables::being_worked_out_words(&lines))}/// Work a window's virtual rows out in memory. The current index supplies/// the same opening as the stored view; no virtual value enters `_computed`.pub(crate) fn values_for_read_rows(db: &Driver, table: &TableDefinition, mut rows: Vec<(String, Data)>) -> Result<Vec<(String, Data)>> {if !table.has_computed() {return ordered_input_rows(db,table,rows);}if !is_current(db)? { returnErr(being_worked_out(db)); }let catalogue = Catalogue::load(db)?.ok_or_else(||being_worked_out(db))?;for (_, key) in catalogue.order.iter().filter(|(id, _)| id == &table.id) {letSome(computed) = table.column(key).and_then(|column| column.computed.as_ref()) else { continue };if computed.is_ordered() { rows = ordered_input_rows(db, table, rows)?; }ifletComputed::Running(shape) = computed {ifletSome(by) = &shape.order { rows = catalogue.order_running_rows(db,table,by,rows,true)?; } }letmut ordered = OrderedValues::new(table, key, computed);for (id,data) in &mut rows {let value = if computed.is_ordered() { ordered.step(&catalogue,db,id,data,true)? } else { catalogue.compute_in(db,table,id,data,key,true)? }; data.insert(key.clone(),value); } } ordered_input_rows(db,table,rows)}/// Match a zero comparison on mixed amount sums without adding currencies./// Single-currency scalars use the index; mixed rows use the very same rollup/// once per currency. No engine has a second definition of the contributing rows.pub(crate) fn mixed_rollup_matches_zero(db: &Driver, table: &TableDefinition, key: &str, zero: bool) -> Result<Vec<String>> {letSome(column) = table.column(key).filter(|column| column.column_type == ColumnType::Amount) else { returnOk(Vec::new()) };letSome(Computed::Rollup(shape)) = column.computed.as_ref().filter(|computed| matches!(computed,Computed::Rollup(shape) if shape.op == RollupOp::Sum)) else { returnOk(Vec::new()) };letSome(catalogue) = Catalogue::load(db)? else { returnOk(Vec::new()) };letSome(other) = catalogue.table(&shape.table) else { returnOk(Vec::new()) };letSome(amount) = &shape.column else { returnOk(Vec::new()) };let scalar: BTreeSet<String> = db.all("SELECT record_id FROM _computed WHERE table_id=? AND key=? AND value IS NOT NULL",&[SqlValue::Text(table.id.clone()),SqlValue::Text(key.into())])? .into_iter().filter_map(|row| row.text("record_id").map(str::to_string)).collect();letmut matching = Vec::new();for (id,_) in live_records(db,table)? {if scalar.contains(&id) { continue; }letmut currencies = BTreeSet::new();for (child,data) in catalogue.rollup_records_in(db,other,&id,shape.read(),None)? {ifletSome(currency) = catalogue.resolved_currency(db,other,&child,&data,amount)? { currencies.insert(currency); } }if currencies.len() < 2 { continue; }letmut all_zero = true;letmut known = true;for currency in currencies {let value = catalogue.rollup_in(db,&id,shape.read(),Some(¤cy))?; known &= value.is_number(); all_zero &= value.as_f64() == Some(0.0); }if known && all_zero == zero { matching.push(id); } }Ok(matching)}/// Work out again every table whose stamp moved — every table, from/// nothing, on a file whose index no stamp vouches for ([`Rework`]).pubfn rebuild(db: &Driver) -> Result<()> { rework_in_place(db).map(drop)}/// [`rebuild`], saying whether it worked every table out from nothing: then/// a fold's own rows are in its values already.fn rework_in_place(db: &Driver) -> Result<bool> {let _rows = RebuildRows::begin(); db.transaction(|db| {let catalogue = Catalogue::load(db)?;let rework = Rework::of(db, catalogue.as_deref())?;// Rows a fold left for a background rebuild that never swapped:// the tables this pass keeps have yet to see them.let pending = if rework.whole { Vec::new() } else { pending_rows(db)? }; rework.clear(db, "main")?; db.run("DELETE FROM main._computed WHERE table_id = '' AND key = ?", &[SqlValue::Text(PENDING.to_string())])?; rework.work_out(db, catalogue.as_deref())?;if !pending.is_empty() { derive_rows(db, &pending)?; }Ok(rework.whole) })}/// One fold's pass over the rows it changed. A redefinition works out the/// tables it moved ([`rebuild`]), then the fold's other rows as any fold's.fn derive_rows(db: &Driver, rows: &[(String, String)]) -> Result<()> {if rows.iter().any(|(table, _)| table == "cotton_table_definitions") && rework_in_place(db)? {returnOk(()); }letSome(catalogue) = Catalogue::load(db)? else {returnOk(()); };let rows: Vec<(String, String)> = rows.iter().filter(|(table, _)| table != "cotton_table_definitions").cloned().collect(); derive_rows_with_catalogue(db, &rows, &catalogue)}/// What one rebuild works out again: every table whose stamp moved, the/// tables no longer worked out at all, and the links their rollups gather/// records by. `whole` when the file keeps no stamps — a file an older/// build indexed, or one whose rows no stamp vouches for any more/// ([`derived::mark_stale`]): every table is worked out from nothing, once.structRework { whole: bool, changed: BTreeSet<String>, gone: BTreeSet<String>, shadows: BTreeSet<(String, String)>,/// The unchanged tables whose values the changed ones read. inputs: BTreeSet<String>, stamps: BTreeMap<String, String>, derivation: String,}implRework {fn of(db: &Driver, catalogue: Option<&Catalogue>) -> Result<Rework> {let kept: BTreeMap<String, String> = db .all("SELECT record_id, value FROM main._computed WHERE table_id = '' AND key = ?", &[SqlValue::Text(derived::STAMP.to_string())], )? .into_iter() .filter_map(|row| Some((row.text("record_id")?.to_string(), row.text("value")?.to_string()))) .collect();let stamps = catalogue.map(|catalogue| catalogue.stamps.clone()).unwrap_or_default();let whole = kept.is_empty();let changed: BTreeSet<String> = stamps .iter() .filter(|(table, stamp)| whole || kept.get(*table) != Some(*stamp)) .map(|(table, _)| table.clone()) .collect();let gone = kept.keys().filter(|table| !stamps.contains_key(*table)).cloned().collect();letmut shadows = BTreeSet::new();letmut inputs = BTreeSet::new();ifletSome(catalogue) = catalogue {let all: Vec<&TableDefinition> = catalogue.tables.iter().collect();for table in catalogue.tables.iter().filter(|table| changed.contains(&table.id)) {for computed in table.columns.iter().filter_map(|column| column.computed.as_ref()) {ifletSome(link) = computed.rollup().and_then(|rollup| rollup.link) { shadows.insert((computed.rollup().map(|rollup| rollup.table.to_string()).unwrap_or_default(), link.to_string())); }for (other, _) in computed.reads(table, &all) {if !changed.contains(other) { inputs.insert(other.to_string()); } } } } shadows.extend(catalogue.gathered.iter().filter(|(table, _)| changed.contains(table)).cloned()); shadows.retain(|pair| catalogue.gathered.contains(pair)); }let derivation = catalogue.map_or_else(|| stamp_over(&BTreeMap::new()), |catalogue| catalogue.derivation.clone());Ok(Rework { whole, changed, gone, shadows, inputs, stamps, derivation }) }/// Take away, from `schema`'s `_computed`, what this rework writes again.fn clear(&self, db: &Driver, schema: &str) -> Result<()> {ifself.whole {return db.run(&format!("DELETE FROM {schema}._computed"), &[]).map(drop); }for table inself.changed.iter().chain(&self.gone) { db.run(&format!("DELETE FROM {schema}._computed WHERE table_id = ?"), &[SqlValue::Text(table.clone())])?; }for (table, link) in &self.shadows { db.run( &format!("DELETE FROM {schema}._computed WHERE table_id = ? AND key = ?"), &[SqlValue::Text(table.clone()), SqlValue::Text(shadow_key(link))], )?; } db.run( &format!("DELETE FROM {schema}._computed WHERE table_id = '' AND key IN (?, ?)"), &[SqlValue::Text(derived::STAMP.to_string()), SqlValue::Text("derivation".to_string())], ) .map(drop) }/// Beside the folds: the values the changed tables read, from the file's/// own index into the TEMP one this rebuild works on.fn copy_inputs(&self, db: &Driver) -> Result<()> {for table in &self.inputs { db.run("INSERT INTO temp._computed SELECT * FROM main._computed WHERE table_id = ?", &[SqlValue::Text(table.clone())])?; }Ok(()) }/// Work the changed tables out, their gathered links first, and say the/// index is current with every table's stamp.fn work_out(&self, db: &Driver, catalogue: Option<&Catalogue>) -> Result<()> {ifletSome(catalogue) = catalogue {for (table, link) in &catalogue.gathered {if !self.whole && !self.shadows.contains(&(table.clone(), link.clone())) { continue }letSome(definition) = catalogue.table(table) else { continue };for (id, data) in live_records(db, definition)? { write(db, table, &id, &shadow_key(link), data.get(link).cloned().unwrap_or(Value::Null))?; } }for (table, column) in catalogue.order.iter().filter(|(table, _)| self.changed.contains(table)) {letSome(definition) = catalogue.table(table) else { continue }; catalogue.compute_column(db, definition, column)?; } }for (table, stamp) in &self.stamps { write(db, "", table, derived::STAMP, Value::String(stamp.clone()))?; } derived::mark_rebuilt(db, &self.derivation) }/// The swap: what the TEMP index worked out, into the file's own.fn carry(&self, db: &Driver) -> Result<()> {ifself.whole {return db.run("INSERT INTO main._computed SELECT * FROM temp._computed", &[]).map(drop); }for table in &self.changed { db.run("INSERT INTO main._computed SELECT * FROM temp._computed WHERE table_id = ?", &[SqlValue::Text(table.clone())])?; }for (table, link) inself.shadows.iter().filter(|(table, _)| !self.changed.contains(table)) { db.run("INSERT INTO main._computed SELECT * FROM temp._computed WHERE table_id = ? AND key = ?", &[SqlValue::Text(table.clone()), SqlValue::Text(shadow_key(link))], )?; } db.run("INSERT INTO main._computed SELECT * FROM temp._computed WHERE table_id = '' AND key IN (?, ?)", &[SqlValue::Text(derived::STAMP.to_string()), SqlValue::Text("derivation".to_string())], ) .map(drop) }}/// The rows folds left pending ([`note_pending`]).fn pending_rows(db: &Driver) -> Result<Vec<(String, String)>> {Ok(db .all("SELECT record_id FROM main._computed WHERE table_id = '' AND key = ?", &[SqlValue::Text(PENDING.to_string())])? .into_iter() .filter_map(|row| row.text("record_id").and_then(|at| at.split_once(PENDING_SEPARATOR)).map(|(table, id)| (table.to_string(), id.to_string()))) .collect())}fn derive_rows_with_catalogue(db: &Driver, rows: &[(String, String)], catalogue: &Catalogue) -> Result<()> {// Work out which columns the fold can move, in dependency order. An// unrelated ordered table must not turn a row-local update into a scan.letmut changed: BTreeSet<String> = rows.iter().flat_map(|(store, _)| { made_of(store).map(str::to_string).into_iter() .chain(catalogue.stored_in(store).into_iter().map(str::to_string)) }).collect();// A view over a changed table changes with it.let viewing: Vec<String> = catalogue.tables.iter() .filter(|table| table.source.as_ref().is_some_and(|source| changed.contains(&source.table))) .map(|table| table.id.clone()) .collect(); changed.extend(viewing);let all: Vec<&TableDefinition> = catalogue.tables.iter().collect();letmut affected = Vec::new();// An activity column moves with the events of its records' handles,// record by record (`Catalogue::derive_activity`), never as a column. catalogue.derive_activity(db, rows)?;for (table, key) in &catalogue.order {letSome(definition) = catalogue.table(table) else { continue };letSome(computed) = definition.column(key).and_then(|column| column.computed.as_ref()) else { continue };if matches!(computed, Computed::Activity(_)) { continue; }if changed.contains(table) || computed.reads(definition, &all).iter().any(|(table, _)| changed.contains(*table)) { affected.push((definition, key)); changed.insert(table.clone()); } }if rows.iter().any(|(store, _)| !catalogue.stored_in(store).is_empty()) || affected.iter().any(|(table, key)| table.column(key).and_then(|column| column.computed.as_ref()).is_some_and(Computed::is_ordered)) {// Ordered values may move on rows the fold did not name. Visit each// affected column once, across all its live rows; downstream lookups// and rollups then read the complete preceding column.for (definition, key) in affected {if !catalogue.compute_row_formula(db, definition, key, rows)? && !catalogue.compute_windows(db, definition, key, rows)? { catalogue.compute_column(db, definition, key)?; } }// Keep the link shadows in step too: the ordinary row-local pass// may resume if the last ordered definition is later removed.for (table, link) in &catalogue.gathered {if !changed.contains(table) { continue; }letSome(definition) = catalogue.table(table) else { continue };let rows = live_records(db, definition)?;let live: BTreeSet<&str> = rows.iter().map(|(id, _)| id.as_str()).collect();let shadow = shadow_key(link);for row in db.all("SELECT record_id FROM _computed WHERE table_id = ? AND key = ?", &[SqlValue::Text(table.clone()), SqlValue::Text(shadow.clone())])? {ifletSome(id) = row.text("record_id").filter(|id| !live.contains(id)) { write(db, table, id, &shadow, Value::Null)?; } }for (id, data) in rows { write(db, table, &id, &shadow, data.get(link).cloned().unwrap_or(Value::Null))?; } }returnOk(()); }// (table, record, whether the fold itself changed it). A record the fold// changed moves whatever reads it; one reached through another moves// what reads it only when its own computed values moved. A made table's// row names its table by the store table it is a row of.letmut queue: VecDeque<(String, String, bool)> = rows .iter() .filter_map(|(store, id)| Some((made_of(store)?.to_string(), id.clone(), true))) .collect();// A built-in's record that changed moves the lookups that read it.for (store, id) in rows {for builtin in catalogue.stored_in(store) {for (reader, through) in catalogue.lookups_into(builtin) {letSome(reading) = catalogue.table(&reader) else { continue };for (dependent, _) in linked_records(db, reading, &through, id)? { queue.push_back((reader.clone(), dependent, false)); } } } }letmut visits = 0usize;whileletSome((table, id, folded)) = queue.pop_front() { visits += 1;if visits > MOST_VISITS {returnErr(cotton_store::StoreError::Refused("a fold moved more computed values than one pass works out".into(), )); }letSome(definition) = catalogue.table(&table) else { continue };let data = live_record(db, definition, &id)?;letmut moved = folded;for (_, column) in catalogue.order.iter().filter(|(of, _)| *of == table) {let value = match &data {Some(data) => catalogue.compute(db, definition, &id, data, column)?,None => Value::Null, }; moved |= write(db, &table, &id, column, value)?; }// The records whose rollups gather this one: where its link points// now, and where it pointed when this pass last saw it.for (_, link) in catalogue.gathered.iter().filter(|(of, _)| *of == table) {letSome(host) = definition.column(link).and_then(|column| column.link_to.clone()) else { continue };let now = data.as_ref().and_then(|data| data.get(link)).cloned().unwrap_or(Value::Null);let before = read(db, &table, &id, &shadow_key(link), ColumnType::Text)?;let relinked = write(db, &table, &id, &shadow_key(link), now.clone())?;if moved || relinked {for target in [before, now].iter().filter_map(Value::as_str) { queue.push_back((host.clone(), target.to_string(), false)); } } }if !moved {continue; }// The records that look a value up through a link to this one.for (reader, through) in catalogue.lookups_into(&table) {letSome(reading) = catalogue.table(&reader) else { continue };for (dependent, _) in linked_records(db, reading, &through, &id)? { queue.push_back((reader.clone(), dependent, false)); } } }Ok(())}/// The resolved tables, and what the pass needs to know of/// their computed columns.structCatalogue { tables: Vec<TableDefinition>,/// Every definition-computed column, each after what it reads. order: Vec<(String, String)>,/// `(table, link column)` some rollup gathers records by: the pass keeps/// where each such link last pointed, to find the record it left. gathered: BTreeSet<(String, String)>,/// Each table's stamp ([`table_stamps`]), for the tables in `order`. stamps: BTreeMap<String, String>,/// What `_computed` says once every table is worked out ([`derivation_of`]). derivation: String,}// The resolved catalogue already invalidates on file, workspace, schema and// definition bytes. Keep only its immutable graph, never record data or values.std::thread_local! {static DERIVE_CATALOGUE: std::cell::RefCell<Option<( std::sync::Arc<crate::definitions::Definitions<TableDefinition>>,Option<std::sync::Arc<Catalogue>>, )>> = const { std::cell::RefCell::new(None) };}implCatalogue {/// `None` while no table has a computed column — every fold's cheap/// way out — or while the definitions do not stand side by side.fn load(db: &Driver) -> Result<Option<std::sync::Arc<Catalogue>>> {let any = db.get("SELECT 1 AS found FROM cotton_table_definitions \ WHERE instr(definition, '\"computed\"') > 0 LIMIT 1", &[], )?;if any.is_none() && !builtin_table_definitions().iter().any(TableDefinition::has_computed) {returnOk(None); }let workspace = cotton_store::meta::read_meta(db)?.map(|meta| meta.workspace_id).unwrap_or_default();let definitions = crate::definitions::shared_table_definitions_from_driver(db, &workspace) .map_err(cotton_store::StoreError::refused)?;let cached = DERIVE_CATALOGUE.with(|cache| { cache.borrow().as_ref().filter(|(held, _)| std::sync::Arc::ptr_eq(held, &definitions)) .map(|(_, catalogue)| catalogue.clone()) });ifletSome(cached) = cached { returnOk(cached); }let catalogue = Self::prepare(definitions.definitions.clone()).map(std::sync::Arc::new); DERIVE_CATALOGUE.with(|cache| *cache.borrow_mut() = Some((definitions, catalogue.clone())));Ok(catalogue) }/// Definition-only work: record values are always read by the current pass.fn prepare(mut tables: Vec<TableDefinition>) -> Option<Self> {// A computed column whose table or column is gone — a rollup over a// tool's table whose definition never reached this device, or was// taken away — holds nothing and the rest are worked out; a column// that read it goes too. Only a cycle, which no install lets in,// leaves the whole index empty.loop {let all: Vec<&TableDefinition> = tables.iter().collect();let gone = dangling(&all);if gone.is_empty() {break; }for table in &mut tables { table.columns.retain(|column| !gone.iter().any(|(t, c)| *t == table.id && *c == column.key)); } }let all: Vec<&TableDefinition> = tables.iter().collect();if validate_across(&all).is_err() {returnNone; }let order: Vec<(String, String)> = derive_order(&all) .into_iter() .filter(|(table, _)| tables.iter().any(|tables| tables.id == *table)) .collect();if order.is_empty() {returnNone; }letmut gathered = BTreeSet::new();for table in &tables {for column in &table.columns {ifletSome(rollup) = column.computed.as_ref().and_then(Computed::rollup) {if tables.iter().any(|tables| tables.id == rollup.table) {ifletSome(link) = rollup.link { gathered.insert((rollup.table.into(), link.into())); } } } } }let stamps: BTreeMap<String, String> = table_stamps(&tables) .into_iter() .filter(|(table, _)| order.iter().any(|(ordered, _)| ordered == table)) .collect();let derivation = stamp_over(&stamps);Some(Catalogue { tables, order, gathered, stamps, derivation }) }fn table(&self, id: &str) -> Option<&TableDefinition> {self.tables.iter().find(|table| table.id == id) }/// The tables whose records are rows of store table `store`: the/// built-ins compiled in ([`builtins_stored_in`]), and every table of the/// file's whose rows live in a built-in's store — a kit's (Money's/// `transaction`, the money tool's) and a view over one (Owed). Without/// the file's own, a fold of a transaction moved none of Owed's signed/// amounts or balances: By person said no "between you" (6 Nov 2026).fn stored_in(&self, store: &str) -> Vec<&str> {letmut ids: Vec<&str> = builtins_stored_in(store);for table in &self.tables {let kept = table.store_table().is_some_and(|kept| holds_rows_of(kept, table.rows_table(), store));if kept && !ids.contains(&table.id.as_str()) { ids.push(&table.id); } } ids }/// `(table, link column)` of every lookup that reads a record of `target`.fn lookups_into(&self, target: &str) -> BTreeSet<(String, String)> {letmut readers = BTreeSet::new();for table in &self.tables {for column in &table.columns {letSome(Computed::Lookup(lookup)) = &column.computed else { continue };let points = table.column(&lookup.through).and_then(|through| through.link_to.as_deref());if points == Some(target) { readers.insert((table.id.clone(), lookup.through.clone())); } } } readers }/// What `key` of one record holds: its stored value, or — a computed/// column — what the pass last worked out for it.fn value_of(&self, db: &Driver, table: &TableDefinition, id: &str, data: &Data, key: &str) -> Result<Value> {match table.column(key) {Some(column) if column.computed.is_some() => read(db, &table.id, id, key, column.column_type), _ => Ok(data.get(key).cloned().unwrap_or(Value::Null)), } }/// Read the currency through the same indexed boundary as a numeric/// value: the currency can itself be a lookup.fn value_in(&self, db: &Driver, table: &TableDefinition, id: &str, data: &Data, key: &str, from_read: bool) -> Result<Value> {if from_read && table.column(key).is_some_and(|column| column.computed.is_some()) {ifletSome(value) = data.get(key) { returnOk(value.clone()); } }self.value_of(db,table,id,data,key) }fn resolved_currency(&self, db: &Driver, table: &TableDefinition, id: &str, data: &Data, key: &str) -> Result<Option<String>> {self.resolved_currency_in(db,table,id,data,key,false) }fn resolved_currency_in(&self, db: &Driver, table: &TableDefinition, id: &str, data: &Data, key: &str, from_read: bool) -> Result<Option<String>> {letSome(currency) = table.column(key).and_then(|column| column.currency.as_deref()) else { returnOk(None) };let currency = if currency == "account" { "account_id" } else { currency };letSome(source) = table.column(currency) else { returnOk(None) };letmut value = self.value_in(db, table, id, data, currency, from_read)?;if source.column_type == ColumnType::Link && source.link_to.as_deref() == Some("money_account") {letSome(account) = value.as_str() else { returnOk(None) }; value = builtin_value(db, "money_account", account, "currency")?; }Ok(value.as_str().filter(|currency| !currency.trim().is_empty()).map(str::to_string)) }/// A formula with only stored, row-local inputs needs only the changed/// records. Resolved values, computed inputs, nonlocal view predicates/// and a soft reference whose parent the fold wrote keep the/// whole-column path, as do all ordered columns.fn compute_row_formula(&self, db: &Driver, table: &TableDefinition, key: &str, changed: &[(String, String)]) -> Result<bool> {letSome(Computed::Formula(formula)) = table.column(key).and_then(|column| column.computed.as_ref()) else { returnOk(false) };letSome(store) = table.store_table() else { returnOk(false) };if !crate::mcp::handlers::tables::derivation_is_row_local(table).map_err(cotton_store::StoreError::refused)? { returnOk(false); }letSome(stored) = cotton_store::schema::specs::columns_of(store) else { returnOk(false) };// A soft reference reads empty once its parent is gone (a person// binned leaves Owed): stored here, but moved by its parent's store,// so a fold that wrote that store works the whole column out.letmut parents: BTreeSet<&str> = BTreeSet::new();letmut plain = |key: &str| {let local = table.column(key).is_some_and(|column| column.computed.is_none()) && stored.iter().any(|(name, _)| *name == key) && !RESOLVED_COLUMNS.contains(&(table.rows_table(), key));for (_, _, parent) in cotton_store::schema::table_specs::SOFT_REFS.iter().filter(|(name, column, _)| *name == store && *column == key) { parents.insert(parent); } local };letmut inputs: BTreeSet<String> = formula.of.iter().cloned().collect();ifletSome(flip) = &formula.flip_when { inputs.insert(flip.column.clone()); }for of in &formula.of {ifletSome(currency) = table.column(of).and_then(|column| column.currency.as_deref()) { inputs.insert(if currency == "account" { "account_id".into() } else { currency.into() }); } }for clause incrate::mcp::handlers::tables::viewed(table).map_err(cotton_store::StoreError::refused)? { inputs.insert(clause.column); }if !inputs.iter().all(|key| plain(key)) || changed.iter().any(|(source, _)| parents.contains(source.as_str())) { returnOk(false); }let ids: Vec<String> = changed.iter().filter(|(source, _)| source == store).map(|(_, id)| id.clone()).collect::<BTreeSet<_>>().into_iter().collect();if ids.is_empty() { returnOk(true); }let workspace = cotton_store::meta::read_meta(db)?.map(|meta| meta.workspace_id).unwrap_or_default();let rows: std::collections::BTreeMap<_, _> = crate::mcp::handlers::tables::derivation_rows_for_ids(db, &workspace, table, &ids) .map_err(cotton_store::StoreError::refused)?.into_iter().collect();for id in ids {let value = match rows.get(&id) {Some(data) => self.compute(db, table, &id, data, key)?,None => Value::Null, }; write(db, &table.id, &id, key, value)?; }Ok(true) }/// ONE WRITE WORKS OUT ONLY THE WINDOWS IT MOVED (coordinator, 7 Nov/// 2026: every money write re-worked Owed's balances over the whole/// book). An ordered column split by a partition is worked out window by/// window: the windows the fold's rows were in (kept beside each row,/// [`window_key`]) and the ones they are in now, each read and folded/// whole by the same [`OrderedValues`] the whole column uses, so a/// row before the moved one keeps its value (nothing is written that did/// not change) and every row after takes the new carry. The whole column/// stays for what a window cannot see: an input another table moves (a/// lookup, an opening gathered elsewhere, a soft reference whose parent/// the fold wrote), a window that appears or empties (the column's/// openings follow its currencies), and a column with no partition.fn compute_windows(&self, db: &Driver, table: &TableDefinition, key: &str, rows: &[(String, String)]) -> Result<bool> {letSome(computed) = table.column(key).and_then(|column| column.computed.as_ref()) else { returnOk(false) };if !keeps_windows(computed) { returnOk(false) }if matches!(computed, Computed::Running(shape) if !matches!(shape.opening, RunningOpening::Number(_))) { returnOk(false) }letSome(parents) = self.local_inputs(table, computed)? else { returnOk(false) };if rows.iter().any(|(store, _)| parents.contains(store.as_str())) { returnOk(false) }let store = table.store_table().map_or_else(|| made_table(table.rows_table()), str::to_string);let ids: Vec<String> = rows.iter().filter(|(of, _)| *of == store).map(|(_, id)| id.clone()).collect::<BTreeSet<_>>().into_iter().collect();if ids.is_empty() { returnOk(false) }let shadow = window_key(key);letmut windows = BTreeSet::new();for id in &ids {ifletSome(window) = read(db, &table.id, id, &shadow, ColumnType::Text)?.as_str() { windows.insert(window.to_string()); } }let now: BTreeMap<String, Data> = match table.store_table() {Some(_) => {let workspace = cotton_store::meta::read_meta(db)?.map(|meta| meta.workspace_id).unwrap_or_default();crate::mcp::handlers::tables::derivation_rows_for_ids(db, &workspace, table, &ids).map_err(cotton_store::StoreError::refused)?.into_iter().collect() }None => {letmut now = BTreeMap::new();for id in &ids { ifletSome(data) = live_record(db, table, id)? { now.insert(id.clone(), data); } } now } };let probe = OrderedValues::new(table, key, computed);for (id, data) in &now { windows.insert(probe.window(self, db, id, data, false)?.0); }let (_, partition) = ordered_shape(computed);for window in &windows {let tuple: Vec<Value> = serde_json::from_str(window).map_err(cotton_store::StoreError::encode)?;// The first partition column narrows the read when it holds a// value; the window's own tuple then keeps its rows exactly.let narrow = tuple.first().and_then(Value::as_str).map(|value| (partition[0].as_str(), value));letmut kept = Vec::new();for (id, data) in ordered_records_where(db, table, narrow)? {if probe.window(self, db, &id, &data, false)?.0 == *window { kept.push((id, data)); } }if kept.iter().all(|(id, _)| ids.binary_search(id).is_ok()) { returnOk(false) }ifletComputed::Running(shape) = computed {ifletSome(by) = &shape.order { kept = self.order_running_rows(db, table, by, kept, false)?; } }letmut fold = OrderedValues::new(table, key, computed);for (id, data) in kept {let value = fold.step(self, db, &id, &data, false)?; write(db, &table.id, &id, key, value)?;// Only a written row's window can have moved.if ids.binary_search(&id).is_ok() { write(db, &table.id, &id, &shadow, Value::String(fold.last_window.clone()))?; } } }// A row binned, or out of a view's rows, holds nothing.for id in ids.iter().filter(|id| !now.contains_key(*id)) { write(db, &table.id, id, key, Value::Null)?; write(db, &table.id, id, &shadow, Value::Null)?; }Ok(true) }/// The stores whose writes can move ordered column `computed`'s inputs/// beside its own rows' — the parents of the soft references it reads/// (a person binned takes their rows out of Owed) — or `None` when it/// reads anything a window cannot keep: another table's column, a value/// resolved or projected at read time, a computed input that is not a/// row-local formula over such columns, or a view whose rows another/// row's change can hide.fn local_inputs(&self, table: &TableDefinition, computed: &Computed) -> Result<Option<BTreeSet<&'static str>>> {if table.store_table().is_some() && !crate::mcp::handlers::tables::derivation_is_row_local(table).map_err(cotton_store::StoreError::refused)? { returnOk(None) }let all: Vec<&TableDefinition> = self.tables.iter().collect();let reads = computed.reads(table, &all);if reads.iter().any(|(of, _)| *of != table.id) { returnOk(None) }letmut inputs: Vec<String> = reads.iter().map(|(_, key)| key.to_string()).collect();for clause incrate::mcp::handlers::tables::viewed(table).map_err(cotton_store::StoreError::refused)? { inputs.push(clause.column); }let stored = table.store_table().and_then(cotton_store::schema::specs::columns_of);letmut parents = BTreeSet::new();letmut seen = BTreeSet::new();whileletSome(key) = inputs.pop() {if !seen.insert(key.clone()) { continue }letSome(column) = table.column(&key) else { returnOk(None) };ifletSome(computed) = &column.computed {letComputed::Formula(formula) = computed else { returnOk(None) }; inputs.extend(computed.reads(table, &all).into_iter().map(|(_, key)| key.to_string()));for of in &formula.of {ifletSome(currency) = table.column(of).and_then(|column| column.currency.as_deref()) { inputs.push(if currency == "account" { "account_id".into() } else { currency.into() }); } }continue; }letSome(store) = table.store_table() else { continue };if !stored.is_some_and(|stored| stored.iter().any(|(name, _)| *name == key)) || RESOLVED_COLUMNS.contains(&(table.rows_table(), key.as_str())) { returnOk(None) }for (_, _, parent) in cotton_store::schema::table_specs::SOFT_REFS.iter().filter(|(name, of, _)| *name == store && *of == key) { parents.insert(*parent); }if column.column_type == ColumnType::Link && column.link_to.as_deref() == Some("money_account") { parents.insert("cotton_money_accounts"); } }Ok(Some(parents)) }fn order_running_rows(&self, db: &Driver, table: &TableDefinition, by: &str, rows: Vec<(String, Data)>, from_read: bool) -> Result<Vec<(String, Data)>> {// Oldest first by `order`; rows alike as the list meets them, the// older of them first when the list reads newest first.let descending = table.sort.as_ref().is_some_and(|sort| sort.descending == Some(true));letmut keyed = Vec::with_capacity(rows.len());for (at,(id,data)) in rows.into_iter().enumerate() {let when = self.value_in(db,table,&id,&data,by,from_read)?; keyed.push((when,if descending {usize::MAX-at} else {at},id,data)); } keyed.sort_by(|a,b| match (a.0.is_null(),b.0.is_null()) { (false,false) => compare_values(&a.0,&b.0), (left,right) => left.cmp(&right), }.then(a.1.cmp(&b.1)));Ok(keyed.into_iter().map(|(_,_,id,data)|(id,data)).collect()) }fn running_opening(&self, db: &Driver, table: &TableDefinition, key: &str, shape: &Running, from_read: bool, currency: Option<&str>) -> Result<(Value, BTreeSet<String>)> {if from_read {let column_type = table.column(key).map(|column| column.column_type).unwrap_or(ColumnType::Amount);if shape.opening_label.is_some() {let cached_currency = read(db,&table.id,OPENING_ROW,&opening_currency_key(key),ColumnType::Text)?;if currency.is_none() || cached_currency.as_str() == currency {let value = read(db,&table.id,OPENING_ROW,key,column_type)?;returnOk((value,cached_currency.as_str().map(str::to_string).into_iter().collect())); } }// A virtual window must never reopen the rollup's source archive.// The writer caches every source currency plus an unseen-currency// opening (which also retains unknown-unit refusals).let cached = read(db,&table.id,OPENING_ROW,&openings_cell(key),ColumnType::Text)?;letSome(cached) = cached.as_str() else {returnErr(being_worked_out(db)); };let (openings, fallback, unpartitioned): CurrencyOpenings = serde_json::from_str(cached).map_err(cotton_store::StoreError::encode)?;returnOk(match currency {Some(currency) => openings.get(currency).cloned().unwrap_or(fallback),None => unpartitioned, }); }letmut currencies = BTreeSet::new();let total = match &shape.opening {RunningOpening::Number(number) => Value::Number(number.clone()),RunningOpening::Rollup(opening) => {let rollup = opening.rollup.read();letmut currency_known = true;iflet (Some(other), Some(column)) = (self.table(rollup.table), rollup.column) {for (source_id, data) inself.rollup_records_in(db, other, "", rollup, currency)? {let currency = self.resolved_currency(db, other, &source_id, &data, column)?; currency_known &= other.column(column).is_none_or(|column| column.currency.is_none()) || currency.is_some();ifletSome(currency) = currency { currencies.insert(currency); } } }let value = self.rollup_in(db, "", rollup, currency)?;if currency_known && currencies.len() <= 1 { value } else { Value::Null } } };Ok((total,currencies)) }/// Work one column out for all its rows. Ordered shapes make one pass,/// rather than scanning the table again for every row of a running sum.fn compute_column(&self, db: &Driver, table: &TableDefinition, key: &str) -> Result<()> {letSome(computed) = table.column(key).and_then(|column| column.computed.as_ref()) else { returnOk(()) };letmut rows = if computed.is_ordered() { ordered_records(db, table)? } else { live_records(db, table)? };ifletComputed::Running(shape) = computed {ifletSome(by) = &shape.order { rows = self.order_running_rows(db,table,by,rows,false)?; } }// Remove values for rows now in the Bin, including the former first// row's previous value after a reorder. The table may not have arrived.let live: BTreeSet<&str> = rows.iter().map(|(id, _)| id.as_str()).collect();let windowed = keeps_windows(computed);for kept in std::iter::once(key.to_string()).chain(windowed.then(|| window_key(key))) {for row in db.all("SELECT record_id FROM _computed WHERE table_id = ? AND key = ?", &[SqlValue::Text(table.id.clone()), SqlValue::Text(kept.clone())])? {ifletSome(id) = row.text("record_id").filter(|id| !live.contains(id)) { write(db, &table.id, id, &kept, Value::Null)?; } } }let has_rows = !rows.is_empty();letmut ordered = OrderedValues::new(table, key, computed);let (total, currencies) = match computed {Computed::Running(shape) => self.running_opening(db,table,key,shape,false,None)?, _ => (json!(0), BTreeSet::new()), };// A running that says its opening (`opening_label`) keeps it, with its// one currency, on the table's own `@opening` row while it has rows to// stand above (as every computed value is a row's), so a change at a// time and a rebuild keep the same.let opening = match computed {Computed::Running(shape) if shape.opening_label.is_some() && !rows.is_empty() => {Some((total.clone(), currencies.iter().next().filter(|_| currencies.len() == 1).cloned())) } _ => None, };// Every record's activity in one read of each store, not one a record.letmut activities = match computed {Computed::Activity(activity) => {let ids: Vec<String> = rows.iter().map(|(id, _)| id.clone()).collect();Some(self.activities(db, &ids, activity)?) } _ => None, };for (id, data) in rows {let value = if computed.is_ordered() {let value = ordered.step(self,db,&id,&data,false)?;if windowed { write(db, &table.id, &id, &window_key(key), Value::String(ordered.last_window.clone()))?; } value } elseifletSome(activities) = activities.as_mut() { activities.remove(&id).unwrap_or(Value::Null) } else {self.compute(db,table,&id,&data,key)? }; write(db, &table.id, &id, key, value)?; }ifletComputed::Running(shape) = computed {if has_rows {letmut currencies: BTreeSet<String> = ordered.openings.keys().flatten().cloned().collect();ifletRunningOpening::Rollup(opening) = &shape.opening {let rollup = opening.rollup.read();iflet (Some(other), Some(column)) = (self.table(rollup.table), rollup.column) {for (id, data) in live_records(db,other)? {ifletSome(currency) = self.resolved_currency(db,other,&id,&data,column)? { currencies.insert(currency); } } } }letmut openings = BTreeMap::new();for currency in ¤cies { openings.insert(currency.clone(),self.running_opening(db,table,key,shape,false,Some(currency))?); }letmut unseen = String::from("@unseen");while currencies.contains(&unseen) { unseen.push('@'); }let fallback = self.running_opening(db,table,key,shape,false,Some(&unseen))?; write(db,&table.id,OPENING_ROW,&openings_cell(key),Value::String(serde_json::to_string(&(openings,fallback,(total,currencies))).map_err(cotton_store::StoreError::encode)?))?; } else { write(db,&table.id,OPENING_ROW,&openings_cell(key),Value::Null)?; } }// An opening no longer said is gone with its currency (the sweep above// took its value: no record holds `@opening`).if matches!(computed, Computed::Running(shape) if shape.opening_label.is_some()) {let (value, currency) = opening.unwrap_or((Value::Null, None));if !value.is_null() { write(db, &table.id, OPENING_ROW, key, value)?; } write(db, &table.id, OPENING_ROW, &opening_currency_key(key), currency.map_or(Value::Null, Value::String))?; }Ok(()) }/// Work out one computed column of one live record.fn compute(&self, db: &Driver, table: &TableDefinition, id: &str, data: &Data, key: &str) -> Result<Value> {self.compute_in(db,table,id,data,key,false) }fn compute_in(&self, db: &Driver, table: &TableDefinition, id: &str, data: &Data, key: &str, from_read: bool) -> Result<Value> {letSome(computed) = table.column(key).and_then(|column| column.computed.as_ref()) else {returnOk(Value::Null); };match computed {Computed::Lookup(lookup) => {let points = table.column(&lookup.through).and_then(|through| through.link_to.as_deref());let (Some(points), Some(linked)) = (points, data.get(&lookup.through).and_then(Value::as_str)) else {returnOk(Value::Null); };letSome(target) = self.table(points) else {return builtin_value(db, points, linked, &lookup.column); };match live_record(db, target, linked)? {Some(there) => self.value_of(db, target, linked, &there, &lookup.column),None => Ok(Value::Null), } }Computed::Rollup(rollup) => self.rollup(db, id, rollup.read()),Computed::Activity(activity) => self.activity(db, id, activity),// Ordered shapes are evaluated as a whole column by compute_column.Computed::Running(_) | Computed::Previous(_) => Ok(Value::Null),Computed::Formula(formula) => {letmut values = Vec::with_capacity(formula.of.len());for of in &formula.of { values.push(self.value_in(db, table, id, data, of, from_read)?); }// Amounts in two currencies have no sum and no difference.if matches!(formula.op, FormulaOp::Sum | FormulaOp::Difference) && mixed(formula.of.iter().map(|of| currency_of(table, of, data))) {returnOk(Value::Null); }Ok(formula_value(formula, &values, data)) } } }/// What an activity column of record `id` holds: the events with the/// handles linked to it ([`crate::activity::of_handles`]).fn activity(&self, db: &Driver, id: &str, activity: &Activity) -> Result<Value> {Ok(self.activities(db, &[id.to_string()], activity)?.remove(id).unwrap_or(Value::Null)) }/// The activity column's value for each of `ids`, worked out for them all/// at once ([`crate::activity::of_records`]).fn activities(&self, db: &Driver, ids: &[String], activity: &Activity) -> Result<BTreeMap<String, Value>> {letSome(handles) = self.table(&activity.handles) else { returnOk(BTreeMap::new()) };letmut held: Vec<(String, Vec<crate::activity::Handle>)> = Vec::with_capacity(ids.len());for id in ids {let handles = linked_records(db, handles, &activity.link, id)? .into_iter() .filter_map(|(_, data)| {let kind = data.get(HANDLE_KIND)?.as_str()?;let value = data.get(HANDLE_VALUE)?.as_str().filter(|value| !value.trim().is_empty())?;Some((kind.to_string(), value.to_string())) }) .collect(); held.push((id.clone(), handles)); }let since = activity.within_days.map(|days| { (chrono::Utc::now() - chrono::Duration::days(i64::from(days))).to_rfc3339_opts(chrono::SecondsFormat::Secs, true) });let workspace = cotton_store::meta::read_meta(db)?.map(|meta| meta.workspace_id).unwrap_or_default();let found = crate::activity::of_records(db, &workspace, &held, since.as_deref())?;Ok(ids .iter() .map(|id| {let (latest, recent) = found.get(id).cloned().unwrap_or((None, 0));let value = match activity.op {ActivityOp::Latest => latest.map_or(Value::Null, Value::String),// A record nobody reached holds nothing, so it lists after the// reached ones in either direction.ActivityOp::Count => if recent > 0 { json!(recent) } else { Value::Null }, }; (id.clone(), value) }) .collect()) }/// Work out again the activity columns of the records a fold's rows/// reach: a record that changed itself, the record a changed handle/// names, and every record holding a handle a changed event was with.fn derive_activity(&self, db: &Driver, rows: &[(String, String)]) -> Result<()> {let columns: Vec<(&TableDefinition, &str, &Activity)> = self.order.iter().filter_map(|(table, key)| {let definition = self.table(table)?;match definition.column(key)?.computed.as_ref()? {Computed::Activity(activity) => Some((definition, key.as_str(), activity)), _ => None, } }).collect();if columns.is_empty() {returnOk(()); }let touched = crate::activity::touched(db, rows)?;let workspace = cotton_store::meta::read_meta(db)?.map(|meta| meta.workspace_id).unwrap_or_default();for (table, key, activity) in columns {letSome(handles) = self.table(&activity.handles) else { continue };let (Some(own), Some(store)) = (table.store_table(), handles.store_table()) else { continue };let link = &activity.link;letmut ids: BTreeSet<String> = rows.iter().filter(|(of, _)| of == own).map(|(_, id)| id.clone()).collect();for (_, handle) in rows.iter().filter(|(of, _)| of == store) {ifletSome(row) = db.get(&format!("SELECT \"{link}\" AS id FROM {store} WHERE id = ?"), &[SqlValue::Text(handle.clone())])? { ids.extend(row.text("id").map(str::to_string)); } }for (kind, value) in &touched {let sql = format!("SELECT DISTINCT \"{link}\" AS id FROM {store} WHERE workspace_id = ? AND \"{HANDLE_KIND}\" = ? AND lower(\"{HANDLE_VALUE}\") = lower(?)");let params = [SqlValue::Text(workspace.clone()), SqlValue::Text(kind.clone()), SqlValue::Text(value.clone())]; ids.extend(db.all(&sql, ¶ms)?.iter().filter_map(|row| row.text("id").map(str::to_string))); }if ids.is_empty() {continue; }let ids: Vec<String> = ids.into_iter().collect();let live: BTreeSet<String> = crate::mcp::handlers::tables::derivation_rows_for_ids(db, &workspace, table, &ids) .map_err(cotton_store::StoreError::refused)? .into_iter() .map(|(id, _)| id) .collect();let live: Vec<String> = live.into_iter().collect();letmut values = self.activities(db, &live, activity)?;for id in ids {let value = values.remove(&id).unwrap_or(Value::Null); write(db, &table.id, &id, key, value)?; } }Ok(()) }/// Filter currency before choosing a first/latest opening.fn rollup_records_in(&self, db: &Driver, other: &TableDefinition, id: &str, rollup: RollupRead<'_>, currency: Option<&str>) -> Result<Vec<(String, Data)>> {letmut gathered = match rollup.link {Some(link) => linked_records(db, other, link, id)?,None => live_records(db, other)?, };ifletSome(filter) = &rollup.where_ { gathered.retain(|(_, data)| holds(filter, data)); }iflet (Some(wanted), Some(column)) = (currency, rollup.column) {letmut matching = Vec::new();for (child, data) in gathered {let units = self.resolved_currency(db,other,&child,&data,column)?;// Unknown units remain unknown; they cannot silently become a zero opening.if units.as_deref().is_none_or(|units| units == wanted) { matching.push((child,data)); } } gathered = matching; }if !matches!(rollup.op, RollupOp::First | RollupOp::Latest) {returnOk(gathered); }letSome(by) = rollup.by.or(other.date.as_deref()) else {returnOk(Vec::new()); };// In order of `by`, then of id, so two devices pick the same one.letmut ordered = Vec::new();for (child, data) in gathered {let at = self.value_of(db, other, &child, &data, by)?;if !at.is_null() { ordered.push((at, child, data)); } } ordered.sort_by(|a, b| compare_values(&a.0, &b.0).then_with(|| a.1.cmp(&b.1)));let picked = if rollup.op == RollupOp::First { ordered.into_iter().next() } else { ordered.pop() };Ok(picked.into_iter().map(|(_, child, data)| (child, data)).collect()) }fn rollup(&self, db: &Driver, id: &str, rollup: RollupRead<'_>) -> Result<Value> {self.rollup_in(db,id,rollup,None) }fn rollup_in(&self, db: &Driver, id: &str, rollup: RollupRead<'_>, currency: Option<&str>) -> Result<Value> {letSome(other) = self.table(rollup.table) else {returnOk(Value::Null); };if other.engine.is_some() && other.store_table().is_none() {returnOk(Value::Null); }ifletSome(filter) = rollup.where_ {if live_records(db, other)?.iter().any(|(_, data)| unprojected(other, &filter.column, data)) {returnOk(Value::Null); } }let gathered = self.rollup_records_in(db, other, id, rollup, currency)?;let read = |key: &str| -> Result<Vec<Value>> { gathered.iter().map(|(child, data)| self.value_of(db, other, child, data, key)).collect() };let column = rollup.column;// A declared engine value absent from the stable projection is// unknown, never an invented zero from summing an empty value list.ifletSome(column) = column {if gathered.iter().any(|(_, data)| unprojected(other, column, data)) { returnOk(Value::Null); } }// Amounts in two currencies have no sum, and no least or greatest:// null, as `records::summarize` answers them "mixed".iflet (RollupOp::Sum | RollupOp::Min | RollupOp::Max, Some(column)) = (rollup.op, column) {if mixed(gathered.iter().map(|(_, data)| currency_of(other, column, data))) {returnOk(Value::Null); } }Ok(match column {None => json!(gathered.len()),Some(_) if rollup.op == RollupOp::Count => json!(gathered.len()),Some(column) => cotton_core::cotton_rules::computed::rollup(rollup.op, gathered.len(), &read(column)?), }) }}fn unprojected(table: &TableDefinition, key: &str, data: &Data) -> bool { table.store_table().is_some() && table.column(key).is_some_and(|column| column.computed.is_none()) && !data.contains_key(key)}/// The currency an amount column of one record is in: its `currency` names a/// sibling column (read from the record) or is the code itself; `None` for a/// column that is not an amount in a currency.fn currency_of(table: &TableDefinition, key: &str, data: &Data) -> Option<String> {let currency = table.column(key)?.currency.as_deref()?;if table.column(currency).is_none() {returnSome(currency.to_string()); } data.get(currency).and_then(Value::as_str).map(str::to_string)}/// Whether the currencies named are more than one.fn mixed(currencies: implIterator<Item = Option<String>>) -> bool { currencies.flatten().collect::<BTreeSet<_>>().len() > 1}/// A formula over the values its `of` names, in order: the one arithmetic/// (`cotton_rules::computed::formula`), `flip_when` read off the record.fn formula_value(formula: &Formula, values: &[Value], data: &Data) -> Value {let flip = formula.flip_when.as_ref().is_some_and(|flip| holds(flip, data)); cotton_core::cotton_rules::computed::formula(formula.op, values, flip, formula.separator.as_deref())}/// Whether the record's column holds one of the values a `where` names.fn holds(filter: &ValueMatch, data: &Data) -> bool { data.get(&filter.column) .and_then(words_of) .is_some_and(|held| filter.values.iter().any(|value| *value == held))}use cotton_core::cotton_rules::computed::words_of;/// The key the pass keeps a gathered link's last target under: no column's/// key starts with `~`, so it can never be a column's.fn shadow_key(link: &str) -> String { format!("~{link}")}/// The bookkeeping key a row's window for ordered column `column` is kept/// under: the window it was last worked out in, so a write that moves it out/// (a person changed, a row binned) works its old window out again too.fn window_key(column: &str) -> String { shadow_key(&format!("{column}@window"))}/// Whether an ordered column keeps each row's window: one split by a/// partition, which a write can move a row between.fn keeps_windows(computed: &Computed) -> bool { computed.is_ordered() && !ordered_shape(computed).1.is_empty()}/// Whether a `_computed` key is a column's, not the pass's own bookkeeping.pubfn is_column_key(key: &str) -> bool { !key.starts_with('~')}/// The live records of made table `table` that `filter` (SQL over its own/// columns) keeps, in order of id, each with its stored values. A table this/// file does not hold yet — its definition arrived, its shape has not — has/// no records.fn made_records(db: &Driver, table: &TableDefinition, filter: &str, params: &[SqlValue]) -> Result<Vec<(String, Data)>> { made_records_ordered(db, table, filter, params, "id")}fn running_step(total: Value, currencies: &mut BTreeSet<String>, amount: Value, currency: Option<String>, currency_known: bool) -> Value {ifletSome(currency) = currency { currencies.insert(currency); }if total.is_number() && amount.is_number() && currencies.len() <= 1 && currency_known { sum_numbers([&total,&amount].into_iter()) } else {// An unknown amount never turns into a known balance.Value::Null }}fn ordered_input_rows(db: &Driver, table: &TableDefinition, rows: Vec<(String, Data)>) -> Result<Vec<(String, Data)>> {letSome(sort) = &table.sort else { returnOk(rows) };let values: Vec<Value> = rows.into_iter().map(|(id,data)| json!({"id":id,"data":data})).collect();let direction = if sort.descending == Some(true) { "DESC" } else { "ASC" };let term = |name: &str| format!("NULLIF(json_extract(value, '$.data.{name}'), '') IS NULL, NULLIF(json_extract(value, '$.data.{name}'), '') COLLATE NOCASE {direction}");letmut terms = vec![term(&sort.column)];ifletSome(tie) = &sort.tie { terms.push(term(tie)); } terms.push("json_extract(value, '$.data.updated_at') DESC, json_extract(value, '$.id')".into());Ok(db.all(&format!("SELECT value FROM json_each(?) ORDER BY {}", terms.join(", ")), &[SqlValue::Text(Value::Array(values).to_string())])? .into_iter().filter_map(|row| {let value: Value = serde_json::from_str(row.text("value")?).ok()?;Some((value.get("id")?.as_str()?.to_string(),value.get("data")?.as_object()?.clone())) }).collect())}fn ordered_records(db: &Driver, table: &TableDefinition) -> Result<Vec<(String, Data)>> { ordered_records_where(db, table, None)}/// [`ordered_records`], only the rows whose stored `column` holds `value`/// when one is named: one window's rows, read in the very order the whole/// table's are, so a window's fold and the whole column's agree.fn ordered_records_where(db: &Driver, table: &TableDefinition, narrow: Option<(&str, &str)>) -> Result<Vec<(String, Data)>> {letSome(sort) = &table.sort else { returnOk(Vec::new()) };if table.store_table().is_some() {letmut rows = match narrow {None => live_records(db,table)?,Some((column, value)) => {let workspace = cotton_store::meta::read_meta(db)?.map(|meta| meta.workspace_id).unwrap_or_default();crate::mcp::handlers::tables::derivation_rows_linked(db, &workspace, table, column, value).map_err(cotton_store::StoreError::refused)? } };for (id,data) in &mut rows {for key in std::iter::once(&sort.column).chain(sort.tie.iter()) {ifletSome(column) = table.column(key).filter(|column| column.computed.is_some()) { data.insert(key.clone(),read(db,&table.id,id,key,column.column_type)?); } } }return ordered_input_rows(db,table,rows); }let direction = if sort.descending == Some(true) { "DESC" } else { "ASC" };let term = |name: &str| {let value = match table.column(name) {Some(column) if column.computed.is_some() => format!("(SELECT value FROM _computed WHERE table_id = '{}' AND record_id = r.id AND key = '{name}')", table.id),Some(_) => format!("r.\"{name}\""),// Catalogue::load removes a computed column whose source is gone;// it was never a physical column. Match UserColumns::expr's blank.None => "NULL".into(), }; format!("NULLIF({value}, '') IS NULL, NULLIF({value}, '') COLLATE NOCASE {direction}") };letmut terms = vec![term(&sort.column)];ifletSome(tie) = &sort.tie { terms.push(term(tie)); } terms.push("r.updated_at DESC, r.id".into());match narrow {None => made_records_ordered(db, table, "", &[], &terms.join(", ")),Some((column, value)) => made_records_ordered(db, table, &format!(" AND r.\"{column}\" = ?"), &[SqlValue::Text(value.to_string())], &terms.join(", ")), }}fn made_records_ordered(db: &Driver, table: &TableDefinition, filter: &str, params: &[SqlValue], order: &str) -> Result<Vec<(String, Data)>> {let store = made_table(table.rows_table());if db.get("SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(store.clone())])?.is_none() {returnOk(Vec::new()); }// A view over a made table keeps the rows its where holds (`viewed`). A// derived value is the same whoever reads it, so a day its where names is// read in UTC, never a reader's zone.let viewed = crate::mcp::handlers::tables::viewed(table).map_err(cotton_store::StoreError::refused)?;let zone = cotton_core::records::where_zone(None);Ok(db .all(&format!("SELECT r.* FROM {store} r WHERE deleted_at IS NULL{filter} ORDER BY {order}"), params)? .iter() .map(|row| {let stored = stored_from_row(table, row); (stored.id, stored.data) }) .filter(|(id, data)| !id.is_empty() && viewed.iter().all(|clause| cotton_core::records::holds(data, clause, &zone))) .collect())}fn live_record(db: &Driver, table: &TableDefinition, id: &str) -> Result<Option<Data>> {if table.store_table().is_some() {returnOk(live_records(db, table)?.into_iter().find(|(candidate, _)| candidate == id).map(|(_, data)| data)); }Ok(made_records(db, table, " AND id = ?", &[SqlValue::Text(id.to_string())])? .into_iter() .next() .map(|(_, data)| data))}fn live_records(db: &Driver, table: &TableDefinition) -> Result<Vec<(String, Data)>> {if table.store_table().is_some() {// Outside a rebuild nothing else holds the rows: no copy.returnOk(std::sync::Arc::try_unwrap(store_rows(db, table)?).unwrap_or_else(|rows| rows.as_ref().clone())); } made_records(db, table, "", &[])}/// A built-in table's live rows, read once per rebuild ([`RebuildRows`]) and/// on every call otherwise.fn store_rows(db: &Driver, table: &TableDefinition) -> Result<std::sync::Arc<Vec<(String, Data)>>> {ifletSome(rows) = RebuildRows::rows(&table.id) {returnOk(rows); }let workspace = cotton_store::meta::read_meta(db)?.map(|meta| meta.workspace_id).unwrap_or_default();let rows = std::sync::Arc::new(crate::mcp::handlers::tables::derivation_rows(db, &workspace, table).map_err(cotton_store::StoreError::refused)?, );RebuildRows::keep(&table.id, &rows);Ok(rows)}/// Rows used repeatedly by a rebuild are cached for that pass alone. Whole/// table operations share their input; rollups cache only each parent's/// linked children. Nothing outlives the rebuild's read snapshot.structRebuildRows { outermost: bool,}#[derive(Default)]structRebuildCache { rows: BTreeMap<String, std::sync::Arc<Vec<(String, Data)>>>, linked: BTreeMap<(String, String, String), std::sync::Arc<Vec<(String, Data)>>>,}thread_local! {static REBUILD_ROWS: std::cell::RefCell<Option<RebuildCache>> = const { std::cell::RefCell::new(None) };}implRebuildRows {fn begin() -> RebuildRows { REBUILD_ROWS.with(|cache| {letmut cache = cache.borrow_mut();let outermost = cache.is_none();if outermost { *cache = Some(RebuildCache::default()); }RebuildRows { outermost } }) }fn rows(table: &str) -> Option<std::sync::Arc<Vec<(String, Data)>>> { REBUILD_ROWS.with(|cache| cache.borrow().as_ref().and_then(|cache| cache.rows.get(table).cloned())) }fn keep(table: &str, rows: &std::sync::Arc<Vec<(String, Data)>>) { REBUILD_ROWS.with(|cache| {ifletSome(cache) = cache.borrow_mut().as_mut() { cache.rows.insert(table.to_string(), std::sync::Arc::clone(rows)); } }); }fn active() -> bool { REBUILD_ROWS.with(|cache| cache.borrow().is_some()) }/// Cache only this parent's linked children, never an unrelated table.fn linked(db: &Driver, table: &TableDefinition, link: &str, target: &str) -> Result<std::sync::Arc<Vec<(String, Data)>>> {let key = (table.id.clone(), link.to_string(), target.to_string());ifletSome(rows) = REBUILD_ROWS.with(|cache| cache.borrow().as_ref().and_then(|cache| cache.linked.get(&key).cloned())) {returnOk(rows); }let rows = std::sync::Arc::new(builtin_linked_records(db, table, link, target)?); REBUILD_ROWS.with(|cache| {ifletSome(cache) = cache.borrow_mut().as_mut() { cache.linked.insert(key, std::sync::Arc::clone(&rows)); } });Ok(rows) }}implDropforRebuildRows {fn drop(&mutself) {ifself.outermost { REBUILD_ROWS.with(|cache| *cache.borrow_mut() = None); } }}/// The live records of `table` whose `link` column points at `target`.fn linked_records(db: &Driver, table: &TableDefinition, link: &str, target: &str) -> Result<Vec<(String, Data)>> {// Only a column the definition holds is ever named in SQL: its key was// validated as an identifier.if table.column(link).is_none_or(|column| column.computed.is_some()) {returnOk(Vec::new()); }if table.store_table().is_some() {ifRebuildRows::active() {returnOk(RebuildRows::linked(db, table, link, target)?.as_ref().clone()); }return builtin_linked_records(db, table, link, target); } made_records(db, table, &format!(" AND \"{link}\" = ?"), &[SqlValue::Text(target.to_string())])}fn builtin_linked_records(db: &Driver, table: &TableDefinition, link: &str, target: &str) -> Result<Vec<(String, Data)>> {let workspace = cotton_store::meta::read_meta(db)?.map(|meta| meta.workspace_id).unwrap_or_default();crate::mcp::handlers::tables::derivation_rows_linked(db, &workspace, table, link, target).map_err(cotton_store::StoreError::refused)}/// A `_computed` value as the reads answer a column of `column_type`.pubfn stored_value(value: Option<&SqlValue>, column_type: ColumnType) -> Value {match value {Some(SqlValue::Integer(whole)) if column_type == ColumnType::Bool => json!(*whole != 0),Some(SqlValue::Integer(whole)) => json!(whole),Some(SqlValue::Real(real)) => json!(real),Some(SqlValue::Text(words)) => json!(words), _ => Value::Null, }}fn read(db: &Driver, table: &str, id: &str, key: &str, column_type: ColumnType) -> Result<Value> {let row = db.get("SELECT value FROM _computed WHERE table_id = ? AND record_id = ? AND key = ?", &[SqlValue::Text(table.to_string()), SqlValue::Text(id.to_string()), SqlValue::Text(key.to_string())], )?;Ok(stored_value(row.as_ref().and_then(|row| row.get("value")), column_type))}/// Keep `value` for one column of one record — nothing is kept for nothing —/// and say whether that changed what was kept./// The record id a table's running opening is kept under (`opening_label`):/// no record's, so no list reads it as a row.pub(crate) const OPENING_ROW: &str = "@opening";/// The cell that caches every source currency's opening for `column`.fn openings_cell(column: &str) -> String { format!("{column}@openings")}/// The key the opening's currency is kept under beside its value.pub(crate) fn opening_currency_key(column: &str) -> String { format!("{column}@currency")}fn write(db: &Driver, table: &str, id: &str, key: &str, value: Value) -> Result<bool> {let stored = match &value {Value::Bool(yes) => SqlValue::Integer(i64::from(*yes)),Value::Number(number) => match number.as_i64() {Some(whole) => SqlValue::Integer(whole),None => SqlValue::Real(number.as_f64().unwrap_or(0.0)), },Value::String(words) => SqlValue::Text(words.clone()),Value::Null => SqlValue::Null,// A list or an object is no computed column's value.Value::Array(_) | Value::Object(_) => SqlValue::Null, };let place = [SqlValue::Text(table.to_string()), SqlValue::Text(id.to_string()), SqlValue::Text(key.to_string())];let before = db .get("SELECT value FROM _computed WHERE table_id = ? AND record_id = ? AND key = ?", &place)? .and_then(|row| row.get("value").cloned()) .unwrap_or(SqlValue::Null);if before == stored {returnOk(false); }if stored == SqlValue::Null { db.run("DELETE FROM _computed WHERE table_id = ? AND record_id = ? AND key = ?", &place)?; } else {letmut params = place.to_vec(); params.push(stored); 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", ¶ms, )?; }Ok(true)}#[cfg(test)]#[path = "derive_tests.rs"]mod tests;