//! The corrections, one test each — and the two things the claim must never do. use cotton_store::create::create_workspace; use cotton_store::driver::Driver; use cotton_store::meta::{read_meta, Meta}; use rusqlite::types::Value as SqlValue; use super::*; const WORKSPACE: &str = "55555555-5555-4555-8555-555555555555"; const THIS_DEVICE: &str = "device:01JAAAAAAAAAAAAAAAAAAAAAAA"; /// The device stamped in the file the SERVER sent — never this one. const THE_SERVERS_DEVICE: &str = "device:server-copy"; const NOW: &str = "2026-09-16T09:00:00.000Z"; /// [`NOW`], as the milliseconds the claim is handed. const NOW_MS: i64 = 1_789_549_200_000; /// A snapshot as it arrives: the server's device id, and the server's rows. fn arrived(dir: &std::path::Path) -> Driver { let db = Driver::open(dir.join("replica.db")).expect("a file"); create_workspace( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: "owner-99".to_string(), device_id: THE_SERVERS_DEVICE.to_string(), last_server_seq: 0, last_hlc: None, }, ) .expect("a workspace"); cotton_tools::test_fixtures::fold_create( &db, "cotton_workspaces", WORKSPACE, serde_json::json!({ "name": "Asha", "owner_user_id": "owner-99", "created_at": NOW }), "1787394600000:0001:device:mac", "device:mac", ); db } /// One row of the server's, at a stamp that author owns. fn todo(db: &Driver, id: &str, author: &str, stamp: &str) { cotton_tools::test_fixtures::fold_create( db, "cotton_todos", id, serde_json::json!({ "title": "Call the bank", "status": "open", "created_at": NOW, "updated_at": NOW, "workspace_id": WORKSPACE, }), &format!("{stamp}:{author}"), author, ); } fn queue_one_outbox_row(db: &Driver) { db.run( "INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes)\n VALUES ('op-outbox', 'create', ?, 'cotton_todos', 'todo-mine', 'h', 1, ?, X'7b7d')", &[ SqlValue::Text(THIS_DEVICE.to_string()), SqlValue::Text(NOW.to_string()), ], ) .expect("a queued op"); } fn queue_one_media_row(db: &Driver) { db.run( "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, state, created_at, updated_at)\n VALUES ('media/one', ?, 'abc', 'image/png', 12, 'pending', ?, ?)", &[ SqlValue::Text(WORKSPACE.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ) .expect("a media row"); } fn count(db: &Driver, table: &str) -> i64 { db.get(&format!("SELECT COUNT(*) AS n FROM {table}"), &[]) .expect("a count") .and_then(|row| row.int("n")) .unwrap_or(0) } // ── the device id ───────────────────────────────────────────────────────── #[test] fn the_file_is_stamped_with_this_device_rather_than_the_one_that_sent_it() { // The device id is the author of every op this device writes AND the name // its own writes are found under in its stream. Inheriting the server's // means writing under the server's name. let dir = tempfile::tempdir().expect("a temp dir"); let db = arrived(dir.path()); assert_eq!( read_meta(&db).expect("meta").expect("a row").device_id, THE_SERVERS_DEVICE ); claim_snapshot(&db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids()).expect("a claim"); assert_eq!( read_meta(&db).expect("meta").expect("a row").device_id, THIS_DEVICE ); } // ── the cursors ─────────────────────────────────────────────────────────── #[test] fn the_cursors_are_set_from_the_arrived_file() { // A device holding a copy has SEEN every write in it. Without this the // first exchange asks every author for everything and folds a whole file's // worth of ops back over itself — and the cursor comes from the FILE, so it // cannot be set past a write the copy did not contain. let dir = tempfile::tempdir().expect("a temp dir"); let db = arrived(dir.path()); todo(&db, "todo-1", "device:mac", "1787394600000:0001"); todo(&db, "todo-2", "device:mac", "1787394600000:0009"); todo(&db, "todo-3", "device:old-phone", "1787394600000:0004"); let claimed = claim_snapshot(&db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids()).expect("a claim"); assert_eq!( claimed.cursors.get("device:mac").map(String::as_str), Some("1787394600000:0009:device:mac"), "each author's cursor is that author's OWN top stamp, not the file's" ); assert_eq!( claimed.cursors.get("device:old-phone").map(String::as_str), Some("1787394600000:0004:device:old-phone") ); // And they are in the file, not only in the answer. let stored: Vec = db .all( "SELECT author_device_id FROM _cursors ORDER BY author_device_id", &[], ) .expect("the cursors read") .iter() .filter_map(|row| row.text("author_device_id").map(str::to_string)) .collect(); // The two the copy backs, and this device's own author — minted by the // claim, at its first stamp. assert_eq!(stored, vec![claimed.author.as_deref().unwrap(), "device:mac", "device:old-phone"]); } /// RULE: Claim preserves the full cut's recorded ceilings even when filtering removed every receipt of an author, so sync never downloads the excluded rows again. #[test] fn a_claim_preserves_the_cuts_recorded_positions() { let dir = tempfile::tempdir().unwrap(); let db = arrived(dir.path()); todo(&db, "excluded", "device:excluded", "1787394600001:0001"); db.run("DELETE FROM cotton_todos WHERE id = 'excluded'", &[]) .unwrap(); // Replacement must accept the cut using its recorded positions even // though the previous file still holds the excluded receipt. let replica = dir.path().join("previous-replica.db"); let saved = crate::bootstrap::previous::path(&replica); std::fs::create_dir(dir.path().join("saved")).unwrap(); let previous = arrived(&dir.path().join("saved")); todo( &previous, "excluded", "device:excluded", "1787394600001:0001", ); drop(previous); std::fs::rename(dir.path().join("saved/replica.db"), &saved).unwrap(); let ceilings = cotton_store::cursors::seen_ceiling(&db).unwrap(); cotton_store::snapshot::strip_for_phone(&db).unwrap(); assert!( cotton_store::receipts::of_row(&db, "cotton_todos", "excluded") .unwrap() .is_empty() ); crate::bootstrap::previous::check_copy(&replica, &db).unwrap(); // A genuinely older cut still refuses; the recorded ceiling is what // proves this one includes the excluded write's position. db.run("DELETE FROM _cursors WHERE author_device_id = 'device:excluded'", &[]).unwrap(); assert!(crate::bootstrap::previous::check_copy(&replica, &db).is_err()); cotton_store::cursors::advance_cursor(&db, "device:excluded", &ceilings["device:excluded"], NOW).unwrap(); let claimed = claim_snapshot( &db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids(), ) .unwrap(); assert_eq!(claimed.cursors, ceilings); for (author, top) in ceilings { assert_eq!( cotton_store::cursors::read_cursors(&db) .unwrap() .get(&author), Some(&top) ); } } // ── the media ledger ────────────────────────────────────────────────────── #[test] fn a_media_row_for_bytes_this_device_does_not_have_is_dropped() { let dir = tempfile::tempdir().expect("a temp dir"); let db = arrived(dir.path()); queue_one_media_row(&db); let claimed = claim_snapshot(&db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids()).expect("a claim"); assert_eq!(claimed.dropped_from_media, 1); assert_eq!(count(&db, "_media"), 0); } // ── what the claim must NOT do ──────────────────────────────────────────── #[test] fn the_outbox_survives_a_claim() { // It used to be emptied, which made the claim a function that could destroy // writes — the re-hydrate had to warn its callers to drain first. The // SERVER's queued ops are emptied by the strip, on the server's own copy; // a device's queued writes are the device's and survive everything. let dir = tempfile::tempdir().expect("a temp dir"); let db = arrived(dir.path()); queue_one_outbox_row(&db); claim_snapshot(&db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids()).expect("a claim"); assert_eq!( count(&db, "_outbox WHERE op_id = 'op-outbox'"), 1, "a queued write was thrown away" ); } #[test] fn a_claim_refuses_a_device_that_has_data() { // A whole-file copy is never put beside a stray life: the two would be // mixed on one device with nobody having said so. let dir = tempfile::tempdir().expect("a temp dir"); let db = arrived(dir.path()); let refused = claim_snapshot(&db, THIS_DEVICE, 1_240, NOW_MS, &mut crate::test_support::fresh_ids()).expect_err("a device with data is told no"); let sentence = refused.to_string(); assert!(sentence.contains("1240"), "{sentence}"); // Nothing was touched. assert_eq!( read_meta(&db).expect("meta").expect("a row").device_id, THE_SERVERS_DEVICE ); } #[test] fn every_correction_lands_together_because_two_of_three_is_a_file_nobody_wrote_a_rule_for() { let dir = tempfile::tempdir().expect("a temp dir"); let db = arrived(dir.path()); todo(&db, "todo-1", "device:mac", "1787394600000:0001"); queue_one_media_row(&db); let claimed = claim_snapshot(&db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids()).expect("a claim"); let meta = read_meta(&db).expect("meta").expect("a row"); assert_eq!(meta.device_id, THIS_DEVICE); assert_eq!(count(&db, "_media"), 0); assert_eq!(claimed.dropped_from_media, 1); assert_eq!(claimed.cursors.len(), 1, "one author wrote everything in this copy"); } // ── the author and the local marks ──────────────────────────────────────── /// RULE: a device filled by snapshot mints under its OWN author, and the marks that described the serving Mac do not survive the claim. /// /// `_meta` travels in the copy. Left alone, `author_id` is the serving Mac's /// — two machines minting one stream — `rotation_check_due` is that Mac's own /// reminder, and `handed_over_epoch` and `heard_serving_epoch` are whatever /// the server had, when what this device owes is measured from the epoch of /// the copy it was handed. #[test] fn snapshot_claim_mints_its_own_author_and_clears_local_marks() { let dir = tempfile::tempdir().expect("a temp dir"); let db = arrived(dir.path()); db.run( "UPDATE _meta SET author_id = 'device:the-servers-author', \ rotation_check_due = '2026-10-01T00:00:00.000Z', handed_over_epoch = 1, \ heard_serving_epoch = 9", &[], ) .expect("the server's marks"); for (id, epoch) in [("fact-2", 2), ("fact-3", 3)] { db.run( "INSERT INTO cotton_serving_machine \ (id, workspace_id, epoch, device_credential_id, author_id, since) \ VALUES (?, ?, ?, 'the-serving-mac', 'device:the-servers-author', ?)", &[ SqlValue::Text(id.to_string()), SqlValue::Text(WORKSPACE.to_string()), SqlValue::Integer(epoch), SqlValue::Text(NOW.to_string()), ], ) .expect("a serving fact"); } let claimed = claim_snapshot(&db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids()) .expect("a claim"); let meta = db .get( "SELECT author_id, rotation_check_due, handed_over_epoch, heard_serving_epoch FROM _meta", &[], ) .expect("a read") .expect("the row"); let author = meta.text("author_id").expect("an author").to_string(); assert_ne!(author, "device:the-servers-author", "never the serving Mac's stream"); assert_eq!(Some(author.clone()), claimed.author); assert_eq!(meta.text("rotation_check_due"), None, "the server's reminder is not this device's"); assert_eq!( meta.int("handed_over_epoch"), Some(3), "the copy's OWN serving epoch — not the server's copied mark, and not an older fact's" ); assert_eq!(claimed.handed_over_epoch, Some(3)); assert_eq!( meta.int("heard_serving_epoch"), Some(3), "heard of the copy's own epoch — not whatever the server had heard" ); // The author is announced: its fact names this device, is in the file, // and is queued so the serving Mac hears of the author first. let fact = db .get("SELECT device_id, reason FROM cotton_authors WHERE id = ?", &[SqlValue::Text(author.clone())]) .expect("a read") .expect("the author's fact"); assert_eq!(fact.text("device_id"), Some(THIS_DEVICE)); assert_eq!(fact.text("reason"), Some("first")); let queued = db .all("SELECT author, tbl FROM _outbox", &[]) .expect("the outbox"); assert_eq!(queued.len(), 1, "the fact, and nothing of the server's"); assert_eq!(queued[0].text("author"), Some(author.as_str())); assert_eq!(queued[0].text("tbl"), Some("cotton_authors")); } /// RULE: A reader corrects its downloaded copy without minting an author or /// queueing a receipt, because accepting the snapshot must not create a write /// from a device that can only read. #[test] fn a_reader_claim_has_no_author_and_no_outbox_write() { let dir = tempfile::tempdir().expect("a temp dir"); let db = arrived(dir.path()); db.set_device_scope(cotton_store::device_scope::DeviceScope::Reader); let claimed = claim_snapshot(&db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids()) .expect("a reader's local snapshot corrections"); assert_eq!(claimed.author, None); assert_eq!(read_meta(&db).unwrap().unwrap().device_id, THIS_DEVICE); assert_eq!(db.get("SELECT author_id FROM _meta", &[]).unwrap().unwrap().text("author_id"), None); assert_eq!(count(&db, "_outbox"), 0); } #[test] fn a_copy_with_no_serving_fact_is_claimed_with_no_mark() { // No fact is no epoch to have been handed: the mark stays empty rather // than becoming a zero that reads as "handed over at epoch 0". let dir = tempfile::tempdir().expect("a temp dir"); let db = arrived(dir.path()); db.run("UPDATE _meta SET heard_serving_epoch = 4", &[]) .expect("an epoch the server had heard of"); let claimed = claim_snapshot(&db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids()) .expect("a claim"); assert_eq!(claimed.handed_over_epoch, None); let heard = db .get("SELECT heard_serving_epoch FROM _meta", &[]) .expect("a read") .and_then(|row| row.int("heard_serving_epoch")); assert_eq!(heard, None, "the server's heard epoch is not this device's"); } /// RULE: A claimed copy's cursors are, author by author, at least the copy's recorded ceilings, so a claimed copy owes only what arrived since it was cut, never its history again (architect, 13 Oct 2026, after the phone's catch-up following the 136 move). #[test] fn a_claim_never_moves_a_cursor_backwards() { let dir = tempfile::tempdir().unwrap(); let db = arrived(dir.path()); todo(&db, "mac-later", "device:mac", "1787394600050:0001"); todo(&db, "old-phone", "device:old-phone", "1787394600010:0001"); let ceilings = cotton_store::cursors::seen_ceiling(&db).unwrap(); claim_snapshot(&db, THIS_DEVICE, 0, NOW_MS, &mut crate::test_support::fresh_ids()).expect("a claim"); let after = cotton_store::cursors::read_cursors(&db).unwrap(); for (key, was) in &ceilings { let now = after.get(key).unwrap_or_else(|| panic!("{key} kept a cursor: {after:?}")); assert!(now >= was, "{key} went back from {was} to {now}"); } }