//! Groundwork slice 7, the store half: media leaves when its last record //! goes. A row of a holder table names its keys in `_media_key_names`, kept //! for present and dormant rows alike and cleared only by an erase; an Erase //! writes one erasure fact per key; a key is dead when an erasure names it and //! no row does; a dead key under this file's prefix enters the device's //! unlink queue, and a re-reference takes it out. //! //! Every row is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]). 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::media_erasure::{ erasure_id, is_dead, is_family_dead, is_family_named, mark_unlinked, may_unlink_now, pending_unlinks, MayUnlink, Unlinked, }; use cotton_store::media_keys::{rebuild_names, rows_naming}; 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::hlc::next_hlc; use cotton_store::protocol::types::CottonOp; use cotton_store::schema::ddl::SCHEMA_VERSION; use cotton_store::wire::op_of_change; 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 PHOTOS: &str = "cotton_photos"; const THREADS: &str = "cotton_msg_threads"; const MESSAGES: &str = "cotton_msg_messages"; const THREAD: &str = "00000000-0000-4000-8000-0000000f0001"; const MESSAGE: &str = "00000000-0000-4000-8000-0000000f0002"; const OTHER_MESSAGE: &str = "00000000-0000-4000-8000-0000000f0003"; 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!("{}-{:05}", self.1, self.0)) } } struct Dev { db: Driver, ids: Ids, fact: CottonOp, } 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, fact: author.fact } } /// Two devices that have heard each other's author. fn pair() -> (Dev, Dev) { let a = device("a"); let b = device("b"); a.take(std::slice::from_ref(&b.fact)); b.take(std::slice::from_ref(&a.fact)); (a, b) } fn obj(value: Value) -> Map { value.as_object().expect("an object").clone() } /// A key under this database's own prefix. fn key(name: &str) -> String { format!("{WORKSPACE}/photos/{name}.jpg") } /// A 64-hex content hash, distinct per `n`. fn sha(n: u8) -> String { format!("{n:064x}") } fn photo_id(n: u8) -> String { format!("photo:{}", sha(n)) } fn photo(n: u8, key: &str) -> Change { let id = photo_id(n); let sha = sha(n); Change::create( PHOTOS, &id, obj(json!({"id": id, "workspace_id": WORKSPACE, "key": key, "sha256": sha, "content_type": "image/jpeg", "size_bytes": 10, "taken_at": NOW, "created_at": NOW, "updated_at": NOW})), ) } fn thread() -> Change { Change::create( THREADS, THREAD, obj(json!({"id": THREAD, "workspace_id": WORKSPACE, "kind": "group", "title": "Synthetic group", "created_at": NOW, "updated_at": NOW})), ) } fn message(id: &str, keys: &[&str]) -> Change { let media: Vec = keys.iter().map(|k| json!({"key": k, "content_type": "image/jpeg"})).collect(); Change::create( MESSAGES, id, obj(json!({"id": id, "thread_id": THREAD, "workspace_id": WORKSPACE, "direction": "in", "channel": "cotton", "origin": "live", "media": media, "sent_at": NOW, "created_at": NOW})), ) } impl Dev { fn act(&mut self, at_ms: i64, changes: Vec) -> Vec { let act = Act { actor: Actor::device_job(JobName::named("test").expect("a job name")), verb: "test".to_string(), history: History::Kept, changes, }; mint(&self.db, &act, &Clock::wall(at_ms), &mut self.ids, Held::Served) .map(|minted| minted.ops) .expect("mints") } /// `change` as this device's author would push it with none of `mint`'s /// own rules asked — the serving Mac's answer for a row a file held before /// a rule existed. fn past_mint(&self, at_ms: i64, change: &Change) -> Vec { let author = self.fact.row_id.clone(); let hlc = next_hlc(&author, None, at_ms).expect("a stamp"); let actor = Actor::device_job(JobName::named("test").expect("a job name")); let op_id = format!("op-held-{}-{}", change.table, change.row_id); vec![op_of_change(&self.db, change, &hlc, &author, &actor, op_id).expect("a receipt")] } fn take(&self, ops: &[CottonOp]) -> FoldResult { arrive(&self.db, ops, Arrival::Pulled).expect("folds") } fn count(&self, sql: &str, params: &[&str]) -> i64 { let params: Vec = params.iter().map(|p| SqlValue::Text((*p).to_string())).collect(); self.db.get(sql, ¶ms).expect("reads").and_then(|row| row.int("n")).unwrap_or(-1) } fn present(&self, table: &str, id: &str) -> bool { self.count(&format!("SELECT COUNT(*) AS n FROM {table} WHERE id = ?"), &[id]) > 0 } fn erasures(&self, key: &str) -> i64 { self.count("SELECT COUNT(*) AS n FROM cotton_media_erasures WHERE key = ?", &[key]) } fn queued(&self) -> Vec { pending_unlinks(&self.db).expect("reads").into_iter().map(|p| p.key).collect() } fn dead(&self, key: &str) -> bool { is_dead(&self.db, key).expect("reads") } /// Whether `table`'s `row_id` names `key` in `_media_key_names`. fn names(&self, key: &str, table: &str, row_id: &str) -> bool { self.count( "SELECT COUNT(*) AS n FROM _media_key_names WHERE key = ? AND tbl = ? AND row_id = ?", &[key, table, row_id], ) > 0 } } /// RULE: A row of a holder table names its keys in _media_key_names on the device that wrote it and on a peer that folded it, a retract keeps the names, and only an erase clears them. #[test] fn a_holder_row_names_its_keys_until_it_is_erased() { let (mut a, b) = pair(); let k = key("a1"); let id = photo_id(1); let made = a.act(T0, vec![photo(1, &k)]); b.take(&made); for dev in [&a, &b] { assert!(dev.names(&k, PHOTOS, &id), "the photo does not name its key"); } let retract = a.act(T0 + 1_000, vec![Change::retract(PHOTOS, &id)]); b.take(&retract); for dev in [&a, &b] { assert!(!dev.present(PHOTOS, &id)); assert!(dev.names(&k, PHOTOS, &id), "a retract dropped the photo's name of its key"); } let erase = a.act(T0 + 2_000, vec![Change::erase(PHOTOS, &id, "bin")]); b.take(&erase); for dev in [&a, &b] { assert!(!dev.names(&k, PHOTOS, &id), "the erased photo still names its key"); } } /// RULE: A dormant row still names its keys: a message whose thread is retracted keeps naming each key in its media, on the writer and on a peer. #[test] fn a_dormant_row_still_names_its_key() { let (mut a, b) = pair(); let (k1, k2) = (key("m1"), key("m2")); let mut ops = a.act(T0, vec![thread()]); ops.extend(a.act(T0 + 1_000, vec![message(MESSAGE, &[&k1, &k2])])); ops.extend(a.act(T0 + 2_000, vec![Change::retract(THREADS, THREAD)])); b.take(&ops); for dev in [&a, &b] { assert!(!dev.present(MESSAGES, MESSAGE), "the premise: the message is dormant"); assert!(dev.names(&k1, MESSAGES, MESSAGE) && dev.names(&k2, MESSAGES, MESSAGE), "a dormant row lost its names"); } } /// RULE: Erasing the last record that names a key writes one erasure fact for it, in the erase's own act and under its author, and the key is dead on the eraser and on a peer that folds the act. #[test] fn last_record_erase_makes_its_key_dead() { let (mut a, b) = pair(); let k = key("d1"); let id = photo_id(1); b.take(&a.act(T0, vec![photo(1, &k)])); assert!(!a.dead(&k), "a named key with no erasure is alive"); let erase = a.act(T0 + 1_000, vec![Change::erase(PHOTOS, &id, "bin")]); assert_eq!(erase.len(), 2, "one erase and one erasure fact: {erase:?}"); assert_eq!(erase[1].table, "cotton_media_erasures"); assert_eq!(erase[1].row_id, erasure_id(&k, PHOTOS, &id)); assert_eq!(erase[1].hlc.rsplit(':').next(), erase[0].hlc.rsplit(':').next(), "the fact is not the eraser's author's"); b.take(&erase); for dev in [&a, &b] { assert_eq!(dev.erasures(&k), 1); assert!(dev.dead(&k), "the erased key is not dead"); assert_eq!(dev.queued(), vec![k.clone()], "the dead key is not queued to unlink"); } assert_eq!(mark_unlinked(&a.db, &k, NOW).expect("marks"), Unlinked::Done); assert!(a.queued().is_empty(), "a done key is still pending"); } /// RULE: An erasure of a key that a second record still names leaves it alive, and a key named again by a new record after its erasure is alive again while the erasure fact stays. #[test] fn key_named_by_a_live_row_survives_an_erasure() { let (mut a, _) = pair(); let k = key("s1"); a.act(T0, vec![photo(1, &k), thread()]); a.act(T0 + 1_000, vec![message(MESSAGE, &[&k])]); a.act(T0 + 2_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin")]); assert_eq!(a.erasures(&k), 1); assert!(!a.dead(&k), "a key a live message names died with the photo"); assert!(a.queued().is_empty(), "a key a live row names was queued"); let k2 = key("s2"); a.act(T0 + 3_000, vec![photo(2, &k2)]); a.act(T0 + 4_000, vec![Change::erase(PHOTOS, &photo_id(2), "bin")]); assert!(a.dead(&k2)); a.act(T0 + 5_000, vec![message(OTHER_MESSAGE, &[&k2])]); assert_eq!(a.erasures(&k2), 1, "the erasure fact is kept"); assert!(!a.dead(&k2), "a key named again is not alive again"); } /// RULE: A retract alone writes no erasure fact and leaves its key alive, and an erase of a record that names no media writes no erasure fact. #[test] fn a_retract_writes_no_erasure_and_an_erase_without_media_writes_none() { let (mut a, _) = pair(); let k = key("r1"); a.act(T0, vec![photo(1, &k), thread()]); let retract = a.act(T0 + 1_000, vec![Change::retract(PHOTOS, &photo_id(1))]); assert_eq!(retract.len(), 1); assert_eq!(a.erasures(&k), 0); assert!(!a.dead(&k)); assert!(a.queued().is_empty(), "a retract queued its key"); let erase = a.act(T0 + 2_000, vec![Change::erase(THREADS, THREAD, "bin")]); assert_eq!(erase.len(), 1, "an erase of a record with no media wrote a fact: {erase:?}"); assert_eq!(a.count("SELECT COUNT(*) AS n FROM cotton_media_erasures", &[]), 0); } /// RULE: Erasing a parent writes an erasure fact for every key of its owned descendants, a dormant one included, each fact naming the descendant that named the key. #[test] fn erase_of_a_parent_writes_erasures_for_dormant_descendants() { let (mut a, b) = pair(); let (k1, k2, k3) = (key("p1"), key("p2"), key("p3")); let mut ops = a.act(T0, vec![thread()]); ops.extend(a.act(T0 + 1_000, vec![message(MESSAGE, &[&k1, &k2]), message(OTHER_MESSAGE, &[&k3])])); ops.extend(a.act(T0 + 2_000, vec![Change::retract(THREADS, THREAD)])); b.take(&ops); assert!(!a.present(MESSAGES, MESSAGE), "the premise: the messages are dormant"); let erase = a.act(T0 + 3_000, vec![Change::erase(THREADS, THREAD, "bin")]); assert_eq!(erase.len(), 4, "one erase and three facts: {erase:?}"); b.take(&erase); for dev in [&a, &b] { for (k, msg) in [(&k1, MESSAGE), (&k2, MESSAGE), (&k3, OTHER_MESSAGE)] { assert_eq!( dev.count("SELECT COUNT(*) AS n FROM cotton_media_erasures WHERE id = ? AND record_table = ? AND record_id = ?", &[&erasure_id(k, MESSAGES, msg), MESSAGES, msg]), 1, "no erasure of {k} by {msg}" ); assert!(dev.dead(k), "{k} of a dormant descendant is not dead"); } assert_eq!(dev.queued().len(), 3, "the dormant descendants' keys are not all queued"); } } /// RULE: A key named again between its queueing and its unlink leaves the queue, and mark_unlinked refuses it as alive again. #[test] fn a_re_reference_before_the_unlink_wins() { let (mut a, b) = pair(); let k = key("q1"); b.take(&a.act(T0, vec![photo(1, &k), thread()])); b.take(&a.act(T0 + 1_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin")])); assert_eq!(b.queued(), vec![k.clone()]); // The peer hears of a new message naming the same bytes. b.take(&a.act(T0 + 2_000, vec![message(MESSAGE, &[&k])])); assert!(b.queued().is_empty(), "the re-referenced key is still queued"); assert_eq!(mark_unlinked(&b.db, &k, NOW).expect("asks"), Unlinked::AliveAgain); assert!(!b.dead(&k)); } /// RULE: A peer queues a dead key whichever it folds first, the erase or its erasure fact, and folding the same erasure again changes nothing — a done key stays done. #[test] fn a_folded_erasure_queues_on_a_peer_in_either_order_and_replay_is_a_no_op() { let (mut a, b) = pair(); let k = key("f1"); b.take(&a.act(T0, vec![photo(1, &k)])); let erase = a.act(T0 + 1_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin")]); b.take(&erase[1..]); assert!(b.queued().is_empty(), "the photo still names the key before its erase folds"); b.take(&erase[..1]); assert_eq!(b.queued(), vec![k.clone()], "the erase folded after its fact left the key unqueued"); assert_eq!(mark_unlinked(&b.db, &k, NOW).expect("marks"), Unlinked::Done); let replay = b.take(&erase); assert!(replay.applied.is_empty(), "{replay:?}"); assert!(b.queued().is_empty(), "a replayed erasure queued a done key again"); assert_eq!(b.erasures(&k), 1); } /// RULE: A dead key outside this database's own prefix never enters the unlink queue, though its erasure fact is written. #[test] fn a_key_outside_this_databases_prefix_is_never_queued() { let (mut a, b) = pair(); let foreign = "22222222-2222-4222-8222-222222222222/photos/x.jpg"; // Mint refuses such a row now; one a file already held arrives past it. let held = a.past_mint(T0, &photo(1, foreign)); a.take(&held); b.take(&held); b.take(&a.act(T0 + 1_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin")])); for dev in [&a, &b] { assert_eq!(dev.erasures(foreign), 1); assert!(dev.dead(foreign)); assert!(dev.queued().is_empty(), "another database's key was queued"); } } /// RULE: A key named only by a dormant row survives an erasure of another record naming it: not dead, never queued. #[test] fn key_named_only_by_a_dormant_row_survives_an_erasure() { let (mut a, _) = pair(); let k = key("o1"); a.act(T0, vec![photo(1, &k), thread()]); a.act(T0 + 1_000, vec![message(MESSAGE, &[&k])]); a.act(T0 + 2_000, vec![Change::retract(THREADS, THREAD)]); a.act(T0 + 3_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin")]); assert_eq!(a.erasures(&k), 1); assert!(!a.dead(&k), "a key a dormant message names died"); assert!(a.queued().is_empty()); } /// RULE: A family's renditions stay alive while any row names a key of the family, and are dead once an erasure names one of its keys and no row names any. #[test] fn a_family_is_dead_only_when_no_key_of_it_is_named() { let (mut a, _) = pair(); let family = format!("{WORKSPACE}/photos/fam."); let (heic, jpg) = (format!("{family}heic"), format!("{family}jpg")); a.act(T0, vec![photo(1, &heic), photo(2, &jpg)]); assert!(is_family_named(&a.db, &family).expect("reads")); assert!(!is_family_dead(&a.db, &family).expect("reads"), "a family with no erasure is dead"); a.act(T0 + 1_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin")]); assert!(a.dead(&heic)); assert!(!is_family_dead(&a.db, &family).expect("reads"), "a sibling key's renditions died with the other key"); a.act(T0 + 2_000, vec![Change::erase(PHOTOS, &photo_id(2), "bin")]); assert!(!is_family_named(&a.db, &family).expect("reads")); assert!(is_family_dead(&a.db, &family).expect("reads"), "a family with every key erased is alive"); let other = format!("{WORKSPACE}/photos/famx."); assert!(!is_family_dead(&a.db, &other).expect("reads"), "a family is read as a prefix of another stem"); } impl Dev { /// Every name `_media_key_names` holds, sorted. fn all_names(&self) -> Vec<(String, String, String)> { self.db .all("SELECT key, tbl, row_id FROM _media_key_names ORDER BY key, tbl, row_id", &[]) .expect("reads") .iter() .map(|row| { let text = |name: &str| row.text(name).expect("a column").to_string(); (text("key"), text("tbl"), text("row_id")) }) .collect() } fn exec(&self, sql: &str) { self.db.exec(sql).expect("runs"); } } /// RULE: rebuild_names over a file built through receipts writes exactly the names the row_taken hook wrote: present rows, a changed key's earlier value, dormant rows, never an erased one. #[test] fn rebuilt_names_are_the_names_the_hook_wrote() { let (mut a, b) = pair(); let (k1, k2, k3, k4, k5) = (key("b1"), key("b2"), key("b3"), key("b4"), key("b5")); let mut ops = a.act(T0, vec![photo(1, &k1), photo(2, &k2), photo(3, &k5), thread()]); ops.extend(a.act(T0 + 1_000, vec![message(MESSAGE, &[&k3, &k1]), message(OTHER_MESSAGE, &[&k4])])); // A changed key: the hook keeps both values. let mut change = Map::new(); change.insert("key".to_string(), json!(k4)); ops.extend(a.act(T0 + 2_000, vec![Change::update(PHOTOS, &photo_id(2), change)])); // A dormant message under a retracted thread, an erased photo. ops.extend(a.act(T0 + 3_000, vec![Change::retract(THREADS, THREAD)])); ops.extend(a.act(T0 + 4_000, vec![Change::erase(PHOTOS, &photo_id(3), "bin")])); b.take(&ops); for dev in [&a, &b] { let hooked = dev.all_names(); assert!(hooked.iter().any(|(k, _, _)| *k == k2), "the premise: the earlier value is named"); assert!(!hooked.iter().any(|(k, _, _)| *k == k5), "the premise: the erased photo names nothing"); assert_eq!(rebuild_names(&dev.db).expect("rebuilds"), 0, "a rebuild over the hook's names added some"); dev.exec("DELETE FROM _media_key_names"); assert!(rebuild_names(&dev.db).expect("rebuilds") > 0); assert_eq!(dev.all_names(), hooked, "the rebuilt names are not the hook's"); } } /// RULE: With _media_key_names empty, a key a present row names is not dead: an erasure only writes it down as a candidate, and may_unlink_now — asked before any bytes go — refuses it, writes the name back and empties its queue entry. #[test] fn a_key_the_index_missed_is_never_called_dead() { let (mut a, _) = pair(); let k = key("x1"); a.act(T0, vec![photo(1, &k), thread()]); a.act(T0 + 1_000, vec![message(MESSAGE, &[&k])]); a.exec("DELETE FROM _media_key_names"); assert_eq!(rows_naming(&a.db, &k).expect("reads").len(), 2, "the direct reader missed a holder"); a.act(T0 + 2_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin")]); assert_eq!(a.erasures(&k), 1); assert!(!a.dead(&k), "a key a present message names was called dead"); // A CANDIDATE, by the index alone — the fold reads no rows — and nothing // more: the last question before bytes go is the one that reads them. assert_eq!(a.queued(), vec![k.clone()]); assert_eq!( may_unlink_now(&a.db, &k).expect("asks"), MayUnlink::Repaired(vec![(k.clone(), MESSAGES.to_string(), MESSAGE.to_string())]) ); assert!(a.names(&k, MESSAGES, MESSAGE), "the guard did not write the name back"); assert!(a.queued().is_empty(), "the guard left the key queued"); assert_eq!(may_unlink_now(&a.db, &k).expect("asks"), MayUnlink::Named); a.exec(&format!("INSERT INTO _media_unlinks (key, queued_at) VALUES ('{k}', '{NOW}')")); a.exec("DELETE FROM _media_key_names"); assert_eq!(mark_unlinked(&a.db, &k, NOW).expect("marks"), Unlinked::AliveAgain, "the mark trusted the index alone"); } /// 10 Oct 2026: one write that erased a few hundred keys held the owner's /// store lock for more than ten minutes — every erasure fact it folded asked /// `is_dead`, whose second read scans every holder table and every receipt of /// one with `instr()`, and that read runs exactly when a key IS dead. /// RULE: Taking erasure facts — minted here or folded from a peer — reads no rows to decide what is dead: a bounded number of point reads of the media index per fact, never a scan of a holder table or of the receipts, whose one place is may_unlink_now. #[test] fn taking_erasure_facts_never_scans_the_media_rows() { let (mut a, b) = pair(); let n: u8 = 40; let mut made = Vec::new(); for i in 1..=n { made.extend(a.act(T0 + i64::from(i), vec![photo(i, &key(&format!("p{i}")))])); } b.take(&made); let asked = |seen: &[String], whose: &str| { let scans: Vec<&String> = seen.iter().filter(|sql| reads_the_rows(sql)).collect(); assert!(scans.is_empty(), "{whose} scanned the rows {} time(s): {}", scans.len(), scans[0]); // The dead-key question itself: the erasures by key, the index by key. let point_reads = seen .iter() .filter(|sql| { sql.contains("FROM cotton_media_erasures WHERE key = ?") || sql.contains("FROM _media_key_names WHERE key = ?") }) .count(); assert!(point_reads > 0, "{whose} never asked the index: the premise of this guard"); assert!( point_reads <= 4 * usize::from(n), "{whose} asked the dead-key question {point_reads} times for {n} erased keys" ); }; // THE WRITER'S OWN FOLD — the path that hung: one act, every photo erased. a.db.watch_statements(); let erased = a.act(T0 + 10_000, (1..=n).map(|i| Change::erase(PHOTOS, &photo_id(i), "bin")).collect()); asked(&a.db.statements_seen(), "the writer"); assert_eq!(a.queued().len(), usize::from(n), "every erased key is a candidate"); // AND A PEER'S, folding the same act as it arrives. b.db.watch_statements(); b.take(&erased); asked(&b.db.statements_seen(), "the peer"); assert_eq!(b.queued().len(), usize::from(n)); // The rows ARE read — once per key, where bytes go. b.db.watch_statements(); assert_eq!(may_unlink_now(&b.db, &key("p1")).expect("asks"), MayUnlink::Yes); assert!(b.db.statements_seen().iter().any(|sql| reads_the_rows(sql)), "the last question read no rows"); } /// RULE: A pass's one read of the rows answers "no row names this key" for every queued key without another read, and its "a row names it" is never acted on as read: the rows are asked again, so a row erased since the read neither keeps the bytes nor writes a name back. #[test] fn one_read_of_the_rows_serves_a_whole_pass_and_a_stale_name_is_asked_again() { use cotton_store::media_erasure::{is_family_named_read, mark_unlinked_read, may_unlink_read}; use cotton_store::media_keys::RowsRead; let (mut a, _) = pair(); let (gone, kept) = (key("r1"), key("r2")); a.act(T0, vec![photo(1, &gone), photo(2, &kept)]); // READ WHILE BOTH ROWS STAND — the pass's read, a moment old by the time // it is used. let early = RowsRead::read(&a.db).expect("reads"); assert!(early.names(&gone) && early.names(&kept)); assert!(early.names_family(&format!("{WORKSPACE}/photos/r1."))); assert!(!early.names_family(&format!("{WORKSPACE}/photos/r.")), "a family is not a prefix of another stem"); a.act(T0 + 1_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin")]); assert_eq!(a.queued(), vec![gone.clone()]); // The early read still says a row names it. Asked again, none does: the // key may go, and no name was written back for the erased row. a.db.watch_statements(); assert_eq!(may_unlink_read(&a.db, &gone, Some(&early)).expect("asks"), MayUnlink::Yes); assert!(a.db.statements_seen().iter().any(|sql| reads_the_rows(sql)), "a stale name was believed"); assert!(!a.names(&gone, PHOTOS, &photo_id(1))); // A read made after the erase says nobody names it, and that is taken // with the index alone — for the guard, the family and the mark. let late = RowsRead::read(&a.db).expect("reads"); assert!(!late.names(&gone) && late.names(&kept)); a.db.watch_statements(); assert_eq!(may_unlink_read(&a.db, &gone, Some(&late)).expect("asks"), MayUnlink::Yes); assert!(!is_family_named_read(&a.db, &format!("{WORKSPACE}/photos/r1."), Some(&late)).expect("reads")); assert_eq!(mark_unlinked_read(&a.db, &gone, NOW, Some(&late)).expect("marks"), Unlinked::Done); let scans = a.db.statements_seen().into_iter().filter(|sql| reads_the_rows(sql)).count(); assert_eq!(scans, 0, "the rows were read again for a key the pass's read does not name"); // And a key a row names is still refused, whatever the read said. a.exec(&format!("INSERT INTO _media_unlinks (key, queued_at) VALUES ('{kept}', '{NOW}')")); assert_eq!(may_unlink_read(&a.db, &kept, Some(&late)).expect("asks"), MayUnlink::Named); } /// A hold's tally (`cotton_store::held`) names a write by its verb and actor /// and a sync batch by its direction, and counts every fact either folds — /// what the slow-hold line reads. #[test] fn a_write_and_a_sync_batch_name_themselves_to_whoever_holds_the_file() { let (mut a, b) = pair(); let tally = cotton_store::held::tally(); let made = a.act(T0, vec![photo(1, &key("t1")), thread()]); let work = tally.done(); assert_eq!(work.doing, vec!["a write (test by device-job:test)".to_string()]); assert_eq!((work.facts, work.folds), (made.len(), 1)); let tally = cotton_store::held::tally(); b.take(&made); let work = tally.done(); assert_eq!(work.doing, vec!["a pulled batch".to_string()]); assert_eq!((work.facts, work.folds), (made.len(), 1)); } /// A statement of the direct reader (`media_keys::read_names`): its read of a /// holder table's key columns, or of every receipt of one. fn reads_the_rows(sql: &str) -> bool { sql.contains("AS row_id") || sql.starts_with("SELECT row_id, hlc, bytes FROM _writes WHERE tbl = ?1") } /// RULE: A key named only by a dormant row's receipts, with _media_key_names empty, is still not dead, and a family whose sibling key only a present row names keeps its renditions. #[test] fn the_direct_reader_sees_dormant_rows_and_families() { let (mut a, _) = pair(); let k = key("y1"); a.act(T0, vec![photo(1, &k), thread()]); a.act(T0 + 1_000, vec![message(MESSAGE, &[&k])]); a.act(T0 + 2_000, vec![Change::retract(THREADS, THREAD)]); let family = format!("{WORKSPACE}/photos/famy."); a.act(T0 + 3_000, vec![photo(2, &format!("{family}heic")), photo(3, &format!("{family}jpg"))]); a.act(T0 + 4_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin"), Change::erase(PHOTOS, &photo_id(2), "bin")]); a.exec("DELETE FROM _media_key_names"); assert!(!a.dead(&k), "a key a dormant message names was called dead"); assert!(is_family_named(&a.db, &family).expect("reads"), "a sibling key's present row was missed"); assert!(!is_family_dead(&a.db, &family).expect("reads")); } /// RULE: may_unlink_now answers Yes only for a queued key an erasure names and no row names, by the index and by the rows. #[test] fn may_unlink_now_lets_a_dead_key_go() { let (mut a, _) = pair(); let k = key("z1"); a.act(T0, vec![photo(1, &k)]); assert_eq!(may_unlink_now(&a.db, &k).expect("asks"), MayUnlink::Named); a.act(T0 + 1_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin")]); assert_eq!(a.queued(), vec![k.clone()]); assert_eq!(may_unlink_now(&a.db, &k).expect("asks"), MayUnlink::Yes); assert_eq!(may_unlink_now(&a.db, &key("never")).expect("asks"), MayUnlink::NotDead); } /// RULE: rebuild_names only adds: over an intact index a retracted row keeps the names the hook gave it, though the fold dropped the receipts a rebuild could read them from. #[test] fn a_rebuild_never_takes_a_name() { let (mut a, _) = pair(); let k = key("c1"); a.act(T0, vec![photo(1, &k)]); a.act(T0 + 1_000, vec![Change::retract(PHOTOS, &photo_id(1))]); assert!(a.names(&k, PHOTOS, &photo_id(1)), "the premise: a retract keeps the name"); assert_eq!(rebuild_names(&a.db).expect("rebuilds"), 0); assert!(a.names(&k, PHOTOS, &photo_id(1)), "a rebuild took a retracted row's name"); } const MEETINGS: &str = "cotton_meetings"; const MEETING: &str = "00000000-0000-4000-8000-0000000f0010"; /// Every container a meeting's recording may be filed under — `full.` /// is built from the id for each. const CONTAINERS: &[&str] = &["m4a", "mp4", "aac", "mp3", "wav", "opus", "ogg", "oga", "flac", "amr", "caf"]; /// A meeting whose manifest has one segment with no stored path, one stored /// path and one lost segment. fn meeting() -> (Change, Vec, String) { let stored = format!("{WORKSPACE}/meetings/{MEETING}/imported/take.m4a"); let lost = format!("{WORKSPACE}/meetings/{MEETING}/segments/003.m4a"); let segments = json!([{"seq": 1}, {"seq": 2, "path": stored}, {"seq": 3, "path": lost, "lost": true}]); let change = Change::create( MEETINGS, MEETING, obj(json!({"id": MEETING, "workspace_id": WORKSPACE, "status": "ready", "source": "recorded", "started_at": NOW, "status_changed_at": NOW, "segments": segments, "created_at": NOW, "updated_at": NOW})), ); let mut keys: Vec = CONTAINERS.iter().map(|ext| format!("{WORKSPACE}/meetings/{MEETING}/full.{ext}")).collect(); keys.push(format!("{WORKSPACE}/meetings/{MEETING}/segments/001.m4a")); keys.push(stored); (change, keys, lost) } /// RULE: A meeting names the keys built from its id (full. in every container, a pathless segment's) and its manifest's stored paths, a lost segment's none, and its Erase writes an erasure fact for each and queues each on the eraser and a peer. #[test] fn a_meetings_id_built_keys_are_named_and_leave_with_its_erase() { let (mut a, b) = pair(); let (create, keys, lost) = meeting(); b.take(&a.act(T0, vec![create])); for dev in [&a, &b] { for k in &keys { assert!(dev.names(k, MEETINGS, MEETING), "the meeting does not name {k}"); } assert!(!dev.names(&lost, MEETINGS, MEETING), "a lost segment is named"); } let erase = a.act(T0 + 1_000, vec![Change::erase(MEETINGS, MEETING, "delete_meeting")]); b.take(&erase); for dev in [&a, &b] { for k in &keys { assert_eq!(dev.erasures(k), 1, "{k} has no erasure fact"); assert!(dev.dead(k), "{k} is not dead"); } let mut queued = dev.queued(); queued.sort(); let mut want = keys.clone(); want.sort(); assert_eq!(queued, want); } } /// RULE: Setting a meeting's audio_deleted_at releases its keys while the row stays: one erasure fact per key in the same act, each dead and queued on the writer and a peer, and a later change to the row names none of them again. #[test] fn releasing_a_meetings_audio_erases_its_keys_while_the_row_stays() { let (mut a, b) = pair(); let (create, keys, _) = meeting(); b.take(&a.act(T0, vec![create])); let release = a.act( T0 + 1_000, vec![Change::update(MEETINGS, MEETING, obj(json!({"audio_deleted_at": NOW, "updated_at": NOW})))], ); assert_eq!(release.len(), 2 + keys.len(), "one change, its history row and an erasure fact per key: {release:?}"); b.take(&release); let later = a.act(T0 + 2_000, vec![Change::update(MEETINGS, MEETING, obj(json!({"title": "Synthetic standup"})))]); b.take(&later); for dev in [&a, &b] { assert!(dev.present(MEETINGS, MEETING), "the release took the row"); for k in &keys { assert_eq!(dev.erasures(k), 1, "{k} has no erasure fact"); assert!(!dev.names(k, MEETINGS, MEETING), "a released meeting still names {k}"); assert!(dev.dead(k), "{k} is not dead"); } assert_eq!(dev.queued().len(), keys.len(), "the released keys are not all queued"); } // Releasing again writes nothing more. let again = a.act(T0 + 3_000, vec![Change::update(MEETINGS, MEETING, obj(json!({"audio_deleted_at": NOW})))]); assert_eq!(again.len(), 1, "a second release wrote erasure facts: {again:?}"); } /// What an erase asks of the file per erased row when it asks badly: what the /// rows own, by a read of a child table's receipts; a row's media-key names, /// by row (the index is keyed by the key); the tombstones, by op id alone. struct ErasesAsked { owners: usize, names_by_row: usize, tombstones_by_op: usize, steps: u64, } fn erases_asked(db: &Driver, steps: u64) -> ErasesAsked { let seen = db.statements_seen(); let count = |pick: &dyn Fn(&str) -> bool| seen.iter().filter(|sql| pick(sql)).count(); ErasesAsked { owners: count(&|sql| sql.contains("FROM _writes_owners o JOIN _writes w")), names_by_row: count(&|sql| sql.contains("_media_key_names WHERE tbl = ? AND row_id = ?")), tombstones_by_op: count(&|sql| sql.contains("_tombstones") && sql.contains("op_id = ?") && !sql.contains("row_id = ?")), steps, } } /// RULE: An act erasing many rows asks what they own once per ownership rule and their media-key names once — as many reads for forty rows as for four — and no op asks the tombstones except by its own row, minted here or folded from a peer. /// 11 Oct 2026: a prune of two thousand runs read every receipt of every child table once per erased row, inside the owner's file, for more than ten minutes. #[test] fn an_erase_asks_what_its_rows_own_once_however_many_rows_it_erases() { let (mut a, b) = pair(); let mut made = Vec::new(); for i in 1..=44u8 { made.extend(a.act(T0 + i64::from(i), vec![photo(i, &key(&format!("p{i}")))])); } b.take(&made); let erase = |dev: &mut Dev, at: i64, rows: std::ops::RangeInclusive| { dev.db.watch_statements(); let before = dev.db.steps(); let ops = dev.act(at, rows.map(|i| Change::erase(PHOTOS, &photo_id(i), "bin")).collect()); (ops, erases_asked(&dev.db, dev.db.steps() - before)) }; let take = |dev: &Dev, ops: &[CottonOp]| { dev.db.watch_statements(); let before = dev.db.steps(); dev.take(ops); erases_asked(&dev.db, dev.db.steps() - before) }; let (four_ops, four) = erase(&mut a, T0 + 10_000, 1..=4); let (forty_ops, forty) = erase(&mut a, T0 + 20_000, 5..=44); let peer_four = take(&b, &four_ops); let peer_forty = take(&b, &forty_ops); for (whose, few, many) in [("the writer", &four, &forty), ("the peer", &peer_four, &peer_forty)] { assert!(few.owners > 0, "{whose} never asked what the rows own: the premise of this guard"); assert_eq!(many.owners, few.owners, "{whose} asked what the rows own once per row"); assert_eq!(many.names_by_row, 0, "{whose} asked the media-key index by row"); assert_eq!(many.tombstones_by_op, 0, "{whose} asked the tombstones by op id alone"); assert!( many.steps / 40 <= few.steps / 4, "{whose}: a row of forty read {} steps, a row of four {}", many.steps / 40, few.steps / 4 ); } for dev in [&a, &b] { assert_eq!(dev.count("SELECT COUNT(*) AS n FROM cotton_photos", &[]), 0); assert_eq!(dev.count("SELECT COUNT(*) AS n FROM _media_key_names", &[]), 0, "the erased rows' names are gone"); assert_eq!(dev.queued().len(), 44); } } /// RULE: What a batch read of its erases' owned rows is never trusted past a write: a child that arrives in the same batch as its parent's erase, before it, is taken with the parent. #[test] fn a_child_written_earlier_in_the_batch_leaves_with_its_parents_erase() { let (mut a, b) = pair(); let k = key("late"); let thread = a.act(T0, vec![thread()]); b.take(&thread); let mut batch = a.act(T0 + 1_000, vec![message(MESSAGE, &[&k])]); batch.extend(a.act(T0 + 2_000, vec![Change::erase(THREADS, THREAD, "bin")])); // One batch on the peer: the message, then the erase of its thread. b.take(&batch); for dev in [&a, &b] { assert!(!dev.present(THREADS, THREAD)); assert!(!dev.present(MESSAGES, MESSAGE), "the child outlived its parent's erase"); assert!(cotton_store::erase::is_gone(&dev.db, MESSAGES, MESSAGE).expect("reads"), "the child is not kept as gone"); assert!(!dev.names(&k, MESSAGES, MESSAGE), "the child's key is still named"); assert_eq!(dev.queued(), vec![k.clone()]); } } /// RULE: A rebuild releases the writer between pages without resurrecting an erased row's names; a new row behind its cursor is already named by the write hook before the unlink queue can drain. #[test] fn paged_rebuild_keeps_interleaved_erases_and_writes() { use cotton_store::media_keys::NameSweep; let mut a = device("paged-rebuild"); let (gone, born) = (key("paged-gone"), key("paged-born")); a.act(T0, vec![photo(1, &gone)]); a.exec("DELETE FROM _media_key_names"); let mut sweep = NameSweep::default(); let mut interleaved = false; while sweep.rebuild_next(&a.db).expect("one rebuild page").is_some() { if !interleaved && a.names(&gone, PHOTOS, &photo_id(1)) { a.act(T0 + 1_000, vec![Change::erase(PHOTOS, &photo_id(1), "bin"), photo(0, &born)]); interleaved = true; } } assert!(interleaved, "the existing name was visited"); assert!(!a.names(&gone, PHOTOS, &photo_id(1)), "a later page resurrected an erased name"); assert!(a.names(&born, PHOTOS, &photo_id(0)), "the write behind the cursor was missed"); assert_eq!(may_unlink_now(&a.db, &gone).unwrap(), MayUnlink::Yes); }