//! Every mint is checked against judge time (slice 1): Checked stamps by the //! wall, Corrected by judge time, Unchecked by the wall and holds; a poisoned //! `last_hlc` moves the file to a fresh author; a replica adopts an answer's //! stamp no further than judge time + the bound. The release pass releases a //! held receipt at its own stamp only when that stamp is honest, re-dates the //! rest to when they were minted under one fresh author, and a `restamps` //! drops only its own device's identical receipt. use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE}; use cotton_store::canonical::{self, Receipt}; use cotton_store::fold::{fold_ops, fold_pulled, fold_pulled_judged}; use cotton_store::judge::ClockState; use cotton_store::meta::{seed_meta, Meta}; use cotton_store::mint::clock::{mint_time, release_held, waiting_for_the_relay, Release, FUTURE_BOUND_MS}; use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource, Minted}; use cotton_store::protocol::hlc::hlc_parts; use cotton_store::protocol::types::CottonOp; use cotton_store::schema::ddl::SCHEMA_VERSION; use cotton_store::Driver; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; /// Judge time in these tests. const J: i64 = 1_790_000_000_000; const YEAR: i64 = 365 * 24 * 60 * 60_000; const BOOT: &str = "6f1c1f55-0000-4000-8000-000000000001"; struct Ids(u32, &'static str); impl IdSource for Ids { fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result { self.0 += 1; Ok(format!("{}{:04}", self.1, self.0)) } } fn file(device: &str) -> Driver { let db = file_at_version(SCHEMA_VERSION); seed_meta( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: device.to_string(), last_server_seq: 0, last_hlc: None, }, SCHEMA_VERSION, ) .expect("seeds the identity"); seed_workspace_row(&db); db.run( "INSERT INTO cotton_sessions (id, workspace_id, tool, last_active_at, created_at, updated_at) \ VALUES ('s1', ?, 'claude-code', ?, ?, ?)", &[ SqlValue::Text(WORKSPACE.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(NOW.to_string()), ], ) .expect("a session row"); db } fn authored(device: &str, prefix: &'static str) -> Driver { let db = file(device); first_author(&db, device, None, AuthorReason::First, &judged(Some(J - 60_000), J - 60_000), &mut Ids(0, prefix), Held::Replica) .expect("the file's author"); db } fn judged(judge: Option, wall: i64) -> Clock { Clock::judged(judge, wall, 5_000, BOOT.to_string()) } fn write(db: &Driver, row: &str, clock: &Clock, ids: &mut Ids) -> cotton_store::Result { write_keeping(db, row, clock, ids, History::None) } /// [`write`], keeping `history`: a kept act's history receipt is stamped in /// the same chain as its write. fn write_keeping(db: &Driver, row: &str, clock: &Clock, ids: &mut Ids, history: History) -> cotton_store::Result { let todo: Map = json!({"id": row, "workspace_id": WORKSPACE, "title": row, "created_at": NOW, "updated_at": NOW}) .as_object() .expect("an object") .clone(); let actor = cotton_store::actor::Actor::session(cotton_store::actor::SessionId::in_file(db, "s1").expect("the row")); mint( db, &Act { actor, verb: "create_todo".into(), history, changes: vec![Change::create("cotton_todos", row, todo)] }, clock, ids, Held::Replica, ) } fn text(db: &Driver, sql: &str) -> Option { db.get(sql, &[]).expect("reads").and_then(|row| row.text("v").map(str::to_string)) } fn count(db: &Driver, sql: &str) -> i64 { db.get(sql, &[]).expect("reads").and_then(|row| row.int("n")).unwrap_or(0) } fn ms(stamp: &str) -> i64 { hlc_parts(stamp).expect("a stamp").ms } /// RULE: A wall clock that jumps ahead while this device holds judge time never makes an unheld future stamp — the next mint is Corrected and stamps by judge time. #[test] fn clock_jump_while_checked_never_mints_unheld_future_stamp() { let db = authored("device:mac", "a-"); let mut ids = Ids(0, "op-"); let before = write(&db, "t1", &judged(Some(J), J), &mut ids).expect("Checked"); assert_eq!(before.state, ClockState::Checked); assert_eq!(ms(&before.ops[0].hlc), J); let after = write(&db, "t2", &judged(Some(J + 1_000), J + YEAR), &mut ids).expect("mints"); assert!(!after.held, "a device with judge time does not hold"); assert_eq!(after.state, ClockState::Corrected { off_by_ms: YEAR - 1_000 }); assert_eq!(ms(&after.ops[0].hlc), J + 1_000, "stamped by judge time, not the wall"); let last = text(&db, "SELECT last_hlc AS v FROM _meta").expect("a clock"); assert!(ms(&last) <= J + FUTURE_BOUND_MS, "no stamp beyond the bound: {last}"); assert_eq!( count(&db, &format!("SELECT COUNT(*) AS n FROM _outbox WHERE substr(hlc, 1, 13) > '{:013}'", J + FUTURE_BOUND_MS)), 0 ); } /// RULE: A wall-clock jump while Checked is caught at the very next mint — no mint after the jump uses the wall clock — and a wall clock set right again is Checked again. #[test] fn wall_clock_jump_while_checked_is_caught_at_the_next_mint() { let db = authored("device:mac", "a-"); let mut ids = Ids(0, "op-"); write(&db, "t1", &judged(Some(J), J), &mut ids).expect("Checked"); for (row, judge) in [("t2", J + 10), ("t3", J + 20)] { let caught = write(&db, row, &judged(Some(judge), judge - YEAR), &mut ids).expect("mints"); assert!(matches!(caught.state, ClockState::Corrected { .. }), "{:?}", caught.state); assert_eq!(ms(&caught.ops[0].hlc), judge); } let fixed = write(&db, "t4", &judged(Some(J + 30), J + 30), &mut ids).expect("mints"); assert_eq!(fixed.state, ClockState::Checked); assert_eq!(ms(&fixed.ops[0].hlc), J + 30); } /// RULE: A last_hlc ahead of judge time + the bound is poisoned: the next mint moves the file to a fresh author (reason redate, first_stamp = judge time) and stamps at or below the bound, never minting ahead. #[test] fn poisoned_last_hlc_moves_to_a_fresh_author_instead_of_minting_ahead() { let db = authored("device:phone", "a-"); let first = text(&db, "SELECT author_id AS v FROM _meta").expect("an author"); let mut ids = Ids(0, "op-"); // Minted Unchecked with the wall a year ahead: held, and `last_hlc` now // sits a year ahead too. let held = write(&db, "t1", &judged(None, J + YEAR), &mut ids).expect("held"); assert!(held.held); assert_eq!(ms(&text(&db, "SELECT last_hlc AS v FROM _meta").expect("a clock")), J + YEAR); let next = write(&db, "t2", &judged(Some(J), J), &mut ids).expect("mints"); let fresh = next.minted_author.as_ref().expect("a fresh author"); assert_ne!(fresh.id, first); assert_eq!(text(&db, "SELECT author_id AS v FROM _meta"), Some(fresh.id.clone())); assert_eq!( text(&db, &format!("SELECT reason AS v FROM cotton_authors WHERE id = '{}'", fresh.id)).as_deref(), Some("redate") ); let parts = hlc_parts(&fresh.first_stamp).expect("a stamp"); assert_eq!((parts.ms, parts.counter), (J, 0), "the stream starts at judge time"); assert!(!next.held); assert_eq!(next.ops[0].device_id, fresh.id); assert!(ms(&next.ops[0].hlc) <= J + FUTURE_BOUND_MS, "{}", next.ops[0].hlc); let last = text(&db, "SELECT last_hlc AS v FROM _meta").expect("a clock"); assert!(ms(&last) <= J + FUTURE_BOUND_MS, "{last}"); // The fact and the write are queued; the held receipt is not. assert_eq!( count(&db, &format!("SELECT COUNT(*) AS n FROM _outbox WHERE author = '{}'", fresh.id)), 2 ); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox WHERE row_id = 't1'"), 0); // One fresh author, not one per mint. let again = write(&db, "t3", &judged(Some(J + 5), J + 5), &mut ids).expect("mints"); assert!(again.minted_author.is_none()); assert_eq!(again.ops[0].device_id, fresh.id); } /// RULE: A replica adopts an answer's newest stamp into last_hlc no further than judge time + the bound (H1) — a peer's future stamp is stored but does not carry this device's next write ahead. #[test] fn replica_never_adopts_a_stamp_beyond_the_bound_into_last_hlc() { // A peer whose wall ran a year ahead before slice 1 caught it. let peer = file("device:peer"); let fact = first_author(&peer, "device:peer", None, AuthorReason::First, &Clock::wall(J + YEAR), &mut Ids(0, "p-"), Held::Replica) .expect("the peer's author") .fact; let ahead = write(&peer, "t1", &Clock::wall(J + YEAR + 1), &mut Ids(0, "pop-")).expect("the peer's write"); let answer = [vec![fact], ahead.ops].concat(); let bounded = authored("device:phone", "a-"); let folded = fold_pulled_judged(&bounded, &answer, Some(J)).expect("folds"); assert!(folded.rejected.is_empty(), "{:?}", folded.rejected); assert_eq!(count(&bounded, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't1'"), 1, "the write applies"); let last = text(&bounded, "SELECT last_hlc AS v FROM _meta").expect("a clock"); assert_eq!(ms(&last), J + FUTURE_BOUND_MS, "adopted up to the bound and no further"); let next = write(&bounded, "t2", &judged(Some(J), J), &mut Ids(0, "op-")).expect("mints"); assert!(next.minted_author.is_none(), "a bounded clock is not poisoned"); assert!(ms(&next.ops[0].hlc) <= J + FUTURE_BOUND_MS); // Without judge time the answer's stamp is adopted whole. let unbounded = authored("device:other", "b-"); fold_pulled(&unbounded, &answer).expect("folds"); let last = text(&unbounded, "SELECT last_hlc AS v FROM _meta").expect("a clock"); assert_eq!(ms(&last), J + YEAR + 1); } /// RULE: A write minted Unchecked is held — applied here, kept in _writes with held = 1 and its mint_cont and mint_boot, never queued — and the file says "N changes are waiting for the relay" while it holds any. #[test] fn held_writes_show_waiting_for_the_relay_while_unchecked() { let db = authored("device:phone", "a-"); assert_eq!(waiting_for_the_relay(&db).expect("reads"), None); let queued_before = count(&db, "SELECT COUNT(*) AS n FROM _outbox"); let mut ids = Ids(0, "op-"); for row in ["t1", "t2"] { let minted = write(&db, row, &judged(None, J), &mut ids).expect("held"); assert!(minted.held); assert_eq!(minted.state, ClockState::Unchecked); assert_eq!(ms(&minted.ops[0].hlc), J, "stamped by the wall clock"); } assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos"), 2, "a held write applies here"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), queued_before, "and is never queued"); assert_eq!( count(&db, &format!("SELECT COUNT(*) AS n FROM _writes WHERE tbl = 'cotton_todos' AND held = 1 AND mint_cont = 5000 AND mint_boot = '{BOOT}'")), 2 ); assert_eq!( waiting_for_the_relay(&db).expect("reads").as_deref(), Some("2 changes are waiting for the relay") ); // A delete is held like any other write: its receipt is the row's // tombstone, kept back with the same marks. let actor = cotton_store::actor::Actor::session(cotton_store::actor::SessionId::in_file(&db, "s1").expect("the row")); let deleted = mint( &db, &Act { actor, verb: "delete_todo".into(), history: History::None, changes: vec![Change::retract("cotton_todos", "t1")] }, &judged(None, J), &mut ids, Held::Replica, ) .expect("an Unchecked delete is held"); assert!(deleted.held); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't1'"), 0, "a held delete applies here"); // The held create it buried is gone (rule 6): the delete is what waits. assert_eq!( count(&db, &format!("SELECT COUNT(*) AS n FROM _tombstones WHERE row_id = 't1' AND held = 1 AND mint_cont = 5000 AND mint_boot = '{BOOT}'")), 1 ); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), queued_before, "and is never queued"); assert_eq!( waiting_for_the_relay(&db).expect("reads").as_deref(), Some("2 changes are waiting for the relay") ); // A Checked write travels, and its queue row carries its clocks too. let checked = write(&db, "t3", &judged(Some(J), J), &mut ids).expect("Checked"); assert!(!checked.held); assert_eq!( count(&db, &format!("SELECT COUNT(*) AS n FROM _outbox WHERE row_id = 't3' AND mint_boot = '{BOOT}' AND mint_cont = 5000")), 1 ); } // --------------------------------------------------------------------------- // The release pass // --------------------------------------------------------------------------- const MINUTE: i64 = 60_000; const OTHER_BOOT: &str = "6f1c1f55-0000-4000-8000-000000000002"; /// A shell's clock with a continuous clock of its own. fn at(judge: Option, wall: i64, cont: i64, boot: &str) -> Clock { Clock::judged(judge, wall, cont, boot.to_string()) } fn session(db: &Driver) -> cotton_store::actor::Actor { cotton_store::actor::Actor::session(cotton_store::actor::SessionId::in_file(db, "s1").expect("the row")) } fn titled(db: &Driver, row: &str, title: &str, clock: &Clock, ids: &mut Ids) -> Minted { let mut patch = Map::new(); patch.insert("title".into(), json!(title)); mint( db, &Act { actor: session(db), verb: "update_todo".into(), history: History::None, changes: vec![Change::update("cotton_todos", row, patch)] }, clock, ids, Held::Replica, ) .expect("a change") } fn delete(db: &Driver, row: &str, clock: &Clock, ids: &mut Ids) -> Minted { mint( db, &Act { actor: session(db), verb: "delete_todo".into(), history: History::None, changes: vec![Change::retract("cotton_todos", row)] }, clock, ids, Held::Replica, ) .expect("a delete") } fn pass(db: &Driver, clock: &Clock) -> Release { release_held(db, clock, &mut Ids(0, "r-"), Held::Replica).expect("the pass") } /// Everything the pass sends: the released, the fresh author's fact, the /// re-dated. fn travelling(release: &Release) -> Vec { let mut ops = release.released.clone(); ops.extend(release.author.iter().map(|author| author.fact.clone())); ops.extend(release.redated.iter().cloned()); ops } fn parts(stamp: &str) -> (i64, i64) { let parts = hlc_parts(stamp).expect("a stamp"); (parts.ms, parts.counter) } fn title(db: &Driver, row: &str) -> Option { text(db, &format!("SELECT title AS v FROM cotton_todos WHERE id = '{row}'")) } /// A peer file — another device's author, with its fact — that `into` knows. fn peer(device: &str, prefix: &'static str, into: &Driver) -> (Driver, String) { let peer = file(device); let author = first_author(&peer, device, None, AuthorReason::First, &Clock::wall(J - 2 * MINUTE), &mut Ids(0, prefix), Held::Replica) .expect("the peer's author"); fold_pulled(into, std::slice::from_ref(&author.fact)).expect("the fact folds"); (peer, author.id) } /// A peer's change of `row`'s title at `ms`, as the peer's own receipt. fn peer_title(peer: &Driver, author: &str, row: &str, title: &str, ms: i64, op_id: &str) -> CottonOp { let mut patch = Map::new(); patch.insert("title".into(), json!(title)); cotton_store::wire::op_of_change( peer, &Change::update("cotton_todos", row, patch), &format!("{ms:013}:0000:{author}"), author, &session(peer), op_id.to_string(), ) .expect("the peer's op") } /// RULE: Held writes with a future clock are re-dated to mint time under one author whose fact comes first; honest held receipts retain their stamps. /// Freeze sequence A: correcting the wall clock must never release the held /// writes at their original 2027 stamps. #[test] fn held_receipts_minted_ahead_release_only_at_or_below_judge_time() { let db = authored("device:mac", "a-"); let mut ids = Ids(0, "op-"); let t0 = J; // An honest held write first: wall right, no judge time yet. let honest = write(&db, "h1", &at(None, t0 - MINUTE, 1_000, BOOT), &mut ids).expect("held"); // X at t0 with the wall in 2027; NTP then fixes it, and Y five seconds // later still stamps above 2027, because last_hlc holds it. let x = write(&db, "x", &at(None, t0 + YEAR, 61_000, BOOT), &mut ids).expect("held"); let y = write(&db, "y", &at(None, t0 + 5_000, 66_000, BOOT), &mut ids).expect("held"); assert!(x.held && y.held && honest.held); assert_eq!(parts(&y.ops[0].hlc), (t0 + YEAR, 1)); // The greeting at t2 = t0 + 10 min; the offset now is about 0, and it is // never read. let t2 = t0 + 10 * MINUTE; let release = pass(&db, &at(Some(t2), t2, 61_000 + 10 * MINUTE, BOOT)); assert_eq!(release.released.len(), 1); assert_eq!(release.released[0].op_id, honest.ops[0].op_id, "the honest one keeps its op id"); assert_eq!(release.released[0].hlc, honest.ops[0].hlc, "and its stamp"); let fresh = release.author.as_ref().expect("one fresh author"); assert_eq!(parts(&fresh.first_stamp), (t0, 0), "the fact at the lowest re-dated stamp"); assert_eq!( text(&db, &format!("SELECT reason AS v FROM cotton_authors WHERE id = '{}'", fresh.id)).as_deref(), Some("redate") ); let stamps: Vec<(i64, i64)> = release.redated.iter().map(|op| parts(&op.hlc)).collect(); assert_eq!(stamps, vec![(t0, 1), (t0 + 5_000, 0)]); assert_eq!(release.redated[0].restamps.as_deref(), Some(x.ops[0].op_id.as_str())); assert_eq!(release.redated[1].restamps.as_deref(), Some(y.ops[0].op_id.as_str())); assert!(release.redated.iter().all(|op| op.device_id == fresh.id)); // No 2027 stamp is left anywhere, nothing is held, and everything travels. let ahead = format!("{:013}", t2); assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM _writes WHERE substr(hlc, 1, 13) > '{ahead}'")), 0); assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM _outbox WHERE substr(hlc, 1, 13) > '{ahead}'")), 0); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _writes WHERE held = 1"), 0); assert_eq!(waiting_for_the_relay(&db).expect("reads"), None); for op in travelling(&release) { assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM _outbox WHERE op_id = '{}'", op.op_id)), 1, "{}", op.op_id); } assert_eq!(title(&db, "x").as_deref(), Some("x"), "the row still shows the write"); assert_eq!(parts(&text(&db, "SELECT last_hlc AS v FROM _meta").expect("a clock")), (t0 + 5_000, 0)); assert_eq!( release.line().as_deref(), Some("This device's clock was off; 2 changes were re-dated to when they were made.") ); } /// RULE: A held receipt stamped ahead of judge time is re-dated, never released at its own stamp — even when it is within 2 minutes of its mint time and the clock reads right now. #[test] fn held_receipt_stamped_ahead_of_judge_time_is_never_released_whatever_the_current_offset() { let db = authored("device:phone", "a-"); let mut ids = Ids(0, "op-"); // Minted at real J with the wall one minute ahead; the pass runs at once. let ahead = write(&db, "t1", &at(None, J + MINUTE, 7_000, BOOT), &mut ids).expect("held"); let release = pass(&db, &at(Some(J), J, 7_000, BOOT)); assert!(release.released.is_empty(), "{:?}", release.released); assert_eq!(release.redated.len(), 1); assert_eq!(release.redated[0].restamps.as_deref(), Some(ahead.ops[0].op_id.as_str())); assert!(ms(&release.redated[0].hlc) <= J, "{}", release.redated[0].hlc); assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM _writes WHERE op_id = '{}'", ahead.ops[0].op_id)), 0, "the old receipt is gone"); } /// RULE: Whatever the held writes were stamped — a year ahead, minutes ahead, a delete, or a file whose very first write (its author's fact) was held ahead — every stamp the pass leaves is at or below judge time, and an author whose fact was held ahead never travels. #[test] fn redate_after_the_clock_was_fixed_lands_at_or_below_judge_time() { // A file whose first write is made offline with the clock ahead: its // author's fact is held too. let db = file("device:phone"); let mut ids = Ids(0, "op-"); let first = write(&db, "t1", &at(None, J + YEAR, 1_000, BOOT), &mut ids).expect("held"); let unannounced = first.minted_author.as_ref().expect("the file's first author").id.clone(); write(&db, "t2", &at(None, J + 5 * MINUTE, 2_000, BOOT), &mut ids).expect("held"); delete(&db, "t2", &at(None, J + 5 * MINUTE, 3_000, BOOT), &mut ids); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _tombstones WHERE held = 1"), 1); let judge = J + 30 * MINUTE; let release = pass(&db, &at(Some(judge), judge, 1_000 + 30 * MINUTE, BOOT)); let ops = travelling(&release); assert!(release.released.is_empty()); // t2's held create lost to its own held delete and is gone (rule 6): // what is re-dated is t1's create and the delete. assert_eq!(release.redated.len(), 2, "a write and the delete"); for op in &ops { assert!(ms(&op.hlc) <= judge, "{} above judge time", op.hlc); assert_ne!(op.device_id, unannounced, "the held-ahead author never travels"); } assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM cotton_authors WHERE id = '{unannounced}'")), 0); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _writes WHERE held = 1"), 0); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _tombstones WHERE held = 1"), 0); let tomb = text(&db, "SELECT hlc AS v FROM _tombstones WHERE row_id = 't2'").expect("the re-dated delete"); assert_eq!(ms(&tomb), J + 2_000, "to when it was made: {tomb}"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't2'"), 0, "still deleted"); assert_eq!(title(&db, "t1").as_deref(), Some("t1")); // A peer folding what travelled shows the same rows. let other = authored("device:mac", "m-"); let folded = fold_pulled(&other, &ops).expect("folds"); assert!(folded.rejected.is_empty() && folded.waiting.is_empty() && folded.parked.is_empty(), "{folded:?}"); assert_eq!(title(&other, "t1").as_deref(), Some("t1")); assert_eq!(count(&other, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't2'"), 0); } /// RULE: Held receipts minted in an earlier boot session go to that boot's latest possible moment, the boot start B = J − C, in mint order — one counter apart, never reordered. #[test] fn held_receipts_from_an_earlier_boot_redate_to_the_boot_start_in_mint_order() { let db = authored("device:phone", "a-"); let mut ids = Ids(0, "op-"); // Kept history: each write's history receipt is held and re-dated with it. let a = write_keeping(&db, "a", &at(None, J + YEAR, 9_000_000, OTHER_BOOT), &mut ids, History::Kept).expect("held"); let b = write_keeping(&db, "b", &at(None, J + YEAR - 5, 50_000, OTHER_BOOT), &mut ids, History::Kept).expect("held"); let c = write_keeping(&db, "c", &at(None, J + YEAR - 9, 90_000, OTHER_BOOT), &mut ids, History::Kept).expect("held"); // The phone rebooted; judge time comes 2 minutes into the new boot. let (judge, cont) = (J + 3 * 60 * MINUTE, 2 * MINUTE); let release = pass(&db, &at(Some(judge), judge, cont, BOOT)); let boot_start = judge - cont; let restamps: Vec<&str> = release.redated.iter().filter_map(|op| op.restamps.as_deref()).collect(); let minted: Vec<&str> = [&a, &b, &c].iter().flat_map(|m| m.ops.iter().map(|op| op.op_id.as_str())).collect(); assert_eq!(minted.len(), 6, "a write and its history row each: {minted:?}"); assert_eq!(restamps, minted, "mint order"); let stamps: Vec<(i64, i64)> = release.redated.iter().map(|op| parts(&op.hlc)).collect(); assert_eq!(stamps, (1..=6).map(|n| (boot_start, n)).collect::>()); assert_eq!(parts(&release.author.as_ref().expect("an author").first_stamp), (boot_start, 0)); } /// RULE: An earlier-boot receipt below the boot boundary retains its stamp, even when clock skew makes an older phone write beat a newer Mac edit. /// Cost in 5.2 point 6 (F-C1): the phone writes at 10:00 stamped 13:00, the Mac /// edits at 12:00, and a 14:00 reboot releases the phone write at 13:00 <= B. #[test] fn earlier_boot_receipt_cost_is_stated_and_tested() { let hour = 60 * MINUTE; let ten = J; let phone = authored("device:phone", "a-"); let mut ids = Ids(0, "op-"); // X exists on both before the phone goes offline. let born = write(&phone, "x", &at(Some(ten - hour), ten - hour, 1_000, OTHER_BOOT), &mut ids).expect("a Checked create"); let (mac, mac_author) = peer("device:mac", "m-", &phone); fold_pulled(&mac, &[phone_fact(&phone), born.ops[0].clone()]).expect("the mac has X"); // Real 10:00: the phone, 3 hours ahead and offline, writes X: 13:00, held. let held = titled(&phone, "x", "phone at 10:00", &at(None, ten + 3 * hour, 2 * hour, OTHER_BOOT), &mut ids); assert!(held.held); assert_eq!(ms(&held.ops[0].hlc), ten + 3 * hour); // Real 12:00: the Mac edits X. let edit = peer_title(&mac, &mac_author, "x", "mac at 12:00", ten + 2 * hour, "m-edit"); fold_ops(&mac, std::slice::from_ref(&edit)).expect("the mac's own edit"); fold_pulled(&phone, std::slice::from_ref(&edit)).expect("the phone hears it"); // Real 14:00: the phone reboots and hears the relay a minute later. let (judge, cont) = (ten + 4 * hour + MINUTE, MINUTE); let release = pass(&phone, &at(Some(judge), judge, cont, BOOT)); assert!(release.redated.is_empty(), "13:00 is below the boot start, 14:00"); assert_eq!(release.released.len(), 1); assert_eq!(ms(&release.released[0].hlc), ten + 3 * hour, "released at its own 13:00 stamp"); fold_pulled(&mac, &release.released).expect("the mac hears the phone"); assert_eq!(title(&phone, "x").as_deref(), Some("phone at 10:00")); assert_eq!(title(&mac, "x").as_deref(), Some("phone at 10:00"), "the same on every device"); } /// The phone's own author fact, as it travelled. fn phone_fact(phone: &Driver) -> CottonOp { let author = text(phone, "SELECT author_id AS v FROM _meta").expect("an author"); let row = phone .get("SELECT op_id, bytes FROM _writes WHERE tbl = 'cotton_authors' AND row_id = ?", &[SqlValue::Text(author)]) .expect("reads") .expect("the fact"); cotton_store::stored::receipt_row(&row).expect("an op") } /// RULE: After the pass last_hlc is never below a stamp the file still holds at or below J + 10 min — a peer's adopted write a few minutes ahead included — so the next local edit of that field is not refused as stale. #[test] fn release_pass_never_lowers_last_hlc_below_a_remaining_stamp() { let phone = authored("device:phone", "a-"); let mut ids = Ids(0, "op-"); let born = write(&phone, "p", &at(Some(J - MINUTE), J - MINUTE, 1_000, BOOT), &mut ids).expect("Checked"); let (mac, mac_author) = peer("device:mac", "m-", &phone); fold_pulled(&mac, &[phone_fact(&phone), born.ops[0].clone()]).expect("the mac has p"); write(&phone, "q", &at(None, J + YEAR, 2_000, BOOT), &mut ids).expect("held"); // The mac's edit, five minutes ahead of judge time, folded in unbounded. let judge = J + 2 * MINUTE; let edit = peer_title(&mac, &mac_author, "p", "mac", judge + 5 * MINUTE, "m-edit"); fold_pulled(&phone, std::slice::from_ref(&edit)).expect("folds"); let release = pass(&phone, &at(Some(judge), judge, 2_000 + 2 * MINUTE, BOOT)); assert_eq!(release.redated.len(), 1); let last = text(&phone, "SELECT last_hlc AS v FROM _meta").expect("a clock"); assert!(ms(&last) <= judge + FUTURE_BOUND_MS, "the year-ahead stamp is gone: {last}"); assert!(last.as_str() >= edit.hlc.as_str(), "{last} below the remaining {}", edit.hlc); let next = titled(&phone, "p", "phone", &at(Some(judge + 1), judge + 1, 3_000 + 2 * MINUTE, BOOT), &mut ids); assert!(next.minted_author.is_none(), "{:?}", next.minted_author); assert_eq!(title(&phone, "p").as_deref(), Some("phone"), "the next edit wins"); } /// RULE: Released and re-dated receipts keep mint order in one running stamp: a write re-dated to a mint time below an earlier released stamp lands one counter above it, never below. #[test] fn released_and_redated_receipts_keep_mint_order_in_one_running_stamp() { let db = authored("device:phone", "a-"); let mut ids = Ids(0, "op-"); let w = J; // X at real w, wall 90 s fast: honest enough to release. let x = write(&db, "x", &at(None, w + 90_000, 1_000, BOOT), &mut ids).expect("held"); // Y ten seconds later, wall a year ahead: re-dated to w + 10 s. let y = write(&db, "y", &at(None, w + YEAR, 11_000, BOOT), &mut ids).expect("held"); let release = pass(&db, &at(Some(w + 10 * MINUTE), w + 10 * MINUTE, 1_000 + 10 * MINUTE, BOOT)); assert_eq!(release.released.len(), 1); assert_eq!(release.released[0].op_id, x.ops[0].op_id); assert_eq!(release.redated.len(), 1); assert_eq!(release.redated[0].restamps.as_deref(), Some(y.ops[0].op_id.as_str())); assert_eq!(parts(&release.redated[0].hlc), (w + 90_000, 1), "max(m, previous + 1 counter)"); assert_eq!(parts(&release.author.as_ref().expect("an author").first_stamp), (w + 90_000, 0)); } /// RULE: A re-dated create is still a create: the row stays present, and its _born is the re-dated create's stamp — the same on this device and on a peer that folds what travelled. #[test] fn redate_of_a_creating_write_keeps_born() { let db = authored("device:phone", "a-"); let mut ids = Ids(0, "op-"); let held = write(&db, "t1", &at(None, J + YEAR, 1_000, BOOT), &mut ids).expect("held"); assert_eq!(text(&db, "SELECT _born AS v FROM cotton_todos WHERE id = 't1'"), Some(held.ops[0].hlc.clone())); let release = pass(&db, &at(Some(J + MINUTE), J + MINUTE, 1_000 + MINUTE, BOOT)); let create = &release.redated[0]; assert_eq!(canonical::decode(create.receipt.as_bytes()).expect("a receipt").kind, cotton_store::canonical::Kind::Create); assert_eq!(text(&db, "SELECT _born AS v FROM cotton_todos WHERE id = 't1'"), Some(create.hlc.clone())); assert_eq!(ms(&create.hlc), J); let other = authored("device:mac", "m-"); fold_pulled(&other, &travelling(&release)).expect("folds"); assert_eq!(text(&other, "SELECT _born AS v FROM cotton_todos WHERE id = 't1'"), Some(create.hlc.clone())); } /// RULE: A held write re-dated to when it was made loses to another device's later write it overtook while it was ahead — that write was kept, and competes again at its own stamp. #[test] fn redate_keeps_a_later_write_from_another_device_winning() { let phone = authored("device:phone", "a-"); let mut ids = Ids(0, "op-"); let born = write(&phone, "x", &at(Some(J - MINUTE), J - MINUTE, 1_000, BOOT), &mut ids).expect("Checked"); let (mac, mac_author) = peer("device:mac", "m-", &phone); fold_pulled(&mac, &[phone_fact(&phone), born.ops[0].clone()]).expect("the mac has x"); titled(&phone, "x", "phone at J", &at(None, J + YEAR, 2_000, BOOT), &mut ids); let later = peer_title(&mac, &mac_author, "x", "mac at J + 5 min", J + 5 * MINUTE, "m-edit"); fold_ops(&mac, std::slice::from_ref(&later)).expect("the mac's own"); fold_pulled(&phone, std::slice::from_ref(&later)).expect("the phone hears it"); assert_eq!(title(&phone, "x").as_deref(), Some("phone at J"), "the held write is ahead"); let release = pass(&phone, &at(Some(J + 10 * MINUTE), J + 10 * MINUTE, 2_000 + 10 * MINUTE, BOOT)); assert_eq!(ms(&release.redated[0].hlc), J); assert_eq!(title(&phone, "x").as_deref(), Some("mac at J + 5 min")); fold_pulled(&mac, &travelling(&release)).expect("the mac hears the re-date"); assert_eq!(title(&mac, "x").as_deref(), Some("mac at J + 5 min")); } /// RULE: A restamps names the receipt it replaces, and drops it only when both authors' facts name the same device credential and the write is the same; else the re-stamp is parked `conflict` and the named receipt stands. #[test] fn restamps_from_another_device_drops_nothing() { let phone = authored("device:phone", "a-"); let mut ids = Ids(0, "op-"); let target = write(&phone, "x", &at(Some(J), J, 1_000, BOOT), &mut ids).expect("Checked"); let named = &target.ops[0]; let receipt = canonical::decode(named.receipt.as_bytes()).expect("a receipt"); let restamp = |author: &str, receipt: &Receipt, op_id: &str| -> CottonOp { let restamping = Receipt { stamp: format!("{:013}:0001:{author}", J - MINUTE), author: author.to_string(), restamps: Some(named.op_id.clone()), ..receipt.clone() }; cotton_store::wire::from_receipt(op_id.to_string(), &restamping).expect("an op") }; let still_there = |db: &Driver| count(db, &format!("SELECT COUNT(*) AS n FROM _writes WHERE op_id = '{}'", named.op_id)); // Another device's author names it. let (_evil, evil) = peer("device:evil", "e-", &phone); let foreign = restamp(&evil, &receipt, "e-restamp"); let folded = fold_pulled(&phone, std::slice::from_ref(&foreign)).expect("folds"); assert_eq!(folded.parked.len(), 1, "{folded:?}"); assert!(folded.applied.is_empty()); assert_eq!(still_there(&phone), 1, "nothing dropped"); assert_eq!(title(&phone, "x").as_deref(), Some("x")); assert_eq!( count(&phone, "SELECT COUNT(*) AS n FROM _parked WHERE op_id = 'e-restamp' AND class = 'conflict'"), 1, "parked `conflict`" ); // This device's own second author, with a different value. let (_twin, twin) = peer("device:phone", "w-", &phone); let mut changed = receipt.clone(); changed.fields.insert("title".into(), json!("not mine")); let altered = restamp(&twin, &changed, "w-restamp"); let folded = fold_pulled(&phone, std::slice::from_ref(&altered)).expect("folds"); assert_eq!(folded.parked.len(), 1, "{folded:?}"); assert_eq!(still_there(&phone), 1, "nothing dropped"); assert_eq!(title(&phone, "x").as_deref(), Some("x")); assert_eq!( count(&phone, "SELECT COUNT(*) AS n FROM _parked WHERE op_id = 'w-restamp' AND class = 'conflict'"), 1, "parked `conflict`" ); // The same device and the same write: the old receipt goes. let same = restamp(&twin, &receipt, "w-same"); let folded = fold_pulled(&phone, std::slice::from_ref(&same)).expect("folds"); assert!(folded.parked.is_empty() && folded.applied.contains(&"w-same".to_string()), "{folded:?}"); assert_eq!(still_there(&phone), 0, "its own identical receipt is replaced"); } /// RULE: A refusal's re-date goes to the time the receipt was minted — J_r − (C − mint_cont) in this boot, the boot start J_r − C otherwise or with no mint_cont — never to the refusal's judge time J_r, "now". #[test] fn refusal_redate_targets_mint_time_not_now() { let j_r = J + 60 * MINUTE; let cont = 50 * MINUTE; assert_eq!(mint_time(j_r, cont, BOOT, Some(20 * MINUTE), Some(BOOT)), j_r - 30 * MINUTE); assert_eq!(mint_time(j_r, cont, BOOT, Some(20 * MINUTE), Some(OTHER_BOOT)), j_r - cont); assert_eq!(mint_time(j_r, cont, BOOT, None, None), j_r - cont); for minted in [Some(0), Some(cont - 1), None] { assert!(mint_time(j_r, cont, BOOT, minted, minted.map(|_| BOOT)) < j_r, "never now"); } } /// RULE (SITES ROWS, 26 Nov 2026): two phones edit one site's same column; the one whose clock runs an hour ahead /// edits first. Its stamp is corrected to judge time, so the later edit in true time carries the later stamp and is /// the one every copy keeps: a fast clock never wins a same-column edit (the core's own clock; Sites keeps none). #[test] fn same_column_edits_with_a_phone_clock_an_hour_ahead() { const HOUR: i64 = 60 * 60_000; let fast = authored("device:fast-phone", "f-"); let right = authored("device:right-phone", "r-"); let first = write(&fast, "site-club", &judged(Some(J), J + HOUR), &mut Ids(0, "fop-")).expect("mints"); assert!(matches!(first.state, ClockState::Corrected { .. }), "{:?}", first.state); assert_eq!(ms(&first.ops[0].hlc), J, "the fast phone's edit is stamped by judge time"); let later = write(&right, "site-club", &judged(Some(J + 60_000), J + 60_000), &mut Ids(0, "rop-")).expect("mints"); assert_eq!(later.state, ClockState::Checked); assert!(later.ops[0].hlc > first.ops[0].hlc, "the edit made a minute later carries the later stamp: {} {}", later.ops[0].hlc, first.ops[0].hlc); } /// RULE (QUEUE BAD OP, coordinator, 26 Nov 2026: one queued op that did not decode stopped every pass of the copy for /// good, and nothing said why): a held receipt that does not read is set aside as a refused push under the code /// `undecodable`, held no longer, counted; the release goes on with the rest. #[test] fn a_held_receipt_that_does_not_read_is_set_aside_and_the_release_goes_on() { let db = authored("dev-a", "a-"); let mut ids = Ids(0, "h-"); let held = judged(None, J); let good = write(&db, "t-good", &held, &mut ids).expect("a held write"); let bad = write(&db, "t-bad", &held, &mut ids).expect("a held write"); let bad_id = bad.ops.iter().find(|op| op.table == "cotton_todos").expect("the change").op_id.clone(); db.run("UPDATE _writes SET bytes = X'00FF' WHERE op_id = ?", &[SqlValue::Text(bad_id.clone())]).expect("damaged"); let release = pass(&db, &judged(Some(J), J)); let sent: Vec = travelling(&release).iter().map(|op| op.op_id.clone()).collect(); let good_id = good.ops.iter().find(|op| op.table == "cotton_todos").expect("the change").op_id.clone(); assert!(sent.contains(&good_id), "the good write goes: {sent:?}"); assert!(!sent.contains(&bad_id)); let parked = db.get("SELECT direction, class, reason, tbl, row_id FROM _parked WHERE op_id = ?", &[SqlValue::Text(bad_id.clone())]).expect("a read").expect("set aside"); assert_eq!((parked.text("direction"), parked.text("class"), parked.text("tbl"), parked.text("row_id")), (Some("push"), Some("conflict"), Some("cotton_todos"), Some("t-bad"))); assert!(parked.text("reason").is_some_and(|reason| reason.starts_with("undecodable: ")), "written down by its code"); assert_eq!(text(&db, &format!("SELECT CAST(held AS TEXT) AS v FROM _writes WHERE op_id = '{bad_id}'")).as_deref(), Some("3"), "set aside, a state of its own (QUEUE BAD OP 3)"); assert_eq!(cotton_store::mint::clock::held_count(&db).expect("held"), 0, "never waiting for the Mac's time over it"); assert_eq!(cotton_store::rejected::undecodable_count(&db).expect("a count"), 1); assert_eq!(cotton_store::outbox::waiting(&db).expect("waiting").by_code.get("undecodable"), Some(&1), "counted by its code"); // A second release before Let go trips on nothing, and sets it aside once. pass(&db, &judged(Some(J + 1_000), J + 1_000)); assert_eq!(cotton_store::rejected::undecodable_count(&db).expect("a count"), 1); } /// RULE (QUEUE BAD OP 3): a set-aside change that reads again (a later build) goes re-dated to a new stamp, never /// at its old one behind the author's later writes, and its park ends; one the person lets go leaves its row's /// receipts and is never set aside again. #[test] fn a_set_aside_change_that_reads_again_is_re_dated_and_one_let_go_leaves() { let db = authored("dev-a", "a-"); let mut ids = Ids(0, "h-"); let held = judged(None, J); let first = write(&db, "t-later", &held, &mut ids).expect("a held write"); let later_id = first.ops.iter().find(|op| op.table == "cotton_todos").expect("the change").op_id.clone(); let second = write(&db, "t-gone", &held, &mut ids).expect("a held write"); let gone_id = second.ops.iter().find(|op| op.table == "cotton_todos").expect("the change").op_id.clone(); let kept = db.get("SELECT bytes FROM _writes WHERE op_id = ?", &[SqlValue::Text(later_id.clone())]).expect("a read").expect("the receipt"); let bytes = match kept.get("bytes") { Some(SqlValue::Blob(bytes)) => bytes.clone(), other => panic!("{other:?}") }; for id in [&later_id, &gone_id] { db.run("UPDATE _writes SET bytes = X'00FF' WHERE op_id = ?", &[SqlValue::Text(id.clone())]).expect("damaged"); } pass(&db, &judged(Some(J), J)); assert_eq!(cotton_store::rejected::undecodable_count(&db).expect("a count"), 2); // A later build reads the first (its park's bytes read now); the person lets the second go. db.run("UPDATE _parked SET bytes = ? WHERE op_id = ?", &[SqlValue::Blob(bytes), SqlValue::Text(later_id.clone())]).expect("reads again"); assert_eq!(cotton_store::rejected::let_go_set_aside(&db, &gone_id).expect("let go"), 1, "its receipt leaves"); cotton_store::rejected::discard(&db, std::slice::from_ref(&gone_id)).expect("its park ends"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't-gone'"), 0, "its row assembled from what remains: nothing"); let release = pass(&db, &judged(Some(J + 1_000), J + 1_000)); assert!(release.released.iter().all(|op| op.op_id != later_id), "never sent at its old stamp"); let redated = release.redated.iter().find(|op| op.restamps.as_deref() == Some(later_id.as_str())).expect("re-dated"); assert_ne!(redated.hlc, first.ops.iter().find(|op| op.op_id == later_id).expect("the old").hlc, "a new stamp"); assert_eq!(cotton_store::rejected::undecodable_count(&db).expect("a count"), 0, "its park ended, and the one let go is not set aside again"); assert_eq!(title(&db, "t-later").as_deref().is_some(), true, "the change stands"); } /// RULE (QUEUE BAD OP 4, B2): a set-aside change that reads again keeps its ORIGINAL time under the fresh author, even /// released in a later boot days on: never the boot's start, so a day-1 edit never beats the person's day-3 edit. #[test] fn a_change_that_reads_again_after_a_reboot_keeps_its_original_time() { let db = authored("dev-a", "a-"); let mut ids = Ids(0, "h-"); let minted = write(&db, "t-day-one", &judged(None, J), &mut ids).expect("a held write"); let op = minted.ops.iter().find(|op| op.table == "cotton_todos").expect("the change"); let original = cotton_store::protocol::hlc::hlc_parts(&op.hlc).expect("a stamp").ms; let kept = db.get("SELECT bytes FROM _writes WHERE op_id = ?", &[SqlValue::Text(op.op_id.clone())]).expect("a read").expect("the receipt"); let bytes = match kept.get("bytes") { Some(SqlValue::Blob(bytes)) => bytes.clone(), other => panic!("{other:?}") }; db.run("UPDATE _writes SET bytes = X'00FF' WHERE op_id = ?", &[SqlValue::Text(op.op_id.clone())]).expect("damaged"); pass(&db, &judged(Some(J), J)); db.run("UPDATE _parked SET bytes = ? WHERE op_id = ?", &[SqlValue::Blob(bytes), SqlValue::Text(op.op_id.clone())]).expect("reads again"); let two_days = 2 * 24 * 60 * 60_000; let later_boot = Clock::judged(Some(J + two_days), J + two_days, 1_000, "6f1c1f55-0000-4000-8000-000000000002".to_string()); let release = release_held(&db, &later_boot, &mut Ids(0, "r-"), Held::Replica).expect("the pass"); let redated = release.redated.iter().find(|redated| redated.restamps.as_deref() == Some(op.op_id.as_str())).expect("re-dated"); assert_eq!(cotton_store::protocol::hlc::hlc_parts(&redated.hlc).expect("a stamp").ms, original, "its own time, not the later boot's start"); assert_ne!(redated.hlc, op.hlc, "a new stamp, under the fresh author"); } /// RULE (QUEUE BAD OP 4, B3): an earlier build's marks are brought to today's: a receipt set aside with `held = 0` /// beside its `undecodable` park is marked set aside (and tried again), and one marked let go (`held = 2`) leaves. #[test] fn an_earlier_builds_marks_are_brought_to_todays() { let db = authored("dev-a", "a-"); let mut ids = Ids(0, "h-"); let kept = write(&db, "t-kept", &judged(Some(J), J), &mut ids).expect("a write"); let kept_id = kept.ops.iter().find(|op| op.table == "cotton_todos").expect("the change").op_id.clone(); let gone = write(&db, "t-let-go", &judged(Some(J), J), &mut ids).expect("a write"); let gone_id = gone.ops.iter().find(|op| op.table == "cotton_todos").expect("the change").op_id.clone(); db.run( "INSERT INTO _parked (op_id, direction, class, reason, first_at, tries, bytes, sig, tbl, row_id) \ SELECT op_id, 'push', 'conflict', 'undecodable: an earlier build', '2026-11-26T00:00:00.000Z', 0, bytes, sig, tbl, row_id FROM _writes WHERE op_id = ?", &[SqlValue::Text(kept_id.clone())], ) .expect("QUEUE BAD OP 2's park"); db.run("UPDATE _writes SET held = 0 WHERE op_id = ?", &[SqlValue::Text(kept_id.clone())]).expect("held 0"); db.run("UPDATE _writes SET held = 2 WHERE op_id = ?", &[SqlValue::Text(gone_id.clone())]).expect("let go, as QUEUE BAD OP 2 marked it"); let moved = cotton_store::rejected::migrate_earlier_marks(&db).expect("migrated"); assert_eq!(moved, 2); assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM _writes WHERE op_id = '{kept_id}' AND held = 3")), 1, "set aside, so it is tried again"); assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM _writes WHERE op_id = '{gone_id}'")), 0, "let go: it leaves"); // Tried again: its bytes read, so it is held to be re-dated. assert_eq!(cotton_store::rejected::try_set_aside_again(&db, None).expect("tried"), vec![kept_id]); }