//! Every case of `packages/store/__tests__/fold.test.ts`, ported. //! //! The retired-table describe block's cases mostly have nothing to name: the //! machinery came back with the ladder (step 5's R4) but //! [`crate::migrate::RETIRED_TABLES`] is EMPTY, because the one entry retires //! nothing. So its final case — "an unknown table that is NOT retired still //! rejects" — is the one that has teeth here, and the two tables it named //! (`cotton_record_tags`, `cotton_prompt_blocks`) are asserted as ordinary //! unknown tables, which is what they now are. `migrate_tests.rs` holds the //! declaration itself, and `fold_reads_the_ladders_retired_list` below holds //! the wiring. use super::*; use crate::protocol::hlc::next_hlc; use crate::protocol::types::OpKind; use crate::test_support::{seeded_file, WORKSPACE as WS}; use serde_json::json; const NOW: &str = "2026-08-22T10:30:00.000Z"; const DEV_A: &str = "device:aaaa"; const DEV_B: &str = "device:bbbb"; /// The TypeScript suite's `seeded()`. fn seeded() -> Driver { seeded_file(DEV_A) } /// The suite's `op()` — everything defaulted but what the case cares about. /// The counter is per builder rather than global, so a case's op ids do not /// depend on which other cases ran. /// /// Every op is a RECEIPT, built as `mint` would build it /// (`wire::op_of_change`). An upsert naming the primary key is a CREATE (it /// names the whole row); one that does not is a CHANGE; a delete is a /// RETRACT. A file seeded by `seeded_file` holds no author fact of its own, /// so no op waits for its author's. struct Ops<'a> { n: u32, db: &'a Driver, } fn test_actor() -> crate::actor::Actor { crate::actor::Actor::device_job(crate::actor::JobName::named("test").expect("a job name")) } fn object(patch: Option) -> Option> { patch.map(|value| match value { JsonValue::Object(map) => map, other => panic!("a patch is an object, got {other}"), }) } impl<'a> Ops<'a> { fn new(db: &'a Driver) -> Ops<'a> { Ops { n: 0, db } } /// The next op id, its stamp and its author. fn next(&mut self, hlc: Option<&str>, device: Option<&str>) -> (String, String, String) { self.n += 1; let device = device.unwrap_or(DEV_A); let hlc = hlc.map_or_else( || next_hlc(device, None, 1_700_000_000_000 + i64::from(self.n)).expect("a stamp in range"), str::to_string, ); (format!("op-{:06}", self.n), hlc, device.to_string()) } fn op( &mut self, kind: OpKind, table: &str, row_id: &str, patch: Option, hlc: Option<&str>, device: Option<&str>, ) -> CottonOp { let (op_id, hlc, author) = self.next(hlc, device); let patch = object(patch); let pk = crate::schema::specs::spec_for(table).expect("a table this build has").pk; let change = match (kind, patch) { (OpKind::Delete, _) => crate::mint::Change::retract(table, row_id), (OpKind::Upsert, Some(patch)) if patch.contains_key(pk) => { crate::mint::Change::create(table, row_id, patch) } (OpKind::Upsert, Some(patch)) => crate::mint::Change::update(table, row_id, patch), (OpKind::Upsert, None) => panic!("an upsert carries a patch"), }; crate::wire::op_of_change(self.db, &change, &hlc, &author, &test_actor(), op_id) .expect("a receipt mint would make") } /// An op whose receipt `mint` would REFUSE to make — a table or a column /// this build does not have — built straight from its fields, the way a /// peer on another build could send it. fn raw( &mut self, kind: OpKind, table: &str, row_id: &str, patch: Option, hlc: Option<&str>, device: Option<&str>, ) -> CottonOp { let (op_id, hlc, author) = self.next(hlc, device); let receipt = Receipt { table: table.to_string(), row_id: row_id.to_string(), kind: match (kind, &patch) { (OpKind::Delete, _) => Kind::Retract, (OpKind::Upsert, Some(JsonValue::Object(map))) if map.contains_key("id") => Kind::Create, (OpKind::Upsert, _) => Kind::Change, }, stamp: hlc, author, actor: test_actor().to_wire(), schema: crate::schema::ddl::SCHEMA_VERSION, restamps: None, erase: None, undo: None, fields: object(patch).unwrap_or_default().into_iter().collect(), }; crate::wire::from_receipt(op_id, &receipt).expect("encodes") } /// [`Ops::todo`], through [`Ops::raw`]. fn raw_todo(&mut self, row_id: &str, patch: JsonValue) -> CottonOp { let mut full = json!({"id": row_id, "workspace_id": WS, "created_at": NOW, "updated_at": NOW}); let object = full.as_object_mut().expect("an object"); for (key, value) in patch.as_object().expect("a patch object") { object.insert(key.clone(), value.clone()); } self.raw(OpKind::Upsert, "cotton_todos", row_id, Some(full), None, None) } fn todo( &mut self, row_id: &str, patch: JsonValue, hlc: Option<&str>, device: Option<&str>, ) -> CottonOp { let mut full = json!({ "id": row_id, "workspace_id": WS, "created_at": NOW, "updated_at": NOW, }); let object = full.as_object_mut().expect("an object"); for (key, value) in patch.as_object().expect("a patch object") { object.insert(key.clone(), value.clone()); } self.op( OpKind::Upsert, "cotton_todos", row_id, Some(full), hlc, device, ) } } fn text(db: &Driver, sql: &str) -> Option { db.get(sql, &[]).expect("reads").and_then(|row| { row.columns().first().and_then(|(_, value)| match value { SqlValue::Text(text) => Some(text.clone()), _ => None, }) }) } fn ids(db: &Driver, sql: &str) -> Vec { db.all(sql, &[]) .expect("reads") .into_iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect() } fn hlc_at(device: &str, ms: i64) -> String { next_hlc(device, None, ms).expect("a stamp in range") } #[test] fn applies_an_upsert() { let db = seeded(); let mut ops = Ops::new(&db); let result = fold_ops( &db, &[ops.todo("t1", json!({"title": "Write the fold"}), None, None)], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert_eq!(result.rejected, vec![]); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("Write the fold".to_string()) ); } #[test] fn is_idempotent_the_same_batch_twice_leaves_an_identical_file() { let db = seeded(); let mut ops = Ops::new(&db); let batch = vec![ ops.todo("t1", json!({"title": "a"}), None, None), ops.todo("t2", json!({"title": "b"}), None, None), ]; fold_ops(&db, &batch).expect("folds"); let first = crate::dump::dump(&db).expect("dumps"); let second = fold_ops(&db, &batch).expect("folds again"); assert_eq!(crate::dump::dump(&db).expect("dumps"), first); assert_eq!(second.applied, Vec::::new()); assert_eq!(second.skipped_stale.len(), 2); } #[test] fn keeps_the_newer_write_when_two_devices_edit_the_same_row() { let db = seeded(); let mut ops = Ops::new(&db); let early = hlc_at(DEV_A, 1_700_000_000_000); let late = hlc_at(DEV_B, 1_700_000_009_000); fold_ops( &db, &[ops.todo("t1", json!({"title": "from A"}), Some(&early), Some(DEV_A))], ) .expect("folds"); fold_ops( &db, &[ops.todo("t1", json!({"title": "from B"}), Some(&late), Some(DEV_B))], ) .expect("folds"); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("from B".to_string()) ); } #[test] fn discards_a_stale_write_that_arrives_late() { let db = seeded(); let mut ops = Ops::new(&db); let birth = hlc_at(DEV_A, 1_699_999_000_000); let early = hlc_at(DEV_A, 1_700_000_000_000); let late = hlc_at(DEV_B, 1_700_000_009_000); // The row's create comes first: an earlier CREATE is never stale — it is // the smallest create, and kept as the row's birth — so the late write // that loses here is a change. fold_ops( &db, &[ops.todo("t1", json!({"title": "original"}), Some(&birth), Some(DEV_A))], ) .expect("folds"); fold_ops( &db, &[ops.op(OpKind::Upsert, "cotton_todos", "t1", Some(json!({"title": "from B"})), Some(&late), Some(DEV_B))], ) .expect("folds"); let result = fold_ops( &db, &[ops.op(OpKind::Upsert, "cotton_todos", "t1", Some(json!({"title": "from A"})), Some(&early), Some(DEV_A))], ) .expect("folds"); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("from B".to_string()) ); assert_eq!(result.skipped_stale.len(), 1); assert_eq!(result.applied, Vec::::new()); } #[test] fn staleness_is_decided_per_row_not_per_batch() { let db = seeded(); let mut ops = Ops::new(&db); let birth = hlc_at(DEV_A, 1_699_999_000_000); let early = hlc_at(DEV_A, 1_700_000_000_000); let late = hlc_at(DEV_B, 1_700_000_009_000); fold_ops( &db, &[ ops.todo("t1", json!({"title": "original"}), Some(&birth), Some(DEV_A)), ops.op(OpKind::Upsert, "cotton_todos", "t1", Some(json!({"title": "newer"})), Some(&late), Some(DEV_B)), ], ) .expect("folds"); let result = fold_ops( &db, &[ ops.op(OpKind::Upsert, "cotton_todos", "t1", Some(json!({"title": "older"})), Some(&early), Some(DEV_A)), ops.todo("t2", json!({"title": "fresh"}), Some(&early), Some(DEV_A)), ], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert_eq!(result.skipped_stale.len(), 1); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("newer".to_string()) ); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't2'"), Some("fresh".to_string()) ); } #[test] fn a_partial_patch_touches_only_the_columns_it_names() { let db = seeded(); let mut ops = Ops::new(&db); fold_ops( &db, &[ops.todo( "t1", json!({"title": "original", "notes": "keep me", "status": "open"}), None, None, )], ) .expect("folds"); fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"status": "done"})), Some(&hlc_at(DEV_A, 1_700_000_050_000)), None, )], ) .expect("folds"); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("original".to_string()) ); assert_eq!( text(&db, "SELECT notes FROM cotton_todos WHERE id = 't1'"), Some("keep me".to_string()) ); assert_eq!( text(&db, "SELECT status FROM cotton_todos WHERE id = 't1'"), Some("done".to_string()) ); } #[test] fn an_absent_patch_key_leaves_the_column_untouched() { // TypeScript's "explicitly-undefined patch value" case. JSON has no // `undefined`, and an op crosses the wire as JSON — so on this side the // only spelling of "not part of this patch" is an ABSENT key, and that is // exactly what the TypeScript case's round-trip proves the two agree on. let db = seeded(); let mut ops = Ops::new(&db); fold_ops( &db, &[ops.todo( "t1", json!({"title": "original", "notes": "keep me"}), None, None, )], ) .expect("folds"); let result = fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"title": "renamed"})), Some(&hlc_at(DEV_A, 1_700_000_050_000)), None, )], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("renamed".to_string()) ); assert_eq!( text(&db, "SELECT notes FROM cotton_todos WHERE id = 't1'"), Some("keep me".to_string()) ); } #[test] fn an_explicit_null_clears_the_column() { let db = seeded(); let mut ops = Ops::new(&db); fold_ops( &db, &[ops.todo( "t1", json!({"title": "original", "notes": "clear me"}), None, None, )], ) .expect("folds"); fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"notes": null})), Some(&hlc_at(DEV_A, 1_700_000_050_000)), None, )], ) .expect("folds"); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("original".to_string()) ); assert_eq!( text(&db, "SELECT notes FROM cotton_todos WHERE id = 't1'"), None ); } #[test] fn a_delete_removes_the_row_and_leaves_a_tombstone() { let db = seeded(); let mut ops = Ops::new(&db); fold_ops( &db, &[ops.todo("t1", json!({"title": "doomed"}), None, None)], ) .expect("folds"); fold_ops( &db, &[ops.op( OpKind::Delete, "cotton_todos", "t1", None, Some(&hlc_at(DEV_A, 1_700_000_050_000)), None, )], ) .expect("folds"); assert!(db .get("SELECT * FROM cotton_todos WHERE id = 't1'", &[]) .expect("reads") .is_none()); let tombstone = db .get("SELECT tbl, row_id FROM _tombstones", &[]) .expect("reads") .expect("a tombstone"); assert_eq!(tombstone.text("tbl"), Some("cotton_todos")); assert_eq!(tombstone.text("row_id"), Some("t1")); } #[test] fn an_older_upsert_arriving_after_a_delete_does_not_resurrect_the_row() { let db = seeded(); let mut ops = Ops::new(&db); let early = hlc_at(DEV_A, 1_700_000_000_000); let delete_at = hlc_at(DEV_B, 1_700_000_050_000); fold_ops( &db, &[ops.todo("t1", json!({"title": "doomed"}), Some(&early), Some(DEV_A))], ) .expect("folds"); fold_ops( &db, &[ops.op( OpKind::Delete, "cotton_todos", "t1", None, Some(&delete_at), Some(DEV_B), )], ) .expect("folds"); let result = fold_ops( &db, &[ops.todo("t1", json!({"title": "zombie"}), Some(&early), Some(DEV_A))], ) .expect("folds"); assert!(db .get("SELECT * FROM cotton_todos WHERE id = 't1'", &[]) .expect("reads") .is_none()); assert_eq!(result.skipped_stale.len(), 1); } #[test] fn a_newer_upsert_after_a_delete_does_resurrect_the_row() { let db = seeded(); let mut ops = Ops::new(&db); let delete_at = hlc_at(DEV_A, 1_700_000_000_000); let recreate = hlc_at(DEV_A, 1_700_000_090_000); fold_ops( &db, &[ops.todo( "t1", json!({"title": "first"}), Some(&hlc_at(DEV_A, 1_699_999_000_000)), None, )], ) .expect("folds"); fold_ops( &db, &[ops.op( OpKind::Delete, "cotton_todos", "t1", None, Some(&delete_at), None, )], ) .expect("folds"); let result = fold_ops( &db, &[ops.todo("t1", json!({"title": "reborn"}), Some(&recreate), None)], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("reborn".to_string()) ); } #[test] fn rejects_an_unknown_column_without_failing() { let db = seeded(); let mut ops = Ops::new(&db); let result = fold_ops( &db, &[ops.raw_todo("t1", json!({"title": "x", "nonsense_column": 1}))], ) .expect("folds"); assert_eq!(result.rejected.len(), 1); assert!( result.rejected[0].reason.contains("unknown column"), "got {}", result.rejected[0].reason ); } #[test] fn rejects_the_op_the_database_refuses_and_keeps_its_neighbours() { let db = seeded(); let mut ops = Ops::new(&db); let result = fold_ops( &db, &[ ops.todo("t1", json!({"title": "fine"}), None, None), ops.todo( "t2", json!({"title": "bad", "status": "not-a-status"}), None, None, ), ], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert_eq!(result.rejected.len(), 1); assert_ne!(result.applied[0], result.rejected[0].op_id); assert!( result.rejected[0] .reason .to_ascii_lowercase() .contains("constraint failed"), "got {}", result.rejected[0].reason ); assert_eq!(ids(&db, "SELECT id FROM cotton_todos"), ["t1"]); } #[test] fn advances_meta_last_hlc_to_the_newest_stamp_it_saw() { let db = seeded(); let mut ops = Ops::new(&db); let late = hlc_at(DEV_B, 1_700_000_090_000); fold_ops( &db, &[ops.todo( "t1", json!({"title": "a"}), Some(&hlc_at(DEV_A, 1_700_000_000_000)), None, )], ) .expect("folds"); fold_ops( &db, &[ops.todo("t2", json!({"title": "b"}), Some(&late), Some(DEV_B))], ) .expect("folds"); assert_eq!(text(&db, "SELECT last_hlc FROM _meta"), Some(late)); } #[test] fn does_not_move_last_hlc_backwards() { let db = seeded(); let mut ops = Ops::new(&db); let late = hlc_at(DEV_B, 1_700_000_090_000); fold_ops( &db, &[ops.todo("t1", json!({"title": "a"}), Some(&late), Some(DEV_B))], ) .expect("folds"); fold_ops( &db, &[ops.todo( "t2", json!({"title": "b"}), Some(&hlc_at(DEV_A, 1_700_000_000_000)), None, )], ) .expect("folds"); assert_eq!(text(&db, "SELECT last_hlc FROM _meta"), Some(late)); } #[test] fn stamps_every_applied_row_with_the_ops_hlc() { let db = seeded(); let mut ops = Ops::new(&db); let hlc = hlc_at(DEV_A, 1_700_000_000_000); fold_ops( &db, &[ops.todo("t1", json!({"title": "a"}), Some(&hlc), None)], ) .expect("folds"); assert_eq!( text(&db, "SELECT _hlc FROM cotton_todos WHERE id = 't1'"), Some(hlc) ); } #[test] fn folds_a_delete_for_a_row_that_was_never_here() { let db = seeded(); let mut ops = Ops::new(&db); let result = fold_ops( &db, &[ops.op( OpKind::Delete, "cotton_todos", "ghost", None, Some(&hlc_at(DEV_A, 1_700_000_000_000)), None, )], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert!(db .get("SELECT row_id FROM _tombstones WHERE row_id = 'ghost'", &[]) .expect("reads") .is_some()); } #[test] fn handles_a_composite_key_table_through_its_synthetic_id() { let db = seeded(); let mut ops = Ops::new(&db); db.run( "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, created_at, updated_at)\n VALUES (?,?,?,?,?,?)", &[ SqlValue::Text("proj-1".to_string()), SqlValue::Text(WS.to_string()), SqlValue::Text("northwind".to_string()), SqlValue::Text("Northwind".to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ) .expect("the parent project"); let result = fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_project_links", "pl-1", Some(json!({ "id": "pl-1", "workspace_id": WS, "project_id": "proj-1", "record_kind": "todo", "record_id": "t1", "applied_by": "user", "created_at": NOW, "updated_at": NOW, })), Some(&hlc_at(DEV_A, 1_700_000_000_000)), None, )], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert_eq!( text( &db, "SELECT record_id FROM cotton_project_links WHERE id = 'pl-1'" ), Some("t1".to_string()) ); } // ───────────────────────────────────────────────────────────────────────────── // Foreign keys inside a fold // ───────────────────────────────────────────────────────────────────────────── #[test] fn accepts_a_batch_whose_child_arrives_before_its_parent() { let db = seeded(); let mut ops = Ops::new(&db); let collection = "22222222-2222-4222-8222-222222222222"; let event = "33333333-3333-4333-8333-333333333333"; // The child first, on purpose. let child = ops.op( OpKind::Upsert, "cotton_events", event, Some(json!({ "id": event, "collection_id": collection, "title": "Standup", "starts_at": "2026-09-01T09:00:00.000Z", "created_at": "2026-08-22T00:00:00.000Z", "updated_at": "2026-08-22T00:00:00.000Z", })), Some("0000000000001:0000:d"), Some("d"), ); let parent = ops.op( OpKind::Upsert, "cotton_collections", collection, Some(json!({ "id": collection, "workspace_id": WS, "kind": "calendar", "name": "Personal", "created_at": "2026-08-22T00:00:00.000Z", })), Some("0000000000002:0000:d"), Some("d"), ); let result = fold_ops(&db, &[child, parent]).expect("folds"); assert_eq!(result.applied.len(), 2); assert_eq!(result.rejected, vec![]); } /// RULE: A create under an owning parent this file does not hold is dormant — stored and reported applied, with no table row — never refused on its foreign key. #[test] fn an_op_whose_owning_parent_never_arrives_is_dormant_not_rejected() { let db = seeded(); let mut ops = Ops::new(&db); let orphan = ops.op( OpKind::Upsert, "cotton_event_attendees", "44444444-4444-4444-8444-444444444444", Some(json!({ "id": "44444444-4444-4444-8444-444444444444", "event_id": "no-such-event", "email": "guest@example.com", "response": "needs_action", "created_at": "2026-08-22T00:00:00.000Z", "updated_at": "2026-08-22T00:00:00.000Z", })), Some("0000000000001:0000:d"), Some("d"), ); let orphan_id = orphan.op_id.clone(); let result = fold_ops(&db, &[orphan]).expect("folds"); assert_eq!(result.applied, vec![orphan_id.clone()]); assert_eq!(result.rejected, vec![]); assert!(ids(&db, "SELECT id FROM cotton_event_attendees").is_empty()); assert_eq!( ids(&db, "SELECT op_id AS id FROM _writes WHERE tbl = 'cotton_event_attendees'"), [orphan_id.as_str()], "the receipt is kept" ); } /// RULE: A dormant child's constraint failure on reassembly must preserve its valid parent and every accepted receipt, so one bad child cannot discard good data. #[test] fn a_dormant_child_constraint_failure_keeps_its_parent_and_receipt() { let db = seeded(); let mut ops = Ops::new(&db); let account = "55555555-5555-4555-8555-555555555555"; let event = "66666666-6666-4666-8666-666666666666"; let guest = "77777777-7777-4777-8777-777777777777"; // Its owning event has not arrived, so the receipt is accepted but // dormant. The invalid response reaches its CHECK only on reassembly. let child_op = ops.op(OpKind::Upsert, "cotton_event_attendees", guest, Some(json!({ "id": guest, "event_id": event, "email": "guest@example.com", "response": "not-a-response", "created_at": NOW, "updated_at": NOW, })), None, None); let account_op = ops.op(OpKind::Upsert, "cotton_money_accounts", account, Some(json!({ "id": account, "workspace_id": WS, "kind": "bank", "subtype": "bank", "name": "Synthetic bank", "currency": "INR", "counterparty_person_id": "no-such-person", "created_at": NOW, "updated_at": NOW, })), None, None); let account_op_id = account_op.op_id.clone(); let child_op_id = child_op.op_id.clone(); let parent_op = ops.op(OpKind::Upsert, "cotton_events", event, Some(json!({ "id": event, "title": "Synthetic event", "starts_at": NOW, "created_at": NOW, "updated_at": NOW, })), None, None); let parent_op_id = parent_op.op_id.clone(); let result = fold_ops(&db, &[child_op, account_op, parent_op]).expect("folds"); assert!(ids(&db, "SELECT id FROM cotton_money_accounts").is_empty()); assert!(ids(&db, "SELECT id FROM cotton_event_attendees").is_empty()); assert_eq!(ids(&db, "SELECT id FROM cotton_events"), [event], "the parent must survive: {result:?}"); assert_eq!(result.rejected.iter().map(|refusal| refusal.op_id.as_str()).collect::>(), [account_op_id.as_str()]); assert!(result.applied.contains(&parent_op_id)); assert!(result.applied.contains(&child_op_id), "the dormant child receipt remains accepted"); assert_eq!(ids(&db, "SELECT row_id AS id FROM _parked WHERE tbl='cotton_event_attendees'"), [guest]); assert_eq!(ids(&db, "SELECT op_id AS id FROM _writes WHERE tbl='cotton_event_attendees'"), [child_op_id]); } // ───────────────────────────────────────────────────────────────────────────── // A constraint failure is one op's problem, never the batch's // ───────────────────────────────────────────────────────────────────────────── const RECURRENCE: &str = "44444444-4444-4444-8444-444444444444"; #[test] fn rejects_the_op_that_violates_a_unique_index_and_keeps_the_rest_of_the_batch() { let db = seeded(); let mut ops = Ops::new(&db); db.run( "INSERT INTO cotton_todo_recurrences\n (id, workspace_id, title, rrule, dtstart, created_at, updated_at)\n VALUES (?,?,?,?,?,?,?)", &[ SqlValue::Text(RECURRENCE.to_string()), SqlValue::Text(WS.to_string()), SqlValue::Text("Pay the rent".to_string()), SqlValue::Text("FREQ=MONTHLY".to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ) .expect("the recurrence"); let at = "2026-11-02T04:00:00.000Z"; let occurrence = |ops: &mut Ops, row_id: &str, device: Option<&str>| { ops.todo( row_id, json!({"title": "Pay the rent", "recurrence_id": RECURRENCE, "occurrence_at": at}), None, device, ) }; let first = fold_ops(&db, &[occurrence(&mut ops, "id-from-the-door", None)]).expect("folds"); assert_eq!(first.rejected, vec![]); // The same occurrence arriving under a DIFFERENT row id — exactly what two // producers that each minted their own key send. let second = fold_ops( &db, &[ occurrence(&mut ops, "id-from-the-phone", Some(DEV_B)), ops.todo( "a-perfectly-good-todo", json!({"title": "Buy cardamom"}), None, Some(DEV_B), ), ], ) .expect("folds"); assert_eq!(second.rejected.len(), 1); assert!(!second.rejected[0].op_id.is_empty()); let reason = second.rejected[0].reason.to_ascii_lowercase(); assert!( reason.contains("constraint") || reason.contains("unique"), "got {reason}" ); assert_eq!(second.applied.len(), 1); let mut rows = ids(&db, "SELECT id FROM cotton_todos ORDER BY id"); rows.sort(); assert_eq!(rows, ["a-perfectly-good-todo", "id-from-the-door"]); } #[test] fn does_not_fail_the_call_on_a_check_violation() { let db = seeded(); let mut ops = Ops::new(&db); assert!(fold_ops( &db, &[ops.todo( "bad-status", json!({"title": "x", "status": "not-a-real-status"}), None, None )] ) .is_ok()); } #[test] fn rejects_a_check_violation_per_op() { let db = seeded(); let mut ops = Ops::new(&db); let result = fold_ops( &db, &[ ops.todo( "bad-status", json!({"title": "x", "status": "not-a-real-status"}), None, None, ), ops.todo("fine", json!({"title": "y"}), None, None), ], ) .expect("folds"); assert_eq!(result.rejected.len(), 1); assert_eq!(ids(&db, "SELECT id FROM cotton_todos").len(), 1); } #[test] fn leaves_this_devices_clock_alone_when_an_op_is_rejected() { let db = seeded(); let mut ops = Ops::new(&db); fold_ops(&db, &[ops.todo("ok", json!({"title": "y"}), None, None)]).expect("folds"); let before = text(&db, "SELECT last_hlc FROM _meta"); let result = fold_ops( &db, &[ops.todo( "bad", json!({"title": "x", "status": "not-a-real-status"}), Some("9999999999999:0001:device:zzz"), Some("device:zzz"), )], ) .expect("folds"); assert_eq!(result.rejected.len(), 1); assert_eq!(text(&db, "SELECT last_hlc FROM _meta"), before); } // ───────────────────────────────────────────────────────────────────────────── // The memory columns cross the fold // ───────────────────────────────────────────────────────────────────────────── #[test] fn folds_an_upsert_carrying_the_memory_columns_and_reads_them_back() { let db = seeded(); let mut ops = Ops::new(&db); let result = fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_memories", "mem-1", Some(json!({ "id": "mem-1", "workspace_id": WS, "slug": "ship-the-server-first", "title": "Ship the server before the app build", "body": "", "status": "active", "machine": null, "visibility": "private", "origin_kind": "agent", "origin_label": "Claude", "source_external_id": null, "archived_at": null, "created_at": NOW, "updated_at": NOW, "source": "https://example.invalid/repo/pull/1", "superseded_by": null, })), None, None, )], ) .expect("folds"); assert_eq!(result.rejected, vec![]); assert_eq!(result.applied.len(), 1); let stored = db .get( "SELECT title, source FROM cotton_memories WHERE id = 'mem-1'", &[], ) .expect("reads") .expect("a row"); assert_eq!( stored.text("source"), Some("https://example.invalid/repo/pull/1") ); let read = read_row(&db, "cotton_memories", "mem-1") .expect("reads") .expect("a row"); assert_eq!( read.get("title"), Some(&JsonValue::String( "Ship the server before the app build".to_string() )) ); } /// RULE: A memory entry is one sentence with no separate temporal state, so an op that still carries the retired dated, next_review_at or review_interval_days column is refused by name rather than quietly dropped. #[test] fn refuses_an_upsert_that_still_carries_a_retired_dated_column() { for column in ["dated", "next_review_at", "review_interval_days"] { let db = seeded(); let mut ops = Ops::new(&db); let mut patch = json!({ "id": "mem-1", "workspace_id": WS, "slug": "ship-the-server-first", "title": "Ship the server before the app build", "status": "active", "origin_kind": "user", "created_at": NOW, "updated_at": NOW, }); patch[column] = json!(1); let result = fold_ops( &db, &[ops.raw( OpKind::Upsert, "cotton_memories", "mem-1", Some(patch), None, None, )], ) .expect("folds"); assert_eq!(result.rejected.len(), 1); assert_eq!(result.rejected[0].op_id, "op-000001"); assert!( result.rejected[0].reason.contains("unknown column") && result.rejected[0].reason.contains(column), "{column} left the file at version 34 and an op naming it is rejected, not dropped: {}", result.rejected[0].reason ); assert!(result.applied.is_empty()); } } #[test] fn rejects_a_superseded_by_on_a_row_that_is_not_archived() { let db = seeded(); let mut ops = Ops::new(&db); let result = fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_memories", "mem-2", Some(json!({ "id": "mem-2", "workspace_id": WS, "slug": "old-fact", "title": "An old fact", "status": "active", "origin_kind": "user", "created_at": NOW, "updated_at": NOW, "superseded_by": "mem-3", })), None, None, )], ) .expect("folds"); assert_eq!(result.rejected.len(), 1); assert!( result.rejected[0].reason.contains("CHECK"), "got {}", result.rejected[0].reason ); } // ───────────────────────────────────────────────────────────────────────────── // There is no retired list any more (spec R2 amendment) // ───────────────────────────────────────────────────────────────────────────── #[test] fn an_op_naming_a_table_a_migration_retired_is_stepped_over_and_never_parked() { // The phone that queued this op was right when it queued it. Version 3 // dropped `cotton_scopes` under it, and a rejection would tell the person // their write failed for a table their own file deliberately let go — so // the op is counted as skipped, the cursor advances, and `_parked` // stays empty. let db = seeded(); let mut ops = Ops::new(&db); let result = fold_ops( &db, &[ops.raw( OpKind::Upsert, "cotton_scopes", "scope-1", Some(json!({"scope": "scope-1"})), Some(&hlc_at(DEV_A, 1_700_000_000_000)), None, )], ) .expect("folds"); assert_eq!(result.skipped_retired.len(), 1); assert!(result.rejected.is_empty()); assert!(db .get("SELECT op_id FROM _parked", &[]) .expect("reads") .is_none()); } // ───────────────────────────────────────────────────────────────────────────── // The result's wire shape // ───────────────────────────────────────────────────────────────────────────── #[test] fn the_result_serializes_under_the_names_the_other_half_uses() { let result = FoldResult { applied: vec!["op-1".to_string()], skipped_stale: vec!["op-2".to_string()], skipped_retired: vec!["op-4".to_string()], rejected: vec![Rejection { op_id: "op-3".to_string(), reason: "unknown table: x".to_string(), }], applied_rows: vec![("cotton_todos".to_string(), "t1".to_string())], waiting: Vec::new(), announced: Vec::new(), board: Vec::new(), parked: Vec::new(), }; assert_eq!( serde_json::to_string(&result).expect("serializes"), r#"{"applied":["op-1"],"skippedStale":["op-2"],"skippedRetired":["op-4"],"rejected":[{"opId":"op-3","reason":"unknown table: x"}],"appliedRows":[["cotton_todos","t1"]]}"# ); } #[test] fn read_row_answers_none_for_a_table_it_does_not_know_and_a_row_that_is_not_there() { let db = seeded(); assert_eq!( read_row(&db, "cotton_not_a_table", "x").expect("reads"), None ); assert_eq!(read_row(&db, "cotton_todos", "nope").expect("reads"), None); } #[test] fn a_quoted_column_name_survives_the_write_and_the_read() { // `position` is a SQLite keyword and a Cotton column; the fold quotes it. let db = seeded(); let mut ops = Ops::new(&db); db.run( "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, created_at, updated_at)\n VALUES (?,?,?,?,?,?)", &[ SqlValue::Text("proj-1".to_string()), SqlValue::Text(WS.to_string()), SqlValue::Text("northwind".to_string()), SqlValue::Text("Northwind".to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ) .expect("the parent project"); let result = fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_project_links", "pl-2", Some(json!({ "id": "pl-2", "workspace_id": WS, "project_id": "proj-1", "record_kind": "todo", "record_id": "t1", "applied_by": "user", "created_at": NOW, "updated_at": NOW, "position": 3, })), Some(&hlc_at(DEV_A, 1_700_000_000_000)), None, )], ) .expect("folds"); assert_eq!(result.rejected, vec![]); let row = read_row(&db, "cotton_project_links", "pl-2") .expect("reads") .expect("a row"); assert_eq!(row.get("position"), Some(&json!(3))); } // ───────────────────────────────────────────────────────────────────────────── // Per-field receipts: the highest stamp naming a field wins it // ───────────────────────────────────────────────────────────────────────────── /// One stamp column of a todo row, as the file holds it. fn stamp(db: &Driver, column: &str, row_id: &str) -> Option { db.get( &format!("SELECT {column} FROM cotton_todos WHERE id = ?"), &[SqlValue::Text(row_id.to_string())], ) .expect("reads") .and_then(|row| row.text(column).map(str::to_string)) } /// The receipts a todo row keeps, as `(stamp, bytes)` in stamp order — the /// part of a row two files compare beside its columns. The op id is left /// out: these cases number their ops in arrival order. fn kept(db: &Driver, row_id: &str) -> Vec<(String, Vec)> { db.all( "SELECT hlc, bytes FROM _writes WHERE tbl = 'cotton_todos' AND row_id = ? ORDER BY hlc", &[SqlValue::Text(row_id.to_string())], ) .expect("reads") .into_iter() .map(|row| { let bytes = match row.get("bytes") { Some(SqlValue::Blob(bytes)) => bytes.clone(), Some(SqlValue::Text(text)) => text.clone().into_bytes(), _ => Vec::new(), }; (row.text("hlc").unwrap_or_default().to_string(), bytes) }) .collect() } #[test] fn two_authors_two_columns_both_survive() { // The case per-field folding exists for: B checks the todo off, A renames // it a moment earlier, and A's op arrives second. Per row, A's whole write // would lose — including the title nobody else touched. let db = seeded(); let mut ops = Ops::new(&db); let birth = hlc_at(DEV_A, 1_700_000_000_100); let late = hlc_at(DEV_B, 1_700_000_000_300); let early = hlc_at(DEV_A, 1_700_000_000_200); fold_ops( &db, &[ops.todo("t1", json!({"title": "original"}), Some(&birth), Some(DEV_A))], ) .expect("folds"); fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"status": "done"})), Some(&late), Some(DEV_B), )], ) .expect("folds"); let result = fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"title": "renamed"})), Some(&early), Some(DEV_A), )], ) .expect("folds"); assert_eq!(result.applied.len(), 1, "the older op still applied"); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("renamed".to_string()) ); assert_eq!( text(&db, "SELECT status FROM cotton_todos WHERE id = 't1'"), Some("done".to_string()) ); assert_eq!(stamp(&db, "_hlc", "t1"), Some(late), "_hlc is the maximum over the row"); assert_eq!(stamp(&db, "_born", "t1"), Some(birth), "the row was born at its create"); } #[test] fn a_partial_loss_still_applies_the_winning_columns() { let db = seeded(); let mut ops = Ops::new(&db); let birth = hlc_at(DEV_A, 1_700_000_000_100); let late = hlc_at(DEV_B, 1_700_000_000_300); let early = hlc_at(DEV_A, 1_700_000_000_200); fold_ops( &db, &[ops.todo("t1", json!({"title": "original"}), Some(&birth), Some(DEV_A))], ) .expect("folds"); fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"title": "from B"})), Some(&late), Some(DEV_B), )], ) .expect("folds"); // Two columns, one of them behind B's write: the title loses, the notes // land, and the op is APPLIED rather than skipped. let result = fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"title": "from A", "notes": "from A"})), Some(&early), Some(DEV_A), )], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert_eq!(result.skipped_stale, Vec::::new()); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("from B".to_string()), "the losing column was not written" ); assert_eq!( text(&db, "SELECT notes FROM cotton_todos WHERE id = 't1'"), Some("from A".to_string()) ); } #[test] fn a_delete_ends_the_life_it_is_above_and_a_later_change_waits_dormant() { // A retract raises the row's stamp T. Every receipt below T belongs to an // earlier life; the row is live only while a create is above T. A change // stamped after the retract but with no create above T is DORMANT: kept, // no table row. (Before receipts, a delete older than the newest column // lost whole; now it ends the life it is above.) let db = seeded(); let mut ops = Ops::new(&db); let birth = hlc_at(DEV_A, 1_700_000_000_100); let column = hlc_at(DEV_B, 1_700_000_000_300); fold_ops( &db, &[ops.todo("t1", json!({"title": "original"}), Some(&birth), Some(DEV_A))], ) .expect("folds"); let change = ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"status": "done"})), Some(&column), Some(DEV_B), ); fold_ops(&db, std::slice::from_ref(&change)).expect("folds"); let retract = fold_ops( &db, &[ops.op( OpKind::Delete, "cotton_todos", "t1", None, Some(&hlc_at(DEV_A, 1_700_000_000_200)), Some(DEV_A), )], ) .expect("folds"); assert_eq!(retract.applied.len(), 1); assert_eq!(ids(&db, "SELECT id FROM cotton_todos"), Vec::::new()); assert_eq!( kept(&db, "t1"), vec![(column.clone(), change.receipt.clone().into_bytes())], "the create below T went; the change above it stays, dormant" ); let killed = fold_ops( &db, &[ops.op( OpKind::Delete, "cotton_todos", "t1", None, Some(&hlc_at(DEV_A, 1_700_000_000_400)), Some(DEV_A), )], ) .expect("folds"); assert_eq!(killed.applied.len(), 1); assert_eq!(ids(&db, "SELECT id FROM cotton_todos"), Vec::::new()); assert_eq!(kept(&db, "t1"), Vec::new(), "a retract above every receipt leaves none"); } #[test] fn a_newer_column_recreates_the_row() { let db = seeded(); let mut ops = Ops::new(&db); let birth = hlc_at(DEV_A, 1_700_000_000_100); let killed = hlc_at(DEV_A, 1_700_000_000_200); fold_ops( &db, &[ops.todo("t1", json!({"title": "first life"}), Some(&birth), Some(DEV_A))], ) .expect("folds"); fold_ops( &db, &[ops.op( OpKind::Delete, "cotton_todos", "t1", None, Some(&killed), Some(DEV_A), )], ) .expect("folds"); // Older than the tombstone: no column of it beats the delete. let stale = fold_ops( &db, &[ops.todo( "t1", json!({"title": "too late"}), Some(&hlc_at(DEV_B, 1_700_000_000_150)), Some(DEV_B), )], ) .expect("folds"); assert_eq!(stale.skipped_stale.len(), 1); assert_eq!(ids(&db, "SELECT id FROM cotton_todos"), Vec::::new()); let reborn = hlc_at(DEV_B, 1_700_000_000_300); let result = fold_ops( &db, &[ops.todo( "t1", json!({"title": "second life"}), Some(&reborn), Some(DEV_B), )], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert_eq!( text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"), Some("second life".to_string()) ); assert_eq!( (stamp(&db, "_hlc", "t1"), stamp(&db, "_born", "t1")), (Some(reborn.clone()), Some(reborn)), "a recreated row is born at the stamp that recreated it" ); } #[test] fn a_partial_recreation_without_a_create_is_dormant() { // A change above the retract, with no create above it, does not bring the // row back: it is stored and reported applied, and the row stays absent // until a create lands. (Before receipts this INSERT tripped NOT NULL and // was rejected.) let db = seeded(); let mut ops = Ops::new(&db); let birth = hlc_at(DEV_A, 1_700_000_000_100); let killed = hlc_at(DEV_A, 1_700_000_000_200); fold_ops( &db, &[ops.todo("t1", json!({"title": "first life"}), Some(&birth), Some(DEV_A))], ) .expect("folds"); fold_ops( &db, &[ops.op( OpKind::Delete, "cotton_todos", "t1", None, Some(&killed), Some(DEV_A), )], ) .expect("folds"); let result = fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"status": "done"})), Some(&hlc_at(DEV_B, 1_700_000_000_300)), Some(DEV_B), )], ) .expect("folds"); assert_eq!(result.applied.len(), 1); assert_eq!(result.rejected, vec![]); assert_eq!(ids(&db, "SELECT id FROM cotton_todos"), Vec::::new()); assert_eq!(kept(&db, "t1").len(), 1, "the change is kept, dormant"); assert_eq!( text(&db, "SELECT hlc FROM _tombstones WHERE row_id = 't1'"), Some(killed), "the retract still stands" ); } #[test] fn applied_rows_counts_a_row_once_for_two_ops() { // A merge is reported from the ROWS the fold changed. One row arriving as // two ops is one row, and counting ops would say two. let db = seeded(); let mut ops = Ops::new(&db); let result = fold_ops( &db, &[ ops.todo( "t1", json!({"title": "one"}), Some(&hlc_at(DEV_A, 1_700_000_000_100)), Some(DEV_A), ), ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"status": "done"})), Some(&hlc_at(DEV_A, 1_700_000_000_200)), Some(DEV_A), ), ops.todo( "t2", json!({"title": "two"}), Some(&hlc_at(DEV_A, 1_700_000_000_300)), Some(DEV_A), ), ], ) .expect("folds"); assert_eq!(result.applied.len(), 3, "three ops landed"); assert_eq!( result.applied_rows, vec![ ("cotton_todos".to_string(), "t1".to_string()), ("cotton_todos".to_string(), "t2".to_string()), ], "two rows moved" ); // A stale op moves no row, and a rejected one moves no row either. (A // CHANGE: an earlier create is never stale — it becomes the row's birth.) let again = fold_ops( &db, &[ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({"title": "stale"})), Some(&hlc_at(DEV_A, 1_700_000_000_050)), Some(DEV_A), )], ) .expect("folds"); assert_eq!(again.skipped_stale.len(), 1); assert_eq!(again.applied_rows, Vec::<(String, String)>::new()); } #[test] fn a_min_non_null_policy_column_is_monotone() { // `snoozed_until` is registered MinNonNull for this crate's tests only, so // the non-LWW path is exercised by a real fold. No shipped column // registers it since revocation became a fact (slice 5a-i). assert_eq!( policy_for("cotton_todos", "snoozed_until"), Policy::MinNonNull ); assert_eq!(policy_for("cotton_todos", "title"), Policy::Lww); let db = seeded(); let mut ops = Ops::new(&db); let at = |ms: i64| hlc_at(DEV_A, ms); fold_ops( &db, &[ops.todo( "t1", json!({"title": "snoozed"}), Some(&at(1_700_000_000_100)), Some(DEV_A), )], ) .expect("folds"); let write = |ops: &mut Ops, value: JsonValue, hlc: &str| { ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(json!({ "snoozed_until": value })), Some(hlc), Some(DEV_A), ) }; let snoozed = || text(&db, "SELECT snoozed_until FROM cotton_todos WHERE id = 't1'"); // Null to a value: it lands. let op = write(&mut ops, json!("2026-09-10T09:00:00.000Z"), &at(1_700_000_000_200)); assert_eq!(fold_ops(&db, &[op]).expect("folds").applied.len(), 1); assert_eq!(snoozed(), Some("2026-09-10T09:00:00.000Z".to_string())); // A NEWER null does not clear it. let op = write(&mut ops, JsonValue::Null, &at(1_700_000_000_300)); assert_eq!(fold_ops(&db, &[op]).expect("folds").skipped_stale.len(), 1); assert_eq!(snoozed(), Some("2026-09-10T09:00:00.000Z".to_string())); // A NEWER but later value does not win either. let op = write(&mut ops, json!("2026-09-20T09:00:00.000Z"), &at(1_700_000_000_400)); assert_eq!(fold_ops(&db, &[op]).expect("folds").skipped_stale.len(), 1); assert_eq!(snoozed(), Some("2026-09-10T09:00:00.000Z".to_string())); // An OLDER but earlier value does: the minimum is the answer, whatever // order the writes arrive in. let op = write(&mut ops, json!("2026-09-01T09:00:00.000Z"), &at(1_700_000_000_150)); assert_eq!(fold_ops(&db, &[op]).expect("folds").applied.len(), 1); assert_eq!(snoozed(), Some("2026-09-01T09:00:00.000Z".to_string())); } /// A row as the file holds it, beside the receipts it keeps — the pair the /// convergence case compares across orders. type Converged = (Vec<(String, SqlValue)>, Vec<(String, Vec)>); #[test] fn three_orders_of_the_same_ops_converge_on_the_same_file() { // THE property. Six writes from two devices — overlapping columns, disjoint // columns, and one stamped before the row existed — folded in three // different orders into three fresh files, which must end identical down to // the receipts each keeps. let birth = hlc_at(DEV_A, 1_700_000_000_100); let stamps = [ (DEV_B, 1_700_000_000_300, json!({"status": "done"})), (DEV_A, 1_700_000_000_200, json!({"title": "renamed by A"})), (DEV_B, 1_700_000_000_400, json!({"title": "renamed by B", "notes": "B's note"})), (DEV_A, 1_700_000_000_250, json!({"label": "errand"})), (DEV_B, 1_700_000_000_150, json!({"notes": "an earlier note"})), (DEV_A, 1_700_000_000_050, json!({"title": "older than the row"})), ]; let orders: [[usize; 6]; 3] = [[0, 1, 2, 3, 4, 5], [5, 4, 3, 2, 1, 0], [2, 5, 0, 4, 1, 3]]; let mut seen: Vec = Vec::new(); for order in orders { let db = seeded(); let mut ops = Ops::new(&db); fold_ops( &db, &[ops.todo("t1", json!({"title": "original"}), Some(&birth), Some(DEV_A))], ) .expect("folds"); // How many ops LOSE depends on the order — a write beaten by a later // one that had not arrived yet in another order is applied and then // overwritten — which is the point: the verdict per op is // order-dependent, the file it leaves is not. let mut stale = 0; for at in order { let (device, ms, patch) = &stamps[at]; let op = ops.op( OpKind::Upsert, "cotton_todos", "t1", Some(patch.clone()), Some(&hlc_at(device, *ms)), Some(device), ); let result = fold_ops(&db, &[op]).expect("folds"); assert_eq!(result.rejected, vec![]); stale += result.skipped_stale.len(); } assert!(stale >= 1, "the op stamped before the row was born must lose"); let row = db .get("SELECT * FROM cotton_todos WHERE id = 't1'", &[]) .expect("reads") .expect("the row"); seen.push((row.columns().to_vec(), kept(&db, "t1"))); } assert_eq!(seen[0], seen[1], "orders 1 and 2 disagree"); assert_eq!(seen[0], seen[2], "orders 1 and 3 disagree"); // And the file really is the merged one, not one writer's copy. let row: std::collections::BTreeMap<&str, &SqlValue> = seen[0] .0 .iter() .map(|(column, value)| (column.as_str(), value)) .collect(); assert_eq!( row["title"], &SqlValue::Text("renamed by B".to_string()), "the newest title" ); assert_eq!(row["notes"], &SqlValue::Text("B's note".to_string())); assert_eq!(row["label"], &SqlValue::Text("errand".to_string())); assert_eq!(row["status"], &SqlValue::Text("done".to_string())); } // ── a fragment of a row is a whole write ──────────────────────────────────── // // Half of the 2026-09-22 loss (Cotton note "Repo landmines — why the build's rules exist"): the Mac // claimed a session, the helper answered with the agent's own id, and the id // never reached the server. What a session row is made of lives in // `schema::ddl::SESSIONS_TABLE`; this builds it by hand because what is under // test is the fold, not the writer. The other half — a page handed over // backwards — is `exchange_tests.rs`, because a page is ordered where it is // BUILT and the fold applies a batch in the order it is given. /// The columns `cotton_sessions` cannot be INSERTed without — what the phone's /// `session.create` writes, as one op. fn session_created(ops: &mut Ops, row_id: &str, hlc: &str) -> CottonOp { ops.op( OpKind::Upsert, "cotton_sessions", row_id, Some(json!({ "id": row_id, "workspace_id": WS, "tool": "claude-code", "prompt": "list the big feature todos", "state": "queued", "state_at": NOW, "last_active_at": NOW, "created_at": NOW, "updated_at": NOW, })), Some(hlc), None, ) } #[test] fn a_fragment_of_a_row_lands_even_where_its_neighbours_are_stale() { let db = seeded(); let mut ops = Ops::new(&db); let created = session_created(&mut ops, "s1", &hlc_at(DEV_A, 1_790_000_000_000)); fold_ops(&db, &[created]).expect("the row"); // A LATER write covers `state` and its neighbours — on the real file this // was the dispatcher's pass, and on the Mac the mirror's next event. let moved_on = ops.op( OpKind::Upsert, "cotton_sessions", "s1", Some(json!({ "state": "queued", "state_at": NOW, "last_active_at": NOW, "updated_at": NOW, })), Some(&hlc_at(DEV_B, 1_790_000_100_000)), Some(DEV_B), ); fold_ops(&db, &[moved_on]).expect("the later write"); // NOW the Mac's own write arrives, at its older stamp. `changes::row_ops` // hands a row over as one op per distinct column stamp, and the fold drops // the columns a newer write has covered — so what reaches the table is a // FRAGMENT: five columns, beside a `state` that still reads `queued`. No // writer ever wrote that combination, which is why a CHECK spanning the two // refused it whole and the session's id was lost. let started = ops.op( OpKind::Upsert, "cotton_sessions", "s1", Some(json!({ "external_id": "19d6eb6a-0000-4000-8000-000000000001", "machine": "mac-c", "cwd": "/Users/owner/Code/cottondb", "state": "running", "state_at": NOW, "started_at": NOW, "last_active_at": NOW, "host_owned": true, "updated_at": NOW, })), Some(&hlc_at(DEV_A, 1_790_000_037_472)), None, ); let result = fold_ops(&db, &[started]).expect("folds"); assert!( result.rejected.is_empty(), "a fragment is a write, not a malformed row: {:?}", result.rejected ); assert_eq!( text(&db, "SELECT external_id FROM cotton_sessions WHERE id = 's1'").as_deref(), Some("19d6eb6a-0000-4000-8000-000000000001"), "the columns nothing newer covered land" ); assert_eq!( text(&db, "SELECT state FROM cotton_sessions WHERE id = 's1'").as_deref(), Some("queued"), "and the column a newer write covered is left alone" ); } /// RULE: Dormant child lookup uses the normalized owner index rather than scanning all receipts, so parent arrivals never make a book of movements cost n². #[test] fn every_owning_reference_finds_its_dormant_children_by_index() { let db = seeded(); for (child,column,_) in crate::schema::table_specs::OWNING_REFS { let pk = spec_for(child).unwrap().pk; let plan = db.all(&format!("EXPLAIN QUERY PLAN {}", dormant_children_sql(child,column,pk)),&[SqlValue::Text("parent".into())]).unwrap(); let detail = plan.iter().filter_map(|row|row.text("detail")).collect::>().join(" | "); assert!(detail.contains("idx_writes_owners") && !detail.contains("SCAN o") && !detail.contains("SCAN w"),"{child}.{column}: {detail}"); } } /// RULE: A kept receipt that names a column the table no longer has — cotton_people.emails, folded into cotton_person_handles at v90 with its receipts kept — never stops the row from being written: a change to that person settles the columns the table has and drops the rest. /// /// 0.29.27 on the serving Mac, 11 Oct 2026: every WhatsApp profile picture for /// a person made before v90 was refused with "no such column: emails", because /// settling the row wrote every field its kept receipts named. #[test] fn a_change_to_a_row_whose_receipts_name_a_dropped_column_lands() { let db = seeded(); let mut ops = Ops::new(&db); let (op_id, stamp, author) = ops.next(None, None); let legacy = Receipt { table: "cotton_people".to_string(), row_id: "p-old".to_string(), kind: Kind::Create, stamp, author, actor: test_actor().to_wire(), schema: 89, restamps: None, erase: None, undo: None, fields: [ ("id", json!("p-old")), ("workspace_id", json!(WS)), ("full_name", json!("Old Friend")), ("emails", json!("[\"old@example.invalid\"]")), ("created_at", json!(NOW)), ("updated_at", json!(NOW)), ] .into_iter() .map(|(name, value)| (name.to_string(), value)) .collect(), }; let op = crate::wire::from_receipt(op_id, &legacy).expect("encodes"); receipts::store(&db, &op, &legacy, false).expect("the legacy receipt is kept"); db.run( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at, _hlc) VALUES ('p-old', ?, 'Old Friend', ?, ?, ?)", &[ SqlValue::Text(WS.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(legacy.stamp.clone()), ], ) .expect("the row as v90 left it"); let change = ops.op( OpKind::Upsert, "cotton_people", "p-old", Some(json!({"city": "Lisbon"})), None, None, ); let result = fold_ops(&db, &[change]).expect("folds"); assert_eq!(result.rejected, vec![], "the change lands"); assert_eq!( text(&db, "SELECT city FROM cotton_people WHERE id = 'p-old'"), Some("Lisbon".to_string()) ); assert_eq!( text(&db, "SELECT full_name FROM cotton_people WHERE id = 'p-old'"), Some("Old Friend".to_string()), "the legacy receipt's other fields still count" ); } /// RULE: An unknown scope is refused before a device receipt reaches SQL, so a newer or malformed peer cannot create a device whose access silently defaults to Full. #[test] fn unknown_device_scope_is_refused_before_a_write() { let db = seeded(); let op = Ops::new(&db).raw(OpKind::Upsert, "cotton_devices", "scope-guard", Some(json!({"id":"scope-guard", "scope":"future-scope"})), None, None); let folded = fold_ops(&db, &[op]).unwrap(); assert!(folded.rejected.iter().any(|refusal| refusal.reason == "unknown device scope or placement grant")); assert!(db.get("SELECT id FROM cotton_devices WHERE id = 'scope-guard'", &[]).unwrap().is_none()); } /// RULE: Restamping drops the replaced receipt's owner entries with its bytes, so a later parent lookup cannot mistake the old receipt for a current owning relationship. #[test] fn restamp_receipt_deletion_removes_its_owner_entries() { let db=seeded(); let mut ops=Ops::new(&db); let op=ops.op(OpKind::Upsert,"cotton_msg_reactions","reaction",Some(json!({"message_id":"message","thread_id":"thread"})),None,None); let receipt=crate::canonical::decode(op.receipt.as_bytes()).unwrap(); receipts::store(&db,&op,&receipt,false).unwrap(); assert!(db.get("SELECT 1 FROM _writes_owners WHERE receipt=?",&[op.op_id.clone().into()]).unwrap().is_some()); drop_receipt(&db,&op.op_id).unwrap(); assert!(db.get("SELECT 1 FROM _writes_owners WHERE receipt=?",&[op.op_id.into()]).unwrap().is_none()); crate::test_support::assert_receipt_owners_are_attached(&db); } /// RULE: The placement grant exists only on a runner: a (full, 1) receipt is refused before SQL, even when both fields arrive together or the scope is read from the existing row. #[test] fn full_device_with_placement_grant_is_refused_before_a_write() { let db = seeded(); let op = Ops::new(&db).raw(OpKind::Upsert, "cotton_devices", "pair-guard", Some(json!({"id":"pair-guard", "scope":"full", "takes_placements":1})), None, None); let folded = fold_ops(&db, &[op]).unwrap(); assert!(folded.rejected.iter().any(|refusal| refusal.reason == "unknown device scope or placement grant")); assert!(db.get("SELECT id FROM cotton_devices WHERE id = 'pair-guard'", &[]).unwrap().is_none()); } fn household_device(db: &Driver, id: &str, scope: &str, approver: &str) { crate::test_support::fold_create( db, "cotton_devices", id, json!({"id":id, "workspace_id":WS, "device_id":id, "name":id, "approved_at":NOW, "approved_by_device":approver, "created_at":NOW, "updated_at":NOW, "scope":scope}), crate::test_support::SEED_AUTHOR, crate::test_support::SEED_MS, ); } fn household_revoke(ops: &mut Ops<'_>, id: &str) -> Vec { vec![ ops.op(OpKind::Upsert, "cotton_revocations", &format!("end-{id}"), Some(json!({"id":format!("end-{id}"), "workspace_id":WS, "subject_table":"cotton_devices", "subject_id":id, "revoked_at":NOW, "actor":"device:test", "reason":"revoked"})), None, None), ops.op(OpKind::Upsert, "cotton_devices", id, Some(json!({"revoked_at":NOW})), None, None), ] } /// RULE: A database must retain an approved Full device that can approve others; a Runner is no substitute, and a refused sync revoke rolls back its fact and mirror with the same plain reason as a local write. #[test] fn household_sync_cannot_revoke_last_full_device() { let db = seeded(); household_device(&db, "first", "full", "self"); household_device(&db, "runner", "runner", "first"); let mut ops = Ops::new(&db); let mut revoke = household_revoke(&mut ops, "first"); revoke.push(ops.op( OpKind::Upsert, "cotton_devices", "runner", Some(json!({"name":"renamed runner"})), None, None, )); let result = fold_pulled(&db, &revoke).unwrap(); assert_eq!(result.rejected.len(), 2); assert!(result .rejected .iter() .all(|r| r.reason == crate::revocation::LAST_FULL_DEVICE)); assert!( result.applied.contains(&revoke[2].op_id), "unrelated sync writes must land" ); assert!(db .get( "SELECT id FROM cotton_revocations WHERE id = 'end-first'", &[] ) .unwrap() .is_none()); assert!(db .get( "SELECT id FROM cotton_devices WHERE id = 'first' AND revoked_at IS NULL", &[] ) .unwrap() .is_some()); } /// RULE: A copy of a household keeps every device: a self-approved row (the owner's serving Mac as it is today) carried beside other approved Full devices — pulled by a replica folding the file from the start, or minted here as the mover's batches are — is history, never judged by the self-approval rule, which only the act that self-approves asks (`DeviceWrite::self_approve`). #[test] fn household_copy_keeps_every_self_approved_row() { let db = seeded(); household_device(&db, "phone", "full", "mac-a"); household_device(&db, "mac-a", "full", "self"); household_device(&db, "mac-b", "full", "self"); let mut ops = Ops::new(&db); let carried = vec![ops.op( OpKind::Upsert, "cotton_devices", "mac-c", Some(json!({"id":"mac-c", "workspace_id":WS, "device_id":"mac-c", "name":"mac-c", "approved_at":NOW, "approved_by_device":"self", "created_at":NOW, "updated_at":NOW, "scope":"full"})), None, None, )]; let result = fold_pulled(&db, &carried).unwrap(); assert!(result.rejected.is_empty(), "{:?}", result.rejected); // Minted here, as the mover mints a carried batch: the owner's serving Mac // as it is today — approved by itself — beside the phone it approved. let device = |id: &str, approver: &str| { crate::mint::Change::create( "cotton_devices", id, json!({"id":id, "workspace_id":WS, "device_id":id, "name":id, "approved_at":NOW, "approved_by_device":approver, "created_at":NOW, "updated_at":NOW, "scope":"full"}) .as_object() .cloned() .unwrap(), ) }; let mut ids = crate::protocol::ulid::Monotonic::new(crate::test_support::counter_seed()); crate::mint::mint( &db, &crate::mint::Act { actor: crate::actor::Actor::DeviceJob(crate::actor::JobName::named("carry").unwrap()), verb: "carry".to_string(), history: crate::mint::History::None, changes: vec![device("serving-mac", "self"), device("phone-2", "serving-mac")], }, &crate::mint::Clock::wall(crate::test_support::SEED_MS + 60_000), &mut ids, crate::mint::Held::Replica, ) .expect("the carried batch mints"); let live = db.all("SELECT id FROM cotton_devices WHERE revoked_at IS NULL", &[]).unwrap().len(); assert_eq!(live, 6, "a device was lost from the copy"); assert!(db .get("SELECT 1 AS n FROM cotton_devices WHERE id = 'serving-mac' AND approved_by_device = 'self' AND revoked_at IS NULL", &[]) .unwrap() .is_some()); } /// RULE: Every device is revocable, including the first self-approved one, once another approved Full device keeps the database able to approve devices. #[test] fn household_first_device_is_revocable() { let db = seeded(); household_device(&db, "first", "full", "self"); household_device(&db, "second", "full", "first"); let mut ops = Ops::new(&db); let revoke = household_revoke(&mut ops, "first"); assert!(fold_ops(&db, &revoke).unwrap().rejected.is_empty()); assert!(db .get( "SELECT id FROM cotton_devices WHERE id = 'first' AND revoked_at IS NOT NULL", &[] ) .unwrap() .is_some()); let error = arrive(&db, &household_revoke(&mut ops, "second"), Arrival::Local) .expect_err("local writes use the same guard"); assert_eq!( error.to_string(), crate::revocation::LAST_FULL_DEVICE ); } /// RULE: The device invariant is checked for the entire atomic act, so replacing the last Full key with a new Full approval can commit without an intermediate lockout. #[test] fn household_replacement_keeps_one_full_device() { let db = seeded(); household_device(&db, "first", "full", "self"); let mut ops = Ops::new(&db); let mut batch = household_revoke(&mut ops, "first"); batch.push(ops.op(OpKind::Upsert, "cotton_devices", "second", Some(json!({"id":"second", "workspace_id":WS, "device_id":"second", "name":"Second", "approved_at":NOW, "approved_by_device":"first", "created_at":NOW, "updated_at":NOW, "scope":"full"})), None, None)); assert!(fold_ops(&db, &batch).unwrap().rejected.is_empty()); } /// RULE: Rust device paths carry no root privilege; every revoke passes through the store's last-approved-Full-device invariant. #[test] fn household_has_no_root_device_flag() { fn scan(path: &std::path::Path) { for entry in std::fs::read_dir(path).unwrap() { let path = entry.unwrap().path(); if path.is_dir() { if path.file_name().is_some_and(|name| name == "target") { continue; } scan(&path); } else if path.extension().is_some_and(|ext| ext == "rs") { let source = std::fs::read_to_string(&path).unwrap(); for forbidden in ["device_is_".to_owned() + "root", "is_".to_owned() + "root"] { assert!( !source .split(|c: char| !c.is_ascii_alphanumeric() && c != '_') .any(|token| token == forbidden), "{} reads a root flag", path.display() ); } } } } scan( crate::manifest_dir() .parent() .unwrap(), ); } /// RULE: A device-key revocation fact alone cannot end the last Full approval; sync must refuse it even if its approval mirror arrives on another page. #[test] fn household_key_fact_cannot_remove_last_approver() { let db = seeded(); household_device(&db, "first", "full", "self"); let mut ops = Ops::new(&db); let fact = ops.op(OpKind::Upsert, "cotton_revocations", "end-key", Some(json!({"id":"end-key", "workspace_id":WS, "subject_table":"device_key", "subject_id":"first", "revoked_at":NOW, "actor":"device:test", "reason":"revoked"})), None, None); let folded = fold_pulled(&db, &[fact]).unwrap(); assert_eq!( folded.rejected[0].reason, crate::revocation::LAST_FULL_DEVICE ); assert!(db .get( "SELECT id FROM cotton_revocations WHERE id = 'end-key'", &[] ) .unwrap() .is_none()); } /// RULE: Only the owner at their own device orders a Mac to become a runner, and only the serving Mac answers the order — a job, token, session or connector cannot write runner_ordered_at, and no other author can write runner_confirmed_at or runner_problem — because the order ends with a Mac's copy dropped, and a Mac that could confirm itself could drop a copy nobody else holds. #[test] fn a_runner_order_is_the_owners_and_its_answer_the_serving_macs() { let db = seeded(); let mut ops = Ops::new(&db); let ordered = ops.raw(OpKind::Upsert, "cotton_devices", "row-mac-d", Some(json!({"runner_ordered_at": NOW})), None, None); let confirmed = ops.raw(OpKind::Upsert, "cotton_devices", "row-mac-d", Some(json!({"runner_confirmed_at": NOW})), None, None); let problem = ops.raw(OpKind::Upsert, "cotton_devices", "row-mac-d", Some(json!({"runner_problem": "[]"})), None, None); let folded = fold_ops(&db, &[ordered, confirmed, problem]).unwrap(); let reasons: Vec<&str> = folded.rejected.iter().map(|refusal| refusal.reason.as_str()).collect(); assert_eq!( reasons, [ "only the owner, at their own device, orders a Mac to become a runner", "only the serving Mac answers a runner order", "only the serving Mac answers a runner order", ] ); }