//! A copy another build stamped, moved in place or held with its unsent //! changes, a copy an update set aside put back, and the erase guard. use cotton_store::driver::Driver; use cotton_store::schema::ddl::SCHEMA_VERSION; use crate::layout::Layout; use crate::replica::{open_replica_with, OpenReplicaInput, ReplicaError}; use crate::seams::{Clock, FixedClock, SeededRandom}; use crate::test_support::{temp_layout, write_snapshot, WORKSPACE}; use super::*; /// A whole synthetic workspace file, as the server served it — the server's /// own device id stamped in it and `writes` rows the server authored. /// /// The rows are real and STAMPED, because that is what the claim reads its /// cursors off: there is no op log and no server sequence, and a file's idea of /// how far it has seen each author comes from the rows themselves. fn served_copy(dir: &std::path::Path, writes: i64) -> std::path::PathBuf { let path = dir.join("served.db"); write_snapshot(&path); let db = Driver::open(&path).expect("the file"); for seq in 1..=writes { cotton_tools::test_fixtures::fold_create( &db, "cotton_todos", &format!("todo-{seq}"), serde_json::json!({ "title": "Call the bank", "status": "open", "created_at": "2026-09-08T10:00:00.000Z", "updated_at": "2026-09-08T10:00:00.000Z", "workspace_id": WORKSPACE, }), &format!("1787394600000:{seq:04}:device:the-server"), "device:the-server", ); } db.run( "UPDATE _meta SET device_id = 'device:the-server'", &[], ) .expect("the server's own stamp"); drop(db); path } /// How far the claimed file says it has seen each author. fn cursors(db: &Driver) -> std::collections::BTreeMap { cotton_store::cursors::read_cursors(db).expect("the cursors read") } /// A whole phone copy, opened once from a snapshot holding `writes` todos, /// then put one schema back the way a bump finds it: stamped one below /// `SCHEMA_VERSION` and missing an index this build's DDL has, its outbox /// sent. Answers the index's name. fn copy_one_schema_back(dir: &std::path::Path, layout: &Layout, writes: i64) -> String { let served = served_copy(dir, writes); let clock = FixedClock::default_start(); let mut ids = crate::test_support::fresh_ids(); let mut claim = |driver: &Driver, device_id: &str| { claim_snapshot(driver, device_id, 0, clock.now().timestamp_millis(), &mut ids) .map(|_| ()) .map_err(ReplicaError::Store) }; drop( open_replica_with(OpenReplicaInput { layout, workspace_id: WORKSPACE, clock: &clock, random: &SeededRandom::default(), judge: None, bootstrap: &mut crate::test_support::bootstrap_from(served), on_migration: None, on_bootstrapped: Some(&mut claim), receipt_signer: cotton_store::signed::SignerSlot::default(), }) .expect("the copy arrives"), ); let db = Driver::open(layout.replica(WORKSPACE)).expect("the copy"); let index = db .get("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'cotton_todos' AND sql IS NOT NULL ORDER BY name LIMIT 1", &[]) .expect("reads") .and_then(|row| row.text("name").map(str::to_string)) .expect("cotton_todos has an index"); db.exec(&format!("DELETE FROM _outbox; DROP INDEX {index}; PRAGMA user_version = {}", SCHEMA_VERSION - 1)).expect("one schema back"); index } fn device_copy_at_141(layout: &Layout) -> Driver { device_copy_at_shape( layout, 141, include_str!("../../../cotton-store/tests/fixtures/schema-v141.json"), ) } fn device_copy_at_shape(layout: &Layout, version: u32, shape: &str) -> Driver { let path = layout.replica(WORKSPACE); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); let db = Driver::open(path).unwrap(); let objects: Vec = serde_json::from_str(shape).unwrap(); for phase in ["table", "fts", "index", "trigger"] { for object in &objects { let kind = if object.is_fts5_virtual() { "fts" } else { &object.kind }; if kind == phase { db.exec(&object.sql).unwrap(); } } } db.run("INSERT INTO _meta(only_one,workspace_id,owner_id,schema_version,device_id) VALUES (1,?,'synthetic-owner',?,'device:phone')", &[rusqlite::types::Value::Text(WORKSPACE.into()), i64::from(version).into()]).unwrap(); crate::test_support::seed_workspace_row(&db); db.run("INSERT INTO cotton_devices(id,workspace_id,device_id,name,approved_at,approved_by_device,created_at,updated_at,_hlc) VALUES ('synthetic-device',?,'device:phone','Synthetic phone','2026-10-11T00:00:00Z','device:mac','2026-10-11T00:00:00Z','2026-10-11T00:00:00Z','1791676800000:0001:device:phone')", &[rusqlite::types::Value::Text(WORKSPACE.into())]).unwrap(); db.run("INSERT INTO cotton_device_keep(id,workspace_id,device_id,kind,target,rule,created_at,updated_at,_hlc) VALUES ('synthetic-keep',?,'device:phone','table','cotton_todos','all','2026-10-11T00:00:00Z','2026-10-11T00:00:00Z','1791676800000:0001:device:phone')", &[rusqlite::types::Value::Text(WORKSPACE.into())]).unwrap(); db.run("INSERT INTO cotton_home_arrangement(workspace_id,tools,view_ids,created_at,updated_at,_hlc) VALUES (?, '[\"notes\",\"messages\"]', '[\"calendar\"]', '2026-10-11T00:00:00Z', '2026-10-11T00:00:00Z', '1791676800000:0001:device:phone')", &[rusqlite::types::Value::Text(WORKSPACE.into())]).unwrap(); db.run("INSERT INTO _media(key,workspace_id,sha256,content_type,size_bytes,state,created_at,updated_at) VALUES ('synthetic-original',?,'synthetic-sha','text/plain',1,'synced','2026-10-11T00:00:00Z','2026-10-11T00:00:00Z')", &[rusqlite::types::Value::Text(WORKSPACE.into())]).unwrap(); cotton_tools::test_fixtures::fold_create( &db, "cotton_todos", "synthetic-todo", serde_json::json!({ "title": "A synthetic task", "status": "open", "workspace_id": WORKSPACE, "created_at": "2026-10-11T00:00:00Z", "updated_at": "2026-10-11T00:00:00Z" }), "1791676800000:0002:device:mac", "device:mac", ); // Freeze the receipt's mint schema too: a previous-build device copy // carries previous-build canonical bytes, not just an older DDL stamp. for row in db.all("SELECT op_id,bytes FROM _writes", &[]).unwrap() { let rusqlite::types::Value::Blob(bytes) = row.get("bytes").unwrap() else { panic!("receipt bytes"); }; let mut receipt = cotton_store::canonical::decode(bytes).unwrap(); receipt.schema = version; db.run( "UPDATE _writes SET bytes=? WHERE op_id=?", &[ rusqlite::types::Value::Blob(cotton_store::canonical::encode(&receipt).unwrap()), row.get("op_id").unwrap().clone(), ], ) .unwrap(); } for (author, top) in cotton_store::cursors::cursor_ceiling(&db).unwrap() { cotton_store::cursors::advance_cursor(&db, &author, &top, "2026-10-11T00:00:00Z").unwrap(); cotton_store::cursors::advance_cursor( &db, &cotton_store::changes::late_cursor_key(&author), &top, "2026-10-11T00:00:00Z", ) .unwrap(); } db.exec(&format!( "DELETE FROM _outbox; PRAGMA user_version={version}" )) .unwrap(); db } /// RULE: An update moves a level device copy across every intervening shape without rewinding asked_from or changing its receipts; re-copying the owner's database wastes a whole download. #[test] fn a_level_schema141_device_copy_moves_without_rewinding_or_receipts() { let (_dir, layout) = temp_layout(); let db = device_copy_at_141(&layout); let before = cursors(&db); let cursor_rows = db .all("SELECT * FROM _cursors ORDER BY author_device_id", &[]) .unwrap(); let receipts = db.all("SELECT tbl, row_id, hlc, author, op_id, kind, actor, held, mint_cont, mint_boot, bytes, fields, sig FROM _writes ORDER BY op_id", &[]).unwrap(); assert_eq!( cotton_store::changes::receipts_past(&db, &before, u64::MAX).unwrap(), 0 ); drop(db); assert_eq!( crate::dev_heal::heal_stale_replica( &layout, WORKSPACE, Some(cotton_core::flavor::Flavor::Real), None ), Some(crate::dev_heal::Heal::Moved { stamped: 141 }) ); let db = Driver::open(layout.replica(WORKSPACE)).unwrap(); let asked = cotton_store::exchange::exchange_request( &db, WORKSPACE, None, &mut cotton_store::exchange::Handover::default(), ) .unwrap() .request .cursors; assert_eq!(asked, before); assert_eq!( db.all("SELECT * FROM _cursors ORDER BY author_device_id", &[]) .unwrap(), cursor_rows ); assert_eq!( db.all("SELECT tbl, row_id, hlc, author, op_id, kind, actor, held, mint_cont, mint_boot, bytes, fields, sig FROM _writes ORDER BY op_id", &[]).unwrap(), receipts ); assert_eq!( cotton_store::changes::receipts_past(&db, &asked, u64::MAX).unwrap(), 0 ); } /// RULE: A mover never stamps a row it did not fill, because a schema-only update must not turn unchanged records into new sync writes. #[test] fn a_device_shape_move_keeps_unfilled_row_stamps() { let (_dir, layout) = temp_layout(); let db = device_copy_at_141(&layout); let stamps = |db: &Driver| { ["cotton_todos", "cotton_devices", "cotton_device_keep"] .into_iter() .map(|table| { ( table, db.all( &format!("SELECT rowid,_hlc,_born FROM {table} ORDER BY rowid"), &[], ) .unwrap(), ) }) .collect::>() }; let before = stamps(&db); cotton_store::shape_move::move_to_current(&db).unwrap(); assert_eq!(stamps(&db), before); } /// RULE: a .before-update left beside a copy from an earlier cycle never blocks: it is removed when it holds nothing the live copy lacks, and kept while the live copy is not yet claimed by this device (its claim still reads it) — 255 stopped on "a previous copy is still waiting for its replacement to open". #[test] fn a_leftover_predecessor_never_blocks_and_goes_when_spent() { let (dir, layout) = temp_layout(); copy_one_schema_back(dir.path(), &layout, 2); let live = layout.replica(WORKSPACE); let saved = previous::path(&live); std::fs::copy(&live, &saved).unwrap(); assert_eq!( crate::dev_heal::heal_stale_replica(&layout, WORKSPACE, Some(cotton_core::flavor::Flavor::Real), None), Some(crate::dev_heal::Heal::Moved { stamped: SCHEMA_VERSION - 1 }) ); assert!(!saved.exists(), "the spent predecessor went"); // Beside a copy not yet claimed by this device, it is kept. std::fs::copy(&live, &saved).unwrap(); Driver::open(&live).unwrap().exec("UPDATE _meta SET device_id = 'device:the-server'").unwrap(); assert!(!previous::release_if_spent(&layout, WORKSPACE)); assert!(saved.exists(), "an unclaimed copy's claim still reads it"); } /// Park one push the Mac refused for good in the copy at `path`. fn park_a_refusal(path: &std::path::Path) { Driver::open(path).unwrap().exec( "INSERT INTO _parked (op_id, direction, class, reason, bytes, tbl, row_id) \ SELECT 'op-refused', 'push', 'conflict', 'refused by the serving Mac', bytes, tbl, row_id FROM _writes LIMIT 1", ).unwrap(); } /// RULE: a copy whose only unsent changes are pushes the Mac refused for good (parked conflict or gone) moves in place at a schema bump with its parks kept, and stays where it is — never discarded — if the move cannot run; two Macs stayed shut on one or two such parks (11 Oct 2026). #[test] fn a_copy_holding_only_refused_pushes_moves_in_place_with_them() { let (dir, layout) = temp_layout(); copy_one_schema_back(dir.path(), &layout, 2); let path = layout.replica(WORKSPACE); park_a_refusal(&path); let real = Some(cotton_core::flavor::Flavor::Real); assert_eq!( crate::dev_heal::heal_stale_replica(&layout, WORKSPACE, real, None), Some(crate::dev_heal::Heal::Moved { stamped: SCHEMA_VERSION - 1 }) ); let db = Driver::open(&path).unwrap(); assert_eq!(cotton_store::migrate::current_version(&db).unwrap(), SCHEMA_VERSION); let parked = db.get("SELECT COUNT(*) AS n FROM _parked WHERE op_id = 'op-refused'", &[]).unwrap().and_then(|r| r.int("n")); assert_eq!(parked, Some(1), "the refusal moved with the copy, still on the owner's board"); drop(db); // A move that cannot run leaves the copy: a refusal is never a reason to discard. let (dir, layout) = temp_layout(); copy_one_schema_back(dir.path(), &layout, 1); let path = layout.replica(WORKSPACE); park_a_refusal(&path); let below = cotton_store::shape_move::LEDGER_BASE - 1; Driver::open(&path).unwrap().exec(&format!("PRAGMA user_version = {below}")).unwrap(); assert!(matches!( crate::dev_heal::heal_stale_replica(&layout, WORKSPACE, real, None), Some(crate::dev_heal::Heal::NotMoved { stamped, .. }) if stamped == below )); assert!(path.exists()); } // ── the first open ──────────────────────────────────────────────────────── // ── single-flight ───────────────────────────────────────────────────────── // ── probation ───────────────────────────────────────────────────────────── // ── the sweep ───────────────────────────────────────────────────────────── /// RULE: a replica takes `erase` only from a serving epoch it has handed over to and not below the newest it has heard of — never from a Mac that took over before its hand-over, nor from an old Mac come back. /// /// Until the phone hands over, a device kept at the take-over that the owner /// had revoked after the restore point is a full device on the new Mac, and /// its *Remove and erase* of the phone would wipe the only copy of every write /// since the restore point. `false` asks the person instead. #[test] fn unstruck_device_cannot_erase_the_phone_before_its_handover() { let cases: [(&str, &str, Option, bool); 8] = [ ("no epoch anywhere, a refusal naming none", "", None, true), ("no epoch anywhere, a refusal naming one", "", Some(1), false), ( "handed over to 1, refused by 1", "UPDATE _meta SET handed_over_epoch = 1, heard_serving_epoch = 1", Some(1), true, ), ( "handed over to 1, refused by the Mac that took over at 2", "UPDATE _meta SET handed_over_epoch = 1, heard_serving_epoch = 2", Some(2), false, ), ( "never handed over, refused by 2", "UPDATE _meta SET heard_serving_epoch = 2", Some(2), false, ), ( "handed over to 2, refused by the old Mac at 1", "UPDATE _meta SET handed_over_epoch = 2, heard_serving_epoch = 2", Some(1), false, ), ( "an epoch heard, a refusal naming none", "UPDATE _meta SET handed_over_epoch = 2, heard_serving_epoch = 2", None, false, ), ( "handed over to 2, refused by 2", "UPDATE _meta SET handed_over_epoch = 2, heard_serving_epoch = 2", Some(2), true, ), ]; for (what, sql, named, erases) in cases { let (_dir, layout) = temp_layout(); let live = a_replica_already_here(&layout); let db = Driver::open(&live).expect("the live file"); if !sql.is_empty() { db.exec(sql).expect(what); } assert_eq!(super::may_erase(&db, named).expect("a read"), erases, "{what}"); assert_eq!(super::may_erase_at(&live, named), erases, "{what}, by path"); } let (_dir, layout) = temp_layout(); assert!( super::may_erase_at(&layout.replica("no-such-database"), Some(3)), "no copy here, nothing to keep" ); } fn a_replica_already_here(layout: &crate::Layout) -> std::path::PathBuf { let path = layout.replica(WORKSPACE); std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder"); write_snapshot(&path); path } /// RULE: Every schema rise must move a device copy cut in the previous build's frozen shape, with local state and receipts intact; a Mac-only move proof missed a full phone re-download. #[test] fn the_previous_builds_device_copy_moves_with_its_local_state() { let (_dir, layout) = temp_layout(); let previous = SCHEMA_VERSION - 1; let shape = std::fs::read_to_string(cotton_store::manifest_dir().join( format!("../cotton-store/tests/fixtures/schema-v{previous}.json"), )) .expect("freeze the previous build's shape before a schema rise"); let db = device_copy_at_shape(&layout, previous, &shape); let before = cursors(&db); let receipts = db.all("SELECT tbl, row_id, hlc, author, op_id, kind, actor, held, mint_cont, mint_boot, bytes, fields, sig FROM _writes ORDER BY op_id", &[]).unwrap(); let media = db .all("SELECT key,local_path,state FROM _media ORDER BY key", &[]) .unwrap(); drop(db); assert_eq!( crate::dev_heal::heal_stale_replica( &layout, WORKSPACE, Some(cotton_core::flavor::Flavor::Real), None ), Some(crate::dev_heal::Heal::Moved { stamped: previous }) ); let db = Driver::open(layout.replica(WORKSPACE)).unwrap(); assert_eq!(cursors(&db), before); assert_eq!( db.all("SELECT tbl, row_id, hlc, author, op_id, kind, actor, held, mint_cont, mint_boot, bytes, fields, sig FROM _writes ORDER BY op_id", &[]).unwrap(), receipts ); assert_eq!( db.all("SELECT key,local_path,state FROM _media ORDER BY key", &[]) .unwrap(), media ); } /// RULE: an in-place move is heard as it runs — `Start` naming the schema it moves to, a `Step` per finished step counting up to the total, then `Done` — because a move that said nothing left the phone on "Opening your database" for two minutes and offered Try again and Join over it (build 264, 13 Oct 2026). #[test] fn an_in_place_move_reports_its_steps_and_the_schema_it_moves_to() { use crate::replica::MigrationEvent; let (dir, layout) = temp_layout(); copy_one_schema_back(dir.path(), &layout, 2); let mut heard = Vec::new(); let heal = crate::dev_heal::heal_stale_replica( &layout, WORKSPACE, Some(cotton_core::flavor::Flavor::Real), Some(&mut |event| heard.push(event)), ); assert_eq!(heal, Some(crate::dev_heal::Heal::Moved { stamped: SCHEMA_VERSION - 1 })); let Some(MigrationEvent::Start { from, to, total }) = heard.first().cloned() else { panic!("the move starts by saying so: {heard:?}"); }; assert_eq!((from, to), (SCHEMA_VERSION - 1, SCHEMA_VERSION)); let steps: Vec = heard .iter() .filter_map(|event| match event { MigrationEvent::Step { version, index, total: of } => { assert_eq!((*version, *of), (SCHEMA_VERSION, total), "{heard:?}"); Some(*index) } _ => None, }) .collect(); assert_eq!(steps, (1..=total).collect::>(), "every step, in order, to the total"); assert!( matches!(heard.last(), Some(MigrationEvent::Done { to, .. }) if *to == SCHEMA_VERSION), "{heard:?}" ); }