//! Presence under owning parents (design 3.7 points 7-9): a row is present //! only while it is live by its own receipts and every owning parent is //! present. The fold moves presence itself — children out before their //! parent, back when it returns — and never leaves it to SQLite, so two files //! that have seen the same writes hold the same rows in any arrival order. //! //! The family used throughout: a repository (`cotton_repos`) owns its runs //! (`cotton_repo_runs.repo_id`), and a run owns its jobs //! (`cotton_repo_jobs.run_id`). use std::collections::BTreeMap; use cotton_store::actor::{Actor, JobName}; use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE}; use cotton_store::fold::{arrive, Arrival, FoldResult}; use cotton_store::meta::{seed_meta, Meta}; use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource}; use cotton_store::protocol::types::CottonOp; use cotton_store::schema::ddl::SCHEMA_VERSION; use cotton_store::Driver; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; const T0: i64 = 1_759_480_000_000; const REPO: &str = "repo-1"; const OTHER_REPO: &str = "repo-2"; const RUN: &str = "run-1"; const JOB: &str = "job-1"; /// The tables a comparison reads, parents first. const FAMILY: &[&str] = &["cotton_repos", "cotton_repo_runs", "cotton_repo_jobs"]; struct Ids(u32, &'static str); impl IdSource for Ids { fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result { self.0 += 1; Ok(format!("{}-{:04}", self.1, self.0)) } } /// One device's file, with its author minted. struct Dev { db: Driver, ids: Ids, author: String, fact: CottonOp, actor: Actor, } /// Every device hears every other's author fact — what a first exchange does. fn meet(devs: &[&Dev]) { for to in devs { for from in devs { if from.author != to.author { to.take(std::slice::from_ref(&from.fact)); } } } } fn device(tag: &'static str) -> Dev { let db = file_at_version(SCHEMA_VERSION); seed_meta( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: format!("device:{tag}"), last_server_seq: 0, last_hlc: None, }, SCHEMA_VERSION, ) .expect("seeds"); seed_workspace_row(&db); let mut ids = Ids(0, tag); let author = first_author(&db, &format!("key-{tag}"), Some(tag), AuthorReason::First, &Clock::wall(T0 - 10), &mut ids, Held::Served) .expect("the author"); Dev { db, ids, author: author.id, fact: author.fact, actor: Actor::device_job(JobName::named("test").expect("a job name")), } } fn obj(value: Value) -> Map { value.as_object().expect("an object").clone() } fn repo(id: &str) -> Change { Change::create( "cotton_repos", id, obj(json!({ "id": id, "workspace_id": WORKSPACE, "key": format!("example.invalid/synthetic/{id}"), "host": "example.invalid", "owner": "synthetic", "name": id, "kind": "cotton", "web_url": format!("https://example.invalid/synthetic/{id}"), "created_at": NOW, "updated_at": NOW, })), ) } /// A run of `repo`, the `index`th in it. fn run(id: &str, repo: &str, index: i64) -> Change { Change::create( "cotton_repo_runs", id, obj(json!({ "id": id, "workspace_id": WORKSPACE, "repo_id": repo, "index_in_repo": index, "workflow": "ci.yml", "event": "push", "ref": "refs/heads/main", "sha": "0123456789abcdef", "created_at": NOW, "updated_at": NOW, })), ) } fn job(id: &str, run: &str, extra: Value) -> Change { let mut fields = obj(json!({ "id": id, "workspace_id": WORKSPACE, "run_id": run, "index_in_run": 1, "task_id": 1, "name": "build", "runs_on": "linux", "created_at": NOW, "updated_at": NOW, })); fields.extend(obj(extra)); Change::create("cotton_repo_jobs", id, fields) } impl Dev { fn act(&mut self, at_ms: i64, changes: Vec) -> Vec { self.try_act(at_ms, changes).expect("mints") } fn try_act(&mut self, at_ms: i64, changes: Vec) -> cotton_store::Result> { let act = Act { actor: self.actor.clone(), verb: "test".to_string(), history: History::None, changes, }; mint(&self.db, &act, &Clock::wall(at_ms), &mut self.ids, Held::Served).map(|minted| minted.ops) } fn retract(&mut self, at_ms: i64, table: &str, row_id: &str) -> Vec { self.act(at_ms, vec![Change::retract(table, row_id)]) } fn take(&self, ops: &[CottonOp]) -> FoldResult { arrive(&self.db, ops, Arrival::Handed).expect("folds") } /// Each op as a batch of its own, in the order given. fn take_each(&self, ops: &[&[CottonOp]]) { for batch in ops { let result = self.take(batch); assert!(result.rejected.is_empty(), "{result:?}"); } } fn present(&self, table: &str, row_id: &str) -> bool { self.db .get(&format!("SELECT 1 AS here FROM {table} WHERE id = ?"), &[SqlValue::Text(row_id.to_string())]) .expect("reads") .is_some() } /// The receipts this file holds for a row, by op id. fn receipt_ids(&self, table: &str, row_id: &str) -> Vec { self.db .all( "SELECT op_id FROM _writes WHERE tbl = ? AND row_id = ? ORDER BY hlc", &[SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())], ) .expect("reads") .iter() .filter_map(|row| row.text("op_id").map(str::to_string)) .collect() } /// Everything the family is, byte for byte: every receipt and tombstone of /// its tables, and every row in them. fn family(&self) -> Vec { let mut out = Vec::new(); for table in FAMILY { for row in self .db .all( "SELECT row_id, hlc, op_id, bytes FROM _writes WHERE tbl = ? ORDER BY row_id, hlc", &[SqlValue::Text((*table).to_string())], ) .expect("reads") { out.push(format!("w {table} {:?}", row.columns())); } for row in self .db .all( "SELECT row_id, hlc, op_id, bytes FROM _tombstones WHERE tbl = ? ORDER BY row_id", &[SqlValue::Text((*table).to_string())], ) .expect("reads") { out.push(format!("t {table} {:?}", row.columns())); } for row in self.db.all(&format!("SELECT * FROM {table} ORDER BY id"), &[]).expect("reads") { let columns: BTreeMap = row.columns().iter().cloned().collect(); out.push(format!("r {table} {columns:?}")); } } out } fn parked(&self, table: &str) -> Vec<(String, String)> { self.db .all( "SELECT row_id, reason FROM _parked WHERE tbl = ? ORDER BY op_id", &[SqlValue::Text(table.to_string())], ) .expect("reads") .iter() .map(|row| { ( row.text("row_id").unwrap_or_default().to_string(), row.text("reason").unwrap_or_default().to_string(), ) }) .collect() } /// Rebuild one table from its own live DDL, with `edit` applied to the /// CREATE statement — its indexes and triggers put back as they were. /// Only on an empty table, before anything is written to it. fn rebuild_table(&self, table: &str, edit: impl Fn(&str) -> String) { let create = self .db .get("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(table.to_string())]) .expect("reads") .and_then(|row| row.text("sql").map(str::to_string)) .expect("the table"); let rest: Vec = self .db .all( "SELECT sql FROM sqlite_master WHERE tbl_name = ? AND type IN ('index', 'trigger') AND sql IS NOT NULL", &[SqlValue::Text(table.to_string())], ) .expect("reads") .iter() .filter_map(|row| row.text("sql").map(str::to_string)) .collect(); let edited = edit(&create); assert_ne!(edited, create, "the edit changed nothing"); self.db.exec(&format!("DROP TABLE {table}")).expect("drops the empty table"); self.db.exec(&edited).expect("the edited table"); for statement in rest { self.db.exec(&statement).expect("its index or trigger"); } } } /// RULE: A parent's retract takes its owning children out of their tables on every device while keeping their receipts, and the parent's undo (a create of the same id) brings the same children back everywhere. #[test] fn child_of_retracted_parent_is_dormant_and_returns_on_undo_on_every_device() { let mut a = device("a"); let b = device("b"); let c = device("c"); meet(&[&a, &b, &c]); let born = a.act(T0, vec![repo(REPO), run(RUN, REPO, 1), job(JOB, RUN, json!({}))]); b.take(&born); let gone = a.retract(T0 + 10, "cotton_repos", REPO); b.take(&gone); for dev in [&a, &b] { assert!(!dev.present("cotton_repos", REPO)); assert!(!dev.present("cotton_repo_runs", RUN), "the child is out of its table"); assert!(!dev.present("cotton_repo_jobs", JOB), "and the grandchild"); assert_eq!(dev.receipt_ids("cotton_repo_runs", RUN), vec![born[1].op_id.clone()], "the child's receipt is kept"); assert_eq!(dev.receipt_ids("cotton_repo_jobs", JOB), vec![born[2].op_id.clone()]); } assert_eq!(a.family(), b.family()); // The undo: a create of the same id, minted now. It names no child. let undo = a.act(T0 + 20, vec![repo(REPO)]); assert_eq!(undo.len(), 1, "nothing is minted for a child"); b.take(&undo); // A third device hears it all, newest first. c.take_each(&[&undo, &gone, &born[2..], &born[1..2], &born[..1]]); for dev in [&a, &b, &c] { assert!(dev.present("cotton_repos", REPO)); assert!(dev.present("cotton_repo_runs", RUN), "the child returns with its parent"); assert!(dev.present("cotton_repo_jobs", JOB), "and the grandchild with it"); } assert_eq!(a.family(), b.family()); assert_eq!(a.family(), c.family()); } /// RULE: A child created while its parent is being retracted elsewhere ends byte-equal on every device whichever arrives first — dormant under the absent parent, never refused or parked. #[test] fn child_created_concurrently_with_its_parents_retract_ends_equal_everywhere() { let mut a = device("a"); let mut b = device("b"); let c = device("c"); let d = device("d"); meet(&[&a, &b, &c, &d]); let born = a.act(T0, vec![repo(REPO)]); b.take(&born); c.take(&born); d.take(&born); // a retracts the repository; b, not having heard, adds a run to it. let gone = a.retract(T0 + 10, "cotton_repos", REPO); let child = b.act(T0 + 20, vec![run(RUN, REPO, 1)]); let early = a.take(&child); assert_eq!(early.applied, vec![child[0].op_id.clone()], "dormant on arrival: stored and applied, {early:?}"); assert!(early.rejected.is_empty()); b.take(&gone); c.take_each(&[&gone, &child]); d.take_each(&[&child, &gone]); for dev in [&a, &b, &c, &d] { assert!(!dev.present("cotton_repo_runs", RUN), "no run under a repository that is not present"); assert_eq!(dev.receipt_ids("cotton_repo_runs", RUN), vec![child[0].op_id.clone()]); assert!(dev.parked("cotton_repo_runs").is_empty(), "dormant, not parked"); } assert_eq!(a.family(), b.family()); assert_eq!(a.family(), c.family()); assert_eq!(c.family(), d.family(), "either arrival order ends byte-equal"); // The repository's undo brings the run every device kept. let undo = a.act(T0 + 30, vec![repo(REPO)]); for dev in [&b, &c, &d] { dev.take(&undo); } for dev in [&a, &b, &c, &d] { assert!(dev.present("cotton_repo_runs", RUN)); } assert_eq!(a.family(), d.family()); } /// RULE: The fold takes owning children out itself before their parent's row: with the schema's CASCADE gone, a parent's retract still lands, every level down, and no child is left for a foreign key to catch. #[test] fn fold_removes_children_itself_and_a_missed_child_is_caught() { let mut a = device("a"); let b = device("b"); // The jobs' key to their run has no CASCADE — SQLite refuses to delete a // run that still has one, instead of quietly removing it. meet(&[&a, &b]); let born = a.act(T0, vec![repo(REPO), run(RUN, REPO, 1), job(JOB, RUN, json!({}))]); b.take(&born); // Directly at the run: its job goes first, or the DELETE fails. let gone = a.retract(T0 + 10, "cotton_repo_runs", RUN); assert!(!a.present("cotton_repo_runs", RUN)); assert!(!a.present("cotton_repo_jobs", JOB)); let result = b.take(&gone); assert_eq!(result.applied, vec![gone[0].op_id.clone()], "{result:?}"); assert!(result.board.is_empty(), "the walk took the child; nothing was missed: {:?}", result.board); assert!(!b.present("cotton_repo_jobs", JOB)); assert_eq!(b.receipt_ids("cotton_repo_jobs", JOB), vec![born[2].op_id.clone()], "dormant, not erased"); // Two levels up: the repository's retract walks to the grandchild too. let back = a.act(T0 + 20, vec![run(RUN, REPO, 1)]); b.take(&back); assert!(b.present("cotton_repo_jobs", JOB), "back with its run"); let repo_gone = a.retract(T0 + 30, "cotton_repos", REPO); let result = b.take(&repo_gone); assert!(result.rejected.is_empty() && result.board.is_empty(), "{result:?}"); for dev in [&a, &b] { assert!(!dev.present("cotton_repos", REPO)); assert!(!dev.present("cotton_repo_runs", RUN)); assert!(!dev.present("cotton_repo_jobs", JOB)); } assert_eq!(a.family(), b.family()); } /// RULE: A child the owning walk does not know, found when its parent's delete trips a foreign key, is made dormant (its receipts kept), the delete is retried, one board line names it, and the rest of the page applies. #[test] fn missed_child_is_made_dormant_and_sync_continues_with_a_board_line() { let mut a = device("a"); let b = device("b"); // A job's `summary` made into a key to a repository that no list of // owning references names — the shape of a reference the walk missed. let missed = |create: &str| { create.replace( "FOREIGN KEY (run_id)", "FOREIGN KEY (summary) REFERENCES cotton_repos(id),\n FOREIGN KEY (run_id)", ) }; a.rebuild_table("cotton_repo_jobs", missed); b.rebuild_table("cotton_repo_jobs", missed); meet(&[&a, &b]); let born = a.act( T0, vec![ repo(REPO), repo(OTHER_REPO), run(RUN, OTHER_REPO, 1), job(JOB, RUN, json!({"summary": REPO})), ], ); b.take(&born); let gone = a.retract(T0 + 10, "cotton_repos", REPO); let beside = a.act(T0 + 20, vec![repo("repo-3")]); let mut page = gone.clone(); page.extend(beside.iter().cloned()); let result = b.take(&page); assert!(result.rejected.is_empty(), "the missed child does not stall the page: {result:?}"); assert_eq!(result.applied, vec![gone[0].op_id.clone(), beside[0].op_id.clone()]); assert_eq!( result.board, vec!["The sync found a child it did not expect: cotton_repo_jobs.summary under cotton_repos".to_string()], "one board line" ); assert!(!b.present("cotton_repos", REPO)); assert!(!b.present("cotton_repo_jobs", JOB), "made dormant"); assert_eq!(b.receipt_ids("cotton_repo_jobs", JOB), vec![born[3].op_id.clone()], "not vanished: its receipt is kept"); assert!(b.present("cotton_repo_runs", RUN), "its owning parent is untouched"); assert!(b.present("cotton_repos", "repo-3")); } /// RULE: A UNIQUE clash while a returning parent re-assembles a child rolls back that child alone — dormant and parked conflict — and the parent's undo stands. #[test] fn reassembly_unique_clash_parks_the_child_not_the_parent() { let mut a = device("a"); let b = device("b"); meet(&[&a, &b]); let born = a.act( T0, vec![ repo(REPO), run(RUN, REPO, 1), run("run-2", REPO, 2), job(JOB, RUN, json!({"task_id": 7})), ], ); b.take(&born); let gone = a.retract(T0 + 10, "cotton_repo_runs", RUN); // While the job is dormant another one takes its task number, which is // unique across the file. let twin = a.act(T0 + 20, vec![job("job-2", "run-2", json!({"task_id": 7}))]); let undo = a.act(T0 + 30, vec![run(RUN, REPO, 1)]); let result = b.take_all(&[&gone, &twin, &undo]); assert!(result.iter().all(|r| r.rejected.is_empty()), "{result:?}"); for dev in [&a, &b] { assert!(dev.present("cotton_repo_runs", RUN), "the parent's undo holds"); assert!(dev.present("cotton_repo_jobs", "job-2")); assert!(!dev.present("cotton_repo_jobs", JOB), "the clashing child stays dormant"); assert_eq!(dev.receipt_ids("cotton_repo_jobs", JOB), vec![born[3].op_id.clone()]); assert_eq!( dev.parked("cotton_repo_jobs"), vec![(JOB.to_string(), "unique clash on re-assembly".to_string())], "parked conflict" ); } assert_eq!(a.family(), b.family()); } /// RULE: Undoing a parent's retract restores exactly the children each device kept, including a child's change that arrived while it was dormant, so every device ends with the same children. #[test] fn undo_of_a_parent_retract_restores_the_same_children_on_every_device() { let mut a = device("a"); let mut b = device("b"); let c = device("c"); meet(&[&a, &b, &c]); let born = a.act( T0, vec![ repo(REPO), run(RUN, REPO, 1), run("run-2", REPO, 2), job(JOB, RUN, json!({})), ], ); b.take(&born); let gone = a.retract(T0 + 10, "cotton_repos", REPO); // b renames a run before it hears of the retract. let rename = b.act(T0 + 15, vec![Change::update("cotton_repo_runs", "run-2", obj(json!({"workflow_name": "Renamed"})))]); b.take(&gone); a.take(&rename); let undo = a.act(T0 + 20, vec![repo(REPO)]); b.take(&undo); c.take_each(&[&rename, &undo, &born[3..], &gone, &born[..3]]); for dev in [&a, &b, &c] { for (table, id) in [("cotton_repo_runs", RUN), ("cotton_repo_runs", "run-2"), ("cotton_repo_jobs", JOB)] { assert!(dev.present(table, id), "{table} {id} is back"); } let name = dev .db .get("SELECT workflow_name FROM cotton_repo_runs WHERE id = 'run-2'", &[]) .expect("reads") .and_then(|row| row.text("workflow_name").map(str::to_string)); assert_eq!(name.as_deref(), Some("Renamed"), "the change kept while dormant shows"); } assert_eq!(a.family(), b.family()); assert_eq!(a.family(), c.family()); } /// RULE: A create minted under an owning parent that is not present is refused at mint, while a create of the parent and its child in one act is not. #[test] fn create_under_a_parent_that_is_not_present_is_refused_at_mint() { let mut a = device("a"); assert!(a.try_act(T0, vec![run(RUN, "no-such-repo", 1)]).is_err(), "no parent at all"); a.act(T0 + 10, vec![repo(REPO), run(RUN, REPO, 1)]); a.retract(T0 + 20, "cotton_repos", REPO); assert!( a.try_act(T0 + 30, vec![job(JOB, RUN, json!({}))]).is_err(), "a parent whose own parent was retracted is not present either" ); assert!(a.receipt_ids("cotton_repo_jobs", JOB).is_empty(), "a refused mint leaves nothing"); // Retracting the parent and writing its child in the same act is not a // write under an absent parent: the child goes with it. a.act(T0 + 40, vec![repo(REPO)]); a.act(T0 + 50, vec![job(JOB, RUN, json!({})), Change::retract("cotton_repo_runs", RUN)]); assert!(!a.present("cotton_repo_jobs", JOB)); } impl Dev { fn take_all(&self, batches: &[&[CottonOp]]) -> Vec { batches.iter().map(|batch| self.take(batch)).collect() } }