//! The one place a copy leaves its place (QUEUE BAD OP 4 and 5): the lint that no other code removes, replaces or //! moves one, the person's act, the store's list of local places, the one question of a copy and of a folder, the //! matrix of real callers x every unsent kind x every stop, recovery at the original time and once, Let go. use std::path::{Path, PathBuf}; use super::*; /// Files whose removals, renames and writes never touch a copy, each with why: their own files only. A file not here /// that removes, renames or writes a file says so statement by statement (`// not a copy: `), or goes through /// this module. const NEVER_A_COPY: &[(&str, &str)] = &[ ("cotton-client/src/copy_keep.rs", "the one place"), ("cotton-client/src/media/", "media files, named by their bytes"), ("cotton-client/src/ingest/", "files brought in from outside, before they are rows"), ("cotton-client/src/ci/", "the build ledger's own files"), ("cotton-client/src/git/", "the git keychain's files"), ("cotton-client/src/vault/", "vault placements, files a person keeps outside a copy"), ("cotton-store/src/test_template.rs", "the test template, only in tests"), ]; fn crates_dir() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).parent().expect("the crates folder").to_path_buf() } fn sources(dir: &Path, out: &mut Vec) { for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { let path = entry.path(); if path.is_dir() { if path.file_name().is_some_and(|name| name != "tests") { sources(&path, out); } } else if path.extension().is_some_and(|ext| ext == "rs") { let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned(); if !name.ends_with("_tests.rs") && name != "tests.rs" && !name.ends_with("_e2e.rs") { out.push(path); } } } } /// Every source file of the core's crates, by its path below the crates folder. fn core_sources() -> Vec<(String, String)> { let root = crates_dir(); let mut files = Vec::new(); for krate in ["cotton-client/src", "cotton-ffi/src", "cotton-store/src"] { sources(&root.join(krate), &mut files); } files .into_iter() .map(|file| (file.strip_prefix(&root).unwrap_or(&file).to_string_lossy().replace('\\', "/"), std::fs::read_to_string(&file).unwrap_or_default())) .collect() } /// The lines of `text` outside inline test modules (skipped by their braces, and only them), with their numbers. fn live_lines(text: &str) -> Vec<(usize, &str)> { let lines: Vec<&str> = text.lines().collect(); let mut out = Vec::new(); let mut skipping: Option = None; for (n, line) in lines.iter().enumerate() { if let Some(depth) = skipping.as_mut() { *depth += line.matches('{').count() as i64 - line.matches('}').count() as i64; if *depth <= 0 { skipping = None; } continue; } if line.trim_start().starts_with("#[cfg(test)]") && lines.get(n + 1).is_some_and(|next| next.trim_start().starts_with("mod ") && next.contains('{')) { skipping = Some(0); continue; } out.push((n, *line)); } out } /// The code of a line: what comes before a `//` that is not inside a string. fn code_of(line: &str) -> &str { let mut in_string = false; let bytes = line.as_bytes(); let mut i = 0; while i < bytes.len() { match bytes[i] { b'\\' if in_string => i += 1, b'"' => in_string = !in_string, b'/' if !in_string && bytes.get(i + 1) == Some(&b'/') => return &line[..i], _ => {} } i += 1; } line } /// The comment of a line (after a `//` outside any string), if any. fn comment_of(line: &str) -> Option<&str> { let code = code_of(line); (code.len() < line.len()).then(|| &line[code.len()..]) } /// What a statement may do to a file: remove, rename, write over, truncate, replace whole, or copy a database into. const TOUCHES: &[&str] = &[ // QUEUE BAD OP 6 (M2): a change leaving its queue or its receipts, a file copied or linked, an empty folder removed. "DELETE FROM _outbox", "DELETE FROM _writes", // QUEUE BAD OP 7: the other places a change waits, and a file cut short. "DELETE FROM _media", "DELETE FROM _parked", "DELETE FROM _tombstones", "set_len(", "fs::copy(", "hard_link(", "remove_dir(", "remove_file(", "remove_dir_all(", "fs::rename(", "rename: Box::new", "fs::write(", "File::create(", ".truncate(true)", "whole_file::replace(", "VACUUM INTO", "rusqlite::backup", ".backup(", "Backup::new(", ]; /// Every statement in the core's crates that removes, renames, writes over, truncates or replaces a file (or copies a /// database) outside this module or an allowed file, and does not say it is not a copy. The marker exempts only its /// own statement: a `// not a copy: …` comment on the same line, or in the comment lines directly above it; never /// from inside a string. An aliased import of a removal or rename is never allowed outside the allowed files. fn unmarked() -> Vec { let mut found = Vec::new(); for (relative, text) in core_sources() { if NEVER_A_COPY.iter().any(|(allowed, _)| relative == *allowed || (allowed.ends_with('/') && relative.starts_with(allowed))) { continue; } let lines: Vec<&str> = text.lines().collect(); // QUEUE BAD OP 7: a removal, rename or copy imported from std::fs by name is caught called bare too. let bare = fs_imports(&text); for (n, line) in live_lines(&text) { let code = code_of(line); if code.trim().is_empty() { continue; } let called_bare = bare.iter().any(|name| { code.match_indices(&format!("{name}(")).any(|(at, _)| at == 0 || !matches!(code.as_bytes()[at - 1], b'.' | b':' | b'_') && !code.as_bytes()[at - 1].is_ascii_alphanumeric()) }); let aliased = code.contains("use ") && code.contains(" as ") && ["remove_file", "remove_dir_all", "remove_dir", "rename", "write", "File", "copy", "hard_link"].iter().any(|name| code.contains(&format!("{name} as "))); if aliased { found.push(format!("{relative}:{}: an aliased import of a file removal or write: {}", n + 1, line.trim())); continue; } if !called_bare && !TOUCHES.iter().any(|call| code.contains(call)) { continue; } let mut said = comment_of(line).is_some_and(|comment| comment.contains("not a copy")); let mut at = n; while !said && at > 0 { at -= 1; let above = lines[at].trim_start(); if !above.starts_with("//") { break; } said = above.contains("not a copy"); } if !said { found.push(format!("{relative}:{}: {}", n + 1, line.trim())); } } } found } /// The file operations a source imports from `std::fs` by name (`use std::fs::{rename, copy}`, `use std::fs::*`), /// which it may then call bare. fn fs_imports(text: &str) -> Vec<&'static str> { const NAMES: [&str; 7] = ["rename", "copy", "remove_file", "remove_dir", "remove_dir_all", "write", "hard_link"]; let mut found = Vec::new(); for line in text.lines().map(str::trim).filter(|line| line.starts_with("use std::fs::")) { let named = &line["use std::fs::".len()..]; for name in NAMES { let listed = named.trim_start_matches('{').trim_end_matches(';').trim_end_matches('}').split(',').map(str::trim).any(|item| item == name || item == "*"); if listed && !found.contains(&name) { found.push(name); } } } found } /// RULE (QUEUE BAD OP 4 item 1, QUEUE BAD OP 5): no code in the core but `copy_keep` deletes, replaces, writes over /// or moves a local copy's file or folder. Every other such statement names what it touches (`// not a copy: …`) or is /// in a file that never holds a copy; a new one that does neither fails here. #[test] fn nothing_else_removes_a_copy() { let found = unmarked(); assert!(found.is_empty(), "{} statement(s) outside copy_keep that touch a file and do not say they are not a copy:\n{}", found.len(), found.join("\n")); } /// RULE: the marker counts only as a comment of its own statement: one inside a string, or above another statement, /// exempts nothing. #[test] fn the_marker_exempts_only_its_own_statement() { assert_eq!(code_of(r#"let x = "// not a copy"; std::fs::remove_file(p);"#), r#"let x = "// not a copy"; std::fs::remove_file(p);"#); assert!(comment_of(r#"let x = "// not a copy"; std::fs::remove_file(p);"#).is_none()); assert_eq!(comment_of("std::fs::remove_file(p); // not a copy: a note"), Some("// not a copy: a note")); } /// RULE (QUEUE BAD OP 5, item 5): the destroying endings are built only from the person's act, and only the three act /// handlers make one: account delete, the person's own Remove of a local database, and Let go. #[test] fn only_the_three_acts_make_a_persons_act() { const ACTS: &[(&str, &str)] = &[ ("cotton-ffi/src/phone/account_delete.rs", "the person deleted their account"), ("cotton-ffi/src/phone/personal_object.rs", "the person's own Remove of a local database"), ("cotton-ffi/src/methods/sync.rs", "the person let go of a kept change"), ]; let mut makers = Vec::new(); for (relative, text) in core_sources() { if relative == "cotton-client/src/copy_keep.rs" { continue; } for (n, line) in live_lines(&text) { if code_of(line).contains("PersonsAct::of_the_person(") { makers.push((relative.clone(), n + 1)); } } } let strangers: Vec<_> = makers.iter().filter(|(file, _)| !ACTS.iter().any(|(act, _)| act == file)).collect(); assert!(strangers.is_empty(), "only the three act handlers make the person's act: {strangers:?}"); for (act, why) in ACTS { let n = makers.iter().filter(|(file, _)| file == act).count(); assert_eq!(n, 1, "{act} ({why}) makes it exactly once: {makers:?}"); } } /// RULE (QUEUE BAD OP 5, item 2): every `_` table any build makes in a copy is on the store's list of local places /// (`cotton_store::local_places`), as a place a change waits in or as derivable with why. Read from the source, so a /// new table cannot be forgotten. #[test] fn every_local_table_is_on_the_list() { let mut made = std::collections::BTreeSet::new(); let root = crates_dir(); let mut files = Vec::new(); for krate in ["cotton-client/src", "cotton-ffi/src", "cotton-store/src"] { sources(&root.join(krate), &mut files); } for file in files { let text = std::fs::read_to_string(&file).unwrap_or_default(); for piece in text.split("CREATE TABLE ").skip(1) { let piece = piece.trim_start().strip_prefix("IF NOT EXISTS ").unwrap_or(piece.trim_start()); let name: String = piece.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect(); if name.starts_with('_') { made.insert(name); } } } assert!(made.contains("_outbox") && made.contains("_media"), "read from the source: {made:?}"); let missing: Vec<_> = made.iter().filter(|table| cotton_store::local_places::place_of(table).is_none()).collect(); assert!(missing.is_empty(), "tables a copy may hold that the store's list of local places does not name: {missing:?}"); } // ── what a copy can hold, from the store's own list ───────────────────────── use crate::test_support::{hold_one_change, open_replica_for, open_test_replica, queue_one_change, WORKSPACE}; /// What a copy (or its folder) holds as it leaves its place: one per way a change waits in each place of the store's /// list, then what stands beside a copy. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Holds { /// A place of `cotton_store::local_places`, and which way of waiting in it. Place(&'static str, usize), /// A carried file beside the copy (QUEUE BAD OP 3), never landed. Carried, /// Rows the server refused, kept beside the copy. KeptRows, /// The sites kept on this phone only. SitesLocal, /// A file nothing names. Unnamed, /// A copy that will not open. WillNotOpen, /// A SQLite file holding tables, none a place a change waits in. NoPlaces, } /// The ways a change waits in each place of the store's list. A place with none fails here: a new place needs one. fn ways(table: &str) -> &'static [&'static str] { match table { "_outbox" => &["a change that reads", "a change that does not read"], "_parked" => &["set aside (held 3)", "an earlier build's set aside (held 0)"], "_writes" => &["held for the clock"], "_tombstones" => &["a delete held, not reading"], "_media" => &["an upload not done"], other => panic!("a place a change waits in ({other}) that the matrix has no way to fill: add one"), } } fn all_holds() -> Vec { let mut all: Vec = cotton_store::local_places::unsent_places().flat_map(|(table, _, _)| (0..ways(table).len()).map(move |way| Holds::Place(table, way))).collect(); all.extend([Holds::Carried, Holds::KeptRows, Holds::SitesLocal, Holds::Unnamed, Holds::WillNotOpen, Holds::NoPlaces]); all } impl Holds { fn name(self) -> String { match self { Holds::Place(table, way) => format!("{table}: {}", ways(table)[way]), other => format!("{other:?}"), } } /// Whether this build reads the change, so recovery sends it. fn reads(self) -> bool { matches!(self, Holds::Place("_outbox", 0) | Holds::Place("_writes", 0) | Holds::Place("_parked", 1)) } /// Whether it lives beside the copy rather than in it or in its own files (a copy's question leaves it in place). fn beside(self) -> bool { matches!(self, Holds::KeptRows | Holds::SitesLocal | Holds::Unnamed) } /// The file that holds it, below the database's folder. fn file(self) -> &'static str { match self { Holds::Carried => "replica.db.set-aside.json", Holds::KeptRows => KEPT_ROWS, Holds::SitesLocal => SITES_LOCAL, Holds::Unnamed => "a-note-someone-left", _ => "replica.db", } } } /// A copy of the test database at its place, holding `holds`; answers the stamp's millisecond of the change that reads. fn copy_holding(holds: Holds) -> (tempfile::TempDir, Layout, PathBuf, Option) { let (dir, layout, replica) = open_test_replica(); let path = replica.path.clone(); let run = |sql: &str| { replica.driver.run(sql, &[]).expect(sql); }; let readable_ms = |sql: &str| -> Option { let row = replica.driver.get(sql, &[]).expect("a read")?; let bytes = match row.get("bytes") { Some(rusqlite::types::Value::Blob(bytes)) => bytes.clone(), _ => return None, }; let receipt = cotton_store::canonical::decode(&bytes).ok()?; cotton_store::protocol::hlc::hlc_parts(&receipt.stamp).ok().map(|parts| parts.ms) }; let mut ms = None; let folder = path.parent().expect("a folder").to_path_buf(); match holds { Holds::Place("_outbox", 0) => { queue_one_change(&replica, "Ring the bank"); ms = readable_ms("SELECT bytes FROM _outbox WHERE tbl = 'cotton_todos'"); } Holds::Place("_outbox", 1) => run( "INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes, sig) \ VALUES ('bad-queued', 'change', 'synthetic-author', 'cotton_todos', 'todo-damaged', '0000000000001:0000:x', 1, '2026-09-08T09:00:00.000Z', X'00FF', NULL)", ), Holds::Place("_parked", 0) => { cotton_store::rejected::set_aside_undecodable(&replica.driver, "bad-aside", Some(&[0, 255]), None, "cotton_todos", "todo-damaged", "it does not read", "2026-09-08T09:00:00.000Z").expect("set aside"); } Holds::Place("_parked", 1) => { queue_one_change(&replica, "Ring the bank"); ms = readable_ms("SELECT bytes FROM _outbox WHERE tbl = 'cotton_todos'"); run("INSERT INTO _parked (op_id, direction, class, reason, first_at, tries, bytes, sig, tbl, row_id) \ SELECT op_id, 'push', 'conflict', 'undecodable: an earlier build', queued_at, 0, bytes, sig, tbl, row_id FROM _outbox WHERE tbl = 'cotton_todos'"); run("DELETE FROM _outbox WHERE tbl = 'cotton_todos'"); run("UPDATE _writes SET held = 0 WHERE tbl = 'cotton_todos'"); } Holds::Place("_writes", 0) => { hold_one_change(&replica, "Ring the bank"); ms = readable_ms("SELECT bytes FROM _writes WHERE tbl = 'cotton_todos' AND held = 1"); } Holds::Place("_tombstones", 0) => run( "INSERT INTO _tombstones (tbl, row_id, hlc, op_id, author, actor, bytes, sig, held) \ VALUES ('cotton_todos', 'todo-gone', '0000000000001:0000:x', 'bad-tomb', 'synthetic-author', 'synthetic-author', X'00FF', NULL, 1)", ), Holds::Place("_media", 0) => run( "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, state, created_at, updated_at) \ VALUES ('media-not-up', 'w', 'abc', 'image/jpeg', 3, 'a/b', 'pending', '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z')", ), Holds::Place(table, way) => panic!("no way {way} for {table}"), Holds::Carried => { let carried = cotton_store::rejected::SetAside { op_id: "bad-carried".into(), reason: "undecodable: carried".into(), first_at: "2026-09-08T09:00:00.000Z".into(), bytes: vec![0, 255], sig: None, table: "cotton_todos".into(), row_id: "todo-damaged".into(), }; crate::transport::object::carry_set_aside_to(&with_suffix(&path, CARRIED_SUFFIX), &[carried]).expect("carried"); } Holds::KeptRows => { let row = crate::unsent::KeptRow { table: "cotton_todos".into(), row_id: "todo-refused".into(), data: serde_json::json!({"title": "Refused"}), why: "a test".into(), at: "2026-09-08T09:00:00.000Z".into() }; std::fs::write(folder.join(KEPT_ROWS), serde_json::to_vec(&vec![row]).unwrap()).unwrap(); } Holds::SitesLocal => std::fs::write(folder.join(SITES_LOCAL), b"sealed sites kept on this phone only").unwrap(), Holds::Unnamed => std::fs::write(folder.join("a-note-someone-left"), b"something only this phone has").unwrap(), Holds::WillNotOpen | Holds::NoPlaces => {} } drop(replica); match holds { Holds::WillNotOpen => { for suffix in ["-wal", "-shm"] { let _ = std::fs::remove_file(with_suffix(&path, suffix)); } std::fs::write(&path, b"this is not a database, and it is somebody's").expect("a damaged copy"); } Holds::NoPlaces => { for suffix in ["", "-wal", "-shm"] { let _ = std::fs::remove_file(with_suffix(&path, suffix)); } let file = rusqlite::Connection::open(&path).unwrap(); file.execute_batch("CREATE TABLE notes (id TEXT, body TEXT); INSERT INTO notes VALUES ('n1', 'written somewhere no build knows');").unwrap(); } _ => {} } (dir, layout, path, ms) } /// Every byte under `dir`, by name. fn bytes_under(dir: &Path) -> Vec<(String, Vec)> { let mut all = Vec::new(); let mut walk = vec![dir.to_path_buf()]; while let Some(folder) = walk.pop() { for entry in std::fs::read_dir(&folder).into_iter().flatten().flatten() { let path = entry.path(); if path.is_dir() { walk.push(path); } else { all.push((path.file_name().unwrap_or_default().to_string_lossy().into_owned(), std::fs::read(&path).unwrap_or_default())); } } } all.sort(); all } /// Each holding made once (a copy built from its snapshot is the slow part), its data folder copied for each cell. fn template(holds: Holds) -> (PathBuf, Option) { use std::sync::{Mutex, OnceLock}; static MADE: OnceLock)>>> = OnceLock::new(); let made = MADE.get_or_init(|| Mutex::new(Vec::new())); let mut made = made.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); if let Some((_, root, ms)) = made.iter().find(|(kind, _, _)| *kind == holds.name()) { return (root.clone(), *ms); } let (dir, layout, path, ms) = copy_holding(holds); // The journal folded in, so the copy's own bytes are one file the cells compare. if let Ok(file) = rusqlite::Connection::open(&path) { let _ = file.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())); } let root = layout.root().to_path_buf(); std::mem::forget(dir); made.push((holds.name(), root.clone(), ms)); (root, ms) } fn copy_tree(from: &Path, to: &Path) { std::fs::create_dir_all(to).expect("a folder"); for entry in std::fs::read_dir(from).expect("a folder").flatten() { let (source, target) = (entry.path(), to.join(entry.file_name())); if source.is_dir() { copy_tree(&source, &target); } else { std::fs::copy(&source, &target).expect("a file copied"); } } } /// A snapshot the live copies of the cells are made from, written once. fn live_snapshot() -> PathBuf { use std::sync::OnceLock; static SNAPSHOT: OnceLock = OnceLock::new(); SNAPSHOT .get_or_init(|| { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("snapshot.db"); crate::test_support::write_snapshot(&path); std::mem::forget(dir); path }) .clone() } /// A caller of the one function, run by its own code: (name, where the holding stands, the run). struct Caller { name: &'static str, /// The file and the function its call to the one function stands in, to tie the matrix to the source. at: &'static str, in_fn: &'static str, /// The holding stands at the copy saved before an update, not the copy. before_update: bool, run: fn(&Layout), } /// The callers in this crate, each run by its real function. fn callers() -> Vec { vec![ Caller { name: "leave (this device left the database)", at: "cotton-client/src/join/leave.rs", in_fn: "delete_replica_files", before_update: false, run: |layout| { crate::join::leave::delete_replica_files(layout, WORKSPACE, Ending::keep("this device left it")); } }, // QUEUE BAD OP 6: the erase itself, not the leave's code again. Caller { name: "erase this device (erase_device)", at: "cotton-client/src/join/leave.rs", in_fn: "delete_replica_files", before_update: false, run: |layout| { let connection = crate::connection::ConnectionFile::at(layout.connection_json()); let _ = crate::join::leave::erase_device(layout, &connection, Some(WORKSPACE)); } }, Caller { name: "database out of scope (deleted, or this device removed)", at: "cotton-client/src/join/bin.rs", in_fn: "purge_copy", before_update: false, run: |layout| { let _ = crate::join::bin::purge_copy(layout, WORKSPACE); } }, Caller { name: "previous::release (the copy saved before an update)", at: "cotton-client/src/bootstrap/previous.rs", in_fn: "release", before_update: true, run: |layout| { crate::bootstrap::previous::release(&layout.replica(WORKSPACE)); } }, Caller { name: "start (a database it made and could not finish)", at: "cotton-client/src/start.rs", in_fn: "forget_unfinished", before_update: false, run: |layout| { crate::start::forget_unfinished(&layout.replica(WORKSPACE)); } }, Caller { name: "replica (a download that wrote nothing)", at: "cotton-client/src/replica.rs", in_fn: "let_go_of_empty_download", before_update: false, run: |layout| { crate::replica::let_go_of_empty_download(&layout.replica(WORKSPACE)); } }, ] } /// Where a run stops, as a phone killed part way would. const KILLS: [Option; 4] = [None, Some(Stop::FailMove), Some(Stop::BeforeMove), Some(Stop::BeforeSettle)]; /// One cell: the caller's own code run, stopped where a kill stops it, then the next launch (the same caller again, /// and the next look at the kept copies). The holding's bytes are on disk after, recovery finds it (or it stands where /// it is read), and a build that reads it sends it at its original time. Answers the cell's line. fn cell(caller: &Caller, holds: Holds, kill: Option) -> String { let (root, ms) = template(holds); let scratch = tempfile::tempdir().expect("a folder"); let layout = Layout::new(scratch.path().join("CottonDB")); copy_tree(&root, layout.root()); let live = layout.replica(WORKSPACE); let folder = live.parent().expect("a folder").to_path_buf(); if caller.before_update { let saved = crate::bootstrap::previous::path(&live); std::fs::rename(&live, &saved).expect("the holding at the copy saved before an update"); let _ = std::fs::rename(with_suffix(&live, CARRIED_SUFFIX), with_suffix(&saved, CARRIED_SUFFIX)); } let file = if caller.before_update && !holds.beside() { format!("replica.db{}", crate::bootstrap::previous::SUFFIX) } else { holds.file().to_string() }; let file = if caller.before_update && holds == Holds::Carried { format!("replica.db{}{CARRIED_SUFFIX}", crate::bootstrap::previous::SUFFIX) } else { file }; let bytes = std::fs::read(folder.join(&file)).expect("the holding's bytes"); let label = format!("{} | {} | {}", caller.name, holds.name(), kill.map_or("none".to_string(), |kill| format!("{kill:?}"))); // The run, stopped where a kill stops it. stop_for_tests(kill); (caller.run)(&layout); stop_for_tests(None); if kill == Some(Stop::FailMove) { assert_eq!(std::fs::read(folder.join(&file)).ok().as_ref(), Some(&bytes), "{label}: a move that fails leaves it where it stood"); } // The next launch: the kept copies looked at (a stopped move settled), the same caller again. let _ = kept(&layout, Some(WORKSPACE)); (caller.run)(&layout); // On disk after: the holding's own bytes, whole, somewhere under the data folder. let on_disk = bytes_under(layout.root()).iter().any(|(name, held)| *name == file && *held == bytes); assert!(on_disk, "{label}: its bytes are on disk"); // Findable: kept and listed, or standing where it is read (beside the live copy: its folder stays the database's). let listed = !kept_changes(&layout, WORKSPACE).is_empty(); let in_place = folder.join(&file).exists(); assert!(listed || (holds.beside() && in_place), "{label}: recovery finds it (listed {listed}, in place {in_place})"); if !listed { return format!("| {label} | on disk | stays where it is read | - |"); } // A later build that reads it: the new copy made, recovery sends it at its original time, after a reboot days on. if !caller.before_update && live.exists() { retire(&layout, WORKSPACE, &live, Ending::keep("the next build's copy")).expect("its place made free"); } let made = crate::open_replica(&layout, WORKSPACE, &crate::seams::FixedClock::default_start(), &crate::seams::SeededRandom::default(), &mut crate::test_support::bootstrap_from(live_snapshot())).expect("the new copy"); let later = cotton_store::mint::Clock::judged(Some(1_770_000_000_000), 1_770_000_000_000, 10_000, "a-later-boot".to_string()); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(7))); let recovery = recover_by(&layout, WORKSPACE, &made.driver, &made.path, 1_770_000_000_000, Some(&later), &mut ids).expect("recovery"); let sent = if holds.reads() { assert!(recovery.sent >= 1, "{label}: a change that reads is sent: {recovery:?}"); let ms = ms.expect("its original time"); let stamps: Vec = made .driver .all("SELECT o.hlc FROM _outbox o JOIN _kept_taken k ON k.new_op_id = o.op_id", &[]) .expect("the sent changes") .iter() .filter_map(|row| row.text("hlc").map(str::to_string)) .collect(); assert!(!stamps.is_empty(), "{label}: queued here"); for stamp in &stamps { assert_eq!(cotton_store::protocol::hlc::hlc_parts(stamp).expect("a stamp").ms, ms, "{label}: sent at its original time, not the boot's or now"); } "sent at its own time" } else if holds == Holds::KeptRows { assert!(crate::unsent::kept_rows(&layout, WORKSPACE).iter().any(|row| row.row_id == "todo-refused"), "{label}: back beside the live copy, where a pass posts it"); "back beside the live copy" } else { assert!(!kept_changes(&layout, WORKSPACE).is_empty(), "{label}: still kept, listed for Let go"); "kept, listed, bytes whole" }; format!("| {label} | on disk | listed | {sent} |") } /// Every source line that calls the one function, outside this module. fn source_callers() -> Vec { let mut found = Vec::new(); for (relative, text) in core_sources() { if relative == "cotton-client/src/copy_keep.rs" { continue; } let mut in_fn = String::new(); for (n, line) in live_lines(&text) { let code = code_of(line); if let Some(at) = code.find("fn ") { let name: String = code[at + 3..].chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect(); if !name.is_empty() && (at == 0 || !code.as_bytes()[at - 1].is_ascii_alphanumeric()) { in_fn = name; } } if ["copy_keep::retire_folder(", "copy_keep::retire_at(", "copy_keep::retire(", "copy_keep::retire_database("].iter().any(|call| code.contains(call)) { found.push(format!("{relative}:{}:{in_fn}", n + 1)); } } } found } /// Where each caller of the one function is run for real outside this crate's matrix ([`callers`]): by its file AND /// the function its call stands in (QUEUE BAD OP 6: never a whole file), each in the phone's matrix /// (`cotton-ffi` `backup_tests::every_phone_caller_keeps_what_its_folder_holds_through_a_kill`). const RUN_ELSEWHERE: &[(&str, &str, &str)] = &[ ("cotton-ffi/src/phone/personal_object.rs", "remove_database_folder", "phone matrix: the adopt's ending (end_adopt, a real carried list) and an empty database giving way (give_way)"), ("cotton-ffi/src/phone/personal_object.rs", "end_remade", "phone matrix: a remake"), ("cotton-ffi/src/phone/personal_object.rs", "end_waiting", "phone matrix: the copy that waited for the data key"), ("cotton-ffi/src/phone/personal_object.rs", "remove_copy", "phone matrix: a copy that did not finish being made"), ("cotton-ffi/src/phone/personal_object.rs", "end_restored", "phone matrix: the copy a server's restore left behind (RESTORE 2), marked from before it, never sent"), ("cotton-ffi/src/phone/backup.rs", "prune_one", "phone matrix: a restore's Undo window ended"), ]; /// RULE (QUEUE BAD OP 5, the matrix): each caller of the one function, run by its own code, x each way a change waits /// in each place of the store's list and each thing beside a copy, x each stop (none, the move failing, before the /// move, after it before its state is settled): the bytes are on disk after, recovery finds them, and a build that /// reads them sends them at their original time. Prints the matrix and its cell count. #[test] fn every_caller_keeps_every_unsent_change_through_a_kill() { let ours = callers(); for line in source_callers() { let mut parts = line.split(':'); let (file, in_fn) = (parts.next().unwrap_or_default(), parts.nth(1).unwrap_or_default()); assert!( ours.iter().any(|caller| caller.at == file && caller.in_fn == in_fn) || RUN_ELSEWHERE.iter().any(|(at, function, _)| *at == file && *function == in_fn), "{line} calls the one function and no matrix runs it" ); } let holds = all_holds(); for one in &holds { template(*one); } let _ = live_snapshot(); let mut lines = vec!["| caller | holds | stop | bytes | recovery | a build that reads it |".to_string(), "|---|---|---|---|---|---|".to_string()]; let rows: Vec> = std::thread::scope(|scope| { let handles: Vec<_> = ours .iter() .map(|caller| { let holds = holds.clone(); scope.spawn(move || holds.iter().flat_map(|one| KILLS.iter().map(move |kill| (*one, *kill))).map(|(one, kill)| cell(caller, one, kill)).collect::>()) }) .collect(); handles.into_iter().map(|handle| handle.join().expect("a caller's cells")).collect() }); lines.extend(rows.into_iter().flatten()); println!("{}", lines.join("\n")); let cells = lines.len() - 2; println!("{cells} cells: {} callers x {} holdings x {} stops", ours.len(), holds.len(), KILLS.len()); assert_eq!(cells, ours.len() * holds.len() * KILLS.len()); } // ── the one question ────────────────────────────────────────────────────────── /// RULE: a copy holding nothing the server has not acknowledged goes; the three endings remove whatever it holds. #[test] fn a_copy_with_nothing_unsent_goes_and_the_three_endings_remove() { let (_dir, layout, replica) = open_test_replica(); let path = replica.path.clone(); drop(replica); assert_eq!(unsent_in(&path), Unsent::Nothing); assert_eq!(retire(&layout, WORKSPACE, &path, Ending::keep("nothing in it")).unwrap(), Retired::Gone); assert!(kept(&layout, Some(WORKSPACE)).is_empty()); let act = PersonsAct::of_the_person(); for ending in [Ending::AccountDelete(&act), Ending::OwnRemove(&act), Ending::LetGo(&act)] { let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); assert_eq!(retire(&layout, WORKSPACE, &path, ending).unwrap(), Retired::Gone, "{ending:?}"); assert!(!path.exists()); } } /// RULE: the question fails shut: a copy that will not open is kept, so is a journal without its file, and so is a /// SQLite file holding tables but none of the places a change waits in; one with no tables at all holds nothing. #[test] fn a_copy_that_cannot_be_asked_is_kept() { let (_dir, _layout, path, _) = copy_holding(Holds::WillNotOpen); assert!(matches!(unsent_in(&path), Unsent::Unknown(_)), "{:?}", unsent_in(&path)); let (_dir, _layout, path, _) = copy_holding(Holds::NoPlaces); assert!(matches!(unsent_in(&path), Unsent::Unknown(_)), "{:?}", unsent_in(&path)); let dir = tempfile::tempdir().unwrap(); let alone = dir.path().join("replica.db"); std::fs::write(with_suffix(&alone, "-wal"), b"a journal").unwrap(); assert!(matches!(unsent_in(&alone), Unsent::Unknown(_))); let empty = dir.path().join("empty.db"); drop(rusqlite::Connection::open(&empty).unwrap().execute_batch("CREATE TABLE _meta (k TEXT); PRAGMA user_version = 1;")); assert_eq!(unsent_in(&empty), Unsent::Nothing, "no table of a person's: nothing in it"); } /// RULE (QUEUE BAD OP 5, item 2): the question of a folder covers every file in it: the rows the server refused kept /// beside the copy, the sites kept on this phone only, an upload not done, a copy saved before an update, a file /// nothing names; only the files named derivable (each with why) do not count. #[test] fn the_question_of_a_folder_covers_every_file_in_it() { for holds in [Holds::KeptRows, Holds::SitesLocal, Holds::Unnamed, Holds::Place("_media", 0)] { let (_dir, layout, path, _) = copy_holding(holds); let folder = path.parent().unwrap().to_path_buf(); assert!(matches!(unsent_in_folder(&folder, &[]), Unsent::Holds(_)), "{holds:?}: {:?}", unsent_in_folder(&folder, &[])); let Retired::Kept(dir) = retire_folder(&layout, WORKSPACE, &folder, Ending::keep("a test")).unwrap() else { panic!("{holds:?}: kept") }; assert!(!folder.exists(), "{holds:?}: the folder moved whole, nothing moved back to be removed"); assert!(bytes_under(&dir).iter().any(|(name, _)| name == holds.file()), "{holds:?}: it moved with the folder"); assert!(!kept_changes(&layout, WORKSPACE).is_empty(), "{holds:?}: listed"); } // A copy saved before an update is asked like a copy. let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 1)); let folder = path.parent().unwrap().to_path_buf(); std::fs::rename(&path, crate::bootstrap::previous::path(&path)).unwrap(); assert!(matches!(unsent_in_folder(&folder, &[]), Unsent::Holds(_))); assert!(matches!(retire_folder(&layout, WORKSPACE, &folder, Ending::keep("a test")).unwrap(), Retired::Kept(_))); // Only derivable files: the folder goes. let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); let folder = path.parent().unwrap().to_path_buf(); let ids: Vec = rusqlite::Connection::open(&path).unwrap().prepare("SELECT op_id FROM _outbox").unwrap().query_map([], |row| row.get(0)).unwrap().collect::>().unwrap(); for (name, _) in DERIVABLE_FILES.iter().filter(|(name, _)| !name.starts_with(['.', '-'])) { std::fs::write(folder.join(name), b"derived").unwrap(); } assert_eq!(unsent_in_folder(&folder, &ids), Unsent::Nothing, "the derivable files and an acknowledged change do not count"); assert_eq!(retire_folder(&layout, WORKSPACE, &folder, Ending::keep_beyond("a test", &ids)).unwrap(), Retired::Gone); } /// RULE (QUEUE BAD OP 5, item 3): a copy leaving its place moves only itself and its own files; the folder it stood in /// (which may hold the live copy, and holds what is the database's) is never moved, and nothing in it is touched. #[test] fn a_copy_saved_before_an_update_leaves_without_its_folder() { let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 1)); let folder = path.parent().unwrap().to_path_buf(); let saved = crate::bootstrap::previous::path(&path); std::fs::rename(&path, &saved).unwrap(); // The live copy beside it, and the database's own files. std::fs::write(&path, b"the live copy").unwrap(); std::fs::write(folder.join(KEPT_ROWS), b"[]").unwrap(); std::fs::write(folder.join(SITES_LOCAL), b"sites").unwrap(); crate::bootstrap::previous::release(&path); assert!(!saved.exists()); assert_eq!(std::fs::read(&path).unwrap(), b"the live copy", "the live copy never moved"); assert!(folder.join(KEPT_ROWS).exists() && folder.join(SITES_LOCAL).exists(), "the database's files stay where they are read"); assert_eq!(kept(&layout, Some(WORKSPACE)).len(), 1); } /// RULE: a change the server answered (a remake's send) is left out of the question; one it did not is not. #[test] fn what_the_server_answered_is_left_out_and_nothing_else() { let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); let ids: Vec = rusqlite::Connection::open(&path).unwrap().prepare("SELECT op_id FROM _outbox").unwrap().query_map([], |row| row.get(0)).unwrap().collect::>().unwrap(); assert_eq!(unsent_beyond(&path, &ids), Unsent::Nothing); assert_eq!(retire(&layout, WORKSPACE, &path, Ending::keep_beyond("sent", &ids)).unwrap(), Retired::Gone); let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); assert!(matches!(retire(&layout, WORKSPACE, &path, Ending::keep_beyond("sent", &["another".into()])).unwrap(), Retired::Kept(_))); } // ── where it is kept ────────────────────────────────────────────────────────── /// RULE (QUEUE BAD OP 5, item 1): a copy is kept under the database it belongs to now: an adopted local database under /// the signed-in one, listed there, and removed with that account. What the adopt carried does not count: a local /// database it carried whole goes. #[test] fn an_adopted_copy_is_kept_under_the_database_it_belongs_to() { let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 1)); let folder = path.parent().unwrap().to_path_buf(); let Retired::Kept(dir) = retire_folder(&layout, WORKSPACE, &folder, Ending::keep_into("adopted", "the-signed-in-one", &[])).unwrap() else { panic!("kept") }; assert!(dir.starts_with(kept_dir(&layout, "the-signed-in-one")), "{}", dir.display()); let kept = kept(&layout, Some("the-signed-in-one")); assert_eq!((kept.len(), kept[0].state.adopted_from.as_deref()), (1, Some(WORKSPACE))); assert!(kept_changes(&layout, WORKSPACE).is_empty() && !kept_changes(&layout, "the-signed-in-one").is_empty(), "listed under the live database"); forget_account(&layout, "the-signed-in-one", &PersonsAct::of_the_person()).unwrap(); assert!(kept_folders(&layout, None).is_empty(), "account delete removes it with the rest"); // Carried whole: nothing kept. let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); let folder = path.parent().unwrap().to_path_buf(); let carried: Vec = rusqlite::Connection::open(&path).unwrap().prepare("SELECT op_id FROM _outbox").unwrap().query_map([], |row| row.get(0)).unwrap().collect::>().unwrap(); assert_eq!(retire_folder(&layout, WORKSPACE, &folder, Ending::keep_into("adopted", "the-signed-in-one", &carried)).unwrap(), Retired::Gone); } /// RULE: the journal travels with its copy: a change only in the write-ahead log is kept with it, and read there. #[test] fn the_journal_travels_with_the_copy() { let (_dir, layout, replica) = open_test_replica(); let path = replica.path.clone(); replica.driver.run("PRAGMA wal_autocheckpoint = 0", &[]).ok(); queue_one_change(&replica, "Only in the journal"); assert!(with_suffix(&path, "-wal").metadata().is_ok_and(|meta| meta.len() > 0), "the change is in the journal"); let wal = std::fs::read(with_suffix(&path, "-wal")).unwrap(); std::mem::forget(replica); let Retired::Kept(dir) = retire(&layout, WORKSPACE, &path, Ending::keep("a test")).unwrap() else { panic!("kept") }; assert!(bytes_under(&dir).iter().any(|(name, bytes)| name == "replica.db-wal" && *bytes == wal), "the journal moved with it"); assert!(!with_suffix(&path, "-wal").exists()); assert!(kept_changes(&layout, WORKSPACE).iter().any(|change| change.table == "cotton_todos"), "and is read there"); } /// RULE: a move another volume refuses moves nothing: the copy stays where it is, nothing half-kept. #[test] fn a_move_that_fails_keeps_the_copy_where_it_is() { for folder_wise in [false, true] { let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 1)); let before = std::fs::read(&path).unwrap(); stop_for_tests(Some(Stop::FailMove)); let result = if folder_wise { retire_folder(&layout, WORKSPACE, path.parent().unwrap(), Ending::keep("a test")) } else { retire(&layout, WORKSPACE, &path, Ending::keep("a test")) }; stop_for_tests(None); assert!(result.is_err(), "{result:?}"); assert_eq!(std::fs::read(&path).unwrap(), before, "it stays where it is"); assert!(kept(&layout, Some(WORKSPACE)).is_empty(), "nothing half-kept"); } } /// RULE (QUEUE BAD OP 6, LOW): a copy's file leaves its place BEFORE its journal; a stop between them leaves the /// journal behind without its copy, which cannot be asked (never opened as a copy) and which the next look finishes /// moving; the kept folder, holding the only copy of the file, is never removed as half-made. #[test] fn a_stop_between_a_copys_files_never_leaves_a_copy_without_its_journal() { let (_dir, layout, replica) = open_test_replica(); let path = replica.path.clone(); replica.driver.run("PRAGMA wal_autocheckpoint = 0", &[]).ok(); queue_one_change(&replica, "Only in the journal"); let wal = std::fs::read(with_suffix(&path, "-wal")).unwrap(); std::mem::forget(replica); stop_for_tests(Some(Stop::AfterFirstRemoval)); let stopped = retire(&layout, WORKSPACE, &path, Ending::keep("a test")); stop_for_tests(None); assert!(stopped.is_err(), "{stopped:?}"); assert!(!path.exists(), "the copy's file left first"); assert!(with_suffix(&path, "-wal").exists(), "its journal is behind it"); assert!(matches!(unsent_in(&path), Unsent::Unknown(_)), "a journal without its copy cannot be asked"); let found = kept(&layout, Some(WORKSPACE)); assert_eq!(found.len(), 1, "the kept folder stays, with the only copy of the file"); assert!(!with_suffix(&path, "-wal").exists(), "the next look finished the move"); assert!(bytes_under(&found[0].dir).iter().any(|(name, bytes)| name == "replica.db-wal" && *bytes == wal), "the journal is with its copy"); assert!(kept_changes(&layout, WORKSPACE).iter().any(|change| change.table == "cotton_todos"), "and read there"); } /// RULE (QUEUE BAD OP 7, H1): a kept folder that does not read cannot say what it holds, so nothing is removed: /// recovery sends nothing from it and leaves it, and a Let go of one change in it is refused, the folder untouched. #[test] fn a_kept_folder_that_does_not_read_is_never_removed() { let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); let Retired::Kept(dir) = retire(&layout, WORKSPACE, &path, Ending::keep("a test")).unwrap() else { panic!("kept") }; let op_id = kept_changes(&layout, WORKSPACE).first().expect("a kept change").op_id.clone(); let (_scratch, live, later) = live_and_clock(&layout); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(5))); stop_for_tests(Some(Stop::FailRead)); let recovered = recover_by(&layout, WORKSPACE, &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids); let let_go_refused = let_go(&layout, WORKSPACE, &op_id, &PersonsAct::of_the_person()); stop_for_tests(None); let recovered = recovered.expect("recovery goes on past it"); assert_eq!((recovered.sent, recovered.kept_copies_gone), (0, 0), "nothing sent from it, and it is not removed: {recovered:?}"); assert!(let_go_refused.is_err(), "a Let go it cannot check is refused: {let_go_refused:?}"); assert!(dir.join(STATE).exists(), "the kept folder stands, its state whole"); assert!(kept_changes(&layout, WORKSPACE).iter().any(|change| change.op_id == op_id), "and what it holds is still listed"); } /// RULE (QUEUE BAD OP 7, H2): a carried file that does not read or parse whole (an entry missing a field too) is left /// untouched by recovery: never removed, never written again without what it could not say. #[test] fn a_carried_file_that_does_not_parse_whole_is_left_untouched() { let (_dir, layout) = crate::test_support::temp_layout(); let (_scratch, live, later) = live_and_clock(&layout); let carried = with_suffix(&live.path, CARRIED_SUFFIX); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(5))); for damaged in [&br#"[{"op_id":"a-change","reason":"it did not read","bytes":"AAE=","table":"cotton_todos"}]"#[..], &b"[{\"op_id\": half a file"[..]] { std::fs::write(&carried, damaged).unwrap(); let recovered = recover_by(&layout, WORKSPACE, &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).expect("recovery goes on"); assert_eq!(recovered.sent, 0); assert_eq!(std::fs::read(&carried).unwrap(), damaged, "the carried file is untouched"); } } /// RULE (QUEUE BAD OP 6, M3): a kept folder is renamed to a tombstone before it is deleted; a stop part way through the /// delete (its state gone first) leaves a tombstone nothing reads as a kept copy, never one whose state is made up /// (and whose let-go or adopted changes recovery would send), and the next look finishes removing it. #[test] fn a_kept_folder_stopped_part_way_through_its_removal_is_never_read_again() { let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); let Retired::Kept(dir) = retire(&layout, WORKSPACE, &path, Ending::keep("a test")).unwrap() else { panic!("kept") }; // As a kill in the delete leaves it: the folder under its tombstone name, its state already gone. let tomb = dir.parent().unwrap().join(format!("{GONE}{}.0", dir.file_name().unwrap().to_string_lossy())); std::fs::rename(&dir, &tomb).unwrap(); std::fs::remove_file(tomb.join(STATE)).unwrap(); assert!(kept(&layout, Some(WORKSPACE)).is_empty(), "a tombstone is no kept copy"); assert!(kept_changes(&layout, WORKSPACE).is_empty(), "nothing in it is listed"); assert!(!tomb.exists(), "and its removal is finished"); let (_scratch, live, later) = live_and_clock(&layout); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(5))); let recovered = recover_by(&layout, WORKSPACE, &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).unwrap(); assert_eq!(recovered.sent, 0, "nothing is sent from it"); // And every removal goes by a tombstone: Let go of a whole kept copy leaves no folder behind. let (_dir2, layout2, path2, _) = copy_holding(Holds::Place("_outbox", 0)); let Retired::Kept(dir2) = retire(&layout2, WORKSPACE, &path2, Ending::keep("a test")).unwrap() else { panic!("kept") }; assert!(let_go_copy(&layout2, WORKSPACE, &dir2, &PersonsAct::of_the_person()).unwrap()); assert!(std::fs::read_dir(dir2.parent().unwrap()).map(|entries| entries.count()).unwrap_or(0) == 0, "no folder and no tombstone left"); } // ── recovery ────────────────────────────────────────────────────────────────── fn live_and_clock(layout: &Layout) -> (tempfile::TempDir, crate::Replica, cotton_store::mint::Clock) { let scratch = tempfile::tempdir().unwrap(); let live = open_replica_for(layout, scratch.path(), WORKSPACE); let later = cotton_store::mint::Clock::judged(Some(1_770_000_000_000), 1_770_000_000_000, 10_000, "boot".to_string()); (scratch, live, later) } /// RULE: recovery sends each change once, even when a launch stopped after sending and before its kept copy went. #[test] fn recovery_sends_a_change_once_across_a_stop() { let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); let Retired::Kept(dir) = retire(&layout, WORKSPACE, &path, Ending::keep("a test")).unwrap() else { panic!("kept") }; let state = std::fs::read(dir.join(STATE)).unwrap(); let (_scratch, live, later) = live_and_clock(&layout); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(5))); // Sent, then stopped BEFORE the kept folder is deleted; and its state as it was before the send (the state write // lost too, the harder case). stop_for_tests(Some(Stop::BeforeSettle)); let stopped = recover_by(&layout, WORKSPACE, &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids); stop_for_tests(None); assert!(stopped.is_err(), "stopped before the kept folder went: {stopped:?}"); assert!(dir.exists(), "the kept folder is still there"); std::fs::write(dir.join(STATE), &state).unwrap(); let queued = |db: &cotton_store::Driver| db.get("SELECT COUNT(*) AS n FROM _outbox WHERE tbl = 'cotton_todos'", &[]).unwrap().and_then(|row| row.int("n")).unwrap_or(0); let once = queued(&live.driver); assert_eq!(once, 1, "sent once"); let again = recover_by(&layout, WORKSPACE, &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).unwrap(); assert_eq!(queued(&live.driver), once, "never twice"); assert_eq!(again.kept_copies_gone, 1, "and then its kept copy goes"); } /// RULE (QUEUE BAD OP 5, item 6): one change the copy refuses does not hold the others back: it stays kept, listed, /// and the others are sent, in this kept copy and the next. #[test] fn one_refused_change_does_not_block_recovery() { let (_dir, layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); // A second change in the same copy whose bytes name a table this build does not have: the copy refuses it. { let file = rusqlite::Connection::open(&path).unwrap(); file.execute("INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes, sig) SELECT 'refused-one', kind, author, 'no_such_table', 'r1', hlc, schema_version, queued_at, X'00FF', sig FROM _outbox LIMIT 1", []).unwrap(); } assert!(matches!(retire(&layout, WORKSPACE, &path, Ending::keep("a test")).unwrap(), Retired::Kept(_))); // A second kept copy, with a change that reads. let (_dir2, layout2, path2, _) = copy_holding(Holds::Place("_writes", 0)); let Retired::Kept(other) = retire(&layout2, WORKSPACE, &path2, Ending::keep("a test")).unwrap() else { panic!("kept") }; copy_tree(&other, &kept_dir(&layout, WORKSPACE).join("zz-second")); let (_scratch, live, later) = live_and_clock(&layout); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(9))); let recovery = recover_by(&layout, WORKSPACE, &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).unwrap(); assert!(recovery.sent >= 2, "the others were sent: {recovery:?}"); assert!(kept_changes(&layout, WORKSPACE).iter().any(|change| change.op_id == "refused-one"), "the refused one stays kept, listed"); } /// RULE: Let go is the person's: a kept change let go leaves the list, and its kept copy goes once nothing is left. #[test] fn let_go_ends_a_kept_change_and_then_its_kept_copy() { let (_dir, layout, path, _) = copy_holding(Holds::Place("_parked", 0)); let Retired::Kept(dir) = retire(&layout, WORKSPACE, &path, Ending::keep("a test")).unwrap() else { panic!("kept") }; let found = kept_changes(&layout, WORKSPACE); assert_eq!(found.len(), 1, "{found:?}"); assert!(let_go(&layout, WORKSPACE, &found[0].op_id, &PersonsAct::of_the_person()).unwrap()); assert!(kept_changes(&layout, WORKSPACE).is_empty()); assert!(!dir.exists(), "nothing left in it: it goes"); } /// RULE: a kept copy kept whole (a remake whose send did not finish) stays even with nothing unsent, until let go. #[test] fn a_copy_kept_whole_stays_until_let_go() { let (_dir, layout, replica) = open_test_replica(); let path = replica.path.clone(); drop(replica); let Retired::Kept(dir) = retire(&layout, WORKSPACE, &path, Ending::Keep { why: "its send did not finish", whole: true, acknowledged: &[], belongs_to: None, held_back: &[], before_restore: None }).unwrap() else { panic!("kept") }; let (_scratch, live, later) = live_and_clock(&layout); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(3))); recover_by(&layout, WORKSPACE, &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).unwrap(); assert!(dir.exists(), "kept whole"); assert!(kept_bytes(&layout, Some(WORKSPACE)) > 0, "its size is said"); assert!(let_go_copy(&layout, WORKSPACE, &dir, &PersonsAct::of_the_person()).unwrap()); assert!(!dir.exists()); } /// RULE: a new copy is never put over one standing in its place. #[test] fn a_new_copy_never_replaces_one() { let dir = tempfile::tempdir().unwrap(); let (made, place) = (dir.path().join("replica.db.making"), dir.path().join("replica.db")); std::fs::write(&made, b"new").unwrap(); std::fs::write(&place, b"old, with a change in it").unwrap(); assert!(place_new(&made, &place).is_err()); assert_eq!(std::fs::read(&place).unwrap(), b"old, with a change in it"); } // ── a database's founding never travels into another (KEPT FOUR) ───────────── /// A copy holding its founding (the rows `founding::personal` and `Founder::record` hold for the server), and, when /// `todo`, one change of the person's too. fn copy_holding_its_founding(todo: bool) -> (tempfile::TempDir, Layout, PathBuf) { let (dir, layout, replica) = open_test_replica(); for (n, (table, _)) in crate::founding::FOUNDING_TABLES.iter().enumerate() { replica .driver .run( "INSERT INTO _writes (tbl, row_id, hlc, author, op_id, kind, actor, held, bytes) VALUES (?, ?, ?, 'synthetic-author', ?, 'create', 'synthetic-author', 1, X'00FF')", &[ rusqlite::types::Value::Text((*table).to_string()), rusqlite::types::Value::Text(format!("founding-{n}")), rusqlite::types::Value::Text(format!("000000000000{n}:0000:x")), rusqlite::types::Value::Text(format!("founding-op-{n}")), ], ) .expect("a founding row, held"); } if todo { hold_one_change(&replica, "Ring the bank"); } let path = replica.path.clone(); drop(replica); (dir, layout, path) } /// RULE (KEPT FOUR, Android walk 27 Nov 2026): a local database's founding is its own identity. Leaving into another /// database (an adopt, a give way) it is never counted: a folder holding only its founding goes, and one holding the /// person's work too is kept for that work alone, which is all it lists. #[test] fn a_founding_never_counts_in_a_copy_leaving_into_another_database() { let (_dir, layout, path) = copy_holding_its_founding(false); let folder = path.parent().unwrap().to_path_buf(); assert_eq!(retire_folder(&layout, WORKSPACE, &folder, Ending::keep_into("adopted", "the-signed-in-one", &[])).unwrap(), Retired::Gone, "its founding alone: nothing kept"); assert!(kept_folders(&layout, None).is_empty()); let (_dir, layout, path) = copy_holding_its_founding(true); let folder = path.parent().unwrap().to_path_buf(); assert!(matches!(retire_folder(&layout, WORKSPACE, &folder, Ending::keep_into("adopted", "the-signed-in-one", &[])).unwrap(), Retired::Kept(_)), "the person's work keeps it"); let listed: Vec = kept_changes(&layout, "the-signed-in-one").into_iter().map(|change| change.table).collect(); assert!(listed.iter().any(|table| table == "cotton_todos") && !listed.iter().any(|table| crate::founding::is_founding(table)), "only the person's work is listed: {listed:?}"); } /// RULE (KEPT FOUR): the founding of a copy kept under its OWN database (a remake, an update) is still its own and /// still waits: it is listed and recovery sends it. #[test] fn a_founding_kept_under_its_own_database_still_waits() { let (_dir, layout, path) = copy_holding_its_founding(false); assert!(matches!(retire(&layout, WORKSPACE, &path, Ending::keep("a remake")).unwrap(), Retired::Kept(_))); assert_eq!(kept_changes(&layout, WORKSPACE).len(), crate::founding::FOUNDING_TABLES.len(), "each founding row waits"); } /// RULE (KEPT FOUR, heal): a phone already showing the founding as waiting (a kept folder an earlier build filed /// under the signed-in database, holding nothing else) says nothing waits with this build, and the next launch's /// recovery removes the folder. One holding the person's work too keeps it, untouched. #[test] fn a_kept_founding_an_earlier_build_filed_heals_at_the_next_launch() { let earlier_build_kept = |todo: bool| { let (dir, layout, path) = copy_holding_its_founding(todo); let folder = path.parent().unwrap().to_path_buf(); // What the earlier build did: the folder moved whole under the signed-in database, adopted from the local one. let kept = new_kept(&layout, "the-signed-in-one", Some(WORKSPACE), "adopted", false, &folder, &[], &[], None).unwrap(); std::fs::rename(&folder, kept.join(COPY)).unwrap(); settle(&kept); (dir, layout, kept) }; let (_dir, layout, kept) = earlier_build_kept(false); assert!(kept_changes(&layout, "the-signed-in-one").is_empty(), "nothing is said to wait"); let (_scratch, live, later) = live_and_clock(&layout); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(5))); let recovered = recover_by(&layout, "the-signed-in-one", &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).unwrap(); assert_eq!((recovered.sent, recovered.kept_copies_gone, recovered.still_kept), (0, 1, 0), "{recovered:?}"); assert!(!kept.exists(), "the folder went"); let (_dir, layout, kept) = earlier_build_kept(true); let (_scratch, live, later) = live_and_clock(&layout); let recovered = recover_by(&layout, "the-signed-in-one", &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).unwrap(); let listed: Vec = kept_changes(&layout, "the-signed-in-one").into_iter().map(|change| change.table).collect(); assert_eq!((recovered.sent, recovered.kept_copies_gone, recovered.still_kept), (0, 0, listed.len()), "the person's work stays kept: {recovered:?}"); assert!(listed.iter().any(|table| table == "cotton_todos") && !listed.iter().any(|table| crate::founding::is_founding(table)), "{listed:?}"); assert!(kept.join(COPY).exists()); } // ── a local vault key is let go only on evidence (KEPT FOUR 2) ─────────────── /// Every function of this module that removes a file or a folder, each with how a local vault key is safe in it. /// The test below reads the module: a new removal fails until it is named here. const REMOVALS_AND_THE_VAULT: &[(&str, &str)] = &[ ("retire", "Keep into another database asks `vault_depends` beside its unsent count; Keep into its own database keeps every unsent change, and a local copy's secrets are unsent; the three person's endings remove what the person asked to remove"), ("retire_folder", "the same as `retire`, for a whole folder"), ("retire_database", "through `retire_folder`; its media go only with a folder that went"), ("recover", "through `recover_by`"), ("recover_by", "a kept folder with nothing left goes only when `vault_lets_go`; a carried file holds changes, never a key"), ("place_new", "a new copy moved into an empty place: refused when a copy stands there, so it replaces nothing"), ("let_go", "a change let go, and its folder only when `vault_lets_go`; a whole copy that does not open is refused unless `vault_lets_go` answers"), ("let_go_copy", "refused unless `vault_lets_go`"), ("forget_account", "the account is deleted: the rows that depended on the key go with it"), ("remove_for_account", "the account's own folders, the account deleted"), ("new_kept", "never: it makes a folder"), ("settle_moves", "an empty kept folder, links of a copy still whole in its place, or originals of a move already whole in the kept folder: never the only copy of anything"), ("kept_folders", "a tombstone, whose removal had begun and is finished"), ("remove_copy_files", "the removal itself, asked by the functions above"), ("remove_folder", "the removal itself"), ("remove_kept", "the removal itself"), ("remove_copy_file_only", "the removal itself"), ("move_copy_files", "originals linked into the kept folder first"), ("relocate", "a move: linked first, then the original removed"), ("relocate_folder", "a move"), ("keep_media_with_kept", "a move into a kept folder"), ("fence_kept_rows", "a rename of the rows kept beside a copy into the copy's own name (RESTORE 2): nothing is removed, and the copy leaves through `retire` with them"), ]; /// RULE (KEPT FOUR 2, "test by enumerating every path that removes a folder holding a vault key wrap"): every /// function here that removes a file or folder is named, with how a local vault key is safe in it. #[test] fn every_removal_is_named_with_how_a_vault_key_is_safe_in_it() { let text = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/copy_keep.rs")).unwrap(); let removals = ["remove_copy_files(", "remove_folder(", "remove_kept(", "remove_copy_file_only(", "remove_dir_all(", "remove_file(", "fs::rename("]; let mut current: Option = None; let mut unnamed = BTreeSet::new(); for line in text.lines() { if line.starts_with("#[cfg(test)]") { break; } let trimmed = line.trim_start(); if let Some(rest) = trimmed.strip_prefix("pub fn ").or_else(|| trimmed.strip_prefix("fn ")).or_else(|| trimmed.strip_prefix("pub(crate) fn ")) { current = rest.split(['(', '<']).next().map(str::to_string); } if trimmed.starts_with("//") { continue; } if removals.iter().any(|call| line.contains(call)) { if let Some(name) = ¤t { if !REMOVALS_AND_THE_VAULT.iter().any(|(named, _)| named == name) { unnamed.insert(name.clone()); } } } } assert!(unnamed.is_empty(), "removals not named in REMOVALS_AND_THE_VAULT: {unnamed:?}"); } const AT: &str = "2026-11-27T09:00:00.000Z"; fn wrap_in(driver: &cotton_store::Driver, database: &str) { driver .run( "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at) VALUES ('founder:d', ?, 'd', 'pub', 'w1:LOCAL', 1, ?, ?)", &[rusqlite::types::Value::Text(database.into()), rusqlite::types::Value::Text(AT.into()), rusqlite::types::Value::Text(AT.into())], ) .expect("a vault key's wrap"); } fn secret_in(driver: &cotton_store::Driver, database: &str, value: &str) { driver .run( "INSERT INTO cotton_secrets (id, workspace_id, name, kind, value_enc, vmk_version, created_at, updated_at) VALUES ('secret-1', ?, 'An invented login', 'password', ?, 1, ?, ?)", &[rusqlite::types::Value::Text(database.into()), rusqlite::types::Value::Text(value.into()), rusqlite::types::Value::Text(AT.into()), rusqlite::types::Value::Text(AT.into())], ) .expect("a secret"); } /// A kept folder an earlier build filed under the signed-in database, adopted from this phone's local database, /// whose copy holds the local vault key's wrap and a secret sealed under it; the live copy holds that secret as it was /// carried up (byte for byte: an older build's adopt into an account that had a vault). fn kept_holding_a_key_the_account_depends_on() -> (tempfile::TempDir, Layout, PathBuf, tempfile::TempDir, crate::Replica) { let (dir, layout, replica) = open_test_replica(); wrap_in(&replica.driver, WORKSPACE); secret_in(&replica.driver, WORKSPACE, "v2:SEALED-UNDER-THE-LOCAL-KEY"); let folder = replica.path.parent().unwrap().to_path_buf(); drop(replica); let kept = new_kept(&layout, "the-signed-in-one", Some(WORKSPACE), "adopted", false, &folder, &[], &[], None).unwrap(); std::fs::rename(&folder, kept.join(COPY)).unwrap(); settle(&kept); let scratch = tempfile::tempdir().unwrap(); let live = open_replica_for(&layout, scratch.path(), "the-signed-in-one"); secret_in(&live.driver, "the-signed-in-one", "v2:SEALED-UNDER-THE-LOCAL-KEY"); (dir, layout, kept, scratch, live) } /// RULE (KEPT FOUR 2, M2): a kept folder holding the vault key a row of the live copy still opens with is never /// removed: not by recovery with nothing left to send, not by a Let go of the whole copy; once the row is sealed again /// under the account's key, recovery removes it. #[test] fn a_kept_vault_key_the_account_still_depends_on_is_never_removed() { let (_dir, layout, kept, _scratch, live) = kept_holding_a_key_the_account_depends_on(); assert_eq!(live.path, layout.replica("the-signed-in-one"), "the live copy is where a kept folder's database is"); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(5))); let later = cotton_store::mint::Clock::judged(Some(1_770_000_000_000), 1_770_000_000_000, 10_000, "boot".to_string()); let recovered = recover_by(&layout, "the-signed-in-one", &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).unwrap(); assert_eq!(recovered.kept_copies_gone, 0, "{recovered:?}"); assert!(kept.join(STATE).exists(), "the key stays"); assert!(let_go_copy(&layout, "the-signed-in-one", &kept, &PersonsAct::of_the_person()).is_err(), "a Let go of the whole copy is refused"); assert!(kept.join(STATE).exists()); // The next unlock seals it again under the account's key, in the live copy only (offline): recovery before the // push keeps it (KEPT FOUR 3 C: carried means the SERVER holds it). live.driver.run("UPDATE cotton_secrets SET value_enc = 'v2:SEALED-UNDER-THE-ACCOUNT-KEY' WHERE id = 'secret-1'", &[]).unwrap(); let recovered = recover_by(&layout, "the-signed-in-one", &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).unwrap(); assert_eq!(recovered.kept_copies_gone, 0, "not on the server yet: {recovered:?}"); // The push accepted: a complete server read holds it sealed again; the key is let go, and recovery removes it. let mut reading = crate::vault_keep::ServerReading::default(); reading.row("cotton_secrets", "secret-1", crate::vault_keep::ServerRow { version: 4, deleted: false, sealed: [("value_enc".to_string(), "v2:SEALED-UNDER-THE-ACCOUNT-KEY".to_string())].into() }); assert!(matches!(crate::vault_keep::settle(&layout, WORKSPACE, reading.finish(true).as_ref()).unwrap(), crate::vault_keep::Evidence::Settled(_))); let recovered = recover_by(&layout, "the-signed-in-one", &live.driver, &live.path, 1_770_000_000_000, Some(&later), &mut ids).unwrap(); assert_eq!(recovered.kept_copies_gone, 1, "{recovered:?}"); assert!(!kept.exists()); } /// RULE (KEPT FOUR 2): a local database leaving into another whose vault key a row of that database still depends on /// is kept, whatever it holds unsent; one whose key founded the account (its wrap is there) goes. #[test] fn a_copy_leaving_into_another_database_keeps_a_key_rows_depend_on() { let (_dir, layout, replica) = open_test_replica(); wrap_in(&replica.driver, WORKSPACE); secret_in(&replica.driver, WORKSPACE, "v2:LOCAL"); let folder = replica.path.parent().unwrap().to_path_buf(); drop(replica); let scratch = tempfile::tempdir().unwrap(); let live = open_replica_for(&layout, scratch.path(), "the-signed-in-one"); secret_in(&live.driver, "the-signed-in-one", "v2:LOCAL"); assert!(matches!(retire_folder(&layout, WORKSPACE, &folder, Ending::keep_into("adopted", "the-signed-in-one", &[])).unwrap(), Retired::Kept(_)), "the account still opens a row with its key"); let (_dir, layout, replica) = open_test_replica(); wrap_in(&replica.driver, WORKSPACE); let folder = replica.path.parent().unwrap().to_path_buf(); drop(replica); let scratch = tempfile::tempdir().unwrap(); let _live = open_replica_for(&layout, scratch.path(), "the-signed-in-one"); // KEPT FOUR 3: the server took this key's founding (the adopt records it, and the key is let go on it). crate::vault_keep::secure(&layout, WORKSPACE, &[folder.join("replica.db")], Some("the-signed-in-one")).unwrap(); crate::vault_keep::note_founded(&layout, WORKSPACE, "the-signed-in-one").unwrap(); assert!(matches!(crate::vault_keep::settle(&layout, WORKSPACE, None).unwrap(), crate::vault_keep::Evidence::Settled(_))); assert_eq!(retire_folder(&layout, WORKSPACE, &folder, Ending::keep_into("adopted", "the-signed-in-one", &[])).unwrap(), Retired::Gone, "founded: its key is the account's"); } /// RULE (owner, 28 Nov 2026): one copy is shared by every app on the phone; an app on an older core than the newest /// that opened it to write never remakes or adopts it out of its place (the person reads `OLDER_CORE`), and the /// person's own acts still go. A core with no stamp never refuses. #[test] fn an_older_core_never_moves_the_shared_copy_out() { let (_dir, layout, replica) = open_test_replica(); let path = replica.path.clone(); drop(replica); super::set_core_built(1_800_000_000); super::stamp_core(&path); let stamp = path.with_file_name("core-built"); assert_eq!(std::fs::read_to_string(&stamp).unwrap(), "1800000000", "the core that opened it to write"); std::fs::write(&stamp, "1800000500").unwrap(); // a newer app's core opened it since let refused = retire(&layout, WORKSPACE, &path, Ending::keep("an older app's remake")).unwrap_err(); assert!(refused.starts_with(super::OLDER_CORE), "{refused}"); assert!(path.exists(), "the copy stays where it is"); let folder = path.parent().unwrap().to_path_buf(); assert!(super::retire_folder(&layout, WORKSPACE, &folder, Ending::keep("an older app's adopt")).unwrap_err().starts_with(super::OLDER_CORE)); super::stamp_core(&path); assert_eq!(std::fs::read_to_string(&stamp).unwrap(), "1800000500", "an older core never lowers the stamp"); // The person's own act still goes. let act = PersonsAct::of_the_person(); assert_eq!(retire(&layout, WORKSPACE, &path, Ending::OwnRemove(&act)).unwrap(), Retired::Gone); super::set_core_built(0); } // ── RESTORE 2: a copy from before the server's restore ─────────────────────────────────────────────────────────── /// RULE (RESTORE 2): a copy the server's restore left behind leaves through the one function marked as from before /// the restore, with the rows the server refused that were kept beside it; through every stop, its bytes stay on disk /// and are listed, and recovery in a later copy sends none of it (a change that reads included) and puts no kept row /// back beside the live copy for a pass to post: the damage the restore undid may be among them. #[test] fn a_copy_from_before_a_restore_is_listed_and_never_sent() { const RESTORED_TO: &str = "2026-11-20T08:00:00.000Z"; for kill in KILLS { let label = format!("{kill:?}"); let (_dir, layout, path, ms) = copy_holding(Holds::Place("_outbox", 0)); assert!(ms.is_some(), "the queued change reads in this build"); let folder = path.parent().unwrap().to_path_buf(); let row = crate::unsent::KeptRow { table: "cotton_todos".into(), row_id: "todo-refused".into(), data: serde_json::json!({"title": "Refused"}), why: "a test".into(), at: "2026-09-08T09:00:00.000Z".into() }; std::fs::write(folder.join(KEPT_ROWS), serde_json::to_vec(&vec![row]).unwrap()).unwrap(); let ending = || Ending::keep_restored("the server was put back to an earlier time", RESTORED_TO); let run = || { fence_kept_rows(&path).expect("the kept rows are the copy's own"); retire(&layout, WORKSPACE, &path, ending()) }; stop_for_tests(kill); let _ = run(); stop_for_tests(None); assert!(crate::unsent::kept_rows(&layout, WORKSPACE).is_empty(), "{label}: no pass finds the kept rows to post"); // The next launch: the kept copies looked at, the restore's ending again. let _ = kept(&layout, Some(WORKSPACE)); run().expect("the restore's ending"); assert!(!path.exists(), "{label}: the copy left its place"); let copies = kept(&layout, Some(WORKSPACE)); assert_eq!(copies.len(), 1, "{label}: one kept copy"); assert_eq!(copies[0].state.before_restore.as_deref(), Some(RESTORED_TO), "{label}: marked as from before the restore"); let listed = kept_changes(&layout, WORKSPACE); assert!(listed.iter().any(|change| change.place == "queued"), "{label}: the unsent change is listed: {listed:?}"); assert!(listed.iter().any(|change| change.op_id.ends_with(ROWS_SUFFIX)), "{label}: the refused rows are listed: {listed:?}"); // A later copy's recovery: nothing sent, nothing put back, still listed. let made = crate::open_replica(&layout, WORKSPACE, &crate::seams::FixedClock::default_start(), &crate::seams::SeededRandom::default(), &mut crate::test_support::bootstrap_from(live_snapshot())).expect("the new copy"); let later = cotton_store::mint::Clock::judged(Some(1_770_000_000_000), 1_770_000_000_000, 10_000, "a-later-boot".to_string()); let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(7))); let recovery = recover_by(&layout, WORKSPACE, &made.driver, &made.path, 1_770_000_000_000, Some(&later), &mut ids).expect("recovery"); assert_eq!(recovery.sent, 0, "{label}: nothing from before the restore is sent: {recovery:?}"); assert_eq!(cotton_store::outbox::pending_count(&made.driver).expect("the outbox"), 0, "{label}: nothing queued in the new copy"); assert!(crate::unsent::kept_rows(&layout, WORKSPACE).is_empty(), "{label}: no kept row back beside the live copy"); assert_eq!(kept_changes(&layout, WORKSPACE).len(), listed.len(), "{label}: still listed for the person"); } } /// RULE (RESTORE 2): rows kept beside a copy a stopped restore already made its own, with new ones beside it again, /// are not merged or moved: an error, and both stay where they are. #[test] fn kept_rows_made_a_copys_own_twice_move_nothing() { let (_dir, _layout, path, _) = copy_holding(Holds::Place("_outbox", 0)); let folder = path.parent().unwrap().to_path_buf(); std::fs::write(folder.join(KEPT_ROWS), b"[1]").unwrap(); fence_kept_rows(&path).expect("made its own"); std::fs::write(folder.join(KEPT_ROWS), b"[2]").unwrap(); assert!(fence_kept_rows(&path).is_err()); assert_eq!(std::fs::read(folder.join(KEPT_ROWS)).unwrap(), b"[2]"); assert_eq!(std::fs::read(with_suffix(&path, ROWS_SUFFIX)).unwrap(), b"[1]"); assert!(matches!(unsent_in(&path), Unsent::Holds(_)), "the copy's own rows count"); }