Cotton code
464 lines · 19.7 KB · RustRaw
//! `packages/store/__tests__/outbox.test.ts` and the parts of//! `syncHardening.test.ts` that survive, ported.//!//! What does NOT survive, and why: the two `drainOutbox single-flight` cases//! assert that several concurrent `await`ing callers coalesce into one push.//! There is no concurrency to coalesce here — the driver is synchronous and//! `&Driver` is not `Sync`, so a second caller cannot exist while the first is//! in the transport. The retired-table drain case goes with the retired list//! (spec R2 amendment).use super::*;use std::cell::RefCell;use crate::actor::{Actor, JobName};use crate::mint::{changes_of, file_author, mint, Act, Clock, Held, History};use crate::protocol::ulid::Monotonic;use crate::test_support::{counter_seed, seeded_file, WORKSPACE as WS};use serde_json::json;const NOW: &str = "2026-08-22T10:30:00.000Z";/// The instant every stamp in these tests is taken at — frozen, because this/// crate reads no clock and a test that did would be a time bomb. It is `NOW`/// in milliseconds, and the outbox assertions read both.const NOW_MS: i64 = 1_787_394_600_000;fn seeded(device_id: &str) -> Driver {    seeded_file(device_id)}fn todo(id: &str, title: &str) -> LocalChange {    LocalChange {        delete: Default::default(),        kind: OpKind::Upsert,        table: "cotton_todos".to_string(),        row_id: id.to_string(),        patch: json!({            "id": id,            "workspace_id": WS,            "title": title,            "created_at": NOW,            "updated_at": NOW,        })        .as_object()        .cloned(),    }}/// A boxed seed so the thread-local below names one concrete type.type SeededIds = Monotonic<Box<dyn FnMut(&mut [u8])>>;thread_local! {    /// ONE id source per test thread, exactly as the app holds one per process.    ///    /// It has to be shared across `write` calls: the ids are monotonic WITHIN a    /// source, and the clock is frozen here — so a fresh source per call would    /// hand out the same id twice and the outbox would refuse the second on its    /// UNIQUE index (which is how this was found).    static IDS: RefCell<SeededIds> = RefCell::new(Monotonic::new(Box::new(counter_seed())));}/// A device's own write through `mint`, held as a replica, with a frozen clock/// and a seeded id source. The author is the file's: the first write in a file/// mints it as `device:<ulid>` with its `cotton_authors` fact, queued ahead.fn write(db: &Driver, changes: &[LocalChange]) -> Result<Vec<CottonOp>> {    IDS.with_borrow_mut(|ids| {        mint(            db,            &Act {                actor: Actor::DeviceJob(JobName::named("test").expect("a job name")),                verb: "outbox_tests".to_string(),                history: History::None,                changes: changes_of(db, changes),            },            &Clock::wall(NOW_MS),            ids,            Held::Replica,        )        .map(|minted| minted.ops)    })}/// The session host's reading of a Mac, stamped at `sampled_at`. Version 14/// folded it onto the device row; before that it was `cotton_machines`.fn machine_reading(id: &str, sampled_at: &str, extra: serde_json::Value) -> LocalChange {    let mut patch = json!({        "id": id,        "workspace_id": WS,        "device_id": id,        "name": "A synthetic Mac",        "approved_at": NOW,        "approved_by_device": "self",        "load1": 0.4,        "cpu_count": 8,        "mem_free_pct": 40,        "sampled_at": sampled_at,        "updated_at": sampled_at,    });    if let (Some(patch), Some(extra)) = (patch.as_object_mut(), extra.as_object()) {        for (key, value) in extra {            patch.insert(key.clone(), value.clone());        }    }    LocalChange {        delete: Default::default(),        kind: OpKind::Upsert,        table: "cotton_devices".to_string(),        row_id: id.to_string(),        patch: patch.as_object().cloned(),    }}fn queued_ops(db: &Driver, table: &str) -> Vec<(String, String)> {    db.all(        "SELECT row_id, CAST(bytes AS TEXT) AS patch FROM _outbox WHERE tbl = ? ORDER BY queued_at, op_id",        &[SqlValue::Text(table.to_string())],    )    .expect("reads")    .into_iter()    .map(|row| {        (            row.text("row_id").unwrap_or_default().to_string(),            row.text("patch").unwrap_or_default().to_string(),        )    })    .collect()}/// RULE: Visits, samples and receipts a device writes about itself stay local, so offline browsing never grows changes waiting to send; a person's edit still queues and replicates.#[test]fn fourteen_minutes_of_offline_reads_leave_only_the_persons_edit_to_send() {    let db = seeded("device:phone");    // Start before the first write: observing a page must not queue even    // the author fact that the local receipt writer needs to establish.    let before = pending_count(&db).unwrap();    let mut local_ops = Vec::new();    for minute in 0..14 {        let at = format!("2026-08-22T10:{:02}:00.000Z", 30 + minute);        for (table, patch) in [            ("cotton_usage", json!({"device":"device:phone","kind":"record_opened","tool":"notes","view":"tool/notes","record":"invented-note","at":at})),            ("cotton_device_samples", json!({"device_id":"device:phone","sampled_at":at,"disk_free_gb":12.0,"load1":0.1})),            ("cotton_account_usage_samples", json!({"account_id":"invented-account","sampled_at":at,"five_hour_pct":12.0})),            ("cotton_push_acks", json!({"device_id":"device:phone","push_id":format!("push-{minute}"),"received_at":at,"how":"opened","created_at":at,"updated_at":at})),        ] {            let id = format!("{table}-{minute}");            let mut patch = patch.as_object().unwrap().clone();            patch.insert("id".into(), json!(id));            patch.insert("workspace_id".into(), json!(WS));            local_ops.extend(write(&db, &[LocalChange::upsert(table, &id, patch)]).unwrap());            assert!(db.get(&format!("SELECT id FROM {table} WHERE id=?"), &[id.into()]).unwrap().is_some(), "local state is retained");        }    }    assert_eq!(pending_count(&db).unwrap(), before);    assert!(db.all("SELECT op_id FROM _outbox", &[]).unwrap().is_empty());    // A previous build may already have queued these receipts. The current    // rule must apply immediately, without a schema move or losing local rows.    for op in &local_ops {        db.run("INSERT INTO _outbox (op_id,kind,author,tbl,row_id,hlc,schema_version,queued_at,bytes) VALUES (?,'create','old',?,?,?,?,?,?)", &[            op.op_id.clone().into(), op.table.clone().into(), op.row_id.clone().into(), op.hlc.clone().into(),            i64::from(op.schema_version).into(), NOW.to_string().into(), SqlValue::Blob(op.receipt.as_bytes().to_vec()),        ]).unwrap();    }    assert_eq!(pending_count(&db).unwrap(), before, "old queued telemetry does not count");    db.run("UPDATE _writes SET held=1 WHERE op_id IN (SELECT op_id FROM _outbox)", &[]).unwrap();    assert_eq!(crate::mint::clock::held_count(&db).unwrap(), 0, "local receipts do not wait for relay time");    db.run("UPDATE _writes SET held=0", &[]).unwrap();    write(&db, &[todo("mine", "A person's edit")]).unwrap();    assert_eq!(pending_count(&db).unwrap(), before + 1);    let handed = crate::exchange::exchange_request(&db, WS, None, &mut crate::exchange::Handover::shut()).unwrap();    assert!(handed.outbox_ops().iter().all(|op| op.table == "cotton_todos"));    let peer = seeded("device:server");    assert!(crate::exchange::fold_incoming(&peer, &handed.request.ops).unwrap().rejected.is_empty(), "the first edit still carries the author fact the peer needs");    assert_eq!(column(&peer, "SELECT title FROM cotton_todos WHERE id='mine'").as_deref(), Some("A person's edit"));    let author = file_author(&db).unwrap();    let stream = crate::changes::changes_since(&db, &author, "", 1000).unwrap();    assert!(stream.ops.iter().all(|op| !local_ops.iter().any(|local| local.table == op.table)), "receipt catch-up cannot send local rows either");    crate::snapshot::strip_for_phone(&db).unwrap();    for op in &local_ops {        assert!(db.get(&format!("SELECT id FROM {} WHERE id=?", op.table), &[op.row_id.clone().into()]).unwrap().is_none(), "another device's snapshot starts without this device's state");    }}// ─────────────────────────────────────────────────────────────────────────────// Presence: a reading supersedes its predecessor rather than queueing beside it// (`crate::presence`).// ─────────────────────────────────────────────────────────────────────────────#[test]fn stamping_presence_twice_leaves_one_queued_op() {    let db = seeded("device-a");    // The row's birth.    write(&db, &[machine_reading("mac-a", NOW, json!({ "created_at": NOW }))])        .expect("the first reading");    for seen_at in [        "2026-08-22T10:31:00.000Z",        "2026-08-22T10:31:30.000Z",        "2026-08-22T10:32:00.000Z",    ] {        write(&db, &[machine_reading("mac-a", seen_at, json!({}))]).expect("a stamp");    }    let queued = queued_ops(&db, "cotton_devices");    // The birth, and ONE stamp — not four. The birth survives because its patch    // names `created_at` and no stamp does.    assert_eq!(queued.len(), 2, "queued: {queued:?}");    assert!(queued[0].1.contains("created_at"));    assert!(queued[1].1.contains("2026-08-22T10:32:00.000Z"));    assert!(!queued[1].1.contains("created_at"));    // And the row itself carries the newest reading, which is the whole point:    // superseding the op never touches the fold.    assert_eq!(        column(&db, "SELECT sampled_at FROM cotton_devices WHERE id = 'mac-a'").as_deref(),        Some("2026-08-22T10:32:00.000Z")    );}#[test]fn a_stamp_does_not_supersede_another_rows_reading() {    let db = seeded("device-a");    write(&db, &[machine_reading("mac-a", NOW, json!({ "created_at": NOW }))])        .expect("mac-a");    write(&db, &[machine_reading("mac-b", NOW, json!({ "created_at": NOW }))])        .expect("mac-b");    write(&db, &[machine_reading("mac-a", "2026-08-22T10:31:00.000Z", json!({}))])        .expect("a stamp on mac-a");    let queued = queued_ops(&db, "cotton_devices");    assert_eq!(queued.len(), 3, "queued: {queued:?}");    assert_eq!(        queued.iter().filter(|(row, _)| row == "mac-b").count(),        1,        "mac-b's own op is untouched"    );}#[test]fn a_write_that_is_not_a_reading_supersedes_nothing() {    // Two ordinary edits to one todo are two ops: history is not a reading, and    // the collapse must never reach a table nobody declared.    let db = seeded("device-a");    write(&db, &[todo("t1", "first")]).expect("the first");    write(&db, &[todo("t1", "second")]).expect("the second");    assert_eq!(queued_ops(&db, "cotton_todos").len(), 2);}fn column(db: &Driver, sql: &str) -> Option<String> {    db.get(sql, &[])        .expect("reads")        .and_then(|row| match row.columns().first() {            Some((_, SqlValue::Text(value))) => Some(value.clone()),            _ => None,        })}fn ids(db: &Driver, sql: &str) -> Vec<String> {    db.all(sql, &[])        .expect("reads")        .into_iter()        .filter_map(|row| row.text("id").map(str::to_string))        .collect()}// ─────────────────────────────────────────────────────────────────────────────// write_local// ─────────────────────────────────────────────────────────────────────────────#[test]fn applies_the_change_immediately_no_network_involved() {    let db = seeded("device:file");    write(&db, &[todo("t1", "Capture offline")]).expect("writes");    assert_eq!(        column(&db, "SELECT title FROM cotton_todos WHERE id = 't1'"),        Some("Capture offline".to_string())    );}#[test]fn queues_the_op_for_later() {    let db = seeded("device:file");    let ops = write(&db, &[todo("t1", "x")]).expect("writes");    assert_eq!(ops.len(), 1);    // The write, and ahead of it the file author's fact the first write mints.    assert_eq!(pending_count(&db).expect("counts"), 2);    assert_eq!(        column(&db, "SELECT op_id FROM _outbox WHERE tbl = 'cotton_todos'"),        Some(ops[0].op_id.clone())    );    assert_eq!(        column(&db, "SELECT tbl FROM _outbox WHERE tbl <> 'cotton_todos'").as_deref(),        Some("cotton_authors")    );}/// RULE (sync seen): what waits to be sent is counted as a person counts it: one record written and edited offline is/// one, whatever writes and bookkeeping it queued.#[test]fn a_record_written_and_edited_offline_waits_as_one() {    let db = seeded("device:file");    write(&db, &[todo("t1", "Capture offline")]).expect("writes");    write(&db, &[todo("t1", "Capture offline, edited")]).expect("writes");    assert!(pending_count(&db).expect("counts") >= 2, "the writes and the author fact are all queued");    assert_eq!(pending_things(&db).expect("counts"), 1);    write(&db, &[todo("t2", "Another")]).expect("writes");    assert_eq!(pending_things(&db).expect("counts"), 2);}#[test]fn folds_and_enqueues_in_one_transaction() {    // If these could come apart, a crash between them would either lose the    // user's edit or leave an op that never happened. The proof here is the    // refusal case below: a batch that refuses leaves NEITHER the row nor the    // outbox entry.    let db = seeded("device:file");    write(&db, &[todo("t1", "x"), todo("t2", "y")]).expect("writes");    // Two writes, and the author fact the first write in a file mints.    assert_eq!(pending_count(&db).expect("counts"), 3);    assert_eq!(        ids(&db, "SELECT id FROM cotton_todos ORDER BY id"),        ["t1", "t2"]    );}#[test]fn a_refused_batch_leaves_neither_the_row_nor_the_outbox_entry() {    let db = seeded("device:file");    let bad = LocalChange {        delete: Default::default(),        kind: OpKind::Upsert,        table: "cotton_todos".to_string(),        row_id: "t-bad".to_string(),        patch: json!({            "id": "t-bad", "workspace_id": WS, "title": "x", "status": "not-a-status",            "created_at": NOW, "updated_at": NOW,        })        .as_object()        .cloned(),    };    let error = write(&db, &[todo("t-good", "fine"), bad])        .expect_err("a local write the fold refuses is a caller bug");    assert!(        error.to_string().contains("was refused by the fold"),        "got {error}"    );    assert_eq!(pending_count(&db).expect("counts"), 0);    assert!(ids(&db, "SELECT id FROM cotton_todos").is_empty());}#[test]fn stamps_each_op_with_a_monotonically_increasing_hlc() {    let db = seeded("device:file");    let ops = write(&db, &[todo("t1", "a"), todo("t2", "b"), todo("t3", "c")]).expect("writes");    let stamps: Vec<&String> = ops.iter().map(|op| &op.hlc).collect();    let mut sorted = stamps.clone();    sorted.sort();    assert_eq!(stamps, sorted);}#[test]fn advances_meta_last_hlc_so_the_next_write_follows_on() {    let db = seeded("device:file");    let first = write(&db, &[todo("t1", "a")]).expect("writes");    let second = write(&db, &[todo("t2", "b")]).expect("writes");    assert!(second[0].hlc > first[0].hlc);    assert_eq!(        column(&db, "SELECT last_hlc FROM _meta"),        Some(second[0].hlc.clone())    );}#[test]fn stamps_each_op_with_the_files_own_author_minted_on_the_first_write() {    let db = seeded("device:known");    let ops = write(&db, &[todo("t1", "a")]).expect("writes");    let author = file_author(&db).expect("the file's author");    assert_eq!(        column(&db, "SELECT author_id FROM _meta").as_deref(),        Some(author.as_str())    );    assert!(author.starts_with("device:"), "got {author}");    assert_ne!(author, "device:known", "the author is not the device's credential");    assert_eq!(ops[0].device_id, author);    assert!(ops[0].hlc.ends_with(&format!(":{author}")), "got {}", ops[0].hlc);}#[test]fn refuses_an_empty_change_list_and_writes_nothing_at_all() {    let db = seeded("device:file");    write(&db, &[]).expect_err("a write that changes nothing is refused");    assert_eq!(pending_count(&db).expect("counts"), 0);    assert_eq!(column(&db, "SELECT author_id FROM _meta"), None);}#[test]fn the_outbox_row_carries_the_receipt_and_the_stamp_the_op_got() {    let db = seeded("device:file");    let ops = write(&db, &[todo("t1", "a")]).expect("writes");    let row = db        .get("SELECT * FROM _outbox WHERE tbl = 'cotton_todos'", &[])        .expect("reads")        .expect("a row");    assert_eq!(row.text("op_id"), Some(ops[0].op_id.as_str()));    assert_eq!(row.text("kind"), Some("create"));    assert_eq!(row.text("author"), Some(ops[0].device_id.as_str()));    assert_eq!(row.text("tbl"), Some("cotton_todos"));    assert_eq!(row.text("hlc"), Some(ops[0].hlc.as_str()));    assert_eq!(row.int("schema_version"), Some(i64::from(crate::schema::ddl::SCHEMA_VERSION)));    assert_eq!(row.text("queued_at"), Some("2026-08-22T10:30:00.000Z"));    let Some(SqlValue::Blob(bytes)) = row.get("bytes") else {        panic!("the receipt bytes");    };    assert_eq!(bytes.as_slice(), ops[0].receipt.as_bytes());    let receipt = crate::canonical::decode(bytes).expect("canonical bytes");    assert_eq!(receipt.fields["title"], json!("a"));}#[test]fn a_delete_queues_a_retract_naming_no_field() {    let db = seeded("device:file");    write(&db, &[todo("t1", "a")]).expect("writes");    write(        &db,        &[LocalChange::delete("cotton_todos", "t1").retract()],    )    .expect("writes");    let row = db        .get("SELECT bytes FROM _outbox WHERE kind = 'retract'", &[])        .expect("reads")        .expect("a row");    let Some(SqlValue::Blob(bytes)) = row.get("bytes") else {        panic!("the receipt bytes");    };    assert!(crate::canonical::decode(bytes).expect("canonical bytes").fields.is_empty());}// ─────────────────────────────────────────────────────────────────────────────// sync_backoff_ms// ─────────────────────────────────────────────────────────────────────────────#[test]fn doubles_from_thirty_seconds_and_stops_at_five_minutes() {    // 0.5 is the midpoint of the ±20% band = no change.    assert_eq!(sync_backoff_ms(0, 0.5), SYNC_BACKOFF_FLOOR_MS);    assert_eq!(sync_backoff_ms(1, 0.5), 60_000);    assert_eq!(sync_backoff_ms(2, 0.5), 120_000);    assert_eq!(sync_backoff_ms(3, 0.5), 240_000);    assert_eq!(sync_backoff_ms(4, 0.5), SYNC_BACKOFF_CEILING_MS);    assert_eq!(sync_backoff_ms(50, 0.5), SYNC_BACKOFF_CEILING_MS);}#[test]fn spreads_the_retries_by_up_to_a_fifth_in_each_direction() {    assert_eq!(sync_backoff_ms(0, 0.0), 24_000);    assert_eq!(sync_backoff_ms(0, 1.0), 36_000);}#[test]fn treats_a_negative_or_absurd_failure_count_as_the_floor_and_the_ceiling() {    assert_eq!(sync_backoff_ms(-3, 0.5), SYNC_BACKOFF_FLOOR_MS);    // `Number.MAX_SAFE_INTEGER` on the other side; the clamp is the point.    assert_eq!(        sync_backoff_ms(9_007_199_254_740_991, 0.5),        SYNC_BACKOFF_CEILING_MS    );}