//! What a leave takes, and the two things it must not. use super::*; use crate::connection::{ConnectionMode, StoredConnection}; use crate::test_support::{temp_layout, WORKSPACE}; fn joined(layout: &Layout) -> ConnectionFile { let connection = ConnectionFile::at(layout.connection_json()); connection .write(StoredConnection { device_scope: None, takes_placements: false, mode: ConnectionMode::Remote, base_url: "https://studio.relay.cottondb.com".to_string(), workspace_id: Some(WORKSPACE.to_string()), owner_id: Some("owner-99".to_string()), connected_at: Some("2026-09-08T10:00:00.000Z".to_string()), }) .expect("the file"); connection } const LEFTOVER_SUFFIXES: &[&str] = &["-wal", "-shm", ".download", ".download.size"]; fn write_replica_and_leftovers(layout: &Layout) -> std::path::PathBuf { let replica = layout.replica(WORKSPACE); std::fs::create_dir_all(replica.parent().expect("the folder")).expect("the folder"); std::fs::write(&replica, b"SQLite format 3\0").expect("the replica"); for suffix in LEFTOVER_SUFFIXES { let mut name = replica.as_os_str().to_string_lossy().to_string(); name.push_str(suffix); std::fs::write(name, b"leftovers").expect("a leftover"); } replica } /// RULE: Leaving removes an update's saved predecessor too, because a disconnected device must not retain a readable copy of that database. #[test] fn leaving_removes_the_saved_predecessor() { let (_dir, layout) = temp_layout(); let connection = joined(&layout); let path = write_replica_and_leftovers(&layout); let saved = path.with_file_name("replica.db.before-update"); std::fs::write(&saved, b"synthetic predecessor").unwrap(); leave_server(&layout, &connection, Some(WORKSPACE)); assert!(!saved.exists()); } /// RULE: Leaving removes every readable replica and sidecar plus its cached address, so a disconnected database cannot remain accessible. #[test] fn it_forgets_the_address_the_workspace_cache_the_replica_and_every_sidecar() { let (_dir, layout) = temp_layout(); let connection = joined(&layout); let replica = write_replica_and_leftovers(&layout); let left = leave_server(&layout, &connection, Some(WORKSPACE)); assert!(left.forgot_server); assert!(left.deleted_replica); for suffix in LEFTOVER_SUFFIXES { assert!(!std::path::PathBuf::from(format!("{}{suffix}", replica.display())).exists(), "a disconnected database leaves no readable sidecar"); } assert!(!layout.connection_json().exists()); assert!(!replica.exists()); assert_eq!(connection.read(), None, "the cache went with the file"); } #[test] fn it_keeps_the_op_author_id_so_a_rejoin_is_the_same_device_to_the_file() { // A new author id would make the file's history read as a fleet of phones, // and the fold would stop recognising this device's own writes. let (_dir, layout) = temp_layout(); let connection = joined(&layout); let author = crate::replica::resolve_device_id( &layout, &crate::seams::FixedClock::default_start(), &crate::seams::SeededRandom::default(), ) .expect("an author id"); leave_server(&layout, &connection, Some(WORKSPACE)); assert!( crate::replica::device_file_path(&layout).exists(), "the op-author id survives the leave" ); let after = crate::replica::resolve_device_id( &layout, &crate::seams::FixedClock::default_start(), &crate::seams::SeededRandom::default(), ) .expect("an author id"); assert_eq!(after, author); } #[test] fn it_touches_no_key_material_because_the_key_is_not_in_this_crates_hands() { // The device key lives in the Keychain and reaches Rust as // `OpenConfig.deviceSecret`. A leave that minted a new one would mean // approving the same phone twice on a rejoin, and a dead row in the // server's device list every time. let (_dir, layout) = temp_layout(); let connection = joined(&layout); let rehearsal = layout.rehearsal_device_key(); std::fs::create_dir_all(rehearsal.parent().expect("the folder")).expect("the folder"); std::fs::write(&rehearsal, b"a synthetic seed").expect("the seed"); leave_server(&layout, &connection, Some(WORKSPACE)); assert!( rehearsal.exists(), "the device key is identity, not address" ); } #[test] fn leaving_with_no_workspace_named_forgets_the_address_and_stops_there() { let (_dir, layout) = temp_layout(); let connection = joined(&layout); let replica = write_replica_and_leftovers(&layout); let left = leave_server(&layout, &connection, None); assert!(left.forgot_server); assert!(!left.deleted_replica); assert!(replica.exists(), "no workspace named, no file identified"); } #[test] fn leaving_a_device_that_joined_nothing_is_not_an_error() { let (_dir, layout) = temp_layout(); let connection = ConnectionFile::at(layout.connection_json()); let left = leave_server(&layout, &connection, None); assert_eq!(left, Left::default()); } // ── the other verb: erase ───────────────────────────────────────────────── /// Everything an erase is supposed to find — the bytes, the scratch, the /// renditions, the export and the identity a LEAVE deliberately keeps. fn write_everything_a_device_holds(layout: &Layout) -> Vec { let mut written = Vec::new(); for folder in [ layout.client_media_dir(), layout.snapshots_dir(), layout.thumbs_cache_dir(), layout.exports_dir(), ] { std::fs::create_dir_all(folder.join("deep")).expect("the folder"); let file = folder.join("deep").join("something"); std::fs::write(&file, b"synthetic").expect("a file"); written.push(folder); } // The op-author id, which a leave keeps and an erase does not. crate::replica::resolve_device_id( layout, &crate::seams::FixedClock::default_start(), &crate::seams::SeededRandom::default(), ) .expect("an author id"); written.push(crate::replica::device_file_path(layout)); // A rehearsal build's device seed — the packaged app has none, and this is // the scratch-data-directory one. let rehearsal = layout.rehearsal_device_key(); std::fs::create_dir_all(rehearsal.parent().expect("the folder")).expect("the folder"); std::fs::write(&rehearsal, b"a synthetic seed").expect("the seed"); written.push(rehearsal); written } /// RULE: Erasing removes all device data and identity, so neither readable database bytes nor credentials survive the erase. #[test] fn an_erase_takes_the_server_the_file_the_bytes_and_the_identity() { let (_dir, layout) = temp_layout(); let connection = joined(&layout); let replica = write_replica_and_leftovers(&layout); let everything = write_everything_a_device_holds(&layout); let erased = erase_device(&layout, &connection, Some(WORKSPACE)); // The leave's half, whole. assert!(erased.left.forgot_server); assert!(erased.left.deleted_replica); assert!(!layout.connection_json().exists()); assert!(!replica.exists()); // And everything a leave keeps. assert!(erased.deleted_author_id); assert!(erased.deleted_rehearsal_key); for path in everything { assert!(!path.exists(), "{} survived an erase", path.display()); } assert!( !replica.parent().expect("the folder").exists(), "an empty folder named after a database this device no longer has" ); } #[test] fn an_erase_is_idempotent_because_the_state_it_wants_is_the_one_it_runs_in() { let (_dir, layout) = temp_layout(); let connection = joined(&layout); write_replica_and_leftovers(&layout); write_everything_a_device_holds(&layout); erase_device(&layout, &connection, Some(WORKSPACE)); let again = erase_device(&layout, &connection, Some(WORKSPACE)); assert_eq!( again, Erased::default(), "a second erase found nothing and said nothing went wrong" ); } #[test] fn an_erase_on_a_device_that_joined_nothing_is_not_an_error() { let (_dir, layout) = temp_layout(); let connection = ConnectionFile::at(layout.connection_json()); assert_eq!(erase_device(&layout, &connection, None), Erased::default()); } #[test] fn the_two_keychain_items_are_named_because_this_crate_cannot_reach_them() { // The device seed and the vault key are Keychain items the APP holds; they // reach Rust as `OpenConfig` values Swift read. An erase that quietly left // them would be a phone that comes back as the same device to a server that // has forgotten it — so the answer NAMES them, and `BootModel.resetKey` // already makes both calls. assert_eq!(super::KEYCHAIN_ITEMS, ["deviceKey", "vaultKey"]); } #[test] fn a_leave_is_not_an_erase_and_the_difference_is_the_whole_reason_for_two_verbs() { let (_dir, layout) = temp_layout(); let connection = joined(&layout); write_replica_and_leftovers(&layout); let everything = write_everything_a_device_holds(&layout); leave_server(&layout, &connection, Some(WORKSPACE)); for path in everything { assert!( path.exists(), "{} is the person's own material, and a leave does not touch it", path.display() ); } } #[test] fn an_erase_takes_every_place_s_replica_so_none_is_left_behind_as_a_stray() { // Left behind, a place's file is a database nothing has an address for, // and a stray refuses every later join: an erased phone that can never // join again. const PLACE: &str = "33333333-3333-4333-8333-333333333333"; let (_dir, layout) = temp_layout(); crate::test_support::write_record(&layout, WORKSPACE, ConnectionMode::Remote, &[PLACE]); let connection = ConnectionFile::at(layout.connection_json()); write_replica_and_leftovers(&layout); let place = crate::test_support::replica_with_rows(&layout, PLACE, 2); let erased = erase_device(&layout, &connection, Some(WORKSPACE)); assert_eq!(erased.deleted_places, 1); assert!(!place.exists()); assert!(!place.parent().expect("its folder").exists()); assert!(crate::join::held_workspaces(&layout, "").is_empty()); } // RULE: A leave deletes the replica of every other database the connection record names and drops held.json, so a rejoin never answers for a file that is no longer here. #[test] fn leaving_deletes_every_held_database_and_its_note() { const PLACE: &str = "33333333-3333-4333-8333-333333333333"; let (_dir, layout) = temp_layout(); crate::test_support::write_record(&layout, WORKSPACE, ConnectionMode::Remote, &[PLACE]); let connection = ConnectionFile::at(layout.connection_json()); write_replica_and_leftovers(&layout); let place = layout.replica(PLACE); std::fs::create_dir_all(place.parent().expect("the folder")).expect("the folder"); std::fs::write(&place, b"SQLite format 3\0").expect("the place's replica"); let notes = crate::connection::held::HeldNotes::beside(&layout.connection_json()); std::fs::write(notes.path(), br#"{"files":{}}"#).expect("the notes"); let left = leave_server(&layout, &connection, Some(WORKSPACE)); assert_eq!(left.deleted_databases, 1); assert!(!place.exists(), "the place's replica went with the server"); assert!(!notes.path().exists(), "held.json went with the server"); } #[test] fn leaving_one_database_keeps_personal_and_other_copies_and_listing_does_not_rejoin_it() { let (_dir, layout) = temp_layout(); let connection = joined(&layout); let personal = write_replica_and_leftovers(&layout); connection.add_made_place("garden", "Garden", None).unwrap(); connection.add_made_place("attic", "Attic", None).unwrap(); for id in ["garden", "attic"] { let replica = layout.replica(id); std::fs::create_dir_all(replica.parent().unwrap()).unwrap(); crate::test_support::write_snapshot_for(&replica, id); } assert!(leave_database(&layout, &connection, "garden", Unsent::Refuse).unwrap()); assert!(personal.exists()); assert!(layout.replica("attic").exists()); assert!(!layout.replica("garden").exists()); assert_eq!(connection.mine_id().as_deref(), Some(WORKSPACE)); assert_eq!(connection.read_record().unwrap().places[0].id, "attic"); let garden = crate::connection::list::ListedDatabase { id: "garden".into(), name: "Garden".into(), kind: "shared".into(), schema_version: 58, }; let listed = crate::connection::list::Listing { databases: vec![garden.clone()] }; assert!(connection.apply_listing(&listed, "2026-10-04").unwrap().new.is_empty()); // A later personal identity update also preserves the explicit leave. connection.write(connection.read().unwrap()).unwrap(); let relaunched = ConnectionFile::at(layout.connection_json()); assert!(relaunched.apply_listing(&listed, "2026-10-04").unwrap().new.is_empty()); assert!(!leave_database(&layout, &connection, WORKSPACE, Unsent::Refuse).unwrap()); assert!(personal.exists()); } /// RULE: Leaving a database whose copy holds unsent writes, parked pushes or an owed hand-over is refused and forgets nothing, until the person chooses to discard them. #[test] fn leave_of_a_place_with_unsent_changes_is_refused_until_discarded() { let owing: [(&str, &str); 3] = [ ( "a queued write", "INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes) \ VALUES ('op-1', 'create', 'device:me', 'cotton_todos', 'todo-1', 'h', 1, '2026-09-16T09:00:00.000Z', X'7b7d')", ), ( "a parked push", "INSERT INTO _parked (op_id, direction, class, tbl, row_id) VALUES ('op-2', 'push', 'waiting', 'cotton_todos', 'todo-1')", ), ("an owed hand-over", "UPDATE _meta SET handed_over_epoch = NULL, heard_serving_epoch = 1"), ]; for (what, sql) in owing { let (_dir, layout) = temp_layout(); let connection = joined(&layout); let personal = write_replica_and_leftovers(&layout); connection.add_made_place("garden", "Garden", None).unwrap(); let replica = layout.replica("garden"); std::fs::create_dir_all(replica.parent().unwrap()).unwrap(); crate::test_support::write_snapshot_for(&replica, "garden"); cotton_store::driver::Driver::open(&replica).expect("the copy").exec(sql).expect(what); let before = std::fs::read(&replica).expect("the bytes"); let refused = leave_database(&layout, &connection, "garden", Unsent::Refuse).expect_err(what); assert!(matches!(refused, LeaveError::Unsent(_)), "{what}: {refused:?}"); assert!(what_leaving_loses(&layout, "garden").unwrap().is_some(), "{what}: the screen can ask first"); assert_eq!(std::fs::read(&replica).expect("the bytes"), before, "{what}: the copy is untouched"); let record = connection.read_record().unwrap(); assert_eq!(record.places.len(), 1, "{what}: still listed"); assert!(record.left_databases.is_empty(), "{what}: not marked left"); assert!(leave_database(&layout, &connection, "garden", Unsent::Discard).expect(what), "{what}: discard leaves"); assert!(!replica.exists(), "{what}: the copy went with the discard"); assert!(personal.exists(), "{what}: Personal is never touched"); } } /// RULE: A copy left on disk by a leave cut short between its mark and its delete is deleted at the next pass, never attached or refilled; Personal and held copies are untouched. #[test] fn a_copy_left_behind_by_a_leave_cut_short_is_swept_and_never_refilled() { let (_dir, layout) = temp_layout(); let connection = joined(&layout); let personal = write_replica_and_leftovers(&layout); for (id, name) in [("garden", "Garden"), ("attic", "Attic")] { connection.add_made_place(id, name, None).unwrap(); let replica = layout.replica(id); std::fs::create_dir_all(replica.parent().unwrap()).unwrap(); crate::test_support::write_snapshot_for(&replica, id); } // The cut-short leave: marked left, the file never deleted. connection.forget_database("garden").unwrap().expect("garden was held"); assert!(layout.replica("garden").exists(), "the stray the crash left"); assert_eq!(sweep_left(&layout, &connection), 1); assert!(!layout.replica("garden").exists(), "the left copy is gone"); assert!(layout.replica("attic").exists(), "a held copy stays"); assert!(personal.exists(), "Personal is never touched"); assert_eq!(sweep_left(&layout, &connection), 0, "a second pass finds nothing"); } /// RULE: A leave the serving Mac has not taken is owed on the connection record (origin, pinned Mac, database) and survives Mine being rewritten, until it is settled; owing the same database twice is one debt. #[test] fn a_leave_the_serving_mac_has_not_taken_is_owed_until_settled() { use crate::connection::PendingLeave; let (_dir, layout) = temp_layout(); let connection = joined(&layout); let owed = PendingLeave { database: "garden".into(), origin: "http://192.168.1.91:9790".into(), server_device_id: "synthetic-serving-device".into(), }; connection.queue_leave(owed.clone()).unwrap(); connection.queue_leave(owed.clone()).unwrap(); assert_eq!(connection.read_record().unwrap().pending_leaves, vec![owed.clone()]); // Mine rewritten (a later personal identity update) keeps the debt. connection.write(connection.read().unwrap()).unwrap(); let relaunched = ConnectionFile::at(layout.connection_json()); assert_eq!(relaunched.read_record().unwrap().pending_leaves, vec![owed]); relaunched.settle_leave("garden").unwrap(); assert!(relaunched.read_record().unwrap().pending_leaves.is_empty()); assert!(connection.read_record().unwrap().pending_leaves.is_empty() || ConnectionFile::at(layout.connection_json()).read_record().unwrap().pending_leaves.is_empty()); } /// RULE: Re-pairing a build machine erases its Cotton database copy and media while retaining independently managed runner and session-host files; granting placements must never leave the previous full copy behind. #[test] fn erase_before_runner_pairing_removes_data_and_keeps_independent_job_files() { let (home, layout) = temp_layout(); let connection = joined(&layout); let replica = write_replica_and_leftovers(&layout); std::fs::create_dir_all(layout.client_media_dir()).unwrap(); std::fs::write(layout.client_media_dir().join("synthetic-photo"), b"synthetic-photo").unwrap(); let runner = home.path().join("independent-runner/registration"); let host = home.path().join("independent-session-host/config"); for path in [&runner, &host] { std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, b"synthetic-job-config").unwrap(); } erase_device(&layout, &connection, Some(WORKSPACE)); assert!(!replica.exists()); assert!(!layout.client_media_dir().exists()); for path in [&runner, &host] { assert_eq!(std::fs::read(path).unwrap(), b"synthetic-job-config"); } } const GARDEN: &str = "11111111-1111-4111-8111-111111111111"; const ATTIC: &str = "22222222-2222-4222-8222-222222222222"; fn holding_two_others(layout: &Layout) -> (ConnectionFile, std::path::PathBuf) { let connection = joined(layout); let personal = write_replica_and_leftovers(layout); for (id, name) in [(GARDEN, "Garden"), (ATTIC, "Attic")] { connection.add_made_place(id, name, None).unwrap(); let replica = layout.replica(id); std::fs::create_dir_all(replica.parent().unwrap()).unwrap(); crate::test_support::write_snapshot_for(&replica, id); let media = layout.client_media_dir().join(id); std::fs::create_dir_all(&media).unwrap(); std::fs::write(media.join("synthetic.jpg"), b"invented bytes").unwrap(); } (connection, personal) } // RULE: A device scoped to Personal removes every other held copy with its file and its media and keeps Personal whole (owner's 70th amendment, 20 Oct 2026), because twelve unscoped copies kept on the 304 phone were counted in its state, never synced and held gigabytes. #[test] fn a_device_scoped_to_personal_removes_every_other_copy_with_its_bytes() { let (_dir, layout) = temp_layout(); let (connection, personal) = holding_two_others(&layout); let removed = remove_out_of_scope(&layout, &connection, |_| false); assert_eq!(removed, vec![GARDEN.to_string(), ATTIC.to_string()]); for id in [GARDEN, ATTIC] { assert!(!layout.replica(id).exists(), "{id}'s file went"); assert!(!layout.replica(id).parent().unwrap().exists(), "{id}'s folder went"); assert!(!layout.client_media_dir().join(id).exists(), "{id}'s media went"); } assert!(personal.exists(), "Personal is never touched"); let record = connection.read_record().unwrap(); assert!(record.places.is_empty(), "the record names only Personal"); assert_eq!(record.mine.workspace_id.as_deref(), Some(WORKSPACE)); assert!(remove_out_of_scope(&layout, &connection, |_| false).is_empty(), "a second call removes nothing"); } // RULE: A scope that admits every database removes nothing, and a scope of one database keeps that one. #[test] fn a_scope_that_admits_a_copy_never_removes_it() { let (_dir, layout) = temp_layout(); let (connection, personal) = holding_two_others(&layout); assert!(remove_out_of_scope(&layout, &connection, |_| true).is_empty()); assert!(layout.replica(GARDEN).exists() && layout.replica(ATTIC).exists()); assert_eq!(remove_out_of_scope(&layout, &connection, |id| id == ATTIC), vec![GARDEN.to_string()]); assert!(layout.replica(ATTIC).exists()); assert!(layout.client_media_dir().join(ATTIC).exists()); assert!(personal.exists()); }