Cotton code
435 lines · 18.7 KB · RustRaw
//! Receipts and row life (design 3.1, 3.7, 3.8): two files that have seen the//! same writes hold the same receipts and the same rows, in any arrival order.use std::collections::BTreeMap;use cotton_store::actor::{Actor, JobName};use cotton_store::changes::changes_since;use cotton_store::cursors::cursor_ceiling;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::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<String> {        self.0 += 1;        Ok(format!("{}-{:04}", self.1, self.0))    }}/// One device's file, with its author minted.struct Dev {    db: Driver,    ids: Ids,    author: String,    fact: CottonOp,    actor: Actor,}/// Every device hears every other's author fact — what a first exchange does.fn meet(devs: &[&Dev]) {    for to in devs {        for from in devs {            if from.author != to.author {                to.take(std::slice::from_ref(&from.fact));            }        }    }}fn device(tag: &'static str, credential: &str) -> Dev {    let _ = NOW;    let db = file_at_version(SCHEMA_VERSION);    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, credential, Some(tag), AuthorReason::First, &Clock::wall(T0 - 10), &mut ids, Held::Served)        .expect("the author");    let actor = Actor::device_job(JobName::named("test").expect("a job name"));    Dev {        db,        ids,        author: author.id,        fact: author.fact,        actor,    }}fn obj(value: Value) -> Map<String, Value> {    value.as_object().expect("an object").clone()}fn todo(row_id: &str, title: &str) -> Map<String, Value> {    obj(json!({"id": row_id, "workspace_id": WORKSPACE, "title": title, "created_at": NOW, "updated_at": NOW}))}impl Dev {    fn act(&mut self, at_ms: i64, changes: Vec<Change>) -> Vec<CottonOp> {        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)            .expect("mints")            .ops    }    fn create(&mut self, at_ms: i64, table: &str, row_id: &str, patch: Map<String, Value>) -> Vec<CottonOp> {        self.act(at_ms, vec![Change::create(table, row_id, patch)])    }    fn change(&mut self, at_ms: i64, table: &str, row_id: &str, patch: Value) -> Vec<CottonOp> {        self.act(at_ms, vec![Change::update(table, row_id, obj(patch))])    }    fn retract(&mut self, at_ms: i64, table: &str, row_id: &str) -> Vec<CottonOp> {        self.act(at_ms, vec![Change::retract(table, row_id)])    }    fn take(&self, ops: &[CottonOp]) -> FoldResult {        arrive(&self.db, ops, Arrival::Handed).expect("folds")    }    /// Every receipt the file holds, as `(table, row, stamp, op id, bytes)`.    fn receipts(&self) -> Vec<(String, String, String, String, String)> {        self.db            .all("SELECT tbl, row_id, hlc, op_id, bytes FROM _writes ORDER BY tbl, row_id, hlc", &[])            .expect("reads")            .iter()            .map(|row| {                (                    row.text("tbl").unwrap_or_default().to_string(),                    row.text("row_id").unwrap_or_default().to_string(),                    row.text("hlc").unwrap_or_default().to_string(),                    row.text("op_id").unwrap_or_default().to_string(),                    match row.get("bytes") {                        Some(SqlValue::Blob(b)) => String::from_utf8_lossy(b).into_owned(),                        _ => String::new(),                    },                )            })            .collect()    }    fn tombstones(&self) -> Vec<(String, String, String, String, String)> {        self.db            .all("SELECT tbl, row_id, hlc, op_id, bytes FROM _tombstones ORDER BY tbl, row_id", &[])            .expect("reads")            .iter()            .map(|row| {                (                    row.text("tbl").unwrap_or_default().to_string(),                    row.text("row_id").unwrap_or_default().to_string(),                    row.text("hlc").unwrap_or_default().to_string(),                    row.text("op_id").unwrap_or_default().to_string(),                    match row.get("bytes") {                        Some(SqlValue::Blob(b)) => String::from_utf8_lossy(b).into_owned(),                        _ => String::new(),                    },                )            })            .collect()    }    fn row(&self, table: &str, row_id: &str) -> Option<BTreeMap<String, SqlValue>> {        self.db            .get(&format!("SELECT * FROM {table} WHERE id = ?"), &[SqlValue::Text(row_id.to_string())])            .expect("reads")            .map(|row| row.columns().iter().cloned().collect())    }    fn text(&self, table: &str, row_id: &str, column: &str) -> Option<String> {        self.row(table, row_id).and_then(|row| match row.get(column) {            Some(SqlValue::Text(t)) => Some(t.clone()),            _ => None,        })    }}fn same_file(a: &Dev, b: &Dev, table: &str, row_id: &str) {    assert_eq!(a.receipts(), b.receipts(), "receipts differ");    assert_eq!(a.tombstones(), b.tombstones(), "tombstones differ");    assert_eq!(a.row(table, row_id), b.row(table, row_id), "the row differs");}#[test]fn a_create_leaves_one_receipt_and_the_row_born_at_its_stamp() {    let mut a = device("a", "key-a");    let ops = a.create(T0, "cotton_todos", "t1", todo("t1", "Buy milk"));    assert_eq!(ops.len(), 1);    let receipts = a.receipts();    let own: Vec<_> = receipts.iter().filter(|r| r.0 == "cotton_todos").collect();    assert_eq!(own.len(), 1);    assert_eq!(own[0].3, ops[0].op_id, "the op id is stored beside the bytes");    assert_eq!(own[0].4, ops[0].receipt, "the bytes are stored as minted");    let row = a.row("cotton_todos", "t1").expect("present");    assert_eq!(row.get("_born"), Some(&SqlValue::Text(ops[0].hlc.clone())));    assert_eq!(row.get("_hlc"), Some(&SqlValue::Text(ops[0].hlc.clone())));    assert_eq!(row.get("title"), Some(&SqlValue::Text("Buy milk".to_string())));}/// RULE: Two devices that have seen the same writes hold byte-equal receipts and the same row, whatever order the writes arrived in.#[test]fn receipt_bytes_are_identical_on_every_device_whatever_the_arrival_order() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    meet(&[&a, &b]);    let c = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    let f1 = a.change(T0 + 10, "cotton_todos", "t1", json!({"title": "two"}));    let f2 = b.change(T0 + 20, "cotton_todos", "t1", json!({"notes": "from b"}));    // b hears a's writes backwards; a hears b's.    b.take(&f1);    b.take(&c);    a.take(&f2);    same_file(&a, &b, "cotton_todos", "t1");    assert_eq!(a.text("cotton_todos", "t1", "title").as_deref(), Some("two"));    assert_eq!(a.text("cotton_todos", "t1", "notes").as_deref(), Some("from b"));}/// RULE: A row's create is kept while it is the smallest create, even once every field it wrote was overwritten, so the row arrives whole on a device that never saw it.#[test]fn row_whose_creation_is_partly_overwritten_arrives_whole() {    let mut a = device("a", "key-a");    let c = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    let f = a.change(T0 + 10, "cotton_todos", "t1", json!({"title": "two", "updated_at": NOW, "created_at": NOW, "workspace_id": WORKSPACE}));    let own: Vec<_> = a.receipts().into_iter().filter(|r| r.0 == "cotton_todos").collect();    assert_eq!(own.len(), 2, "the create stays as the smallest create");    let b = device("b", "key-b");    meet(&[&a, &b]);    let page = changes_since(&a.db, &a.author, "", 100).expect("a page");    assert_eq!(page.ops.iter().filter(|op| op.table == "cotton_todos").count(), 2);    assert_eq!(page.ops.iter().find(|o| o.op_id == c[0].op_id).map(|o| &o.receipt), Some(&c[0].receipt), "the create travels as its minted bytes");    assert_eq!(page.ops.iter().find(|o| o.op_id == f[0].op_id).map(|o| &o.receipt), Some(&f[0].receipt));    b.take(&page.ops);    same_file(&a, &b, "cotton_todos", "t1");    assert_eq!(b.text("cotton_todos", "t1", "title").as_deref(), Some("two"));}/// RULE: The op id is minted once — a receipt forwarded by a third device or re-sent from the tables carries the id it was minted with.#[test]fn op_id_is_the_same_minted_or_forwarded() {    let mut a = device("a", "key-a");    let b = device("b", "key-b");    let c_dev = device("c", "key-c");    meet(&[&a, &b, &c_dev]);    let minted = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    b.take(&minted);    let page = changes_since(&b.db, &a.author, "", 100).expect("a page");    let forwarded: Vec<&CottonOp> = page.ops.iter().filter(|op| op.table == "cotton_todos").collect();    assert_eq!(forwarded.len(), 1);    assert_eq!(forwarded[0].op_id, minted[0].op_id);    assert_eq!(forwarded[0].receipt, minted[0].receipt);    c_dev.take(&page.ops);    assert_eq!(c_dev.receipts(), b.receipts());}/// RULE: Two columns of one record written concurrently on two devices both survive, because a record's fields merge column by column (a made table's values are its own columns since 137).#[test]fn concurrent_edits_to_different_columns_of_one_record_both_survive() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    meet(&[&a, &b]);    let c = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    b.take(&c);    let fa = a.change(T0 + 10, "cotton_todos", "t1", json!({"title": "two"}));    let fb = b.change(T0 + 10, "cotton_todos", "t1", json!({"notes": "kept"}));    a.take(&fb);    b.take(&fa);    same_file(&a, &b, "cotton_todos", "t1");    assert_eq!(a.text("cotton_todos", "t1", "title").as_deref(), Some("two"));    assert_eq!(a.text("cotton_todos", "t1", "notes").as_deref(), Some("kept"));}/// RULE: Clearing a column is a write whose receipt stays, so an older write of that column cannot bring it back.#[test]fn cleared_column_is_not_resurrected_by_older_write() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    meet(&[&a, &b]);    let mut first = todo("t1", "one");    first.insert("notes".into(), json!("first"));    let c = a.create(T0, "cotton_todos", "t1", first);    b.take(&c);    let older = b.change(T0 + 5, "cotton_todos", "t1", json!({"notes": "older"}));    let clear = a.change(T0 + 10, "cotton_todos", "t1", json!({"notes": null}));    b.take(&clear);    a.take(&older);    same_file(&a, &b, "cotton_todos", "t1");    assert_eq!(a.text("cotton_todos", "t1", "notes"), None);}/// RULE: A retract racing a field write ends the same on every device — the row gone, T set, the later change dormant.#[test]fn retract_racing_a_field_write_ends_equal_on_every_device() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    meet(&[&a, &b]);    let c = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    b.take(&c);    let r = b.retract(T0 + 10, "cotton_todos", "t1");    let f = a.change(T0 + 20, "cotton_todos", "t1", json!({"title": "pinned"}));    // Mac: C, F, R. Phone: C, R, F.    a.take(&r);    b.take(&f);    same_file(&a, &b, "cotton_todos", "t1");    assert!(a.row("cotton_todos", "t1").is_none(), "no row");    let dormant: Vec<_> = a.receipts().into_iter().filter(|x| x.0 == "cotton_todos").collect();    assert_eq!(dormant.len(), 1, "the change above T is dormant: {dormant:?}");    assert_eq!(dormant[0].3, f[0].op_id);    assert_eq!(a.tombstones()[0].2, r[0].hlc);    // A later create brings the row back live, with the dormant field.    let c3 = b.create(T0 + 30, "cotton_todos", "t1", todo("t1", "again"));    a.take(&c3);    same_file(&a, &b, "cotton_todos", "t1");    assert_eq!(a.text("cotton_todos", "t1", "title").as_deref(), Some("again"), "the create's own title is newer");}/// RULE: A change that arrives before its create is dormant, then live when the create lands.#[test]fn change_before_its_create_is_dormant_then_live() {    let mut a = device("a", "key-a");    let b = device("b", "key-b");    meet(&[&a, &b]);    let c = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    let f = a.change(T0 + 10, "cotton_todos", "t1", json!({"title": "two"}));    let early = b.take(&f);    assert_eq!(early.applied, vec![f[0].op_id.clone()], "stored, not refused: {early:?}");    assert!(b.row("cotton_todos", "t1").is_none(), "dormant: no table row");    b.take(&c);    same_file(&a, &b, "cotton_todos", "t1");    assert_eq!(b.text("cotton_todos", "t1", "title").as_deref(), Some("two"));}/// RULE: One derived id created on two devices converges: both creates kept, fields per field, `_born` the smaller.#[test]fn same_derived_id_created_on_two_devices_converges_on_born_and_fields() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    meet(&[&a, &b]);    let c1 = a.create(T0, "cotton_todos", "t1", todo("t1", "from a"));    let c2 = b.create(T0 + 10, "cotton_todos", "t1", obj(json!({"id": "t1", "workspace_id": WORKSPACE, "title": "from b", "notes": "only b", "created_at": NOW, "updated_at": NOW})));    b.take(&c1);    a.take(&c2);    same_file(&a, &b, "cotton_todos", "t1");    let row = a.row("cotton_todos", "t1").expect("live");    assert_eq!(row.get("title"), Some(&SqlValue::Text("from b".to_string())));    assert_eq!(row.get("notes"), Some(&SqlValue::Text("only b".to_string())));    assert_eq!(row.get("_born"), Some(&SqlValue::Text(c1[0].hlc.clone())));    assert_eq!(a.receipts().iter().filter(|r| r.0 == "cotton_todos").count(), 2);}/// RULE: A retract travels as its minted receipt — a third device and a snapshot-filled device hold bytes equal to the writer's.#[test]fn forwarded_retract_travels_as_its_minted_bytes() {    let mut a = device("a", "key-a");    let b = device("b", "key-b");    let c_dev = device("c", "key-c");    meet(&[&a, &b, &c_dev]);    let c = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    let r = a.retract(T0 + 10, "cotton_todos", "t1");    b.take(&c);    b.take(&r);    let page = changes_since(&b.db, &a.author, "", 100).expect("a page");    let retract = page.ops.iter().find(|op| op.op_id == r[0].op_id).expect("the retract travels");    assert_eq!(retract.receipt, r[0].receipt);    c_dev.take(&page.ops);    assert_eq!(c_dev.tombstones(), a.tombstones());    assert!(c_dev.row("cotton_todos", "t1").is_none());}/// RULE: A held receipt applies on its writer but never travels — not in a page, not in the position reported as seen.#[test]fn held_receipt_is_never_in_a_page_or_in_seen() {    let mut a = device("a", "key-a");    let c = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    let f = a.change(T0 + 10, "cotton_todos", "t1", json!({"title": "held"}));    a.db.run("UPDATE _writes SET held = 1 WHERE op_id = ?", &[SqlValue::Text(f[0].op_id.clone())]).expect("holds");    assert_eq!(a.text("cotton_todos", "t1", "title").as_deref(), Some("held"), "applies on its writer");    let page = changes_since(&a.db, &a.author, "", 100).expect("a page");    assert!(page.ops.iter().any(|op| op.op_id == c[0].op_id));    assert!(!page.ops.iter().any(|op| op.op_id == f[0].op_id), "a held receipt never travels");    let seen = cursor_ceiling(&a.db).expect("seen");    assert!(seen.get(&a.author).is_some_and(|top| top.as_str() < f[0].hlc.as_str()), "seen stops below the held stamp: {seen:?}");}/// RULE: A receipt that loses only to a held receipt is kept, so the write it overtook is still there when the held one is released or re-dated.#[test]fn receipt_losing_only_to_a_held_receipt_is_kept() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    meet(&[&a, &b]);    let c = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    b.take(&c);    let held = a.change(T0 + 20, "cotton_todos", "t1", json!({"title": "held"}));    a.db.run("UPDATE _writes SET held = 1 WHERE op_id = ?", &[SqlValue::Text(held[0].op_id.clone())]).expect("holds");    let loser = b.change(T0 + 10, "cotton_todos", "t1", json!({"title": "from b"}));    let result = a.take(&loser);    assert_eq!(result.applied, vec![loser[0].op_id.clone()], "kept, not dropped: {result:?}");    assert!(a.receipts().iter().any(|r| r.3 == loser[0].op_id));    assert_eq!(a.text("cotton_todos", "t1", "title").as_deref(), Some("held"), "the held one still shows on its writer");}/// RULE: Two keys of one record's data written concurrently on two devices both survive, because data is merged per key.#[test]fn concurrent_edits_to_different_keys_of_one_user_record_both_survive() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    meet(&[&a, &b]);    let c = a.create(        T0,        "cotton_records",        "r1",        obj(json!({"id": "r1", "workspace_id": WORKSPACE, "table_id": "tbl1", "data": {"a": 1, "b": "x"}, "created_at": NOW, "updated_at": NOW})),    );    b.take(&c);    let fa = a.change(T0 + 10, "cotton_records", "r1", json!({"data": {"a": 2}}));    let fb = b.change(T0 + 10, "cotton_records", "r1", json!({"data": {"b": "y"}}));    a.take(&fb);    b.take(&fa);    same_file(&a, &b, "cotton_records", "r1");    assert_eq!(a.text("cotton_records", "r1", "data").as_deref(), Some(r#"{"a":2,"b":"y"}"#));}/// RULE: Setting a key to null is a write whose receipt stays, so an older write of that key cannot bring it back.#[test]fn cleared_key_is_not_resurrected_by_older_write() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    meet(&[&a, &b]);    let c = a.create(        T0,        "cotton_records",        "r1",        obj(json!({"id": "r1", "workspace_id": WORKSPACE, "table_id": "tbl1", "data": {"a": 1}, "created_at": NOW, "updated_at": NOW})),    );    b.take(&c);    let older = b.change(T0 + 5, "cotton_records", "r1", json!({"data": {"a": 7}}));    let clear = a.change(T0 + 10, "cotton_records", "r1", json!({"data": {"a": null}}));    b.take(&clear);    a.take(&older);    same_file(&a, &b, "cotton_records", "r1");    assert_eq!(a.text("cotton_records", "r1", "data").as_deref(), Some("{}"));}