//! Slice 6: a history row (`cotton_changes`) is a FACT — written once, never //! changed or retracted, and taken out only by an erase, which takes the //! record's history with it on every device. use std::sync::Arc; use cotton_store::actor::{Actor, JobName}; use cotton_store::fact_hooks::HISTORY_TABLE; use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE}; use cotton_store::fold::{arrive, Arrival, FoldResult}; 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::types::CottonOp; use cotton_store::schema::ddl::SCHEMA_VERSION; use cotton_store::signed::{KeySigner, ReceiptSigner}; use cotton_store::Driver; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; const T0: i64 = 1_759_480_000_000; const PROJECTS: &str = "cotton_memory_projects"; const P: &str = "00000000-0000-4000-8000-00000000a001"; const CHANGE: &str = "00000000-0000-4000-8000-00000000c001"; 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!("{}-{:05}", self.1, self.0)) } } struct Dev { db: Driver, ids: Ids, fact: CottonOp, actor: Actor, } fn device(tag: &'static str, seed: u8) -> Dev { let signer = Arc::new(KeySigner::of_seed(seed)); let key = signer.device_key(); let db = file_at_version(SCHEMA_VERSION).signed_by(signer); seed_meta( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: format!("device:{tag}"), last_server_seq: 0, last_hlc: None, }, SCHEMA_VERSION, ) .expect("seeds"); seed_workspace_row(&db); let mut ids = Ids(0, tag); let author = first_author(&db, &key, Some(tag), AuthorReason::First, &Clock::wall(T0 - 10), &mut ids, Held::Served) .expect("the author"); Dev { db, ids, fact: author.fact, actor: Actor::device_job(JobName::named("test").expect("a job name")) } } fn obj(value: Value) -> Map { value.as_object().expect("an object").clone() } impl Dev { fn try_act(&mut self, at_ms: i64, changes: Vec) -> cotton_store::Result> { let act = Act { actor: self.actor.clone(), verb: "test".to_string(), history: History::None, changes }; mint(&self.db, &act, &Clock::wall(at_ms), &mut self.ids, Held::Served).map(|minted| minted.ops) } fn act(&mut self, at_ms: i64, changes: Vec) -> Vec { self.try_act(at_ms, changes).expect("mints") } fn take(&self, ops: &[CottonOp]) -> FoldResult { arrive(&self.db, ops, Arrival::Handed).expect("folds") } fn history(&self) -> Vec { self.db .all(&format!("SELECT id, byline FROM {HISTORY_TABLE} ORDER BY id"), &[]) .expect("reads") .iter() .map(|row| format!("{} {}", row.text("id").unwrap_or_default(), row.text("byline").unwrap_or_default())) .collect() } fn gone(&self, table: &str, row_id: &str) -> bool { self.db .get( "SELECT 1 AS gone FROM _gone WHERE tbl = ? AND row_id = ?", &[SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())], ) .expect("reads") .is_some() } } /// P made, with its history row, in one act on the Mac, and handed to the phone. fn start() -> (Dev, Dev, Vec) { let mut mac = device("mac", 1); let phone = device("phone", 2); mac.take(std::slice::from_ref(&phone.fact)); phone.take(std::slice::from_ref(&mac.fact)); let born = mac.act( T0, vec![ Change::create( PROJECTS, P, obj(json!({"id": P, "workspace_id": WORKSPACE, "slug": "p", "name": "A", "created_at": NOW, "updated_at": NOW})), ), Change::create( HISTORY_TABLE, CHANGE, obj(json!({"id": CHANGE, "workspace_id": WORKSPACE, "table_id": "memory_projects", "record_id": P, "verb": "create", "byline": "Claude", "before": null, "after": {"name": "A"}, "created_at": NOW})), ), ], ); phone.take(&born); (mac, phone, born) } /// RULE: A history row is a fact — a change or a retract of it is refused on every device; only an erase takes it out. #[test] fn no_update_or_delete_of_a_history_row_outside_erase() { let (mut mac, mut phone, _) = start(); let edit = Change::update(HISTORY_TABLE, CHANGE, obj(json!({"undone_by": "someone"}))); assert!(mac.try_act(T0 + 10, vec![edit.clone()]).is_err(), "an edit of a history row is refused"); assert!( mac.try_act(T0 + 20, vec![Change::retract(HISTORY_TABLE, CHANGE)]).is_err(), "a retract of a history row is refused" ); assert!(phone.try_act(T0 + 30, vec![edit]).is_err(), "and on the peer"); assert_eq!(mac.history(), vec![format!("{CHANGE} Claude")]); assert_eq!(phone.history(), mac.history()); } /// RULE: Erasing a record erases its history on every device — no history row outlives it, and a late copy of one is never taken back. #[test] fn erase_leaves_no_history_row() { let (mut mac, phone, born) = start(); let erase = mac.act(T0 + 1_000, vec![Change::erase(PROJECTS, P, "bin")]); assert!(mac.history().is_empty(), "the erase took the history row on the device that erased"); assert!(mac.gone(HISTORY_TABLE, CHANGE), "the history row is kept gone"); phone.take(&erase); assert!(phone.history().is_empty(), "the erase took the history row on the peer"); assert!(phone.gone(HISTORY_TABLE, CHANGE)); phone.take(&born); assert!(phone.history().is_empty(), "a late copy of the history row is never taken back"); }