//! Backup without an account on phones that started their own databases: make, look, restore, undo, and every//! refusal in words. Invented notes only; the two phones are two folders, as a new phone is.use serde_json::{json, Value};usecrate::handle::{CottonHandle, OpenConfig, OpenMode};usecrate::methods::dispatch;fn phone(dir: &tempfile::TempDir, kit: &str) -> CottonHandle {let handle = CottonHandle::open(OpenConfig { mode: OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(json!({"genesis": "personal", "flavour": kit, "name": "Cotton Notes", "databases": "single", "database": "personal","business": { "server": { "real": "https://cottondb.com", "dev": "https://dev.example.invalid" } },"fan": { "home": false, "tools": false, "opens": "notebook" }, "kit": kit, "ground": "blank" })), }) .expect("an open core"); dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started on the phone"); handle}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value { dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}fn write(handle: &CottonHandle, text: &str) {let id = ask(handle, "notes.new", json!({}))["id"].as_str().unwrap().to_string(); ask(handle, "notes.edit", json!({ "id": id, "text": text }));}fn made(handle: &CottonHandle, code: &str) -> String {let made = ask(handle, "backup.make", json!({ "code": code, "device": "android", "withFiles": true })); assert_eq!(made["name"], "Notes.cottonbackup".replace("Notes", made["name"].as_str().unwrap().trim_end_matches(".cottonbackup"))); assert!(made["fitsGoogle"].as_bool().unwrap(), "a few notes fit in Google's 25 MB");let path = made["path"].as_str().unwrap().to_string();// The phone moves it out of the core's folder, as it moves it to iCloud Drive or `files/backup/`.let kept = std::env::temp_dir().join(format!("backup-test-{}-{}.cottonbackup", std::process::id(), rand::random::<u32>())); std::fs::copy(&path, &kept).unwrap(); ask(handle, "backup.placed", json!({ "place": "google", "bytes": made["bytes"], "madeAt": made["madeAt"], "platform": "android" })); kept.display().to_string()}#[test]fn a_backup_made_on_one_phone_restores_on_another_counted_first_and_undoes() {let (a_dir, b_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());let a = phone(&a_dir, "notes");for text in ["# A walk by the sea", "# Bread to buy", "# A line for the play"] { write(&a, text); }let screen = ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert_eq!(screen["row"]["line"], "Off"); assert_eq!(screen["page"]["key"]["id"], "neither", "nothing kept yet: the page says so"); ask(&a, "backup.turn", json!({ "on": true }));let code = ask(&a, "backup.code", json!({ "mint": true }))["code"].as_str().unwrap().to_string(); assert_eq!(ask(&a, "backup.code", json!({ "held": code }))["code"], code, "the held code reads back as itself"); assert_eq!(ask(&a, "backup.due", json!({}))["due"], true, "never backed up: due");let file = made(&a, &code); assert_eq!(ask(&a, "backup.due", json!({}))["due"], false, "just made, nothing changed");let screen = ask(&a, "backup.screen", json!({ "platform": "android", "store": { "held": true, "cloud": true } })); assert!(screen["row"]["line"].as_str().unwrap().starts_with("On · backed up "), "{}", screen["row"]); assert_eq!(screen["page"]["key"]["id"], "android_store");let bytes = std::fs::read(&file).unwrap();for word in ["walk by the sea", "Bread"] { assert!(!String::from_utf8_lossy(&bytes).contains(word), "{word} never stands in the open"); }// A new phone that already holds one note of its own.let b = phone(&b_dir, "notes"); write(&b, "# Already here");let look = ask(&b, "backup.look", json!({ "path": file, "code": code }));let line = look["ask"]["line"].as_str().unwrap(); assert_eq!(look["ask"]["fresh"], false); assert!(line.contains("This phone has 1 note.") && line.contains("3 notes"), "{line}");let restored = ask(&b, "backup.restore", json!({ "path": file, "code": code })); assert!(restored["said"].as_str().unwrap().starts_with("Restored 3 notes"), "{restored}"); assert_eq!(restored["code"], code, "the shell keeps the code that opened it");let after = ask(&b, "backup.look", json!({ "path": file, "code": code })); assert!(after["ask"]["line"].as_str().unwrap().contains("This phone has 3 notes."), "{}", after["ask"]); write(&b, "# Written after the restore");let screen = ask(&b, "backup.screen", json!({ "platform": "android", "store": {} })); assert!(screen["page"]["undo"].is_object(), "Undo restore stands for 30 days"); ask(&b, "backup.undo", json!({}));let back = ask(&b, "backup.look", json!({ "path": file, "code": code })); assert!(back["ask"]["line"].as_str().unwrap().contains("This phone has 1 note."), "{}", back["ask"]);}#[test]fn a_fresh_phone_is_asked_to_restore_and_a_typed_code_opens_it() {let (a_dir, c_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());let a = phone(&a_dir, "notes"); write(&a, "# One note"); ask(&a, "backup.turn", json!({ "on": true }));let code = ask(&a, "backup.code", json!({ "mint": true }))["code"].as_str().unwrap().to_string();let file = made(&a, &code);let c = phone(&c_dir, "notes");// The key store on this phone has nothing: the file says it needs a code.let blind = ask(&c, "backup.look", json!({ "path": file })); assert_eq!(blind["refused"]["code"], "other_key"); assert!(blind["refused"]["ask_code"].is_object());let look = ask(&c, "backup.look", json!({ "path": file, "typed": code.to_lowercase().replace('-', " ") })); assert_eq!(look["ask"]["fresh"], true); assert!(look["ask"]["line"].as_str().unwrap().ends_with("on an Android phone: 1 note."), "{}", look["ask"]);}#[test]fn a_wrong_code_a_damaged_file_or_no_backup_is_refused_and_nothing_changes() {let (a_dir, b_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());let a = phone(&a_dir, "notes"); write(&a, "# Kept safe"); ask(&a, "backup.turn", json!({ "on": true }));let code = ask(&a, "backup.code", json!({ "mint": true }))["code"].as_str().unwrap().to_string();let file = made(&a, &code);let b = phone(&b_dir, "notes"); write(&b, "# Mine");let other = ask(&b, "backup.code", json!({ "mint": true }))["code"].as_str().unwrap().to_string(); assert_eq!(ask(&b, "backup.restore", json!({ "path": file, "code": other }))["refused"]["code"], "other_key"); assert_eq!(ask(&b, "backup.look", json!({ "path": file, "typed": "ABCD-EFGH" }))["refused"]["code"], "code_typed");letmut bytes = std::fs::read(&file).unwrap();let at = bytes.len() - 10; bytes[at] ^= 1;let broken = format!("{file}.broken"); std::fs::write(&broken, &bytes).unwrap();let refused = ask(&b, "backup.restore", json!({ "path": broken, "code": code })); assert_eq!(refused["refused"]["code"], "damaged"); assert!(refused["refused"]["said"].as_str().unwrap().contains("Nothing on this phone was changed"));let cut = format!("{file}.cut"); std::fs::write(&cut, &bytes[..bytes.len() / 2]).unwrap(); assert_eq!(ask(&b, "backup.look", json!({ "path": cut, "code": code }))["refused"]["code"], "cut");let plain = format!("{file}.txt"); std::fs::write(&plain, b"my shopping list").unwrap(); assert_eq!(ask(&b, "backup.look", json!({ "path": plain, "code": code }))["refused"]["code"], "not_a_backup");// Still the phone's own one note.let still = ask(&b, "backup.look", json!({ "path": file, "code": code })); assert!(still["ask"]["line"].as_str().unwrap().contains("This phone has 1 note."), "{}", still["ask"]);}#[test]fn another_apps_backup_is_refused_by_name_and_an_app_without_backup_says_so() {let (a_dir, b_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());let a = phone(&a_dir, "notes"); write(&a, "# A note"); ask(&a, "backup.turn", json!({ "on": true }));let code = ask(&a, "backup.code", json!({ "mint": true }))["code"].as_str().unwrap().to_string();let file = made(&a, &code);let days = phone(&b_dir, "days");let refused = ask(&days, "backup.look", json!({ "path": file, "code": code })); assert_eq!(refused["refused"]["code"], "other_app"); assert!(refused["refused"]["said"].as_str().unwrap().contains("Words"), "{}", refused["refused"]);let c_dir = tempfile::tempdir().unwrap();let comms = phone(&c_dir, "messages");let error = dispatch(&comms, "backup.screen", &json!({ "platform": "ios" })).unwrap_err(); assert_eq!(error.code, "backup_not_here");}/// Every table an app's backup counts stands in that app's own fresh database, so a count is never a silent 0 (Secrets/// counted `cotton_secret`, a table that does not exist, and a phone full of secrets was asked as an empty one: the/// Android walk, 25 Nov 2026). Sites is left out: its list is not in the database yet (CONTRACT row 11b).#[test]fn every_counted_table_stands_in_its_apps_database() {for kit in ["notes", "days", "story", "keys"] {let dir = tempfile::tempdir().unwrap();let _handle = phone(&dir, kit);let replica = walkdir(dir.path()).into_iter().find(|p| p.file_name().is_some_and(|n| n == "replica.db")).unwrap_or_else(|| panic!("{kit}: a replica"));let db = rusqlite::Connection::open(&replica).unwrap();for counted in cotton_core::backup::plan::counted(kit).unwrap() {let columns: i64 = db.query_row(&format!("SELECT COUNT(*) FROM pragma_table_info('{}')", counted.table), [], |row| row.get(0)).unwrap(); assert!(columns > 0, "{kit} counts {} in {}, which its database does not have", counted.noun, counted.table); } }}fn walkdir(dir: &std::path::Path) -> Vec<std::path::PathBuf> {letmut out = Vec::new();for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {let path = entry.path();if path.is_dir() { out.extend(walkdir(&path)) } else { out.push(path) } } out}/// ABSENCE 1 (absence audit, 26 Nov 2026): what a restore set aside is never pruned because the state file cannot be/// read or does not name it. An unreadable state file prunes nothing; a folder the state does not name (a restore that/// stopped between the move and the state write) stays.#[test]fn an_aside_folder_is_never_pruned_on_an_unreadable_or_silent_state() {let dir = tempfile::tempdir().unwrap();let a = phone(&dir, "notes");let client_dir = a.client().layout().client_dir();let aside = client_dir.join("backup-aside").join("20261126T100000Z"); std::fs::create_dir_all(aside.join("database")).unwrap(); std::fs::write(aside.join("database").join("replica.db"), b"an invented earlier database").unwrap();// A state that names no restore (the move happened, the state write did not). ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert!(aside.join("database").join("replica.db").exists(), "an unnamed aside folder stays");// A state file that does not read. std::fs::write(client_dir.join("backup.json"), b"{ not json").unwrap();let _ = dispatch(&a, "backup.screen", &json!({ "platform": "android", "store": {} })); assert!(aside.join("database").join("replica.db").exists(), "an unreadable state prunes nothing"); assert_eq!(std::fs::read(client_dir.join("backup.json")).unwrap(), b"{ not json", "and is not written over");}/// ABSENCE 1: a restore names its aside folder in the state before it moves anything into it, so a restore that stops/// part way leaves an aside the state names (Undo restore finds it); an earlier restore's aside stays named until its/// 30 days pass.#[test]fn a_restore_names_its_aside_before_it_moves_the_database() {let dir_a = tempfile::tempdir().unwrap();let a = phone(&dir_a, "notes"); write(&a, "An invented note to back up"); ask(&a, "backup.turn", json!({ "on": true }));let minted = ask(&a, "backup.code", json!({ "mint": true }))["code"].as_str().unwrap().to_string();let code = minted.as_str();let file = made(&a, code);let dir_b = tempfile::tempdir().unwrap();let b = phone(&dir_b, "notes"); write(&b, "An invented note already on the second phone"); ask(&b, "backup.restore", json!({ "path": file, "code": code }));let first = ask(&b, "backup.screen", json!({ "platform": "android", "store": {} }));let _ = first;// A second restore, a moment later (asides are named by the second). std::thread::sleep(std::time::Duration::from_millis(1100)); ask(&b, "backup.restore", json!({ "path": file, "code": code }));let state: Value = serde_json::from_slice(&std::fs::read(b.client().layout().client_dir().join("backup.json")).unwrap()).unwrap();let named: Vec<String> = std::iter::once(state["restored"]["aside"].clone()).chain(state["earlier"].as_array().cloned().unwrap_or_default().into_iter().map(|r| r["aside"].clone())).filter_map(|v| v.as_str().map(str::to_string)).collect();let folders: Vec<String> = std::fs::read_dir(b.client().layout().client_dir().join("backup-aside")).unwrap().flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect(); assert_eq!(folders.len(), 2, "both restores' asides are kept: {folders:?}");for f in &folders { assert!(named.contains(f), "every aside folder is named in the state: {f} not in {named:?}"); }}fn notes_held(handle: &CottonHandle) -> i64 {letSome(id) = cotton_client::connection::ConnectionFile::at(handle.client().layout().connection_json()).read().and_then(|c| c.workspace_id) else { return -1 };let db = rusqlite::Connection::open(handle.client().layout().replica(&id)).expect("the copy"); db.query_row("SELECT COUNT(*) FROM cotton_notes", [], |r| r.get(0)).unwrap_or_else(|e| panic!("notes: {e}"))}fn state_of(handle: &CottonHandle) -> Value { serde_json::from_slice(&std::fs::read(handle.client().layout().client_dir().join("backup.json")).unwrap()).unwrap()}fn write_state(handle: &CottonHandle, state: &Value) { std::fs::write(handle.client().layout().client_dir().join("backup.json"), serde_json::to_vec(state).unwrap()).unwrap();}/// ABSENCE 3, item 4: an aside the state names that holds no database (a restore that stopped before the move) offers/// no Undo and is cleared from the state; Undo never moves the live database aside for nothing.#[test]fn an_empty_named_aside_offers_no_undo_and_never_hides_the_live_database() {let dir = tempfile::tempdir().unwrap();let a = phone(&dir, "notes"); write(&a, "# The live note");let client_dir = a.client().layout().client_dir(); std::fs::create_dir_all(client_dir.join("backup-aside").join("20261127T080000Z")).unwrap(); write_state(&a, &json!({ "restored": { "at": "2026-11-27T08:00:00Z", "at_s": chrono::Utc::now().timestamp(), "aside": "20261127T080000Z" } }));let refused = dispatch(&a, "backup.undo", &json!({})); assert!(refused.is_err(), "nothing to put back: {refused:?}"); assert_eq!(notes_held(&a), 1, "the live note is still here"); ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert!(state_of(&a)["restored"].is_null(), "an empty named aside is cleared from the state"); assert!(client_dir.join("backup-aside").join("20261127T080000Z").exists(), "its folder is left on disk");}/// ABSENCE 3, item 5: an unreadable state is said on the screen with one act, and a restore refuses before it touches/// anything; "Start backup settings again" keeps every aside folder and names each in the new state.#[test]fn an_unreadable_state_is_said_and_can_be_started_again_keeping_every_aside() {let dir = tempfile::tempdir().unwrap();let a = phone(&dir, "notes"); write(&a, "# The live note");let client_dir = a.client().layout().client_dir(); std::fs::create_dir_all(client_dir.join("backup-aside").join("20261120T080000Z").join("database")).unwrap(); std::fs::write(client_dir.join("backup.json"), b"{ not json").unwrap();let screen = ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert_eq!(screen["broken"]["act"]["method"], "backup.reset", "{screen}"); assert!(screen["broken"]["line"].as_str().is_some_and(|l| !l.is_empty()));let refused = dispatch(&a, "backup.restore", &json!({ "path": "/nowhere", "code": "x" })); assert!(refused.is_err()); assert_eq!(notes_held(&a), 1, "nothing was let go");let reset = ask(&a, "backup.reset", json!({})); assert_eq!(reset["listed"], json!(["20261120T080000Z"]), "{reset}");let state = state_of(&a); assert_eq!(state["listed"], json!(["20261120T080000Z"]), "{state}"); assert!(state["earlier"].as_array().is_none_or(Vec::is_empty), "listed, not named for the prune: {state}");// However many days are counted later, a listed folder is never pruned (ABSENCE 4, item F).letmut later = state_of(&a); later["days"] = json!(400); later["day"] = json!("2000-01-01"); write_state(&a, &later); ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert!(client_dir.join("backup-aside").join("20261120T080000Z").join("database").exists());}/// ABSENCE 3, item 6: an Undo stopped between its two moves finishes when asked again.#[test]fn an_interrupted_undo_finishes_when_asked_again() {let (a_dir, b_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());let a = phone(&a_dir, "notes"); write(&a, "# From the backup"); ask(&a, "backup.turn", json!({ "on": true }));let code = ask(&a, "backup.code", json!({ "mint": true }))["code"].as_str().unwrap().to_string();let file = made(&a, &code);let b = phone(&b_dir, "notes"); write(&b, "# Mine before"); write(&b, "# Mine before too"); ask(&b, "backup.restore", json!({ "path": file, "code": code }));// As if Undo stopped after putting the restored copy aside and before the earlier one came back.let state = state_of(&b);let aside = b.client().layout().client_dir().join("backup-aside").join(state["restored"]["aside"].as_str().unwrap());let id = cotton_client::connection::ConnectionFile::at(b.client().layout().connection_json()).read().unwrap().workspace_id.unwrap(); b.client().detach(); std::fs::create_dir_all(aside.join("undone")).unwrap(); std::fs::rename(b.client().layout().client_dir().join(&id), aside.join("undone").join(&id)).unwrap(); ask(&b, "backup.undo", json!({})); assert_eq!(notes_held(&b), 2, "the earlier notes are back");}/// ABSENCE 3, item 7: an aside holding a change the server never took is never pruned, however old.#[test]fn an_aside_holding_unsent_changes_is_never_pruned() {let dir = tempfile::tempdir().unwrap();let a = phone(&dir, "notes"); write(&a, "# An unsent note");let client_dir = a.client().layout().client_dir();let id = cotton_client::connection::ConnectionFile::at(a.client().layout().connection_json()).read().unwrap().workspace_id.unwrap();let aside = client_dir.join("backup-aside").join("20261001T080000Z"); std::fs::create_dir_all(&aside).unwrap(); std::fs::create_dir_all(aside.join("database")).unwrap();let held = aside.join("database").join("replica.db"); rusqlite::Connection::open(a.client().layout().replica(&id)).unwrap().execute("VACUUM INTO ?1", [held.to_str().unwrap()]).unwrap(); assert!(!cotton_client::unsent::unsent_changes(&held).unwrap().is_empty(), "the copy holds a change the server never took"); std::fs::write(aside.join("database.id"), &id).unwrap();let old = chrono::Utc::now().timestamp() - 40 * 86_400; write_state(&a, &json!({ "days": 40, "day": "2000-01-01", "earlier": [{ "at": "2026-10-01T08:00:00Z", "at_s": old, "aside": "20261001T080000Z", "day_at": 0 }] })); ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert!(aside.join("database").join("replica.db").exists(), "unsent changes keep it");// The same copy as the stale folder of another aside (ABSENCE 4, item H).let other = client_dir.join("backup-aside").join("20261002T080000Z"); std::fs::create_dir_all(other.join("stale")).unwrap(); std::fs::copy(&held, other.join("stale").join("replica.db")).unwrap(); write_state(&a, &json!({ "days": 40, "day": "2000-01-01", "earlier": [{ "at": "2026-10-02T08:00:00Z", "at_s": old, "aside": "20261002T080000Z", "day_at": 0 }] })); ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert!(other.join("stale").join("replica.db").exists(), "unsent changes in the stale folder keep it");}fn an_old_aside(handle: &CottonHandle, name: &str) -> std::path::PathBuf {let aside = handle.client().layout().client_dir().join("backup-aside").join(name); std::fs::create_dir_all(aside.join("database")).unwrap(); rusqlite::Connection::open(aside.join("database").join("replica.db")).unwrap().execute_batch("CREATE TABLE invented (x)").unwrap(); aside}/// ABSENCE 4, item G: an aside goes after 30 counted days, one a calendar day the phone is used; a clock set forward/// counts one day, not the jump.#[test]fn an_aside_goes_after_thirty_counted_days_never_by_the_clock_alone() {let dir = tempfile::tempdir().unwrap();let a = phone(&dir, "notes");let forty_ago = chrono::Utc::now().timestamp() - 40 * 86_400;// The clock says 40 days, but only 6 days were counted.let aside = an_old_aside(&a, "20261001T080000Z"); write_state(&a, &json!({ "days": 5, "day": "2000-01-01", "earlier": [{ "at": "2026-10-01T08:00:00Z", "at_s": forty_ago, "aside": "20261001T080000Z", "day_at": 0 }] })); ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert!(aside.exists(), "a clock set forward never prunes"); assert_eq!(state_of(&a)["days"], 6, "one day counted"); ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert_eq!(state_of(&a)["days"], 6, "the same day counts once");// Thirty counted days. write_state(&a, &json!({ "days": 29, "day": "2000-01-01", "earlier": [{ "at": "2026-10-01T08:00:00Z", "at_s": forty_ago, "aside": "20261001T080000Z", "day_at": 0 }] })); ask(&a, "backup.screen", json!({ "platform": "android", "store": {} })); assert!(!aside.exists(), "thirty counted days and the clock agree: it goes");}// ── the phone's callers of the one function, run by their own code (QUEUE BAD OP 5, the matrix) ─────────────────/// What a phone's database folder holds as it leaves: a change in a place of the store's list, or a file beside the/// copy.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enumPhoneHolds {/// A note written and never sent (`_outbox`).Queued,/// A change set aside because it did not read (`_parked`, held 3).SetAside,/// An upload not done (`_media` pending).Upload,/// Rows the server refused, kept beside the copy (`kept-rows.json`).KeptRows,/// The sites kept on this phone only (`sites.local.c1`).SitesLocal,/// A file nothing names.Unnamed,/// A copy that will not open.WillNotOpen,}const PHONE_HOLDS: [PhoneHolds; 7] = [PhoneHolds::Queued, PhoneHolds::SetAside, PhoneHolds::Upload, PhoneHolds::KeptRows, PhoneHolds::SitesLocal, PhoneHolds::Unnamed, PhoneHolds::WillNotOpen];/// A phone with its own database holding `holds`, closed (as at a launch); answers the phone, its database and the/// file that holds it, with its bytes.fn phone_holding(dir: &tempfile::TempDir, holds: PhoneHolds) -> (CottonHandle, String, std::path::PathBuf, Vec<u8>) {let handle = phone(dir, "notes"); write(&handle, "an invented note");if holds == PhoneHolds::Queued {// The note an adopt or a remake carries (the first), and the one it did not (the holding). write(&handle, "a note nothing carried"); }let database = handle.client().attached_database().expect("its own database");let replica = handle.client().layout().replica(&database);let folder = replica.parent().unwrap().to_path_buf(); handle.client().detach();let file = match holds {PhoneHolds::Queued => replica.clone(),PhoneHolds::SetAside | PhoneHolds::Upload => {let db = cotton_store::Driver::open(&replica).expect("the copy");if holds == PhoneHolds::SetAside { cotton_store::rejected::set_aside_undecodable(&db, "bad-aside", Some(&[0, 255]), None, "note", "note-damaged", "it does not read", "2026-09-08T09:00:00.000Z").expect("set aside"); } else { db.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')", &[]).expect("an upload not done"); } db.run("DELETE FROM _outbox", &[]).expect("only the one thing"); db.run("PRAGMA wal_checkpoint(TRUNCATE)", &[]).ok(); replica.clone() }PhoneHolds::KeptRows => folder.join("kept-rows.json"),PhoneHolds::SitesLocal => folder.join("sites.local.c1"),PhoneHolds::Unnamed => folder.join("a-note-someone-left"),PhoneHolds::WillNotOpen => replica.clone(), };match holds {PhoneHolds::KeptRows => std::fs::write(&file, br#"[{"table":"note","rowId":"n1","data":{"text":"refused"},"why":"a test","at":"2026-09-08T09:00:00.000Z"}]"#).unwrap(),PhoneHolds::SitesLocal => std::fs::write(&file, b"sealed sites kept on this phone only").unwrap(),PhoneHolds::Unnamed => std::fs::write(&file, b"something only this phone has").unwrap(),PhoneHolds::WillNotOpen => {for suffix in ["-wal", "-shm"] {let _ = std::fs::remove_file(format!("{}{suffix}", replica.display())); } std::fs::write(&replica, b"this is not a database, and it is somebody's").unwrap(); } _ => {} }if matches!(holds, PhoneHolds::KeptRows | PhoneHolds::SitesLocal | PhoneHolds::Unnamed) {// Only the file beside it: the note itself was sent.let db = cotton_store::Driver::open(&replica).expect("the copy"); db.run("DELETE FROM _outbox", &[]).ok(); db.run("UPDATE _writes SET held = 0", &[]).ok(); db.run("PRAGMA wal_checkpoint(TRUNCATE)", &[]).ok(); }let bytes = std::fs::read(&file).expect("the holding's bytes"); (handle, database, file, bytes)}fn every_file_under(dir: &std::path::Path) -> Vec<(String, Vec<u8>)> { walkdir(dir).into_iter().filter(|path| path.is_file()).map(|path| (path.file_name().unwrap().to_string_lossy().into_owned(), std::fs::read(&path).unwrap_or_default())).collect()}/// The op ids a caller carried, as an adopt or a remake answers them: the queued changes of the FIRST note when more/// than one note waits (the other is what nothing carried); none otherwise.fn carried_of(replica: &std::path::Path) -> Vec<String> {letOk(db) = rusqlite::Connection::open_with_flags(replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) else { returnVec::new() };let rows: Vec<(String, String)> = db .prepare("SELECT op_id, row_id FROM _outbox ORDER BY rowid") .and_then(|mut statement| statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?))).map(|rows| rows.flatten().collect())) .unwrap_or_default();let notes: std::collections::BTreeSet<&String> = rows.iter().map(|(_, row)| row).collect();match rows.first() {Some((_, first)) if notes.len() > 1 => rows.iter().filter(|(_, row)| row == first).map(|(op, _)| op.clone()).collect(), _ => Vec::new(), }}/// RULE (QUEUE BAD OP 5 and 6, the matrix): each phone caller of the one function, run by its own code with a real/// list of what it carried (the adopt's ending, an empty local database giving way, a restore's Undo window ending, a/// remake, the copy that waited for the data key, a copy that did not finish), x each thing a database's folder can/// hold that the server has not acknowledged or this phone alone has, x each stop: the bytes are on disk after, and/// listed as kept under the database they belong to (or, beside a copy that leaves alone, standing where they are/// read); nothing carried is listed. Prints the matrix and its cell count.#[test]fn every_phone_caller_keeps_what_its_folder_holds_through_a_kill() {use cotton_client::copy_keep::{self, Stop};const LIVE: &str = "the-signed-in-one";const RESTORED_TO: &str = "2026-11-20T08:00:00.000Z";typeRun = fn(&CottonHandle, &str, &[String]);// (name, the database it is kept under ("" = its own), whether the copy leaves alone (its folder stays), run)let callers: [(&str, &str, bool, Run); 8] = [ ("adopt's ending (end_adopt)", LIVE, false, |handle, database, carried| {crate::phone::adopt::end_adopt(handle.client().layout(), database, LIVE, carried.to_vec()); }), ("an empty local database gives way (give_way)", LIVE, false, |handle, database, _| {crate::phone::personal_object::give_way(handle.client().layout(), database, LIVE, "an empty local database gave way to the signed-in copy"); }), ("a restore's Undo window ended (prune_one)", "", false, |handle, database, _| {let layout = handle.client().layout().clone();let aside = layout.client_dir().join(super::ASIDE).join("20261001T080000Z");let folder = layout.replica(database).parent().unwrap().to_path_buf();if folder.exists() { std::fs::create_dir_all(&aside).unwrap(); std::fs::write(aside.join("database.id"), database).unwrap(); std::fs::rename(&folder, aside.join("database")).unwrap(); }if aside.exists() {let client = handle.client();let backup = super::Backup { client: &client, kit: "notes", app: "Words" }; backup.prune_one(&aside); } }),// QUEUE BAD OP 7: a kept folder that names no database is filed under the live one, never under "unknown". ("a restore's Undo window ended, no database.id (prune_one)", "", false, |handle, database, _| {let layout = handle.client().layout().clone();let aside = layout.client_dir().join(super::ASIDE).join("20261001T080000Z");let folder = layout.replica(database).parent().unwrap().to_path_buf();if folder.exists() { std::fs::create_dir_all(&aside).unwrap(); std::fs::rename(&folder, aside.join("database")).unwrap(); }if aside.exists() {let client = handle.client();let backup = super::Backup { client: &client, kit: "notes", app: "Words" }; backup.prune_one(&aside); } }), ("a remake (end_remade)", "", true, |handle, database, carried| {let client = handle.client();let layout = client.layout();let sent = crate::phone::personal_object::SentWhole { acknowledged: carried.to_vec(), ..Default::default() };let _ = crate::phone::personal_object::end_remade(layout, database, &layout.replica(database), "was made again in a test", &sent); }), ("the copy that waited for the data key (end_waiting)", "", true, |handle, database, carried| {let client = handle.client();let layout = client.layout();let replica = layout.replica(database);let waiting = crate::phone::personal_object::waiting_copy(layout, database);if replica.exists() && !waiting.exists() { std::fs::create_dir_all(waiting.parent().unwrap()).unwrap();for suffix in ["", "-wal", "-shm"] {let _ = std::fs::rename(format!("{}{suffix}", replica.display()), format!("{}{suffix}", waiting.display())); } }let sent = crate::phone::personal_object::SentWhole { acknowledged: carried.to_vec(), ..Default::default() };let _ = crate::phone::personal_object::end_waiting(layout, database, &waiting, &sent); }), ("a copy that did not finish being made (remove_copy)", "", true, |handle, database, _| {let client = handle.client();let layout = client.layout();crate::phone::personal_object::remove_copy(layout, database, &layout.replica(database)); }),// RESTORE 2: the copy the server's restore left behind, the rows refused beside it with it; kept marked as from// before the restore, so recovery lists it and never sends it (asserted below). ("the copy a restore left behind (end_restored)", "", true, |handle, database, _| {let client = handle.client();let layout = client.layout();let _ = crate::phone::personal_object::end_restored(layout, database, &layout.replica(database), RESTORED_TO); }), ];let kills = [None, Some(Stop::FailMove), Some(Stop::BeforeMove), Some(Stop::BeforeSettle)];letmut lines = vec!["| caller | holds | stop | carried | bytes | listed |".to_string(), "|---|---|---|---|---|---|".to_string()];for (name, belongs, alone, run) in callers {for holds in PHONE_HOLDS {for kill in kills {let dir = tempfile::tempdir().unwrap();let (handle, database, file, bytes) = phone_holding(&dir, holds);let carried = carried_of(&handle.client().layout().replica(&database));let label = format!("{name} | {holds:?} | {}", kill.map_or("none".into(), |kill| format!("{kill:?}"))); copy_keep::stop_for_tests(kill); run(&handle, &database, &carried); copy_keep::stop_for_tests(None);// The next launch: the kept copies looked at, the same caller again.let belongs = if belongs.is_empty() { database.clone() } else { belongs.to_string() };let _ = copy_keep::kept(handle.client().layout(), Some(&belongs)); run(&handle, &database, &carried);let name_of = file.file_name().unwrap().to_string_lossy().into_owned();// A restore makes the refused rows the copy's own file (`replica.db.kept-rows.json`), bytes unchanged.let restored_name = (name.contains("end_restored") && holds == PhoneHolds::KeptRows).then(|| format!("replica.db.{name_of}"));let named = |held_as: &str| held_as == name_of || restored_name.as_deref() == Some(held_as); assert!(every_file_under(dir.path()).iter().any(|(held_as, held)| named(held_as) && *held == bytes), "{label}: its bytes are on disk");let listed = copy_keep::kept_changes(handle.client().layout(), &belongs);let beside = matches!(holds, PhoneHolds::KeptRows | PhoneHolds::SitesLocal | PhoneHolds::Unnamed);let in_place = std::fs::read(&file).ok().as_ref() == Some(&bytes); assert!(!listed.is_empty() || (alone && beside && in_place), "{label}: listed under {belongs}, or standing where it is read"); assert!(listed.iter().all(|change| !carried.contains(&change.op_id)), "{label}: nothing carried is listed: {listed:?}");if name.contains("end_restored") {// Every kept copy marked as from before the restore, and the refused rows never left beside the copy for// a pass to post (that recovery sends none of it: copy_keep_tests a_copy_from_before_a_restore_...).let copies = copy_keep::kept(handle.client().layout(), Some(&belongs)); assert!(copies.iter().all(|copy| copy.state.before_restore.as_deref() == Some(RESTORED_TO)), "{label}: marked as from before the restore");if holds == PhoneHolds::KeptRows { assert!(cotton_client::unsent::kept_rows(handle.client().layout(), &database).is_empty(), "{label}: no pass posts the refused rows"); assert!(!listed.is_empty(), "{label}: the refused rows are listed"); } }let said = if listed.is_empty() { "stays where it is read".to_string() } else { format!("listed ({})", listed.len()) }; lines.push(format!("| {label} | {} | on disk | {said} |", carried.len())); } } } println!("{}", lines.join("\n"));let cells = lines.len() - 2; println!("{cells} cells: {} phone callers x {} holdings x {} stops", callers.len(), PHONE_HOLDS.len(), kills.len()); assert_eq!(cells, callers.len() * PHONE_HOLDS.len() * kills.len());}