//! Stripping a copy for a phone: what goes and what stays.usesuper::*;usecrate::create::create_workspace;usecrate::meta::Meta;const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111";const AT: &str = "2026-09-11T10:00:00.000Z";fn copy() -> Driver {let db = Driver::open_in_memory().expect("an in-memory file"); create_workspace( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: "owner-1".to_string(),// The SERVER's, which is the whole reason a copy has to be claimed. device_id: "device:serving-mac".to_string(), last_server_seq: 0, last_hlc: None, }, ) .expect("the ladder runs"); db.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)", &[SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text("Owner".to_string()),SqlValue::Text("owner-1".to_string()),SqlValue::Text(AT.to_string()), ], ) .expect("the workspace row"); db}fn rows(db: &Driver, table: &str) -> i64 { db.get(&format!("SELECT COUNT(*) AS n FROM {table}"), &[]) .expect("the count runs") .and_then(|row| row.int("n")) .unwrap_or(-1)}#[test]fn the_outbox_is_emptied_by_the_strip_so_the_claim_never_has_to() {// The claim runs on a device; the strip runs on the SERVER's own copy. A// queued op in a copy is the server's, and pushing it back up would be this// device claiming somebody else's write — so it goes here, where the only// rows in reach belong to the file being copied. The claim deliberately// does not touch `_outbox` at all: a device joining with data keeps// everything it has queued.let db = copy(); db.run("INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes)\n VALUES ('op-1', 'create', 'server:mcp', 'cotton_todos', 'todo-1', 'h', 1, ?, X'7b7d')", &[SqlValue::Text(AT.to_string())], ) .expect("a queued op"); strip_for_phone(&db).expect("the strip runs"); assert_eq!(rows(&db, "_outbox"), 0);}#[test]fn empties_every_declared_table_and_leaves_the_life_alone() {let db = copy(); db.run("INSERT INTO cotton_todos (id, workspace_id, title, status, priority, created_at, updated_at) \ VALUES ('todo-1', ?, 'buy cardamom', 'open', 0, ?, ?)", &[SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text(AT.to_string()),SqlValue::Text(AT.to_string()), ], ) .expect("a todo"); db.run("INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes)\n VALUES ('op-1', 'create', 'server:mcp', 'cotton_todos', 'todo-1', 'h', 1, ?, X'7b7d')", &[SqlValue::Text(AT.to_string())], ) .expect("a queued op");let counts = strip_for_phone(&db).expect("the strip runs"); assert_eq!(rows(&db, "_outbox"), 0);// The LIFE is untouched — that is the whole point of the named list. assert_eq!(rows(&db, "cotton_todos"), 1);// And the search index still answers, because `fts_*` is deliberately kept// (see the module doc): a phone must not have to rebuild one before it can// paint its first screen. assert!(rows(&db, "fts_todos") >= 1, "the search index travelled");let named: Vec<&str> = counts .emptied .iter() .map(|(name, _)| name.as_str()) .collect(); assert!(named.contains(&"_outbox"));}#[test]fn a_table_the_server_never_created_is_skipped_not_an_error() {// `_media_feature_prints` and `_media_face_embeddings` are made lazily by// the analyze worker, so a file whose owner has never had a photo analysed// has neither.let db = copy(); assert!(!table_exists(&db, "_media_feature_prints").expect("the lookup runs"));let counts = strip_for_phone(&db).expect("the strip runs");let named: Vec<&str> = counts .emptied .iter() .map(|(name, _)| name.as_str()) .collect(); assert!(!named.contains(&"_media_feature_prints"));}#[test]fn every_declared_table_carries_its_reason() {// A list entry with no sentence is a table somebody dropped from a person's// database without saying why.for (table, why) in NOT_ON_A_PHONE { assert!(!table.is_empty()); assert!(why.len() > 20, "{table} needs a reason, not a label"); }}/// RULE: A phone cut keeps receipts only for rows it carries, and records the full cut's ceilings before filtering so claiming it cannot replay or reject the dropped writes.#[test]fn a_cut_drops_orphan_receipts_and_preserves_full_ceilings() {let db = crate::test_support::seeded_file("device:serving-mac");let author = "device:cut-author";for (id, ms) in [("kept", 100), ("dormant", 200)] {crate::test_support::fold_create( &db,"cotton_todos", id, serde_json::json!({"workspace_id": crate::test_support::WORKSPACE,"title": id, "status": "open", "created_at": AT, "updated_at": AT}), author, ms, ); }// A dormant row has receipts but no table row. The live Mac keeps those// for undo; the phone's cut carries only rows it can show. db.run("DELETE FROM cotton_todos WHERE id = 'dormant'", &[]) .unwrap();crate::test_support::fold_create( &db,"cotton_mcp_audit","audit", serde_json::json!({"workspace_id": crate::test_support::WORKSPACE,"token_id": "invented-token", "tool": "invented.tool", "ok": true, "created_at": AT}), author,300, ); assert!(!crate::receipts::of_row(&db, "cotton_mcp_audit", "audit") .unwrap() .is_empty()); db.run("INSERT INTO _tombstones (tbl,row_id,hlc,op_id,author,actor,bytes) VALUES ('cotton_todos','deleted','0000000000400:0000:device:cut-author','deleted-op',?,'test',X'7b7d')", &[author.to_owned().into()]).unwrap();let ceilings = crate::cursors::seen_ceiling(&db).unwrap(); assert!(crate::cursors::read_cursors(&db).unwrap().is_empty()); strip_for_phone(&db).unwrap(); assert_eq!(crate::receipts::of_row(&db, "cotton_todos", "dormant") .unwrap() .len(),0 ); assert!(!crate::receipts::of_row(&db, "cotton_todos", "kept") .unwrap() .is_empty()); assert_eq!(rows(&db, "cotton_mcp_audit"), 0); assert!(crate::receipts::of_row(&db, "cotton_mcp_audit", "audit") .unwrap() .is_empty()); assert_eq!( rows(&db, "_tombstones"),1,"retracts outlive their absent rows" ); assert_eq!(crate::cursors::read_cursors(&db).unwrap(), ceilings); assert_eq!(crate::cursors::seen_ceiling(&db).unwrap(), ceilings);for spec incrate::schema::table_specs::TABLE_SPECS {let sql = format!("SELECT 1 FROM _writes w WHERE tbl = ? AND NOT EXISTS (SELECT 1 FROM \"{}\" r WHERE r.\"{}\" = w.row_id) LIMIT 1", spec.name, spec.pk); assert!( db.get(&sql, &[spec.name.to_owned().into()]) .unwrap() .is_none(),"{} left an orphan receipt", spec.name ); }}/// RULE: Snapshot receipt pruning uses each table's primary key, including installed package tables, so a cut never discards a present package row's receipts by assuming its key is id.#[test]fn a_cut_matches_package_receipts_by_the_tables_primary_key() {let db = copy(); db.exec("CREATE TABLE installed_receipt_rows (record_key TEXT PRIMARY KEY); INSERT INTO installed_receipt_rows VALUES ('kept')").unwrap();for id in ["kept", "absent"] { db.run("INSERT INTO _writes (tbl,row_id,hlc,op_id,bytes) VALUES ('installed_receipt_rows',?,'0000000000001:0000:device:package',?,X'7b7d')", &[id.to_owned().into(), format!("package-op-{id}").into()]).unwrap(); } strip_for_phone(&db).unwrap();let row = db.get("SELECT row_id FROM _writes WHERE tbl = 'installed_receipt_rows'", &[]).unwrap().unwrap(); assert_eq!(row.text("row_id"), Some("kept")); assert_eq!(rows(&db, "_writes"), 1);}/// RULE: Held and absent-row receipts leave no owner relationships in a snapshot, because ownership belongs to the receipt rather than to a historical row id.#[test]fn snapshot_receipt_deletions_cascade_to_owner_references() {let db = crate::test_support::seeded_file("device:owner-snapshot");for (id,held) in [("absent",false),("held",true)] {let receipt = crate::canonical::Receipt { table:"cotton_emails".into(), row_id:id.into(), kind:crate::canonical::Kind::Change, stamp:format!("0000000000100:0000:device:{id}"), author:format!("device:{id}"), actor:crate::fixtures::fixture_actor().to_wire(), schema:crate::schema::ddl::SCHEMA_VERSION, restamps:None,erase:None,undo:None, fields:[("thread_id".into(),serde_json::json!("thread"))].into_iter().collect(), };let op=crate::wire::from_receipt(format!("op-{id}"),&receipt).unwrap();crate::receipts::store(&db,&op,&receipt,held).unwrap(); } assert_eq!(rows(&db,"_writes_owners"),2); strip_for_phone(&db).unwrap(); assert_eq!(rows(&db,"_writes_owners"),0);crate::test_support::assert_receipt_owners_are_attached(&db);}