Cotton code
917 lines · 39.7 KB · RustRaw
//! Receipts converge (design 3.7, 3.5, 3.9): a file's state is a function of//! the receipts it holds — `_writes`, `_tombstones`, and the rows they make//! present — and never of the order those receipts arrived in. Two files that//! hold the same receipts hold the same rows, column for column, whichever//! device minted what and whichever way the writes travelled.//!//! The family used throughout is the projects family: a project//! (`cotton_memory_projects`, UNIQUE (workspace_id, slug)) OWNS its links//! (`cotton_project_links.project_id`, UNIQUE (project_id, record_kind,//! record_id)), and a session (`cotton_sessions.project_id`) names a project//! SOFTLY. Its CHECKs are easy to satisfy from a generator, and the design's//! four worked sequences are told in it.//!//! Only the store's public API is used: `mint` writes, `arrive` folds, and//! `changes_since` is what a full exchange sends.use std::collections::{BTreeMap, BTreeSet};use cotton_store::actor::{Actor, JobName};use cotton_store::changes::changes_since;use cotton_store::fixtures::{file_at_version, parked, 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;const PROJECTS: &str = "cotton_memory_projects";const LINKS: &str = "cotton_project_links";const SESSIONS: &str = "cotton_sessions";/// The replicated tables a comparison reads, parents first.const FAMILY: &[&str] = &[PROJECTS, LINKS, SESSIONS];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!("{}-{:05}", 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) -> Dev {    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, &format!("key-{tag}"), Some(tag), AuthorReason::First, &Clock::wall(T0 - 10), &mut ids, Held::Served)        .expect("the author");    Dev {        db,        ids,        author: author.id,        fact: author.fact,        actor: Actor::device_job(JobName::named("test").expect("a job name")),    }}fn obj(value: Value) -> Map<String, Value> {    value.as_object().expect("an object").clone()}fn project(id: &str, slug: &str, name: &str) -> Change {    Change::create(        PROJECTS,        id,        obj(json!({"id": id, "workspace_id": WORKSPACE, "slug": slug, "name": name, "created_at": NOW, "updated_at": NOW})),    )}fn link(id: &str, project_id: &str, record_id: &str, extra: Value) -> Change {    let mut fields = obj(json!({        "id": id, "workspace_id": WORKSPACE, "project_id": project_id, "record_kind": "note",        "record_id": record_id, "applied_by": "user", "created_at": NOW, "updated_at": NOW,    }));    fields.extend(obj(extra));    Change::create(LINKS, id, fields)}fn session(id: &str, project_id: Option<&str>, extra: Value) -> Change {    let mut fields = obj(json!({        "id": id, "workspace_id": WORKSPACE, "tool": "claude-code",        "last_active_at": NOW, "created_at": NOW, "updated_at": NOW,    }));    if let Some(p) = project_id {        fields.insert("project_id".to_string(), json!(p));    }    fields.extend(obj(extra));    Change::create(SESSIONS, id, fields)}fn bytes_text(value: Option<&SqlValue>) -> String {    match value {        Some(SqlValue::Blob(b)) => String::from_utf8_lossy(b).into_owned(),        Some(SqlValue::Text(t)) => t.clone(),        other => format!("{other:?}"),    }}impl Dev {    fn act(&mut self, at_ms: i64, changes: Vec<Change>) -> Vec<CottonOp> {        self.try_act(at_ms, changes).expect("mints")    }    fn try_act(&mut self, at_ms: i64, changes: Vec<Change>) -> cotton_store::Result<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).map(|minted| minted.ops)    }    fn take(&self, ops: &[CottonOp]) -> FoldResult {        arrive(&self.db, ops, Arrival::Handed).expect("folds")    }    fn present(&self, table: &str, row_id: &str) -> bool {        self.db            .get(&format!("SELECT 1 AS here FROM {table} WHERE id = ?"), &[SqlValue::Text(row_id.to_string())])            .expect("reads")            .is_some()    }    fn column(&self, table: &str, row_id: &str, column: &str) -> Option<SqlValue> {        self.db            .get(&format!("SELECT {column} AS v FROM {table} WHERE id = ?"), &[SqlValue::Text(row_id.to_string())])            .expect("reads")            .and_then(|row| row.get("v").cloned())    }    fn text(&self, table: &str, row_id: &str, column: &str) -> Option<String> {        match self.column(table, row_id, column) {            Some(SqlValue::Text(t)) => Some(t),            _ => None,        }    }    /// The op ids of a row's receipts, in stamp order.    fn receipt_ids(&self, table: &str, row_id: &str) -> Vec<String> {        self.db            .all(                "SELECT op_id FROM _writes WHERE tbl = ? AND row_id = ? ORDER BY hlc, op_id",                &[SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())],            )            .expect("reads")            .iter()            .filter_map(|row| row.text("op_id").map(str::to_string))            .collect()    }    /// A row's tombstone, as `(stamp, op id)`.    fn tombstone(&self, table: &str, row_id: &str) -> Option<(String, String)> {        self.db            .get(                "SELECT hlc, op_id FROM _tombstones WHERE tbl = ? AND row_id = ?",                &[SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())],            )            .expect("reads")            .map(|row| (row.text("hlc").unwrap_or_default().to_string(), row.text("op_id").unwrap_or_default().to_string()))    }    /// Everything that replicates, item by item: every receipt and every    /// tombstone in the file (all tables, author facts included), as    /// `(table, row, stamp, op id, bytes)`, then every row of the family's    /// tables, every column.    fn state(&self) -> Vec<String> {        let mut out = Vec::new();        for row in self            .db            .all("SELECT tbl, row_id, hlc, op_id, bytes FROM _writes ORDER BY tbl, row_id, hlc, op_id", &[])            .expect("reads")        {            out.push(format!(                "_writes {} {} {} {} {}",                row.text("tbl").unwrap_or_default(),                row.text("row_id").unwrap_or_default(),                row.text("hlc").unwrap_or_default(),                row.text("op_id").unwrap_or_default(),                bytes_text(row.get("bytes")),            ));        }        for row in self            .db            .all("SELECT tbl, row_id, hlc, op_id, bytes FROM _tombstones ORDER BY tbl, row_id", &[])            .expect("reads")        {            out.push(format!(                "_tombstones {} {} {} {} {}",                row.text("tbl").unwrap_or_default(),                row.text("row_id").unwrap_or_default(),                row.text("hlc").unwrap_or_default(),                row.text("op_id").unwrap_or_default(),                bytes_text(row.get("bytes")),            ));        }        for table in FAMILY {            for row in self.db.all(&format!("SELECT * FROM {table} ORDER BY id"), &[]).expect("reads") {                let columns: BTreeMap<String, SqlValue> = row.columns().iter().cloned().collect();                out.push(format!("row {table} {columns:?}"));            }        }        out    }    /// Hand this device every receipt `from` holds, of every author, page by    /// page — what a full exchange in one direction sends.    fn take_everything_from(&self, from: &Dev, authors: &[String]) -> Vec<String> {        let mut rejected = Vec::new();        for author in authors {            let mut since = String::new();            loop {                let page = changes_since(&from.db, author, &since, 500).expect("a page");                if page.ops.is_empty() {                    break;                }                rejected.extend(self.take(&page.ops).rejected.into_iter().map(|r| r.reason));                match (page.has_more, page.next_hlc) {                    (true, Some(next)) => since = next,                    _ => break,                }            }        }        rejected    }}/// The first item two states differ in, or `None` when they are equal.fn first_difference(a: &[String], b: &[String]) -> Option<String> {    let left: BTreeSet<&String> = a.iter().collect();    let right: BTreeSet<&String> = b.iter().collect();    if let Some(only) = left.difference(&right).next() {        return Some(format!("only on the first: {only}"));    }    if let Some(only) = right.difference(&left).next() {        return Some(format!("only on the second: {only}"));    }    if a != b {        return Some(format!("same items, different multiplicity ({} vs {})", a.len(), b.len()));    }    None}fn assert_same_files(devs: &[&Dev], context: &str) {    let first = devs[0].state();    for (i, dev) in devs.iter().enumerate().skip(1) {        if let Some(diff) = first_difference(&first, &dev.state()) {            panic!("{context}: device 0 and device {i} differ — {diff}");        }    }}// ---------------------------------------------------------------------------// The property test// ---------------------------------------------------------------------------/// splitmix64: small, deterministic, and enough for shuffles and choices.struct Rng(u64);impl Rng {    fn next(&mut self) -> u64 {        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);        let mut z = self.0;        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);        z ^ (z >> 31)    }    fn below(&mut self, n: usize) -> usize {        (self.next() % n as u64) as usize    }    fn chance(&mut self, percent: u64) -> bool {        self.next() % 100 < percent    }    fn pick<'a>(&mut self, from: &[&'a str]) -> &'a str {        from[self.below(from.len())]    }    fn shuffle<T>(&mut self, items: &mut [T]) {        for i in (1..items.len()).rev() {            let j = self.below(i + 1);            items.swap(i, j);        }    }}const PROJECT_IDS: &[&str] = &["p0", "p1", "p2"];const RECORD_IDS: &[&str] = &["n0", "n1", "n2"];const SESSION_IDS: &[&str] = &["s0", "s1"];const LINK_IDS: &[&str] = &["l0", "l1", "l2", "l3"];const NAMES: &[&str] = &["Alpha", "Beta", "Gamma", "Delta"];const SLUGS: &[&str] = &["alpha", "beta", "gamma"];const TITLES: &[&str] = &["first", "second", "third"];/// How a history is drawn.#[derive(Clone, Copy)]struct Shape {    /// Whether different row ids may take one UNIQUE value: two projects one    /// slug, two links one (project, kind, record). When false every UNIQUE    /// value is derived from the row id, so only same-id creates collide.    unique_collisions: bool,    /// Whether sessions take part, pointing their SOFT `project_id` at    /// projects.    soft_refs: bool,    /// Whether every create names every field a change may write (with a    /// value that is not the column's default), so no field of a live row is    /// ever given by a change alone.    full_creates: bool,}/// What the generator did across a run, so the run can show it was not vacuous.#[derive(Default, Debug)]struct Tally {    minted_acts: usize,    refused_acts: usize,    retracts: usize,    same_id_creates: usize,    recreates_after_retract: usize,    child_creates: usize,    soft_points: usize,    rejected_on_arrival: usize,    rejection_reasons: BTreeMap<String, usize>,    dormant_at_end: usize,    parked_at_end: i64,}impl Tally {    fn reject(&mut self, reasons: Vec<String>) {        self.rejected_on_arrival += reasons.len();        for reason in reasons {            let short: String = reason.chars().take(90).collect();            *self.rejection_reasons.entry(short).or_default() += 1;        }    }}/// One random act's changes for device `d`.fn random_change(rng: &mut Rng, shape: Shape) -> (Change, &'static str, String) {    let roll = rng.below(if shape.soft_refs { 100 } else { 75 });    let derived_slug = |p: &str| format!("slug-{p}");    match roll {        // a project's create — same ids on several devices are the point        0..=17 => {            let id = rng.pick(PROJECT_IDS);            let slug = if shape.unique_collisions { rng.pick(SLUGS).to_string() } else { derived_slug(id) };            let name = rng.pick(NAMES);            let mut change = project(id, &slug, name);            if shape.full_creates || rng.chance(40) {                change = Change::create(                    PROJECTS,                    id,                    obj(json!({"id": id, "workspace_id": WORKSPACE, "slug": slug, "name": name,                        "description": format!("about {name}"), "created_at": NOW, "updated_at": NOW})),                );            }            (change, "create", format!("{PROJECTS}/{id}"))        }        // a change of one or two of a project's fields        18..=29 => {            let id = rng.pick(PROJECT_IDS);            let mut patch = Map::new();            match rng.below(3) {                1 if shape.full_creates => {                    patch.insert("description".into(), json!(rng.pick(TITLES)));                }                0 => {                    patch.insert("name".into(), json!(rng.pick(NAMES)));                }                1 => {                    patch.insert("description".into(), json!(rng.pick(TITLES)));                    patch.insert("status".into(), json!(if rng.chance(50) { "archived" } else { "active" }));                }                _ => {                    patch.insert("name".into(), json!(rng.pick(NAMES)));                    patch.insert("description".into(), Value::Null);                }            }            (Change::update(PROJECTS, id, patch), "change", format!("{PROJECTS}/{id}"))        }        30..=39 => {            let id = rng.pick(PROJECT_IDS);            (Change::retract(PROJECTS, id), "retract", format!("{PROJECTS}/{id}"))        }        // a link under a project        40..=57 => {            let p = rng.pick(PROJECT_IDS);            let r = rng.pick(RECORD_IDS);            let id = if shape.unique_collisions { rng.pick(LINK_IDS).to_string() } else { format!("l-{p}-{r}") };            let extra = if shape.full_creates || rng.chance(50) { json!({"note": rng.pick(TITLES)}) } else { json!({}) };            (link(&id, p, r, extra), "child", format!("{LINKS}/{id}"))        }        58..=67 => {            let id = if shape.unique_collisions {                rng.pick(LINK_IDS).to_string()            } else {                format!("l-{}-{}", rng.pick(PROJECT_IDS), rng.pick(RECORD_IDS))            };            let patch = if shape.full_creates {                obj(json!({"note": rng.pick(TITLES)}))            } else if rng.chance(50) {                obj(json!({"pinned": rng.chance(50)}))            } else {                obj(json!({"note": rng.pick(TITLES), "pinned": rng.chance(50)}))            };            (Change::update(LINKS, &id, patch), "change", format!("{LINKS}/{id}"))        }        68..=74 => {            let id = if shape.unique_collisions {                rng.pick(LINK_IDS).to_string()            } else {                format!("l-{}-{}", rng.pick(PROJECT_IDS), rng.pick(RECORD_IDS))            };            (Change::retract(LINKS, &id), "retract", format!("{LINKS}/{id}"))        }        // sessions: create, point the soft column at a project, retract        75..=82 => {            let id = rng.pick(SESSION_IDS);            let p = if rng.chance(60) { Some(rng.pick(PROJECT_IDS)) } else { None };            (session(id, p, json!({"title": rng.pick(TITLES)})), "create", format!("{SESSIONS}/{id}"))        }        83..=95 => {            let id = rng.pick(SESSION_IDS);            let mut patch = obj(json!({"project_id": rng.pick(PROJECT_IDS)}));            if rng.chance(30) {                patch.insert("title".into(), json!(rng.pick(TITLES)));            }            (Change::update(SESSIONS, id, patch), "soft", format!("{SESSIONS}/{id}"))        }        _ => {            let id = rng.pick(SESSION_IDS);            (Change::retract(SESSIONS, id), "retract", format!("{SESSIONS}/{id}"))        }    }}/// One seed: a random history over three devices, every op delivered to every/// other device in a random order, then full exchanges. Returns the devices/// for the caller to compare.fn run_seed(seed: u64, shape: Shape, tally: &mut Tally) -> [Dev; 3] {    let mut rng = Rng(seed.wrapping_mul(0x2545_F491_4F6C_DD1D) ^ 0xC077_0DB0);    let mut devs = [device("a"), device("b"), device("c")];    meet(&[&devs[0], &devs[1], &devs[2]]);    let authors: Vec<String> = devs.iter().map(|d| d.author.clone()).collect();    // Every op each device minted, act by act.    let mut minted: [Vec<Vec<CottonOp>>; 3] = [Vec::new(), Vec::new(), Vec::new()];    // Which rows were created on which device, and which were retracted, so    // the tally can count same-id creates and re-creates.    let mut created_on: BTreeMap<String, BTreeSet<usize>> = BTreeMap::new();    let mut retracted: BTreeSet<String> = BTreeSet::new();    let acts = 20 + rng.below(21);    for step in 0..acts {        let d = rng.below(3);        // Now and then a device hears part of what another has minted so far,        // in a random order, so later acts build on rows made elsewhere.        if rng.chance(25) {            let from = (d + 1 + rng.below(2)) % 3;            let mut heard: Vec<CottonOp> = minted[from].iter().flatten().cloned().collect();            rng.shuffle(&mut heard);            heard.truncate(rng.below(heard.len() + 1));            if !heard.is_empty() {                if tracing() {                    eprintln!("GOSSIP dev{d} hears {:?}", heard.iter().map(|o| &o.op_id).collect::<Vec<_>>());                }                let reasons = devs[d].take(&heard).rejected.into_iter().map(|r| r.reason).collect();                tally.reject(reasons);            }        }        let (change, kind, key) = random_change(&mut rng, shape);        let mut changes = vec![change];        // Sometimes a link rides in the same act as its parent's create.        if kind == "create" && key.starts_with(PROJECTS) && rng.chance(25) {            let p = key.trim_start_matches(&format!("{PROJECTS}/")).to_string();            let r = rng.pick(RECORD_IDS);            let id = if shape.unique_collisions { rng.pick(LINK_IDS).to_string() } else { format!("l-{p}-{r}") };            changes.push(link(&id, &p, r, json!({"note": rng.pick(TITLES)})));        }        // Distinct, strictly increasing per device; the three clocks interleave.        let at = T0 + 1_000 * step as i64 + d as i64;        let trace = tracing();        let described = if trace { format!("{changes:?}") } else { String::new() };        let outcome = devs[d].try_act(at, changes);        if trace {            match &outcome {                Ok(ops) => eprintln!("ACT dev{d} at {at}: {described} -> {:?}", ops.iter().map(|o| (&o.op_id, &o.hlc)).collect::<Vec<_>>()),                Err(e) => eprintln!("REFUSED dev{d} at {at}: {described} -> {e}"),            }        }        match outcome {            Ok(ops) => {                tally.minted_acts += 1;                match kind {                    "retract" => {                        tally.retracts += 1;                        retracted.insert(key.clone());                    }                    "create" | "child" => {                        if kind == "child" {                            tally.child_creates += 1;                        }                        let on = created_on.entry(key.clone()).or_default();                        if on.iter().any(|other| *other != d) {                            tally.same_id_creates += 1;                        }                        on.insert(d);                        if retracted.contains(&key) {                            tally.recreates_after_retract += 1;                        }                    }                    "soft" => tally.soft_points += 1,                    _ => {}                }                minted[d].push(ops);            }            // A local act mint refuses (a change to a row the device does not            // show, a create under a parent it does not show, a UNIQUE clash on            // this file) is simply not part of the history.            Err(_) => tally.refused_acts += 1,        }    }    // Every op to every other device, a different random order per receiver,    // in random batch sizes.    for (to, receiver) in devs.iter().enumerate() {        let mut incoming: Vec<CottonOp> =            (0..3).filter(|from| *from != to).flat_map(|from| minted[from].iter().flatten().cloned()).collect();        rng.shuffle(&mut incoming);        let mut rest = incoming.as_slice();        while !rest.is_empty() {            let size = 1 + rng.below(4.min(rest.len()));            let (batch, tail) = rest.split_at(size);            if tracing() {                eprintln!("DELIVER dev{to} takes {:?}", batch.iter().map(|o| &o.op_id).collect::<Vec<_>>());            }            let reasons = receiver.take(batch).rejected.into_iter().map(|r| r.reason).collect();            tally.reject(reasons);            rest = tail;        }    }    // Full exchanges until quiet: every device takes every other's whole    // stream, twice round.    for _ in 0..2 {        for receiver in &devs {            for sender in &devs {                if sender.author != receiver.author {                    let reasons = receiver.take_everything_from(sender, &authors);                    tally.reject(reasons);                }            }        }    }    devs}fn dormant_count(dev: &Dev) -> usize {    let mut n = 0;    for table in FAMILY {        n += dev            .db            .all(                &format!("SELECT DISTINCT row_id FROM _writes WHERE tbl = ? AND row_id NOT IN (SELECT id FROM {table})"),                &[SqlValue::Text((*table).to_string())],            )            .expect("reads")            .len();    }    n}/// Check one seed's three files; `Err` names the seed and the first difference.fn check_seed(seed: u64, shape: Shape, tally: &mut Tally) -> Result<(), String> {    let devs = run_seed(seed, shape, tally);    let states: Vec<Vec<String>> = devs.iter().map(Dev::state).collect();    for (i, state) in states.iter().enumerate().skip(1) {        if let Some(diff) = first_difference(&states[0], state) {            return Err(format!("seed {seed}: device a and device {} differ — {diff}", ["a", "b", "c"][i]));        }    }    let parks: Vec<i64> = devs.iter().map(|d| parked(&d.db)).collect();    if parks.iter().any(|p| *p != parks[0]) {        return Err(format!("seed {seed}: parked differs across devices: {parks:?}"));    }    tally.parked_at_end += parks[0];    tally.dormant_at_end += dormant_count(&devs[0]);    Ok(())}const SEEDS: u64 = 60;/// `CONVERGE_TRACE=1` prints every act, refusal and delivery of a run, to/// shrink a failing seed by hand.fn tracing() -> bool {    std::env::var("CONVERGE_TRACE").is_ok()}fn property(shape: Shape) {    let mut tally = Tally::default();    let mut failures = Vec::new();    for seed in 0..SEEDS {        if let Err(failure) = check_seed(seed, shape, &mut tally) {            failures.push(failure);        }    }    eprintln!("receipts_converge tally over {SEEDS} seeds: {tally:?}");    assert!(failures.is_empty(), "{} of {SEEDS} seeds diverged; first: {}\nall: {failures:#?}", failures.len(), failures[0]);    // Not vacuous: the histories really held what the property is about.    assert!(tally.retracts > 0 && tally.same_id_creates > 0 && tally.recreates_after_retract > 0, "{tally:?}");    assert!(tally.child_creates > 0 && tally.dormant_at_end > 0, "{tally:?}");    assert!(!shape.soft_refs || tally.soft_points > 0, "{tally:?}");}/// RULE: Three devices that wrote random histories with creates, same-id creates, UNIQUE collisions, changes, retracts, re-creates, owned children and soft references end with equal receipts, tombstones and rows once each has heard everything, whatever order it heard it in.#[test]#[ignore = "diverges today in two ways, each pinned by a narrower test below: a soft column is still a FOREIGN KEY (cotton_sessions.project_id, 3b), a UNIQUE clash between different ids is refused on arrival (B7, 3c)"]fn fields_converge_on_random_histories_with_deletes_and_same_id_creates() {    property(Shape { unique_collisions: true, soft_refs: true, full_creates: false });}/// RULE: Random histories over an owning family — creates, same-id creates, changes, retracts, re-creates, children created under parents that other devices retract — end with equal receipts, tombstones and rows on all three devices, whatever order each heard them in.#[test]fn fields_converge_on_random_histories_of_an_owning_family() {    property(Shape { unique_collisions: false, soft_refs: false, full_creates: true });}/// RULE: The owning-family property still holds when a field is written only by changes, never by the row's surviving create.#[test]fn fields_converge_on_random_histories_where_changes_write_fields_no_create_names() {    property(Shape { unique_collisions: false, soft_refs: false, full_creates: false });}/// RULE: The owning-family property holds with sessions pointing their soft `project_id` at projects that come and go.#[test]fn fields_converge_on_random_histories_with_soft_references() {    property(Shape { unique_collisions: false, soft_refs: true, full_creates: true });}/// RULE: The owning-family property holds when two different row ids take one UNIQUE value on two devices.#[test]#[ignore = "B7 (accepted until slice 3c, design 5.1): a UNIQUE clash between two different row ids is refused on arrival, so which row holds the key depends on arrival order"]fn fields_converge_on_random_histories_with_unique_collisions_between_ids() {    property(Shape { unique_collisions: true, soft_refs: false, full_creates: true });}/// RULE: A field whose only receipt falls below a retract is no longer that field's value, even on the device where the row stayed live through the retract because a newer create had already landed.#[test]fn field_written_only_below_a_retract_is_gone_on_every_device() {    let mut a = device("a");    let mut b = device("b");    meet(&[&a, &b]);    let c = a.act(T0, vec![project("p0", "slug-p0", "Alpha")]);    b.take(&c);    // a archives the project; b, not having heard, retracts it; a, not having    // heard the retract, creates the same id again.    let f = a.act(T0 + 10, vec![Change::update(PROJECTS, "p0", obj(json!({"status": "archived"})))]);    let r = b.act(T0 + 20, vec![Change::retract(PROJECTS, "p0")]);    let c2 = a.act(T0 + 30, vec![project("p0", "slug-p0", "Alpha")]);    a.take(&r);    b.take(&f);    b.take(&c2);    for dev in [&a, &b] {        assert_eq!(dev.receipt_ids(PROJECTS, "p0"), vec![c2[0].op_id.clone()], "only the create above the retract is kept");    }    assert_eq!(b.text(PROJECTS, "p0", "status").as_deref(), Some("active"));    assert_eq!(a.text(PROJECTS, "p0", "status").as_deref(), Some("active"), "no kept receipt names status: the default");    assert_same_files(&[&a, &b], "a field written only below the retract");}/// RULE: The convergence check can fail — two devices that did not exchange, or that differ in one column or one receipt, are reported different.#[test]fn convergence_check_detects_two_files_that_did_not_exchange() {    let mut a = device("a");    let mut b = device("b");    meet(&[&a, &b]);    a.act(T0, vec![project("p0", "slug-p0", "Alpha")]);    b.act(T0 + 1, vec![project("p0", "slug-p0", "Alpha")]);    let diff = first_difference(&a.state(), &b.state()).expect("two unexchanged files differ");    assert!(diff.contains("_writes"), "the first difference is a receipt: {diff}");    // After a full exchange they are equal; one changed column is then caught.    let authors = [a.author.clone(), b.author.clone()];    a.take_everything_from(&b, &authors);    b.take_everything_from(&a, &authors);    assert_eq!(first_difference(&a.state(), &b.state()), None, "after an exchange they are equal");    b.db.run("UPDATE cotton_memory_projects SET name = 'Tampered' WHERE id = 'p0'", &[]).expect("tampers");    let diff = first_difference(&a.state(), &b.state()).expect("a changed column is caught");    assert!(diff.contains("row cotton_memory_projects"), "{diff}");    // And a seed the property ran is really compared: one missing receipt fails it.    let mut tally = Tally::default();    let devs = run_seed(7, Shape { unique_collisions: false, soft_refs: false, full_creates: true }, &mut tally);    assert_eq!(first_difference(&devs[0].state(), &devs[1].state()), None, "seed 7 converges");    devs[1].db.run("DELETE FROM _writes WHERE rowid = (SELECT max(rowid) FROM _writes)", &[]).expect("drops one");    assert!(first_difference(&devs[0].state(), &devs[1].state()).is_some(), "a missing receipt is caught");}// ---------------------------------------------------------------------------// The design's four worked sequences (3.7)// ---------------------------------------------------------------------------const P: &str = "proj-p";/// RULE: One derived id created on two devices converges whichever arrives first: both creates kept, each field from the newer create that names it, `_born` the smaller create.#[test]fn sequence_1_one_derived_id_created_on_two_devices() {    let mut mac = device("mac");    let mut phone = device("phone");    meet(&[&mac, &phone]);    let p = mac.act(T0, vec![project(P, "pp", "P")]);    phone.take(&p);    let id = "link-n-p";    // The phone (offline) links N to P at t1; the Mac links the same pair at t2.    let c1 = phone.act(T0 + 10, vec![link(id, P, "note-n", json!({"note": "from the phone", "applied_by": "router"}))]);    let c2 = mac.act(T0 + 20, vec![link(id, P, "note-n", json!({"applied_by": "agent"}))]);    assert!(c1[0].hlc < c2[0].hlc, "t1 < t2");    // Mac: C2, then C1. Phone: C1, then C2.    mac.take(&c1);    phone.take(&c2);    for dev in [&mac, &phone] {        assert!(dev.present(LINKS, id), "live");        assert_eq!(dev.text(LINKS, id, "applied_by").as_deref(), Some("agent"), "C2's where both name it");        assert_eq!(dev.text(LINKS, id, "note").as_deref(), Some("from the phone"), "C1's where only C1 names it");        assert_eq!(dev.text(LINKS, id, "_born"), Some(c1[0].hlc.clone()), "_born is the smaller create");        assert_eq!(dev.receipt_ids(LINKS, id), vec![c1[0].op_id.clone(), c2[0].op_id.clone()], "receipts {{C1, C2}}");    }    assert_same_files(&[&mac, &phone], "sequence 1");}/// RULE: A retract racing a later field write ends with no row, the tombstone at the retract and the write dormant on every device, and a later re-create makes the row live from the re-create and that write.#[test]fn sequence_2_a_retract_racing_a_field_write() {    let mut mac = device("mac");    let mut phone = device("phone");    meet(&[&mac, &phone]);    let id = "link-x";    let born = mac.act(T0, vec![project(P, "pp", "P"), link(id, P, "note-x", json!({"note": "first life"}))]);    phone.take(&born);    let c = &born[1];    // The phone unlinks at t1; the Mac pins at t2 > t1.    let r = phone.act(T0 + 10, vec![Change::retract(LINKS, id)]);    let f = mac.act(T0 + 20, vec![Change::update(LINKS, id, obj(json!({"pinned": true})))]);    assert!(c.hlc < r[0].hlc && r[0].hlc < f[0].hlc, "t0 < t1 < t2");    // Mac: C, F, R. Phone: C, R, F.    mac.take(&r);    phone.take(&f);    for dev in [&mac, &phone] {        assert!(!dev.present(LINKS, id), "no row");        assert_eq!(dev.tombstone(LINKS, id), Some((r[0].hlc.clone(), r[0].op_id.clone())), "T = t1");        assert_eq!(dev.receipt_ids(LINKS, id), vec![f[0].op_id.clone()], "C dropped, F dormant");    }    assert_same_files(&[&mac, &phone], "sequence 2, after the race");    // The phone re-links at t3: both make the row live from C3 and F.    let c3 = phone.act(T0 + 30, vec![link(id, P, "note-x", json!({"note": "second life"}))]);    mac.take(&c3);    for dev in [&mac, &phone] {        assert!(dev.present(LINKS, id), "live again");        assert_eq!(dev.text(LINKS, id, "note").as_deref(), Some("second life"), "C3's field");        assert_eq!(dev.column(LINKS, id, "pinned"), Some(SqlValue::Integer(1)), "F's field, kept while dormant");        assert_eq!(dev.text(LINKS, id, "_born"), Some(c3[0].hlc.clone()), "born again at C3");    }    assert_same_files(&[&mac, &phone], "sequence 2, after the re-link");}/// RULE: A parent retracted while a child is created under it elsewhere leaves the parent absent and both children dormant on every device, a create of the parent's id brings both children back everywhere, and a device that already folded the retract refuses a new child under it at mint.#[test]fn sequence_3_a_parent_retracted_while_a_child_is_created_under_it_then_the_retract_undone() {    let mut mac = device("mac");    let mut phone = device("phone");    meet(&[&mac, &phone]);    let (l0, l) = ("link-m", "link-n");    let born = mac.act(T0, vec![project(P, "pp", "P"), link(l0, P, "note-m", json!({}))]);    phone.take(&born);    // Step 1. The Mac retracts P at t1; the phone, offline, links N at t2 > t1.    let r = mac.act(T0 + 10, vec![Change::retract(PROJECTS, P)]);    assert_eq!(r.len(), 1, "a parent's retract mints nothing for its children");    assert!(!mac.present(LINKS, l0) && !mac.present(PROJECTS, P));    let child = phone.act(T0 + 20, vec![link(l, P, "note-n", json!({}))]);    assert!(r[0].hlc < child[0].hlc, "t1 < t2");    assert!(phone.present(LINKS, l));    // Step 2. The exchange.    let on_mac = mac.take(&child);    assert!(on_mac.rejected.is_empty(), "dormant, not refused: {on_mac:?}");    phone.take(&r);    for dev in [&mac, &phone] {        assert!(!dev.present(PROJECTS, P), "P absent");        assert!(!dev.present(LINKS, l0) && !dev.present(LINKS, l), "L0 and L dormant: no table rows");        assert_eq!(dev.receipt_ids(LINKS, l0), vec![born[1].op_id.clone()], "L0's receipt kept");        assert_eq!(dev.receipt_ids(LINKS, l), vec![child[0].op_id.clone()], "L's create kept");        assert!(dev.receipt_ids(PROJECTS, P).is_empty(), "P's receipts below t1 dropped");        assert_eq!(dev.tombstone(PROJECTS, P).map(|t| t.0), Some(r[0].hlc.clone()), "T_P = t1");        assert_eq!(parked(&dev.db), 0, "nothing parked");    }    assert_same_files(&[&mac, &phone], "sequence 3, after the exchange");    // The note's last sentence: a device that has folded R refuses a new link under P.    assert!(        phone.try_act(T0 + 25, vec![link("link-o", P, "note-o", json!({}))]).is_err(),        "a create under a parent that is not present is refused at mint"    );    assert!(phone.receipt_ids(LINKS, "link-o").is_empty(), "a refused mint leaves nothing");    // Steps 3-4. The undo, as the design mints it (3.5): a create of P's id at    // t3 > t2, naming P's fields (no receipt of P above t1 exists, so they are    // history's `before`). It names no child.    let u = mac.act(T0 + 30, vec![project(P, "pp", "P")]);    assert_eq!(u.len(), 1, "the undo names no child");    assert!(mac.present(LINKS, l0) && mac.present(LINKS, l), "the Mac re-assembles L0 and L");    phone.take(&u);    for dev in [&mac, &phone] {        assert!(dev.present(PROJECTS, P) && dev.present(LINKS, l0) && dev.present(LINKS, l), "P, L0, L present");        assert_eq!(dev.receipt_ids(PROJECTS, P), vec![u[0].op_id.clone()], "_writes for P = {{U}}");        assert_eq!(dev.tombstone(PROJECTS, P).map(|t| t.0), Some(r[0].hlc.clone()), "_tombstones = {{P: t1}}");    }    assert_same_files(&[&mac, &phone], "sequence 3, after the undo");}const SESSION: &str = "session-s";/// Sequence 4's start: P, and session S naming P softly, on both devices.fn sequence_4_start() -> (Dev, Dev, Vec<String>) {    let mut mac = device("mac");    let phone = device("phone");    meet(&[&mac, &phone]);    let born = mac.act(T0, vec![project(P, "pp", "P"), session(SESSION, Some(P), json!({"title": "work"}))]);    phone.take(&born);    let before = mac.receipt_ids(SESSIONS, SESSION);    assert_eq!(phone.receipt_ids(SESSIONS, SESSION), before);    (mac, phone, before)}/// RULE: Retracting a project that a session names softly, and undoing it, mints nothing for the session, leaves its receipts as they were on every device, never takes the session out, and keeps the two devices equal.#[test]fn sequence_4_a_soft_reference_mints_nothing_and_its_receipts_hold() {    let (mut mac, phone, before) = sequence_4_start();    let r = mac.act(T0 + 10, vec![Change::retract(PROJECTS, P)]);    assert!(        r.iter().all(|op| op.table == PROJECTS && op.row_id == P),        "the retract mints only for P: {:?}",        r.iter().map(|o| (&o.table, &o.row_id)).collect::<Vec<_>>()    );    phone.take(&r);    for dev in [&mac, &phone] {        assert_eq!(dev.receipt_ids(SESSIONS, SESSION), before, "S's receipts unchanged");        assert!(dev.present(SESSIONS, SESSION), "a soft reference never affects presence");    }    assert_same_files(&[&mac, &phone], "sequence 4, after the retract");    let u = mac.act(T0 + 20, vec![project(P, "pp", "P")]);    assert!(u.iter().all(|op| op.table == PROJECTS && op.row_id == P), "the undo mints nothing for S");    phone.take(&u);    for dev in [&mac, &phone] {        assert_eq!(dev.receipt_ids(SESSIONS, SESSION), before, "S's receipts still unchanged");    }    assert_same_files(&[&mac, &phone], "sequence 4, after the undo");}/// RULE: A session that names a project softly keeps that value in its row while the project is retracted, and shows the project again on every device after the undo — nothing nulls it.#[test]fn sequence_4_a_soft_reference_keeps_its_value_and_mints_nothing() {    let (mut mac, phone, _) = sequence_4_start();    let r = mac.act(T0 + 10, vec![Change::retract(PROJECTS, P)]);    assert_eq!(r.len(), 1, "nothing minted for S");    phone.take(&r);    let u = mac.act(T0 + 20, vec![project(P, "pp", "P")]);    phone.take(&u);    for dev in [&mac, &phone] {        assert_eq!(dev.text(SESSIONS, SESSION, "project_id").as_deref(), Some(P), "after the undo S shows P again");    }    let (mut mac, phone, _) = sequence_4_start();    let r = mac.act(T0 + 10, vec![Change::retract(PROJECTS, P)]);    phone.take(&r);    for dev in [&mac, &phone] {        assert_eq!(dev.text(SESSIONS, SESSION, "project_id").as_deref(), Some(P), "S keeps project_id = P in its row");    }    assert_same_files(&[&mac, &phone], "sequence 4, after the retract");}