usesuper::*;use cotton_store::meta::Meta;use cotton_store::test_template::create_workspace_in_memory_for_test;use serde_json::json;const WS: &str = "22222222-2222-4222-8222-222222222222";const AT: &str = "2026-10-05T00:00:00.000Z";/// RULE: Ordered columns work on engine-backed tables too; their value spans the whole logical table and a source reorder refreshes every affected row.#[test]fn previous_on_a_builtin_table_tracks_its_full_sort_order() {let db = practice();letmut definition = builtin_table_definitions().iter().find(|table| table.id == "person").unwrap().clone(); definition.sort = Some(serde_json::from_value(json!({"column":"full_name"})).unwrap()); definition.order = None; definition.day_grouping = None; definition.columns.push(serde_json::from_value(json!({"key":"previous_name", "type":"text", "computed":{"previous":{"column":"full_name"}}})).unwrap()); definition.validate().unwrap();// Model a shipped engine definition, not a person's column-look edit.let catalogue = Catalogue { tables: vec![definition.clone()], order: vec![("person".into(),"previous_name".into())], gathered: BTreeSet::new(), stamps: BTreeMap::new(), derivation: String::new() };for (id,name) in [("p1","Alpha"),("p2","beta")] { db.run("INSERT INTO cotton_people (id,workspace_id,full_name,created_at,updated_at) VALUES (?,?,?,?,?)", &[text(id),text(WS),text(name),text(AT),text(AT)]).unwrap(); } catalogue.compute_column(&db, &definition, "previous_name").unwrap(); assert_eq!(kept(&db,"person","p2")["previous_name"],"Alpha"); db.run("UPDATE cotton_people SET full_name='Zulu' WHERE id='p1'",&[]).unwrap(); derive_rows_with_catalogue(&db,&[("cotton_people".into(),"p1".into())], &catalogue).unwrap(); assert!(kept(&db,"person","p2")["previous_name"].is_null()); assert_eq!(kept(&db,"person","p1")["previous_name"],"beta");let incremental = whole(&db); db.run("DELETE FROM _computed", &[]).unwrap(); catalogue.compute_column(&db, &definition, "previous_name").unwrap(); assert_eq!(whole(&db),incremental);}/// RULE: A stale index refused where only the file is at hand still says the file's own database's/// `refusal.tables.being_worked_out`, never the kit's: a database that rewords it hears its words/// from a virtual window's read too, as it does from a list (leftovers-b's restored_said precedent).#[test]fn a_file_only_refusal_says_the_databases_own_words() {let db = practice();letmut definition = builtin_table_definitions().iter().find(|table| table.id == "person").unwrap().clone(); definition.columns.push(serde_json::from_value(json!({"key":"previous_name", "type":"text", "computed":{"previous":{"column":"full_name"}}})).unwrap()); assert!(!is_current(&db).unwrap(), "a file never worked out holds no current index");let kit = crate::mcp::handlers::tables::being_worked_out_words(&[]);let refused = |db: &Driver| match values_for_read_rows(db, &definition, Vec::new()) {Err(cotton_store::StoreError::Refused(words)) => words, other => panic!("a stale index answered {other:?}"), }; assert_eq!(refused(&db), kit);let words = "Still sorting this list out, ask again shortly."; db.run(&format!("CREATE TABLE IF NOT EXISTS {} (id TEXT PRIMARY KEY, workspace_id TEXT, \"set\" TEXT, line TEXT, words TEXT, deleted_at TEXT)", crate::presentation::LINES), &[]).unwrap(); db.run(&format!("INSERT INTO {} (id, workspace_id, \"set\", line, words) VALUES ('l1', ?, 'refusal', 'tables.being_worked_out', ?)", crate::presentation::LINES), &[text(WS), text(words)]).unwrap(); assert_eq!(refused(&db), words); assert!(crate::mcp::handlers::tables::take_being_worked_out(), "the refusal left its typed note");}/// RULE: A view (`source {table, where}`, ruling 03:55 17 Oct) is its/// source's rows that its where keeps, and its computed columns walk those/// rows only: So far's balance after counts what So far shows, never an/// expected row Ahead holds.#[test]fn a_view_works_out_its_columns_over_its_own_rows() {let db = practice();letmut definition = builtin_table_definitions().iter().find(|table| table.id == "person").unwrap().clone(); definition.id = "people_but_beta".into(); definition.source = Some(serde_json::from_value(json!({"table":"person","where":{"full_name":{"not":["beta"]}}})).unwrap()); definition.sort = Some(serde_json::from_value(json!({"column":"full_name"})).unwrap()); definition.order = None; definition.day_grouping = None;// A view holds no store of its own and names no engine: it reads People's. definition.tables = None; definition.engine = None; definition.columns.push(serde_json::from_value(json!({"key":"previous_name", "type":"text", "computed":{"previous":{"column":"full_name"}}})).unwrap());// Only a shipped definition names an engine (so a view is shipped); this// one stands in for a shipped view, as the catalogue below does. assert_eq!(definition.store_table(), Some("cotton_people"));let catalogue = Catalogue { tables: vec![definition.clone()], order: vec![("people_but_beta".into(),"previous_name".into())], gathered: BTreeSet::new(), stamps: BTreeMap::new(), derivation: String::new() };for (id,name) in [("p1","Alpha"),("p2","beta"),("p3","Gamma")] { db.run("INSERT INTO cotton_people (id,workspace_id,full_name,created_at,updated_at) VALUES (?,?,?,?,?)", &[text(id),text(WS),text(name),text(AT),text(AT)]).unwrap(); } catalogue.compute_column(&db, &definition, "previous_name").unwrap(); assert_eq!(kept(&db,"people_but_beta","p3")["previous_name"],"Alpha"); assert!(kept(&db,"people_but_beta","p2").get("previous_name").is_none_or(Value::is_null));}/// RULE (coordinator, 6 Nov 2026: By person said no "between you" and Owed/// no balance): a kit's table over a built-in store — Money's `transaction`/// and its view Owed, the money tool's and never compiled in — is worked out/// by the fold that writes its row, as a compiled table is: the store is/// read, the file's tables in it are found, and Owed's signed amounts and/// running balance follow each write.#[test]fn a_kit_view_over_a_builtin_store_is_worked_out_by_the_fold_that_writes_it() {let kit = |json: &str| -> TableDefinition { serde_json::from_str(json).expect("a kit table") };let transaction = kit(include_str!("../../cotton-core/kits/personal/tables/transaction.json"));let owed = kit(include_str!("../../cotton-core/kits/personal/tables/money_owed.json")); assert!(builtin_table_definitions().iter().all(|table| table.id != "transaction" && table.id != "money_owed"), "both are the money tool's"); assert_eq!(owed.store_table(), Some("cotton_money_transactions")); assert!(CoreDerive.reads("cotton_money_transactions"), "a fold of a transaction runs the pass");let order = vec![("money_owed".to_string(), "owed_signed".to_string()), ("money_owed".to_string(), "balance_after".to_string())];let catalogue = Catalogue { tables: vec![transaction, owed], order, gathered: BTreeSet::new(), stamps: BTreeMap::new(), derivation: String::new() }; assert_eq!(catalogue.stored_in("cotton_money_transactions"), ["transaction", "money_owed"]);let db = practice(); db.run("INSERT INTO cotton_people (id,workspace_id,full_name,created_at,updated_at) VALUES ('p-orrel',?,'Orrel Hartsvane',?,?)", &[text(WS), text(AT), text(AT)]).unwrap();// They paid 1,500 for dinner (owed by you); you paid 500 of it back.for (id, day, amount, direction) in [("t-dinner", "2026-11-01", 150000, "in"), ("t-repaid", "2026-11-03", 50000, "out")] { db.run("INSERT INTO cotton_money_transactions (id,workspace_id,occurred_on,description,counterparty_person_id,amount_minor,direction,currency,status,moves_money,created_at,updated_at) VALUES (?,?,?,'Invented',?,?,?,'INR','actual',0,?,?)", &[text(id), text(WS), text(day), text("p-orrel"), SqlValue::Integer(amount), text(direction), text(AT), text(AT)], ).unwrap(); derive_rows_with_catalogue(&db, &[("cotton_money_transactions".into(), id.into())], &catalogue).unwrap(); } assert_eq!(kept(&db, "money_owed", "t-dinner"), json!({"owed_signed": -150000, "balance_after": -150000})); assert_eq!(kept(&db, "money_owed", "t-repaid"), json!({"owed_signed": 50000, "balance_after": -100000}));}/// Owed over the money store, its catalogue as the money tool brings it,/// five invented people, and a writer of transactions that runs the fold.fn owed_book() -> (Driver, Catalogue) {let kit = |json: &str| -> TableDefinition { serde_json::from_str(json).expect("a kit table") };let transaction = kit(include_str!("../../cotton-core/kits/personal/tables/transaction.json"));let owed = kit(include_str!("../../cotton-core/kits/personal/tables/money_owed.json"));let order = vec![("money_owed".to_string(), "owed_signed".to_string()), ("money_owed".to_string(), "balance_after".to_string())];let catalogue = Catalogue { tables: vec![transaction, owed], order, gathered: BTreeSet::new(), stamps: BTreeMap::new(), derivation: String::new() };let db = practice();for at in0..5 { db.run("INSERT INTO cotton_people (id,workspace_id,full_name,created_at,updated_at) VALUES (?,?,?,?,?)", &[text(&format!("p-{at}")), text(WS), text(&format!("Invented Person {at}")), text(AT), text(AT)]).unwrap(); } (db, catalogue)}/// Write one transaction's columns (made when new) and run the fold over it.fn spend(db: &Driver, catalogue: &Catalogue, id: &str, set: &[(&str, SqlValue)], moment: &str) { db.run("INSERT OR IGNORE INTO cotton_money_transactions (id,workspace_id,occurred_on,description,counterparty_person_id,amount_minor,direction,currency,status,moves_money,created_at,updated_at) VALUES (?,?,'2026-10-01','Invented','p-0',100,'out','INR','actual',0,?,?)", &[text(id), text(WS), text(moment), text(moment)], ).unwrap();for (column, value) in set { db.run(&format!("UPDATE cotton_money_transactions SET {column} = ?, updated_at = ? WHERE id = ?"), &[value.clone(), text(moment), text(id)]).unwrap(); } derive_rows_with_catalogue(db, &[("cotton_money_transactions".into(), id.into())], catalogue).unwrap();}/// RULE (coordinator, 7 Nov 2026: one money write re-worked Owed over the/// whole book): a write works out only the windows it moved. A row of/// another person's window is never visited: a value planted there stays.#[test]fn a_money_write_works_out_only_its_own_persons_window() {let (db, catalogue) = owed_book();letmut moment = 0;letmut at = || { moment += 1; format!("2026-11-07T10:{:02}:{:02}.000Z", moment / 60, moment % 60) };for (id, person, day) in [("t-a1", "p-1", "2026-10-01"), ("t-a2", "p-1", "2026-10-03"), ("t-b1", "p-2", "2026-10-02"), ("t-b2", "p-2", "2026-10-04")] { spend(&db, &catalogue, id, &[("counterparty_person_id", text(person)), ("occurred_on", text(day))], &at()); } assert_eq!(kept(&db, "money_owed", "t-a2")["balance_after"], json!(200));// A value planted in p-2's window: a whole-book pass would put it right. db.run("UPDATE _computed SET value = 999 WHERE table_id = 'money_owed' AND record_id = 't-b2' AND key = 'balance_after'", &[]).unwrap(); spend(&db, &catalogue, "t-a1", &[("amount_minor", SqlValue::Integer(500))], &at()); assert_eq!(kept(&db, "money_owed", "t-a2")["balance_after"], json!(600), "the carry moves forward in its window"); assert_eq!(kept(&db, "money_owed", "t-b2")["balance_after"], json!(999), "another window is never visited");// Moving a row to p-2 works both windows out: the one it left and the one it joined. spend(&db, &catalogue, "t-a1", &[("counterparty_person_id", text("p-2"))], &at()); assert_eq!(kept(&db, "money_owed", "t-a2")["balance_after"], json!(100)); assert_eq!(kept(&db, "money_owed", "t-b2")["balance_after"], json!(700));}/// RULE (coordinator, 7 Nov 2026): a full rebuild and any sequence of single/// writes end byte-identical — the window pass and the whole column share one/// fold. A random sequence of creates, amount, date, direction, person and/// narration edits, rows leaving and rejoining the view, and bins, on a book/// with same-day ties, against the whole column worked out from nothing.#[test]fn single_money_writes_end_byte_identical_to_a_rebuild() {let (db, catalogue) = owed_book();letmut seed: u64 = 0x5eed_cafe;letmut roll = |n: u64| { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) % n };letmut moment = 0;letmut made = 0;for step in0..400 { moment += 1;let at = format!("2026-11-07T{:02}:{:02}:{:02}.000Z", 10 + moment / 3600, (moment / 60) % 60, moment % 60);let id = if made < 30 || roll(5) == 0 { made += 1; format!("t-{made:03}") } else { format!("t-{:03}", 1 + roll(made)) };let set: Vec<(&str, SqlValue)> = match roll(9) {0 => vec![("amount_minor", SqlValue::Integer(100 + roll(5000) as i64))],1 => vec![("occurred_on", text(&format!("2026-10-{:02}", 1 + roll(8))))],2 => vec![("direction", text(if roll(2) == 0 { "in" } else { "out" }))],3 => vec![("counterparty_person_id", text(&format!("p-{}", roll(5))))],4 => vec![("description", text(&format!("Invented {step}")))],5 => vec![("status", text(if roll(3) == 0 { "expected" } else { "actual" }))],6 => vec![("trashed_at", if roll(3) == 0 { text(&at) } else { SqlValue::Null })],7 => vec![("currency", text(if roll(6) == 0 { "EUR" } else { "INR" }))], _ => vec![("occurred_on", text(&format!("2026-10-{:02}", 1 + roll(8)))), ("counterparty_person_id", text(&format!("p-{}", roll(5))))], }; spend(&db, &catalogue, &id, &set, &at);// After every write, not only at the end: a later write to a stale// window would work it out again and hide the miss.let stepped = whole(&db); db.run("DELETE FROM _computed", &[]).unwrap();for (table, key) in &catalogue.order { catalogue.compute_column(&db, catalogue.table(table).unwrap(), key).unwrap(); } assert_eq!(whole(&db), stepped, "step {step}, {id}"); } assert!(whole(&db).iter().filter(|(table, _, key, _)| table == "money_owed" && key == "balance_after").count() > 20);}/// RULE: a made table's partitioned running and previous, written one row at/// a time at random, end as a rebuild from nothing ends.#[test]fn a_made_tables_windows_end_as_a_rebuild_does() {let (db, definition) = partition_fixture(Some(json!(["person"])), true);letmut seed: u64 = 7;letmut roll = |n: u64| { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) % n };for step in0..150 {let id = format!("m-{}", roll(25));if roll(8) == 0 { delete(&db, &definition.id, &id);continue; }let person = if roll(2) == 0 { "alice" } else { "bob" };let currency = if roll(5) == 0 { "EUR" } else { "INR" }; put(&db, &definition.id, &id, json!({"name": format!("n{step}"), "position": roll(10), "person": person, "currency": currency, "amount": roll(1000)}));let before = whole(&db); derived::mark_stale(&db).unwrap(); rebuild(&db).unwrap(); assert_eq!(whole(&db), before, "step {step}, {id}"); }}fn table(id: &str, date: Option<&str>, columns: Value) -> String { json!({"id": id, "name": id, "plural": format!("{id}s"), "picture": null, "builtin": false, "engine": null,"columns": columns, "title": "name", "date": date, "project": null, "order": null,"slip": { "title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null },"tile": { "face": "slip-list" }, "page": [{ "heading": null, "columns": ["name"] }],"instructions": "A table of the derive pass's tests." }) .to_string()}/// A client and the visits that link to it: every computed shape, and one/// computed column read by another in each direction.fn practice() -> Driver {let db = create_workspace_in_memory_for_test(&Meta { workspace_id: WS.to_string(), owner_id: "owner-1".to_string(), device_id: "device:test".to_string(), last_server_seq: 0, last_hlc: None, }) .expect("a file"); db.run("INSERT OR IGNORE INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, 'Home', 'owner-1', ?)", &[text(WS), text(AT)], ) .expect("a workspace");let client = table("client",None, json!([ { "key": "name", "type": "text" }, { "key": "visits", "type": "number", "computed": { "rollup": { "table": "visit", "link": "client", "op": "count" } } }, { "key": "paid", "type": "amount", "computed": { "rollup": { "table": "visit", "link": "client", "op": "sum", "column": "fee", "where": { "column": "status", "values": ["paid"] } } } }, { "key": "last_seen", "type": "date", "computed": { "rollup": { "table": "visit", "link": "client", "op": "latest", "column": "day" } } }, { "key": "first_note", "type": "text", "computed": { "rollup": { "table": "visit", "link": "client", "op": "first", "column": "name" } } }, { "key": "dearest", "type": "amount", "computed": { "rollup": { "table": "visit", "link": "client", "op": "max", "column": "owed" } } } ]), );let visit = table("visit",Some("day"), json!([ { "key": "name", "type": "text" }, { "key": "client", "type": "link", "link_to": "client" }, { "key": "host", "type": "link", "link_to": "person" }, { "key": "host_name", "type": "text", "computed": { "lookup": { "through": "host", "column": "full_name" } } }, { "key": "day", "type": "date" }, { "key": "fee", "type": "amount" }, { "key": "tip", "type": "amount" }, { "key": "status", "type": "choice", "choices": ["paid", "due", "refunded"] }, { "key": "client_name", "type": "text", "computed": { "lookup": { "through": "client", "column": "name" } } }, { "key": "client_visits", "type": "number", "computed": { "lookup": { "through": "client", "column": "visits" } } }, { "key": "total", "type": "amount", "computed": { "formula": { "op": "sum", "of": ["fee", "tip"] } } }, { "key": "owed", "type": "amount", "computed": { "formula": { "op": "signed", "of": ["total"], "flip_when": { "column": "status", "values": ["refunded"] } } } }, { "key": "less_tip", "type": "amount", "computed": { "formula": { "op": "difference", "of": ["total", "tip"] } } }, { "key": "label", "type": "text", "computed": { "formula": { "op": "join", "of": ["name", "client_name"] } } } ]), );for (id, definition) in [("client", client), ("visit", visit)] {TableDefinition::from_json(&definition).expect("parses").validate().expect("stands alone"); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)", &[text(id), text(WS), text(&definition), text(AT), text(AT)], ) .expect("a definition"); }// Each made table's own table, as a definition's arrival steps the file. cotton_store::schema::package_shape::step_file(&db).expect("the made tables"); db}fn text(value: &str) -> SqlValue {SqlValue::Text(value.to_string())}/// One value as a made table's column holds it.fn cell(value: &Value) -> SqlValue {match value {Value::Bool(yes) => SqlValue::Integer(i64::from(*yes)),Value::Number(number) => number.as_i64().map_or_else(|| SqlValue::Real(number.as_f64().unwrap_or(0.0)), SqlValue::Integer),Value::String(words) => text(words), _ => SqlValue::Null, }}/// Write one record as a fold would leave it, then run the fold's pass.fn put(db: &Driver, table: &str, id: &str, data: Value) {let store = made_table(table); db.run(&format!("DELETE FROM {store} WHERE id = ?"), &[text(id)]).expect("the old row");let object = data.as_object().expect("an object");letmut columns = vec!["id".to_string(), "workspace_id".to_string(), "created_at".to_string(), "updated_at".to_string()];letmut params = vec![text(id), text(WS), text(AT), text(AT)];for (key, value) in object { columns.push(format!("\"{key}\"")); params.push(cell(value)); }let marks = vec!["?"; columns.len()].join(", "); db.run(&format!("INSERT INTO {store} ({}) VALUES ({marks})", columns.join(", ")), ¶ms).expect("a record"); derive_rows(db, &[(store, id.to_string())]).expect("the pass");}fn delete(db: &Driver, table: &str, id: &str) {let store = made_table(table); db.run(&format!("UPDATE {store} SET deleted_at = ? WHERE id = ?"), &[text(AT), text(id)]).expect("deleted"); derive_rows(db, &[(store, id.to_string())]).expect("the pass");}/// Every computed value kept for one record, bookkeeping left out.fn kept(db: &Driver, table: &str, id: &str) -> Value {letmut values = serde_json::Map::new();for row in db .all("SELECT key, value FROM _computed WHERE table_id = ? AND record_id = ? ORDER BY key", &[text(table), text(id)]) .expect("reads") {let key = row.text("key").expect("a key").to_string();if is_column_key(&key) { values.insert(key, stored_value(row.get("value"), ColumnType::Text)); } }Value::Object(values)}/// Everything `_computed` holds, to compare two ways of arriving at it.fn whole(db: &Driver) -> Vec<(String, String, String, SqlValue)> { db.all("SELECT table_id, record_id, key, value FROM _computed WHERE table_id <> '' ORDER BY 1, 2, 3", &[]) .expect("reads") .iter() .map(|row| {let word = |name: &str| row.text(name).unwrap_or_default().to_string(); (word("table_id"), word("record_id"), word("key"), row.get("value").cloned().unwrap_or(SqlValue::Null)) }) .collect()}fn seeded() -> Driver {let db = practice(); put(&db, "client", "c1", json!({ "name": "Asha" })); put(&db, "client", "c2", json!({ "name": "Bram" })); put(&db, "visit", "v1", json!({ "name": "First", "client": "c1", "day": "2026-09-01", "fee": 5000, "tip": 500, "status": "paid" })); put(&db, "visit", "v2", json!({ "name": "Second", "client": "c1", "day": "2026-09-20", "fee": 7000, "status": "due" })); put(&db, "visit", "v3", json!({ "name": "Refund", "client": "c1", "day": "2026-09-10", "fee": 2000, "status": "refunded" })); db}/// RULE: A computed column holds what its shape says — a lookup the linked record's value, a rollup the count, sum, smallest, largest, first or latest of the records linking here, a formula the sum, difference, turned-over amount or joined words of its own record.#[test]fn each_shape_holds_what_it_says() {let db = seeded(); assert_eq!( kept(&db, "client", "c1"), json!({ "visits": 3, "paid": 5000, "last_seen": "2026-09-20", "first_note": "First", "dearest": 7000 }) ); assert_eq!(kept(&db, "client", "c2"), json!({ "visits": 0, "paid": 0 })); assert_eq!( kept(&db, "visit", "v1"), json!({ "client_name": "Asha", "client_visits": 3, "total": 5500, "owed": 5500, "less_tip": 5000, "label": "First Asha" }) );// A refund reads the other way up, and a missing part of a sum is nothing added. assert_eq!(kept(&db, "visit", "v3")["owed"], json!(-2000)); assert_eq!(kept(&db, "visit", "v2")["total"], json!(7000));}/// RULE: A difference takes from its first number: with none there it says nothing (a membership with no class count has no classes left, never a negative count), and an empty second takes nothing away.#[test]fn a_difference_without_its_first_number_is_empty() {let formula: Formula = serde_json::from_value(json!({"op":"difference","of":["classes","used"]})).unwrap();let data = Data::new(); assert_eq!(formula_value(&formula, &[Value::Null, json!(3)], &data), Value::Null); assert_eq!(formula_value(&formula, &[json!(10), json!(3)], &data), json!(7)); assert_eq!(formula_value(&formula, &[json!(10), Value::Null], &data), json!(10));}/// RULE: A change to one record moves every computed value that reads it, on other records too — the record it links to now, the one it linked to before, and the records that look a value up through a link to it.#[test]fn a_change_moves_what_reads_it() {let db = seeded();// The client is renamed: every visit's lookup and the words joined from it follow. put(&db, "client", "c1", json!({ "name": "Asha K" })); assert_eq!(kept(&db, "visit", "v2")["client_name"], json!("Asha K")); assert_eq!(kept(&db, "visit", "v2")["label"], json!("Second Asha K"));// A visit moves to another client: both clients' rollups follow, and the// count each visit looks up through its client. put(&db, "visit", "v2", json!({ "name": "Second", "client": "c2", "day": "2026-09-20", "fee": 7000, "status": "paid" })); assert_eq!(kept(&db, "client", "c1")["visits"], json!(2)); assert_eq!(kept(&db, "client", "c1")["last_seen"], json!("2026-09-10")); assert_eq!(kept(&db, "client", "c2"), json!({ "visits": 1, "paid": 7000, "last_seen": "2026-09-20", "first_note": "Second", "dearest": 7000 })); assert_eq!(kept(&db, "visit", "v1")["client_visits"], json!(2)); assert_eq!(kept(&db, "visit", "v2")["client_visits"], json!(1));// A deleted visit is gathered by nothing and holds nothing. delete(&db, "visit", "v2"); assert_eq!(kept(&db, "client", "c2"), json!({ "visits": 0, "paid": 0 })); assert_eq!(kept(&db, "visit", "v2"), json!({}));// A deleted client: its visits look up nothing. delete(&db, "client", "c1"); assert_eq!(kept(&db, "visit", "v1")["client_name"], Value::Null); assert_eq!(kept(&db, "visit", "v1")["label"], json!("First"));}/// RULE: The values a device arrives at change by change are exactly the values a rebuild from nothing arrives at, because two devices that hold the same records must hold the same computed values whatever order the records reached them in.#[test]fn change_by_change_equals_a_rebuild() {let db = seeded(); put(&db, "client", "c1", json!({ "name": "Asha K" })); put(&db, "visit", "v2", json!({ "name": "Second", "client": "c2", "day": "2026-09-20", "fee": 7000, "status": "paid" })); delete(&db, "visit", "v3");let stepped = whole(&db); assert!(!stepped.is_empty()); rebuild(&db).expect("a rebuild"); assert_eq!(whole(&db), stepped);// The rebuild says which derivation it was, and an open after it has nothing to do. assert_eq!(derived::derivation(&db).expect("reads"), Some(super::derivation_of(&db).expect("derives"))); derived::mark_stale(&db).expect("stale"); db.run("DELETE FROM _computed", &[]).expect("emptied"); ensure_current(&db).expect("an open"); assert_eq!(whole(&db), stepped);}/// RULE: A change to any table's definition works every computed column out again, because a new column or a new shape reads records no fold will touch.#[test]fn a_new_definition_rebuilds() {let db = seeded();let renamed = db .get("SELECT definition FROM cotton_table_definitions WHERE id = 'visit'", &[]) .expect("reads") .and_then(|row| row.text("definition").map(|json| json.replace("\"op\":\"join\",\"of\":[\"name\",\"client_name\"]", "\"op\":\"join\",\"of\":[\"client_name\",\"name\"]"))) .expect("the definition"); db.run("UPDATE cotton_table_definitions SET definition = ? WHERE id = 'visit'", &[text(&renamed)]).expect("redefined"); derive_rows(&db, &[("cotton_table_definitions".to_string(), "visit".to_string())]).expect("the pass"); assert_eq!(kept(&db, "visit", "v1")["label"], json!("Asha First"));}/// RULE: A lookup may read a built-in's record — a visit's host is a person — and follows that record when it changes, because a made table that links to People must be able to say the person's name.#[test]fn a_lookup_reads_a_builtins_record_and_follows_it() {let db = seeded();// The People tool is here: a built-in a lookup reads is one a tool draws.let person = cotton_core::definitions::builtin_table_definitions().iter().find(|table| table.id == "person").expect("the kit's person").to_json(); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES ('person', ?, ?, 1, ?, ?)", &[text(WS), text(&person), text(AT), text(AT)], ) .expect("the person definition"); db.run("INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('p1', ?, 'Jelena', ?, ?)", &[text(WS), text(AT), text(AT)], ) .expect("a person"); put(&db, "visit", "v1", json!({ "name": "First", "client": "c1", "host": "p1", "day": "2026-09-01", "fee": 5000, "tip": 500, "status": "paid" })); assert_eq!(kept(&db, "visit", "v1")["host_name"], json!("Jelena")); db.run("UPDATE cotton_people SET full_name = 'Jelena M' WHERE id = 'p1'", &[]).expect("renamed"); assert!(CoreDerive.reads("cotton_people")); assert!(CoreDerive.reads("cotton_visit"), "a made table's own rows are read"); derive_rows(&db, &[("cotton_people".to_string(), "p1".to_string())]).expect("the pass"); assert_eq!(kept(&db, "visit", "v1")["host_name"], json!("Jelena M"));let stepped = whole(&db); rebuild(&db).expect("a rebuild"); assert_eq!(whole(&db), stepped);}/// RULE: A computed column whose table is gone holds nothing and every other computed column is still worked out — a rollup over another tool's table may outlive that table's definition on a device (a removal, or a definition not yet arrived), and one dangling column must never empty the whole index, as it did while the pass took the tables all or nothing.#[test]fn a_column_whose_table_is_gone_holds_nothing_and_the_rest_still_work_out() {let db = seeded(); db.run("DELETE FROM cotton_table_definitions WHERE id = 'client'", &[]).expect("the client table gone"); derive_rows(&db, &[("cotton_table_definitions".to_string(), "client".to_string())]).expect("the pass");let visit = kept(&db, "visit", "v1"); assert_eq!(visit["client_name"], Value::Null, "a lookup into the gone table holds nothing: {visit}"); assert_eq!(visit["client_visits"], Value::Null, "{visit}"); assert_eq!(visit["total"], json!(5500), "the visit's own formulas are still worked out: {visit}"); assert_eq!(visit["owed"], json!(5500), "{visit}"); assert_eq!(visit["label"], json!("First"), "a formula that read the gone lookup reads what is left: {visit}"); put(&db, "visit", "v4", json!({ "name": "Fourth", "client": "c1", "day": "2026-09-30", "fee": 100, "tip": 20 })); assert_eq!(kept(&db, "visit", "v4")["total"], json!(120), "a new record is worked out too");}/// RULE: Previous reads the preceding live row in the table sort order, and running includes each signed value from its opening; edits, reordering and deletion refresh every affected row.#[test]fn ordered_shapes_follow_table_sort_and_refresh_following_rows() {let db = practice();letmut definition: Value = serde_json::from_str(&table("movement", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"amount", "type":"amount"}, {"key":"balance", "type":"amount", "computed":{"running":{"column":"amount", "opening":100}}}, {"key":"before", "type":"amount", "computed":{"previous":{"column":"balance"}}} ]))).unwrap(); definition["sort"] = json!({"column":"position", "descending":true});let parsed = TableDefinition::from_json(&definition.to_string()).unwrap(); parsed.validate().expect("valid at save"); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES ('movement', ?, ?, 0, ?, ?)", &[text(WS), text(&definition.to_string()), text(AT), text(AT)]).unwrap(); cotton_store::schema::package_shape::step_file(&db).unwrap(); put(&db, "movement", "a", json!({"name":"last", "position":1, "amount":-5})); put(&db, "movement", "z", json!({"name":"first", "position":3, "amount":20})); put(&db, "movement", "m", json!({"name":"middle", "position":2, "amount":-10})); assert_eq!(kept(&db, "movement", "z"), json!({"balance":120})); assert_eq!(kept(&db, "movement", "m"), json!({"balance":110,"before":120})); assert_eq!(kept(&db, "movement", "a"), json!({"balance":105,"before":110})); put(&db, "movement", "m", json!({"name":"now first", "position":4, "amount":-30})); assert_eq!(kept(&db, "movement", "z"), json!({"balance":90,"before":70})); delete(&db, "movement", "m"); assert_eq!(kept(&db, "movement", "z"), json!({"balance":120})); assert_eq!(kept(&db, "movement", "a"), json!({"balance":115,"before":120}));let incremental = whole(&db); rebuild(&db).unwrap(); assert_eq!(whole(&db), incremental);}/// RULE: Running accepts computed signed values and live rollup openings; changing an opening refreshes downstream previous/lookups, without inventing a balance after an unknown amount.#[test]fn ordered_shapes_start_from_one_global_opening_and_refresh_every_row() {let db = practice();letmut movement: Value = serde_json::from_str(&table("movement", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"amount", "type":"amount"}, {"key":"direction", "type":"choice", "choices":["in","out"]}, {"key":"signed", "type":"amount", "computed":{"formula":{"op":"signed", "of":["amount"], "flip_when":{"column":"direction", "values":["out"]}}}}, {"key":"balance", "type":"amount", "computed":{"running":{"column":"signed", "opening":{"rollup":{"table":"opening", "column":"amount", "op":"sum"}}}}}, {"key":"before", "type":"amount", "computed":{"previous":{"column":"balance"}}} ]))).unwrap(); movement["sort"] = json!({"column":"position", "tie":"name"});let opening: Value = serde_json::from_str(&table("opening", None, json!([ {"key":"name", "type":"text"}, {"key":"movement", "type":"link", "link_to":"movement"}, {"key":"amount", "type":"amount"}, {"key":"read_balance", "type":"amount", "computed":{"lookup":{"through":"movement", "column":"before"}}} ]))).unwrap();for definition in [&movement, &opening] {let parsed = TableDefinition::from_json(&definition.to_string()).unwrap(); parsed.validate().unwrap(); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)", &[text(definition["id"].as_str().unwrap()),text(WS),text(&definition.to_string()),text(AT),text(AT)]).unwrap(); } cotton_store::schema::package_shape::step_file(&db).unwrap(); put(&db,"movement","z",json!({"name":"Alpha","position":1,"amount":10,"direction":"in"})); put(&db,"movement","a",json!({"name":"beta","position":1,"amount":3,"direction":"out"})); put(&db,"opening","o",json!({"name":"start","movement":"z","amount":100})); put(&db,"opening","p",json!({"name":"another row","movement":"a","amount":0})); assert_eq!(kept(&db,"movement","z")["balance"],110); assert_eq!(kept(&db,"movement","a")["balance"],107); assert_eq!(kept(&db,"movement","a")["before"],110); assert_eq!(kept(&db,"opening","p")["read_balance"],110); put(&db,"opening","o",json!({"name":"changed","movement":"z","amount":200})); assert_eq!(kept(&db,"movement","a")["before"],210); assert_eq!(kept(&db,"opening","p")["read_balance"],210); put(&db,"movement","unknown",json!({"name":"unknown","position":2,"direction":"out"})); put(&db,"movement","after",json!({"name":"after","position":3,"amount":5,"direction":"in"})); assert!(kept(&db,"movement","unknown")["balance"].is_null()); assert!(kept(&db,"movement","after")["balance"].is_null());let incremental = whole(&db); rebuild(&db).unwrap(); assert_eq!(whole(&db),incremental);}/// RULE: Ordered arithmetic keeps whole numbers exact beyond Double precision, fractions fractional, blanks last, and ties deterministic so replicas derive the same preceding row.#[test]fn ordered_shapes_keep_numeric_precision_and_the_lists_blank_and_tie_order() {let db = practice();letmut definition: Value = serde_json::from_str(&table("ordered_number", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"whole", "type":"number"}, {"key":"fraction", "type":"number"}, {"key":"total", "type":"number", "computed":{"running":{"column":"whole", "opening":9007199254740993_i64}}}, {"key":"fraction_total", "type":"number", "computed":{"running":{"column":"fraction", "opening":0.25}}}, {"key":"before", "type":"text", "computed":{"previous":{"column":"name"}}} ]))).unwrap(); definition["sort"] = json!({"column":"name", "tie":"position"}); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES ('ordered_number', ?, ?, 0, ?, ?)", &[text(WS),text(&definition.to_string()),text(AT),text(AT)]).unwrap(); cotton_store::schema::package_shape::step_file(&db).unwrap();for (id,name,position) in [("a","SAME",2),("z","same",1),("blank","",0)] { put(&db,"ordered_number",id,json!({"name":name,"position":position,"whole":1,"fraction":0.5})); } assert_eq!(kept(&db,"ordered_number","z")["total"],9007199254740994_i64); assert_eq!(kept(&db,"ordered_number","a")["total"],9007199254740995_i64); assert_eq!(kept(&db,"ordered_number","blank")["total"],9007199254740996_i64); assert_eq!(kept(&db,"ordered_number","blank")["before"],"SAME"); assert_eq!(kept(&db,"ordered_number","blank")["fraction_total"],1.75);let incremental = whole(&db); rebuild(&db).unwrap(); assert_eq!(whole(&db),incremental);}/// RULE: A running amount never adds different currencies, including its opening; first/latest openings contribute only the selected row's currency, because other rows add no money.#[test]fn ordered_amounts_do_not_add_mixed_currencies() {let db = practice();letmut movement: Value = serde_json::from_str(&table("currency_movement", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"currency", "type":"text"}, {"key":"amount", "type":"amount", "currency":"currency"}, {"key":"balance", "type":"amount", "currency":"currency", "computed":{"running":{"column":"amount", "opening":0}}}, {"key":"opened", "type":"amount", "currency":"currency", "computed":{"running":{"column":"amount", "opening":{"rollup":{"table":"currency_opening", "column":"amount", "op":"sum"}}}}}, {"key":"latest_opened", "type":"amount", "currency":"currency", "computed":{"running":{"column":"amount", "opening":{"rollup":{"table":"currency_opening", "column":"amount", "op":"latest", "by":"position"}}}}} ]))).unwrap(); movement["sort"] = json!({"column":"position"});let opening: Value = serde_json::from_str(&table("currency_opening", None, json!([ {"key":"name", "type":"text"}, {"key":"movement", "type":"link", "link_to":"currency_movement"}, {"key":"currency", "type":"text"}, {"key":"position", "type":"number"}, {"key":"amount", "type":"amount", "currency":"currency"} ]))).unwrap();for definition in [&movement,&opening] {TableDefinition::from_json(&definition.to_string()).unwrap().validate().unwrap(); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)", &[text(definition["id"].as_str().unwrap()),text(WS),text(&definition.to_string()),text(AT),text(AT)]).unwrap(); } cotton_store::schema::package_shape::step_file(&db).unwrap(); put(&db,"currency_movement","a",json!({"name":"first","position":1,"amount":10,"currency":"INR"})); put(&db,"currency_opening","o",json!({"name":"opening","movement":"a","amount":100,"currency":"USD","position":2})); assert_eq!(kept(&db,"currency_movement","a")["balance"],10); assert_eq!(kept(&db,"currency_movement","a")["opened"],10); put(&db,"currency_movement","b",json!({"name":"second","position":2,"amount":20,"currency":"USD"})); assert_eq!(kept(&db,"currency_movement","b")["balance"],20); put(&db,"currency_movement","a",json!({"name":"first","position":1,"amount":10,"currency":"USD"})); put(&db,"currency_opening","old",json!({"name":"older opening","movement":"a","amount":200,"currency":"INR","position":1})); assert_eq!(kept(&db,"currency_movement","a")["opened"],110); assert_eq!(kept(&db,"currency_movement","a")["latest_opened"],110);// RULE: A virtual window uses indexed per-currency openings, including a// currency with no stored movement; it never decodes the opening archive. rebuild(&db).unwrap();let definition = TableDefinition::from_json(&movement.to_string()).unwrap();letmut rows = live_records(&db,&definition).unwrap(); rows.push(("virtual-inr".into(),serde_json::from_value(json!({"name":"virtual INR","position":3,"amount":7,"currency":"INR"})).unwrap())); rows.push(("virtual-eur".into(),serde_json::from_value(json!({"name":"virtual EUR","position":4,"amount":9,"currency":"EUR"})).unwrap())); db.watch_statements();let resolved = values_for_read_rows(&db,&definition,rows).unwrap();let virtual_row = |id: &str| &resolved.iter().find(|(key,_)|key == id).unwrap().1; assert_eq!(virtual_row("virtual-inr")["opened"],207); assert_eq!(virtual_row("virtual-eur")["opened"],9); assert_eq!(virtual_row("virtual-inr")["latest_opened"],207); assert!(!db.steps_by_statement().iter().any(|(_,sql)|sql.contains("cotton_currency_opening")),"a virtual read must use the opening index: {:?}",db.steps_by_statement()); put(&db,"currency_opening","unknown",json!({"name":"unknown units","amount":999,"position":5}));let rows = vec![("virtual-eur".into(),serde_json::from_value(json!({"name":"virtual EUR","position":4,"amount":9,"currency":"EUR"})).unwrap())];let resolved = values_for_read_rows(&db,&definition,rows).unwrap(); assert!(resolved[0].1["opened"].is_null(),"an unseen currency must still refuse an opening with unknown units");}/// RULE: Losing the source of a computed sort leaves blank sort values, as the list does, while other ordered computations still derive instead of failing the entire index.#[test]fn ordered_shapes_keep_working_when_a_sort_lookup_loses_its_source() {let db = practice();let source: Value = serde_json::from_str(&table("ordering_source", None, json!([ {"key":"name", "type":"text"} ]))).unwrap();letmut movement: Value = serde_json::from_str(&table("sorted_movement", None, json!([ {"key":"name", "type":"text"}, {"key":"source", "type":"link", "link_to":"ordering_source"}, {"key":"amount", "type":"amount"}, {"key":"sort_value", "type":"text", "computed":{"lookup":{"through":"source", "column":"name"}}}, {"key":"balance", "type":"amount", "computed":{"running":{"column":"amount", "opening":0}}}, {"key":"before", "type":"text", "computed":{"previous":{"column":"name"}}} ]))).unwrap(); movement["sort"] = json!({"column":"sort_value"});for definition in [&movement,&source] {TableDefinition::from_json(&definition.to_string()).unwrap().validate().unwrap(); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)", &[text(definition["id"].as_str().unwrap()),text(WS),text(&definition.to_string()),text(AT),text(AT)]).unwrap(); } cotton_store::schema::package_shape::step_file(&db).unwrap(); put(&db,"ordering_source","s1",json!({"name":"zeta"})); put(&db,"ordering_source","s2",json!({"name":"alpha"})); put(&db,"sorted_movement","a",json!({"name":"later","source":"s1","amount":1})); put(&db,"sorted_movement","z",json!({"name":"earlier","source":"s2","amount":2})); assert_eq!(kept(&db,"sorted_movement","z")["balance"],2); db.run("DELETE FROM cotton_table_definitions WHERE id = 'ordering_source'",&[]).unwrap(); rebuild(&db).expect("a missing sort source cannot poison other computed columns"); assert_eq!(kept(&db,"sorted_movement","a"),json!({"balance":1})); assert_eq!(kept(&db,"sorted_movement","z"),json!({"balance":3,"before":"later"}));}/// RULE: A currency supplied by a lookup is still a currency; it is derived before a running amount and mixed currencies never produce an invented balance.#[test]fn running_amounts_read_computed_currencies_before_summing() {let db = practice();let account: Value = serde_json::from_str(&table("unit_account", None, json!([ {"key":"name", "type":"text"}, {"key":"currency", "type":"text"} ]))).unwrap();letmut movement: Value = serde_json::from_str(&table("currency_lookup_movement", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"account", "type":"link", "link_to":"unit_account"}, {"key":"amount", "type":"amount", "currency":"currency"}, {"key":"balance", "type":"amount", "currency":"currency", "computed":{"running":{"column":"amount", "opening":0}}}, {"key":"currency", "type":"text", "computed":{"lookup":{"through":"account", "column":"currency"}}} ]))).unwrap(); movement["sort"] = json!({"column":"position"});for definition in [&movement,&account] {TableDefinition::from_json(&definition.to_string()).unwrap().validate().unwrap(); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)", &[text(definition["id"].as_str().unwrap()),text(WS),text(&definition.to_string()),text(AT),text(AT)]).unwrap(); } cotton_store::schema::package_shape::step_file(&db).unwrap(); put(&db,"unit_account","usd",json!({"name":"Dollar account","currency":"USD"})); put(&db,"unit_account","inr",json!({"name":"Rupee account","currency":"INR"})); put(&db,"currency_lookup_movement","a",json!({"name":"first","position":1,"account":"usd","amount":10})); put(&db,"currency_lookup_movement","b",json!({"name":"second","position":2,"account":"inr","amount":20})); assert_eq!(kept(&db,"currency_lookup_movement","a")["balance"],10); assert_eq!(kept(&db,"currency_lookup_movement","b")["balance"],20); put(&db,"unit_account","inr",json!({"name":"Same currency now","currency":"USD"})); assert_eq!(kept(&db,"currency_lookup_movement","b")["balance"],30); put(&db,"unit_account","usd",json!({"name":"Currency not known"})); assert!(kept(&db,"currency_lookup_movement","a")["balance"].is_null()); assert_eq!(kept(&db,"currency_lookup_movement","b")["balance"],20);}/// RULE: A running sum starts with its opening before adding rows in order, so a small amount after cancelling large values is retained.#[test]fn running_starts_with_the_numeric_opening() {let db = practice();letmut definition: Value = serde_json::from_str(&table("opening_number", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"amount", "type":"number"}, {"key":"total", "type":"number", "computed":{"running":{"column":"amount", "opening":1e20}}} ]))).unwrap(); definition["sort"] = json!({"column":"position"});TableDefinition::from_json(&definition.to_string()).unwrap().validate().unwrap(); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)", &[text("opening_number"),text(WS),text(&definition.to_string()),text(AT),text(AT)]).unwrap(); cotton_store::schema::package_shape::step_file(&db).unwrap(); put(&db,"opening_number","a",json!({"name":"cancel opening","position":1,"amount":-1e20})); put(&db,"opening_number","b",json!({"name":"small later amount","position":2,"amount":1})); assert_eq!(kept(&db,"opening_number","a")["total"].as_f64(),Some(0.0)); assert_eq!(kept(&db,"opening_number","b")["total"].as_f64(),Some(1.0));let incremental = whole(&db); rebuild(&db).unwrap(); assert_eq!(whole(&db),incremental);}/// RULE: A running sum with an `order` walks oldest first by that column however the list reads (ruling 03:55 item 2): So far lists newest first and each row still says the balance after it, and moving a row's day moves every balance after it.#[test]fn running_with_an_order_walks_oldest_first_under_a_newest_first_list() {let db = practice();letmut definition: Value = serde_json::from_str(&table("dated_movement", Some("day"), json!([ {"key":"name", "type":"text"}, {"key":"day", "type":"date"}, {"key":"amount", "type":"number"}, {"key":"after", "type":"number", "computed":{"running":{"column":"amount", "opening":100, "order":"day"}}} ]))).unwrap(); definition["sort"] = json!({"column":"day", "descending": true});TableDefinition::from_json(&definition.to_string()).unwrap().validate().unwrap(); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)", &[text("dated_movement"),text(WS),text(&definition.to_string()),text(AT),text(AT)]).unwrap(); cotton_store::schema::package_shape::step_file(&db).unwrap(); put(&db,"dated_movement","a",json!({"name":"first","day":"2026-10-01","amount":10})); put(&db,"dated_movement","b",json!({"name":"second","day":"2026-10-02","amount":-30})); put(&db,"dated_movement","c",json!({"name":"third","day":"2026-10-03","amount":5})); assert_eq!(kept(&db,"dated_movement","a")["after"],110); assert_eq!(kept(&db,"dated_movement","b")["after"],80); assert_eq!(kept(&db,"dated_movement","c")["after"],85); put(&db,"dated_movement","a",json!({"name":"first","day":"2026-10-04","amount":10})); assert_eq!(kept(&db,"dated_movement","b")["after"],70, "the first row moved after the others"); assert_eq!(kept(&db,"dated_movement","a")["after"],85);let incremental = whole(&db); rebuild(&db).unwrap(); assert_eq!(whole(&db),incremental);}/// RULE: A global opening starts the sum before ordered addition, and a count opening tracks source insertions/deletions even without a source column or backlink.#[test]fn global_opening_is_added_once_and_counts_follow_the_source_row_set() {let db = practice();let source: Value = serde_json::from_str(&table("global_pool", None, json!([ {"key":"name", "type":"text"}, {"key":"amount", "type":"number"}, {"key":"pooled", "type":"bool"} ]))).unwrap();letmut movement: Value = serde_json::from_str(&table("global_movement", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"amount", "type":"number"}, {"key":"quantity", "type":"number"}, {"key":"counted", "type":"number", "computed":{"running":{"column":"quantity", "opening":{"rollup":{"table":"global_pool", "op":"count"}}}}}, {"key":"total", "type":"number", "computed":{"running":{"column":"amount", "opening":{"rollup":{"table":"global_pool", "op":"sum", "column":"amount", "where":{"column":"pooled", "values":["true"]}}}}}} ]))).unwrap(); movement["sort"] = json!({"column":"position"});for definition in [&movement,&source] {TableDefinition::from_json(&definition.to_string()).unwrap().validate().unwrap(); db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)", &[text(definition["id"].as_str().unwrap()),text(WS),text(&definition.to_string()),text(AT),text(AT)]).unwrap(); } cotton_store::schema::package_shape::step_file(&db).unwrap(); put(&db,"global_pool","o",json!({"name":"pooled opening","amount":1e20,"pooled":true})); put(&db,"global_movement","a",json!({"name":"cancel opening","position":1,"amount":-1e20,"quantity":2})); put(&db,"global_movement","b",json!({"name":"small amount after cancellation","position":2,"amount":1,"quantity":3})); assert_eq!(kept(&db,"global_movement","a")["total"].as_f64(),Some(0.0)); assert_eq!(kept(&db,"global_movement","b")["total"].as_f64(),Some(1.0)); assert_eq!(kept(&db,"global_movement","a")["counted"],3); assert_eq!(kept(&db,"global_movement","b")["counted"],6); put(&db,"global_pool","excluded",json!({"name":"outside the pool","amount":555,"pooled":false})); assert_eq!(kept(&db,"global_movement","b")["total"].as_f64(),Some(1.0)); assert_eq!(kept(&db,"global_movement","a")["counted"],4); assert_eq!(kept(&db,"global_movement","b")["counted"],7); delete(&db,"global_pool","excluded"); assert_eq!(kept(&db,"global_movement","b")["counted"],6);let incremental = whole(&db); rebuild(&db).unwrap(); assert_eq!(whole(&db),incremental);}/// RULE: Reusing a resolved definition graph must never reuse record values,/// survive a definition edit, or cross into another file with the same workspace.#[test]fn a_reused_catalogue_reads_fresh_values_and_definition_edits_in_its_own_file() {fn file(path: &std::path::Path) -> Driver {let memory = practice();letmut disk = rusqlite::Connection::open(path).unwrap(); rusqlite::backup::Backup::new(memory.connection(), &mut disk) .unwrap() .run_to_completion(4096, std::time::Duration::ZERO, None) .unwrap(); drop(disk);Driver::open(path).unwrap() }let scratch = tempfile::tempdir().unwrap();let first = file(&scratch.path().join("first.db"));let second = file(&scratch.path().join("second.db"));for db in [&first, &second] { put(db, "client", "c", json!({"name":"Synthetic family"})); } put( &first,"visit","v", json!({"name":"Synthetic visit","client":"c","fee":100,"tip":5}), ); assert_eq!(kept(&first, "visit", "v")["total"], 105); put( &first,"visit","v", json!({"name":"Synthetic visit","client":"c","fee":200,"tip":9}), ); assert_eq!(kept(&first, "visit", "v")["total"], 209);let row = first .get("SELECT definition FROM cotton_table_definitions WHERE id='visit'", &[], ) .unwrap() .unwrap();letmut definition: Value = serde_json::from_str(row.text("definition").unwrap()).unwrap();let total = definition["columns"] .as_array_mut() .unwrap() .iter_mut() .find(|column| column["key"] == "total") .unwrap(); total["computed"] = json!({"formula":{"op":"difference","of":["fee","tip"]}}); first .run("UPDATE cotton_table_definitions SET definition=? WHERE id='visit'", &[text(&definition.to_string())], ) .unwrap(); derive_rows( &first, &[("cotton_table_definitions".into(), "visit".into())], ) .unwrap(); assert_eq!(kept(&first, "visit", "v")["total"], 191); put( &second,"visit","v", json!({"name":"Synthetic visit","client":"c","fee":100,"tip":5}), ); assert_eq!(kept(&second, "visit", "v")["total"], 105); put( &first,"visit","v", json!({"name":"Synthetic visit","client":"c","fee":120,"tip":20}), ); assert_eq!(kept(&first, "visit", "v")["total"], 100);}/// RULE: A formula over one row's stored columns follows that row into and/// out of a view, while ordered values still refresh every affected neighbour;/// incremental results must equal a full rebuild.#[test]fn row_formulas_follow_view_membership_and_match_a_full_rebuild() {let db = practice();letmut shape: Value = serde_json::from_str(&table("people_without_beta",None,json!([ {"key":"full_name","type":"text"}, {"key":"role_title","type":"text"}, {"key":"local_name","type":"text","computed":{"formula":{"op":"join","of":["full_name","role_title"]}}}, {"key":"previous_name","type":"text","computed":{"previous":{"column":"full_name"}}} ]))).unwrap(); shape["source"] = json!({"table":"person","where":{"full_name":{"not":["beta"]}}}); shape["sort"] = json!({"column":"full_name"}); shape["title"] = json!("full_name"); shape["slip"]["title"] = json!("full_name"); shape["page"] = json!([{"heading":null,"columns":["full_name","role_title"]}]);let definition: TableDefinition = serde_json::from_value(shape).unwrap(); definition.validate().unwrap();let catalogue = Catalogue { tables: vec![definition.clone()], order: vec![(definition.id.clone(),"local_name".into()),(definition.id.clone(),"previous_name".into())], gathered: BTreeSet::new(), stamps: BTreeMap::new(), derivation: String::new() };for (id,name) in [("p1","Alpha"),("p2","beta"),("p3","Gamma")] { db.run("INSERT INTO cotton_people (id,workspace_id,full_name,created_at,updated_at) VALUES (?,?,?,?,?)", &[text(id),text(WS),text(name),text(AT),text(AT)]).unwrap(); }for (_,key) in &catalogue.order { catalogue.compute_column(&db,&definition,key).unwrap(); } db.run("UPDATE cotton_people SET full_name='beta' WHERE id='p1'",&[]).unwrap(); db.run("UPDATE cotton_people SET full_name='Delta' WHERE id='p2'",&[]).unwrap(); derive_rows_with_catalogue(&db,&[("cotton_people".into(),"p1".into()),("cotton_people".into(),"p2".into())],&catalogue).unwrap(); assert!(kept(&db,&definition.id,"p1")["local_name"].is_null()); assert_eq!(kept(&db,&definition.id,"p2")["local_name"],"Delta"); assert_eq!(kept(&db,&definition.id,"p3")["previous_name"],"Delta");let incremental = whole(&db); db.run("DELETE FROM _computed",&[]).unwrap();for (_,key) in &catalogue.order { catalogue.compute_column(&db,&definition,key).unwrap(); } assert_eq!(whole(&db),incremental);}/// RULE: A source whose visibility is controlled by another row keeps the/// whole-column pass: clearing a thread can hide messages beyond the one a/// fold named, and none of their derived text may stay behind.#[test]fn a_thread_visibility_change_sweeps_every_hidden_messages_formula() {let db = practice();letmut definition = builtin_table_definitions().iter().find(|table| table.id == "message").unwrap().clone(); definition.columns.push(serde_json::from_value(json!({"key":"local_body","type":"text","computed":{"formula":{"op":"join","of":["body","channel"],"separator":" · "}}})).unwrap()); definition.validate().unwrap();let catalogue = Catalogue { tables: vec![definition.clone()], order: vec![("message".into(),"local_body".into())], gathered: BTreeSet::new(), stamps: BTreeMap::new(), derivation: String::new() }; db.run("INSERT INTO cotton_msg_threads(id,workspace_id,title,created_at,updated_at) VALUES('synthetic-thread',?,'Synthetic thread',?,?)", &[text(WS),text(AT),text(AT)]).unwrap();for (id, body) in [("m1","Synthetic first"),("m2","Synthetic second")] { db.run("INSERT INTO cotton_msg_messages(id,workspace_id,thread_id,direction,channel,origin,body,sent_at,created_at) VALUES(?,?,'synthetic-thread','in','cotton','live',?,?,?)", &[text(id),text(WS),text(body),text(AT),text(AT)]).unwrap(); } catalogue.compute_column(&db,&definition,"local_body").unwrap(); assert_eq!(kept(&db,"message","m2")["local_body"], "Synthetic second · cotton"); db.run("UPDATE cotton_msg_threads SET cleared_before=? WHERE id='synthetic-thread'", &[text(AT)]).unwrap(); db.run("UPDATE cotton_msg_messages SET body='Synthetic changed' WHERE id='m1'", &[]).unwrap(); derive_rows_with_catalogue(&db,&[("cotton_msg_threads".into(),"synthetic-thread".into()),("cotton_msg_messages".into(),"m1".into())],&catalogue).unwrap(); assert!(kept(&db,"message","m1")["local_body"].is_null()); assert!(kept(&db,"message","m2")["local_body"].is_null(), "the neighboring message left through its thread too");let incremental=whole(&db); db.run("DELETE FROM _computed",&[]).unwrap(); catalogue.compute_column(&db,&definition,"local_body").unwrap(); assert_eq!(whole(&db),incremental);}/// RULE: The computed index's stamp moves with what the index is worked out from — a table's columns or a view's source — and never with how a table looks: a change to a page, a card, the slips table or a word rebuilds no computed value on any device (phone 296, 17 Oct 2026: a presentation change rebuilt every computed value before the open).#[test]fn a_presentation_change_leaves_the_index_stamp_and_a_column_change_moves_it() {let shipped = cotton_core::definitions::builtin_table_definitions().to_vec();let before = super::table_stamps(&shipped);letmut looks = shipped.clone();for table in &mut looks { table.instructions = Some("Invented words for a test.".to_string()); table.parts = None; table.slips = None; } assert_eq!(super::table_stamps(&looks), before, "a look change moved the index stamp");letmut columns = shipped.clone();let at = columns.iter().position(TableDefinition::has_computed).expect("a shipped computed column");let key = columns[at].columns.iter().rev().find(|column| column.computed.is_some()).unwrap().key.clone(); columns[at].columns.retain(|column| column.key != key); assert_ne!(super::table_stamps(&columns).get(&columns[at].id), before.get(&columns[at].id), "a column change must move the stamp");}fn partition_fixture(partition: Option<Value>, amount: bool) -> (Driver, TableDefinition) {let db = practice();let kind = if amount { "amount" } else { "number" };letmut value: Value = serde_json::from_str(&table("partition_movement", None, json!([ {"key":"name","type":"text"}, {"key":"position","type":"number"}, {"key":"person","type":"link","link_to":"person"}, {"key":"currency","type":"text"}, {"key":"amount","type":kind,"currency":"currency"}, {"key":"balance","type":kind,"currency":"currency","computed":{"running":{"column":"amount","opening":100}}}, {"key":"before","type":kind,"currency":"currency","computed":{"previous":{"column":"amount"}}} ]))).unwrap(); value["sort"] = json!({"column":"position"});if !amount {for column in value["columns"].as_array_mut().unwrap() { column.as_object_mut().unwrap().remove("currency"); } }ifletSome(partition) = partition { value["columns"][5]["computed"]["running"]["partition"] = partition.clone(); value["columns"][6]["computed"]["previous"]["partition"] = partition; }let definition = TableDefinition::from_json(&value.to_string()).unwrap(); definition.validate().unwrap(); db.run("INSERT INTO cotton_table_definitions(id,workspace_id,definition,builtin,created_at,updated_at) VALUES(?,?,?,0,?,?)", &[text(&definition.id),text(WS),text(&value.to_string()),text(AT),text(AT)]).unwrap(); cotton_store::schema::package_shape::step_file(&db).unwrap();for (id,name) in [("alice","Invented Alice"),("bob","Invented Bob")] { db.run("INSERT INTO cotton_people(id,workspace_id,full_name,created_at,updated_at) VALUES(?,?,?,?,?)",&[text(id),text(WS),text(name),text(AT),text(AT)]).unwrap(); }// The synthetic people were inserted as a batch above; prepare their// computed columns just as the writer does before measuring later folds. rebuild(&db).unwrap(); (db, definition)}/// RULE: A household's interleaved rows restart running and previous per person, including after reassignment, so one person's payment never changes another's balance.#[test]fn partitioned_running_and_previous_keep_household_people_separate() {let (db, definition) = partition_fixture(Some(json!(["person"])), false);for (id,position,person,amount) in [("a",1,"alice",10),("b",2,"bob",20),("c",3,"alice",3),("d",4,"bob",4)] { put(&db,&definition.id,id,json!({"name":id,"position":position,"person":person,"amount":amount})); } assert_eq!(kept(&db,&definition.id,"c"),json!({"balance":113,"before":10})); assert_eq!(kept(&db,&definition.id,"d"),json!({"balance":124,"before":20})); put(&db,&definition.id,"b",json!({"name":"b","position":2,"person":"alice","amount":20})); assert_eq!(kept(&db,&definition.id,"c"),json!({"balance":133,"before":20})); assert_eq!(kept(&db,&definition.id,"d"),json!({"balance":104}));let before = whole(&db); rebuild(&db).unwrap(); assert_eq!(whole(&db),before,"a rebuild and the fold agree");let rows = live_records(&db,&definition).unwrap();let read = values_for_read_rows(&db,&definition,rows).unwrap();for (id,data) in read { assert_eq!(data["balance"],kept(&db,&definition.id,&id)["balance"],"read-time running has the same partitions"); }}/// RULE: Omitting partition preserves the original computation and wire bytes; an empty partition is the same global ordered scope, so existing definitions need no rewrite.#[test]fn unpartitioned_ordered_values_and_shape_stay_byte_for_byte_unchanged() {let (db, definition) = partition_fixture(None, false);for (id,position,amount) in [("a",1,9007199254740993_i64),("b",2,-9007199254740993_i64),("c",3,7)] { put(&db,&definition.id,id,json!({"name":id,"position":position,"amount":amount})); } assert_eq!(kept(&db,&definition.id,"c"),json!({"balance":107,"before":-9007199254740993_i64}));let computed = definition.column("balance").unwrap().computed.as_ref().unwrap(); assert_eq!(serde_json::to_string(computed).unwrap(),r#"{"running":{"column":"amount","opening":100}}"#);let before = whole(&db);letmut value = serde_json::to_value(&definition).unwrap(); value["columns"][5]["computed"]["running"]["partition"] = json!([]); value["columns"][6]["computed"]["previous"]["partition"] = json!([]); db.run("UPDATE cotton_table_definitions SET definition=? WHERE id=?",&[text(&value.to_string()),text(&definition.id)]).unwrap(); rebuild(&db).unwrap(); assert_eq!(whole(&db),before);}/// RULE: Currency implicitly partitions an amount's running and previous even without a declared partition, so a household's two currencies yield independent balances.#[test]fn running_amounts_implicitly_partition_each_currency() {let (db, definition) = partition_fixture(None, true);for (id,position,currency,amount) in [("a",1,"EUR",10),("b",2,"INR",20),("c",3,"EUR",3),("d",4,"INR",4)] { put(&db,&definition.id,id,json!({"name":id,"position":position,"currency":currency,"amount":amount})); } assert_eq!(kept(&db,&definition.id,"c"),json!({"balance":113,"before":10})); assert_eq!(kept(&db,&definition.id,"d"),json!({"balance":124,"before":20}));let before = whole(&db); rebuild(&db).unwrap(); assert_eq!(whole(&db),before);for (id,data) in values_for_read_rows(&db,&definition,live_records(&db,&definition).unwrap()).unwrap() { assert_eq!(data["balance"],kept(&db,&definition.id,&id)["balance"]); }}/// RULE: a rebuild beside the folds that another rebuild overtook throws its/// work away: two may run at once on their own connections, and the later/// swap would put an index worked out from an older read over the rows the/// first one patched, and call it current.#[test]fn a_rebuild_another_rebuild_overtook_never_swaps_its_older_index_in() {let db = seeded(); rebuild(&db).unwrap();let current = whole(&db);// An older rebuild's work: worked out before any of these rows existed. db.exec("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))", ) .unwrap();let rework = Rework::of(&db, Catalogue::load(&db).unwrap().as_deref()).unwrap(); assert!(matches!(db.transaction(|db| swap_in(db, &rework)).unwrap(), Swap::Overtaken)); db.exec("DROP TABLE IF EXISTS temp._computed").unwrap(); assert_eq!(whole(&db), current, "the index the first rebuild swapped in stands");}/// RULE: A rollup over a built-in table reads only the children whose link/// names this parent. Loading every unrelated note for each parent's change/// made the bulk seed quadratic and timed out the CI runner.#[test]fn a_builtin_rollup_reads_only_its_linked_children() {let db = practice();for (id, project) in [("ours", "one"), ("theirs", "two")] { db.run("INSERT INTO cotton_notes(id,workspace_id,title,body,project_id,created_at,updated_at) VALUES(?,?,?,?,?,?,?)", &[text(id),text(WS),text(id),text("invented"),text(project),text(AT),text(AT)]).unwrap(); }let definition = builtin_table_definitions().iter().find(|table| table.id == "note").unwrap();for rebuilding in [false, true] {let _cache = rebuilding.then(RebuildRows::begin); db.watch_statements();let rows = linked_records(&db, definition, "project_id", "one").unwrap(); assert_eq!(rows.iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), ["ours"]);let reads: Vec<_> = db.statements_seen().into_iter() .filter(|sql| sql.starts_with("SELECT") && sql.contains("cotton_notes")).collect(); assert!(!reads.is_empty(), "the guard observes the child read"); assert!(reads.iter().all(|sql| sql.contains("\"project_id\" = ?") || sql.contains("project_id = ?")), "{reads:?}"); }}