//! The author of a file and its fact: minted once when the device first holds //! the database; announced to every peer as the first receipt of its stream; //! and what a peer waits for before it applies anything else of that author's. use cotton_store::exchange::fold_incoming; use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE}; use cotton_store::fold::{arrive, author_has_fact, Arrival}; use cotton_store::meta::{seed_meta, Meta}; use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource}; use cotton_store::protocol::hlc::hlc_parts; use cotton_store::rejected::WAITING_FOR_AUTHOR; use cotton_store::schema::ddl::SCHEMA_VERSION; use cotton_store::Driver; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; const T0: i64 = 1_759_480_000_000; 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 unminted(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 } fn session_actor(db: &Driver) -> cotton_store::actor::Actor { db.run( "INSERT OR IGNORE 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"); cotton_store::actor::Actor::session(cotton_store::actor::SessionId::in_file(db, "s1").expect("the row")) } fn todo(row_id: &str, title: &str) -> Map { json!({"id": row_id, "workspace_id": WORKSPACE, "title": title, "created_at": NOW, "updated_at": NOW}) .as_object() .expect("an object") .clone() } fn text(db: &Driver, sql: &str) -> Option { db.get(sql, &[]).expect("reads").and_then(|row| { row.columns().first().and_then(|(_, value)| match value { SqlValue::Text(text) => Some(text.clone()), _ => None, }) }) } fn count(db: &Driver, sql: &str) -> i64 { db.get(sql, &[]).expect("reads").and_then(|row| row.int("n")).unwrap_or(0) } /// RULE: A file's author is minted once as device:, kept in _meta.author_id, and announced by a cotton_authors fact that is the first receipt of its own stream at first_stamp with counter 0; a second first-author is refused and every later mint stamps with that author. #[test] fn first_author_mints_the_files_author_and_its_fact() { let db = unminted("device:seeded-device"); let author = first_author(&db, "key-1", Some("Phone"), AuthorReason::First, &Clock::wall(T0), &mut Ids(0, "a-"), Held::Replica) .expect("mints the author"); assert_eq!(author.id, "device:a-0001", "the ulid is the caller's"); assert_eq!(text(&db, "SELECT author_id FROM _meta").as_deref(), Some(author.id.as_str())); let parts = hlc_parts(&author.first_stamp).expect("a stamp"); assert_eq!(parts.counter, 0, "a stream starts at counter 0"); assert_eq!(parts.ms, T0); assert_eq!(parts.device_id, author.id); assert_eq!(author.fact.table, "cotton_authors"); assert_eq!(author.fact.hlc, author.first_stamp, "the fact IS the first receipt of the stream"); assert_eq!(text(&db, "SELECT reason FROM cotton_authors").as_deref(), Some("first")); assert_eq!(text(&db, "SELECT device_id FROM cotton_authors").as_deref(), Some("key-1")); assert_eq!(text(&db, "SELECT device_name FROM cotton_authors").as_deref(), Some("Phone")); assert_eq!(text(&db, "SELECT first_stamp FROM cotton_authors"), Some(author.first_stamp.clone())); assert_eq!(text(&db, "SELECT _hlc FROM cotton_authors"), Some(author.first_stamp.clone())); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), 1, "a replica queues its fact"); assert!(author_has_fact(&db, &author.id).expect("asks")); let again = first_author(&db, "key-1", None, AuthorReason::First, &Clock::wall(T0 + 1), &mut Ids(0, "b-"), Held::Replica) .expect_err("one author per holding"); assert!(again.to_string().contains("already has the author"), "{again}"); let no_credential = first_author(&unminted("x"), "", None, AuthorReason::First, &Clock::wall(T0), &mut Ids(0, "c-"), Held::Served) .expect_err("names a credential"); assert!(no_credential.to_string().contains("device credential"), "{no_credential}"); let minted = mint( &db, &Act { actor: session_actor(&db), verb: "t".into(), history: History::None, changes: vec![Change::create("cotton_todos", "t1", todo("t1", "x"))] }, &Clock::wall(T0 + 5), &mut Ids(0, "op-"), Held::Replica, ) .expect("mints"); assert_eq!(minted.ops[0].device_id, author.id, "every later write is the author's"); assert!(minted.ops[0].hlc > author.first_stamp); } /// RULE: A take-over or a re-date replaces an author and refuses a file with none; a new stream starts above everything the file has stamped. #[test] fn a_take_over_replaces_the_author_and_starts_above_the_files_clock() { let db = unminted("device:seeded-device"); let refused = first_author(&db, "key-1", None, AuthorReason::TakeOver, &Clock::wall(T0), &mut Ids(0, "a-"), Held::Served) .expect_err("nothing to replace"); assert!(refused.to_string().contains("has none yet"), "{refused}"); let first = first_author(&db, "key-1", None, AuthorReason::First, &Clock::wall(T0), &mut Ids(0, "a-"), Held::Served).expect("first"); // The file's clock ran ahead of the wall (a peer's future stamp folded in). db.run("UPDATE _meta SET last_hlc = ?", &[SqlValue::Text(format!("{:013}:0007:device:peer", T0 + 60_000))]).expect("a clock ahead"); let next = first_author(&db, "key-1", None, AuthorReason::TakeOver, &Clock::wall(T0 + 1), &mut Ids(0, "b-"), Held::Served).expect("take-over"); assert_ne!(next.id, first.id); assert_eq!(text(&db, "SELECT author_id FROM _meta").as_deref(), Some(next.id.as_str())); let parts = hlc_parts(&next.first_stamp).expect("a stamp"); assert_eq!((parts.ms, parts.counter), (T0 + 60_001, 0), "counter 0, one millisecond above the clock"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_authors"), 2, "both facts stand"); assert_eq!(text(&db, &format!("SELECT reason FROM cotton_authors WHERE id = '{}'", next.id)).as_deref(), Some("take-over")); } /// RULE: A self-naming author fact never waits for itself; a receipt whose author has no fact here parks waiting and is never refused; the fact's arrival applies first and brings that author's parked receipts in. #[test] fn new_author_fact_applies_and_unblocks_its_receipts() { // A, the receiving file, holds its own author's fact — the one write path. let a = unminted("device:a-seed"); first_author(&a, "key-a", None, AuthorReason::First, &Clock::wall(T0), &mut Ids(0, "a-"), Held::Served).expect("A's author"); // B, a peer, mints its author and a todo under it. let b = unminted("device:b-seed"); let b_author = first_author(&b, "key-b", Some("B"), AuthorReason::First, &Clock::wall(T0 + 10), &mut Ids(0, "b-"), Held::Replica).expect("B's author"); let b_todo = mint( &b, &Act { actor: session_actor(&b), verb: "t".into(), history: History::None, changes: vec![Change::create("cotton_todos", "t1", todo("t1", "from B"))] }, &Clock::wall(T0 + 20), &mut Ids(0, "bop-"), Held::Replica, ) .expect("B writes"); let todo_op = b_todo.ops[0].clone(); // The todo reaches A before B's fact: held back, not refused, not applied. let folded = fold_incoming(&a, std::slice::from_ref(&todo_op)).expect("folds"); assert!(folded.rejected.is_empty(), "never refused: {:?}", folded.rejected); assert!(folded.applied_pairs.is_empty(), "not applied before its author is known"); assert_eq!(count(&a, "SELECT COUNT(*) AS n FROM cotton_todos"), 0); let parked_reason = text(&a, "SELECT reason FROM _parked").expect("parked whole"); assert_eq!(parked_reason, format!("{WAITING_FOR_AUTHOR}{}", b_author.id)); assert_eq!(text(&a, "SELECT direction FROM _parked").as_deref(), Some("pull"), "a held receipt is the peer's write this file has not taken"); // A retry before the fact keeps it parked, under the same reason. cotton_store::rejected::retry_rejected(&a, None, NOW).expect("retries"); assert_eq!(text(&a, "SELECT reason FROM _parked").as_deref(), Some(parked_reason.as_str())); assert_eq!(count(&a, "SELECT COUNT(*) AS n FROM cotton_todos"), 0); // B's fact arrives: it applies, and B's parked todo lands with it. let folded = fold_incoming(&a, std::slice::from_ref(&b_author.fact)).expect("folds the fact"); assert!(folded.rejected.is_empty(), "{:?}", folded.rejected); assert!(author_has_fact(&a, &b_author.id).expect("asks")); assert_eq!(count(&a, "SELECT COUNT(*) AS n FROM _parked"), 0, "nothing left parked"); assert_eq!(text(&a, "SELECT title FROM cotton_todos WHERE id = 't1'").as_deref(), Some("from B")); // In one batch, in the wrong order, the fact still goes first. let c = unminted("device:c-seed"); let c_author = first_author(&c, "key-c", None, AuthorReason::First, &Clock::wall(T0 + 30), &mut Ids(0, "c-"), Held::Replica).expect("C"); let c_todo = mint( &c, &Act { actor: session_actor(&c), verb: "t".into(), history: History::None, changes: vec![Change::create("cotton_todos", "t2", todo("t2", "from C"))] }, &Clock::wall(T0 + 40), &mut Ids(0, "cop-"), Held::Replica, ) .expect("C writes"); let result = arrive(&a, &[c_todo.ops[0].clone(), c_author.fact.clone()], Arrival::Handed).expect("folds"); assert_eq!(result.applied.len(), 2, "{result:?}"); assert!(result.waiting.is_empty()); assert_eq!(result.announced, vec![c_author.id.clone()]); assert_eq!(text(&a, "SELECT title FROM cotton_todos WHERE id = 't2'").as_deref(), Some("from C")); } /// RULE: A file whose own author was never minted is still on the old write paths and folds every author as before. #[test] fn an_unminted_file_does_not_wait() { let old = unminted("device:old-seed"); let b = unminted("device:b-seed"); let b_author = first_author(&b, "key-b", None, AuthorReason::First, &Clock::wall(T0), &mut Ids(0, "b-"), Held::Replica).expect("B"); let b_todo = mint( &b, &Act { actor: session_actor(&b), verb: "t".into(), history: History::None, changes: vec![Change::create("cotton_todos", "t1", todo("t1", "x"))] }, &Clock::wall(T0 + 1), &mut Ids(0, "bop-"), Held::Replica, ) .expect("B writes"); let result = arrive(&old, &[b_todo.ops[0].clone()], Arrival::Handed).expect("folds"); assert_eq!(result.applied.len(), 1, "an unminted file applies an unknown author: {result:?}"); assert!(result.waiting.is_empty()); let _ = b_author; } /// RULE: The first mint in a file that has no author yet mints it from `_meta.device_id` — the cotton_authors fact folded first, `_meta.author_id` set, every op stamped with the new author — and a file whose _meta names no device is refused by name instead of stamping for nobody. #[test] fn the_first_mint_in_a_file_with_no_author_mints_it_and_a_file_naming_no_device_is_refused() { let db = unminted("device:seeded-device"); let minted = mint( &db, &Act { actor: session_actor(&db), verb: "create_todo".into(), history: History::None, changes: vec![Change::create("cotton_todos", "t1", todo("t1", "x"))] }, &Clock::wall(T0), &mut Ids(0, "op-"), Held::Served, ) .expect("the first write mints the author"); let author = text(&db, "SELECT author_id FROM _meta").expect("an author"); assert_eq!(author, "device:op-0001", "the author's ulid is the caller's"); assert_ne!(author, "device:seeded-device", "the author is not the device's credential"); assert_eq!(text(&db, "SELECT id FROM cotton_authors"), Some(author.clone())); assert_eq!(text(&db, "SELECT device_id FROM cotton_authors").as_deref(), Some("device:seeded-device")); assert_eq!(text(&db, "SELECT reason FROM cotton_authors").as_deref(), Some("first")); let first_stamp = text(&db, "SELECT first_stamp FROM cotton_authors").expect("a stamp"); assert_eq!(minted.ops.len(), 1); assert_eq!(minted.ops[0].device_id, author); assert_eq!(hlc_parts(&minted.ops[0].hlc).expect("a stamp").device_id, author); assert!(minted.ops[0].hlc > first_stamp, "the fact is the first receipt of the stream"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), 0, "a served file queues nothing"); let nameless = unminted("device:seeded-device"); nameless.run("UPDATE _meta SET device_id = ''", &[]).expect("clears the device"); let refused = mint( &nameless, &Act { actor: session_actor(&nameless), verb: "create_todo".into(), history: History::None, changes: vec![Change::create("cotton_todos", "t1", todo("t1", "x"))] }, &Clock::wall(T0), &mut Ids(0, "op-"), Held::Served, ) .expect_err("no device, no author"); assert!(refused.to_string().contains("names no device"), "{refused}"); assert_eq!(count(&nameless, "SELECT COUNT(*) AS n FROM cotton_todos"), 0); assert_eq!(text(&nameless, "SELECT author_id FROM _meta"), None); }