Cotton code
277 lines · 13.9 KB · RustRaw
//! TRIM (21 Nov 2026): a receipt the object served is kept as its identity//! while its row says it (`receipts::implied`, schema 151). These guard the//! owner's data: what a row assembles from, what a phone's own writes keep,//! and what reads a receipt's bytes, are what they were before.//!//! Every row is synthetic and every value invented.use std::collections::BTreeMap;use cotton_store::actor::{Actor, JobName};use cotton_store::exchange::fold_incoming;use cotton_store::fixtures::{file_at_version, NOW, OWNER, WORKSPACE};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{mint, served, Act, Change, Clock, Held, History, IdSource, ServedRow};use cotton_store::protocol::types::CottonOp;use cotton_store::receipts::{self, implied};use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value as JsonValue};const AUTHOR: &str = "object";fn file() -> Driver {    let db = file_at_version(SCHEMA_VERSION);    seed_meta(        &db,        &Meta { workspace_id: WORKSPACE.into(), owner_id: OWNER.into(), device_id: "phone-1".into(), last_server_seq: 0, last_hlc: None },        SCHEMA_VERSION,    )    .expect("seeds");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",        &[SqlValue::Text(WORKSPACE.into()), SqlValue::Text("A file".into()), SqlValue::Text(OWNER.into()), SqlValue::Text(NOW.into())],    )    .expect("the workspace row");    fold_incoming(&db, &[author()]).expect("the object's author");    db}fn actor() -> Actor {    Actor::device_job(JobName::named("object-sync").expect("a job name"))}fn author() -> CottonOp {    let stamp = format!("{:013}:0000:{AUTHOR}", 0);    let fields: BTreeMap<String, JsonValue> = [        ("workspace_id", json!(WORKSPACE)),        ("device_id", json!(AUTHOR)),        ("device_name", JsonValue::Null),        ("minted_at", json!("1970-01-01T00:00:00.000Z")),        ("reason", json!("first")),        ("first_stamp", json!(stamp)),    ]    .into_iter()    .map(|(k, v)| (k.to_string(), v))    .collect();    served("01JAUTHOR00000000000000000".into(), "cotton_authors", AUTHOR, &stamp, &actor(), ServedRow::Live(fields), None).expect("the fact")}fn fields(pairs: &[(&str, JsonValue)]) -> BTreeMap<String, JsonValue> {    pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()}/// A served todo `id` at `ms`, version `v`.fn todo(id: &str, ms: i64, v: u32, title: &str) -> CottonOp {    let stamp = format!("{ms:013}:{v:04}:{AUTHOR}");    let f = fields(&[        ("workspace_id", json!(WORKSPACE)),        ("title", json!(title)),        ("status", json!("open")),        ("priority", json!(0)),        ("created_at", json!(NOW)),        ("updated_at", json!(NOW)),    ]);    served(format!("01JTODO{id}{v:04}"), "cotton_todos", id, &stamp, &actor(), ServedRow::Live(f), None).expect("a receipt")}fn retracted(id: &str, ms: i64, v: u32) -> CottonOp {    served(format!("01JGONE{id}{v:04}"), "cotton_todos", id, &format!("{ms:013}:{v:04}:{AUTHOR}"), &actor(), ServedRow::Retracted, None).expect("a retract")}struct Ids(u32);impl IdSource for Ids {    fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result<String> {        self.0 += 1;        Ok(format!("op-own-{:06}", self.0))    }}/// The phone's own change of `id`, at wall time `ms`.fn own_change(db: &Driver, id: &str, ms: i64, patch: JsonValue, n: u32) {    mint(        db,        &Act {            actor: Actor::device_job(JobName::named("implied-test").expect("a name")),            verb: "test".into(),            history: History::None,            changes: vec![Change { kind: cotton_store::canonical::Kind::Change, table: "cotton_todos".into(), row_id: id.into(), patch: Some(patch.as_object().unwrap().clone()), delete: None }],        },        &Clock::wall(ms),        &mut Ids(n * 100),        Held::Replica,    )    .expect("the phone's own change");}fn implied_of(db: &Driver, id: &str) -> Vec<(String, bool)> {    db.all("SELECT op_id, implied IS NOT NULL AS implied FROM _writes WHERE tbl = 'cotton_todos' AND row_id = ? ORDER BY hlc", &[SqlValue::Text(id.into())])        .unwrap()        .iter()        .map(|r| (r.text("op_id").unwrap().to_string(), r.int("implied") == Some(1)))        .collect()}fn row(db: &Driver, id: &str) -> Option<(String, Option<String>, String)> {    db.get("SELECT title, notes, status FROM cotton_todos WHERE id = ?", &[SqlValue::Text(id.into())])        .unwrap()        .map(|r| (r.text("title").unwrap().to_string(), r.text("notes").map(str::to_string), r.text("status").unwrap().to_string()))}const T: i64 = 1_792_486_800_000;/// RULE (owner, 21 Nov 2026, TRIM): a served receipt that is its row's only one keeps its identity alone, and every reader of its bytes reads the bytes as minted.#[test]fn a_served_rows_only_receipt_is_implied_and_reads_back_as_minted() {    let db = file();    let op = todo("t-1", T, 4, "Ring the bank");    fold_incoming(&db, &[op.clone()]).expect("folds");    assert_eq!(implied_of(&db, "t-1"), vec![(op.op_id.clone(), true)]);    let held = db.get("SELECT bytes, fields FROM _writes WHERE op_id = ?", &[SqlValue::Text(op.op_id.clone())]).unwrap().unwrap();    assert!(matches!(held.get("bytes"), Some(SqlValue::Null) | None), "its bytes are gone");    let stored = receipts::of_row(&db, "cotton_todos", "t-1").expect("its receipts");    assert_eq!(stored.len(), 1);    assert_eq!(stored[0].bytes, op.receipt.as_bytes(), "the bytes made again are the bytes minted");    assert_eq!(row(&db, "t-1"), Some(("Ring the bank".into(), None, "open".into())));}/// RULE: the phone's own write keeps everything, and a row it changes assembles from the served receipt as minted: the row and every receipt end as they do on a copy whose served receipt was never implied.#[test]fn a_phones_own_write_keeps_everything_and_the_row_ends_as_on_a_copy_never_trimmed() {    let end = |whole: bool| {        let db = file();        let op = todo("t-1", T, 4, "Ring the bank");        fold_incoming(&db, &[op.clone()]).expect("folds");        if whole {            implied::materialize_row(&db, "cotton_todos", "t-1").expect("whole");        }        own_change(&db, "t-1", T + 60_000, json!({"notes": "before noon", "title": "Ring the bank today"}), 1);        own_change(&db, "t-1", T + 120_000, json!({"notes": "after lunch"}), 2);        let own = db.all("SELECT bytes, implied FROM _writes WHERE author <> 'object' AND tbl = 'cotton_todos'", &[]).unwrap();        assert!(!own.is_empty() && own.iter().all(|r| matches!(r.get("bytes"), Some(SqlValue::Blob(_)) | Some(SqlValue::Text(_))) && r.int("implied").is_none()), "the own receipts keep their bytes");        let receipts: Vec<(String, Vec<u8>)> = receipts::of_row(&db, "cotton_todos", "t-1").unwrap().into_iter().map(|s| (s.op_id, s.bytes)).collect();        (row(&db, "t-1"), receipts)    };    let trimmed = end(false);    assert_eq!(trimmed, end(true));    assert_eq!(trimmed.0, Some(("Ring the bank today".into(), Some("after lunch".into()), "open".into())));}/// RULE: a served receipt is implied beside a change of the phone's own to a field it does not name, and stays as minted when the own change touches one it names.#[test]fn a_served_receipt_is_implied_only_while_the_row_says_what_it_names() {    let db = file();    fold_incoming(&db, &[todo("t-1", T, 4, "Ring the bank")]).expect("folds");    own_change(&db, "t-1", T + 60_000, json!({"notes": "before noon"}), 1);    let newer = todo("t-1", T + 120_000, 5, "Ring the bank at noon");    fold_incoming(&db, &[newer.clone()]).expect("folds");    let held = implied_of(&db, "t-1");    assert!(held.contains(&(newer.op_id.clone(), true)), "implied beside the own note: {held:?}");    assert_eq!(row(&db, "t-1"), Some(("Ring the bank at noon".into(), Some("before noon".into()), "open".into())));    own_change(&db, "t-1", T + 180_000, json!({"title": "Ring the bank, then the plumber"}), 2);    assert!(implied_of(&db, "t-1").iter().all(|(_, implied)| !implied), "whole again once the own change lands");}/// RULE: a newer version replaces an implied one and is implied in turn; a retract takes the row away and its create back brings it; nothing is lost across them.#[test]fn a_newer_version_and_a_retract_fold_over_an_implied_receipt() {    let db = file();    fold_incoming(&db, &[todo("t-1", T, 4, "Ring the bank")]).expect("folds");    let newer = todo("t-1", T + 1000, 5, "Ring the bank at noon");    fold_incoming(&db, &[newer.clone()]).expect("folds");    assert!(implied_of(&db, "t-1").contains(&(newer.op_id.clone(), true)), "{:?}", implied_of(&db, "t-1"));    assert_eq!(row(&db, "t-1").map(|r| r.0), Some("Ring the bank at noon".into()));    fold_incoming(&db, &[retracted("t-1", T + 2000, 6)]).expect("folds");    assert_eq!(row(&db, "t-1"), None, "the retract takes it away");    fold_incoming(&db, &[todo("t-1", T + 3000, 7, "Back again")]).expect("folds");    assert_eq!(row(&db, "t-1").map(|r| r.0), Some("Back again".into()));}/// RULE (23 Nov 2026, CONTRACT.md "WhatsApp through the Mac"): a row the object holds ERASED (its tombstone says why) folds here as an erase: the row, every receipt of it and its words go, a `_gone` row keeps the reason, and a later write at its id never applies.#[test]fn a_served_erase_ends_the_row_and_its_receipts_for_good() {    let db = file();    fold_incoming(&db, &[todo("t-9", T, 4, "Invented secret words")]).expect("folds");    own_change(&db, "t-9", T + 500, json!({"title": "Invented secret words, again"}), 9);    let erase = served("01JERASEt-90006".into(), "cotton_todos", "t-9", &format!("{:013}:0006:{AUTHOR}", T + 1000), &actor(), ServedRow::Erased("disappeared".into()), None).expect("an erase");    let receipt = cotton_store::canonical::decode(erase.receipt.as_bytes()).expect("canonical bytes");    assert_eq!((receipt.kind, receipt.erase.as_deref()), (cotton_store::canonical::Kind::Retract, Some("disappeared")));    fold_incoming(&db, &[erase]).expect("folds");    assert_eq!(row(&db, "t-9"), None);    let left = db.all("SELECT op_id FROM _writes WHERE tbl = 'cotton_todos' AND row_id = 't-9'", &[]).unwrap();    assert!(left.is_empty(), "no receipt of it is kept: {}", left.len());    for place in ["_writes", "_outbox", "_parked"] {        let n = db.get(&format!("SELECT count(*) AS n FROM {place} WHERE instr(CAST(bytes AS BLOB), CAST('secret' AS BLOB)) > 0"), &[]).unwrap().and_then(|r| r.int("n")).unwrap_or(0);        assert_eq!(n, 0, "{place} keeps its words");    }    let gone = db.get("SELECT reason FROM _gone WHERE tbl = 'cotton_todos' AND row_id = 't-9'", &[]).unwrap().expect("a _gone row");    assert_eq!(gone.text("reason"), Some("disappeared"));    let later = fold_incoming(&db, &[todo("t-9", T + 2000, 7, "Back again")]).expect("folds");    assert_eq!(row(&db, "t-9"), None, "a later write at an erased id never applies: {:?}", later.rejected);}/// RULE: an existing copy is trimmed in place in bounded steps: every served receipt that may be is implied, a page at a time, and reads back as minted.#[test]fn an_existing_copy_is_trimmed_in_place_in_bounded_steps() {    let db = file();    let n = 1_234;    let ops: Vec<CottonOp> = (0..n).map(|i| todo(&format!("t-{i:05}"), T, 4, &format!("Invented todo {i}"))).collect();    fold_incoming(&db, &ops).expect("folds");    // As a copy before 151 held them: every receipt whole.    for i in 0..n {        implied::materialize_row(&db, "cotton_todos", &format!("t-{i:05}")).expect("whole");    }    let whole = db.get("SELECT COUNT(*) AS n FROM _writes WHERE implied IS NULL AND tbl = 'cotton_todos'", &[]).unwrap().unwrap().int("n").unwrap();    assert_eq!(whole, n as i64);    let (mut at, mut steps, mut trimmed) = (0, 0, 0);    loop {        let (next, implied) = implied::trim_step(&db, at).expect("a step");        steps += 1;        trimmed += implied;        match next {            Some(next) => at = next,            None => break,        }    }    assert_eq!(trimmed, n, "every served receipt implied");    assert!(steps >= n / implied::TRIM_PAGE as usize, "a page at a time: {steps} steps");    for (i, op) in ops.iter().enumerate().step_by(97) {        let stored = receipts::of_row(&db, "cotton_todos", &format!("t-{i:05}")).unwrap();        assert_eq!(stored[0].bytes, op.receipt.as_bytes());    }    let (again, _) = implied::trim_step(&db, 0).expect("again");    assert!(again.is_some() || n < implied::TRIM_PAGE as usize);}/// RULE: a parent's owned children are found through an implied receipt, as through a whole one (an event's attendees; a thread's messages the same way).#[test]fn an_owned_child_is_found_through_its_implied_receipt() {    let db = file();    let event = served(        "01JEVENT000000000000000001".into(),        "cotton_events",        "e-1",        &format!("{T:013}:0004:{AUTHOR}"),        &actor(),        ServedRow::Live(fields(&[("title", json!("Lunch")), ("starts_at", json!(NOW)), ("created_at", json!(NOW)), ("updated_at", json!(NOW))])),        None,    )    .unwrap();    let attendee = served(        "01JATTEND00000000000000001".into(),        "cotton_event_attendees",        "a-1",        &format!("{T:013}:0005:{AUTHOR}"),        &actor(),        ServedRow::Live(fields(&[("event_id", json!("e-1")), ("created_at", json!(NOW)), ("updated_at", json!(NOW))])),        None,    )    .unwrap();    let folded = fold_incoming(&db, &[event, attendee]).expect("folds");    assert!(folded.rejected.is_empty(), "{:?} {:?}", folded.rejected, db.all("SELECT reason FROM _parked", &[]).unwrap());    let implied = db.get("SELECT implied FROM _writes WHERE row_id = 'a-1'", &[]).unwrap().unwrap();    assert!(implied.int("implied").is_some(), "the attendee's receipt is implied");    let owned = cotton_store::erase::owned_descendants(&db, "cotton_events", "e-1").expect("its children");    assert!(owned.iter().any(|(table, id)| table == "cotton_event_attendees" && id == "a-1"), "{owned:?}");}