Cotton code
277 lines · 10.6 KB · RustRaw
//! The writer's own tests, over a real file — the fold is the thing being//! asserted, and a mocked driver would prove nothing about it.use std::sync::Arc;use super::*;use crate::random::SystemRandom;use cotton_store::meta::Meta;use cotton_store::protocol::types::OpKind;use rusqlite::types::Value as SqlValue;use cotton_store::schema::ddl::SCHEMA_VERSION;use serde_json::json;const AT: &str = "2026-09-08T10:00:00.000Z";fn now() -> DateTime<Utc> {    AT.parse::<DateTime<Utc>>().expect("a fixed instant")}struct Fixture {    db: Driver,    workspace_id: String,    owner_id: String,}fn fixture() -> Fixture {    let workspace_id = "00000000-0000-4000-8000-00000000c0c0".to_string();    let owner_id = "00000000-0000-4000-8000-0000000000aa".to_string();    let db = cotton_store::test_template::create_workspace_in_memory_for_test(&Meta {        workspace_id: workspace_id.clone(),        owner_id: owner_id.clone(),        device_id: "device:writer-fixture".to_string(),        last_server_seq: 0,        last_hlc: None,    })    .expect("a fresh file");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, _hlc) VALUES (?, ?, \         ?, ?, '')",        &[            SqlValue::Text(workspace_id.clone()),            SqlValue::Text("Writer fixture".to_string()),            SqlValue::Text(owner_id.clone()),            SqlValue::Text(AT.to_string()),        ],    )    .expect("the workspace row every domain table keys back to");    Fixture {        db,        workspace_id,        owner_id,    }}fn writer(fixture: &Fixture) -> Writer<'_> {    writer_at(fixture, now())}fn writer_at(fixture: &Fixture, at: DateTime<Utc>) -> Writer<'_> {    Writer::acting(        &fixture.db,        &fixture.workspace_id,        &fixture.owner_id,        job("test"),        cotton_store::mint::Held::Served,        at,        Arc::new(SystemRandom),    )}fn todo(id: &str, title: &str) -> Map<String, Value> {    json!({        "id": id,        "title": title,        "status": "open",        "priority": 0,        "created_at": AT,        "updated_at": AT,    })    .as_object()    .cloned()    .expect("an object")}#[test]fn a_write_lands_in_the_file_stamped_by_the_writer() {    // The whole promise: an assistant's edit is a first-class change every    // device pulls, not a side-door write only the server can see.    let fixture = fixture();    let mut writer = writer(&fixture);    writer.upsert("cotton_todos", "todo-1", todo("todo-1", "buy cardamom"));    let ops = writer.commit().expect("the commit lands");    // The write and its history row (slice 6b), not the author fact.    assert_eq!(ops.len(), 2, "the act's own ops, not the author fact");    assert_eq!(ops[1].table, "cotton_changes", "the history row follows its write");    let author = cotton_store::mint::file_author(&fixture.db).expect("the file's author");    assert_eq!(ops[0].device_id, author);    assert_eq!(ops[0].table, "cotton_todos");    assert_eq!(ops[0].schema_version, SCHEMA_VERSION);    let row = fixture        .db        .get(            "SELECT title, workspace_id FROM cotton_todos WHERE id = ?",            &[SqlValue::Text("todo-1".to_string())],        )        .expect("a read")        .expect("the row");    assert_eq!(row.text("title"), Some("buy cardamom"));    // Stamped by the writer, so a handler that forgot it cannot write a row    // into nobody's workspace.    assert_eq!(row.text("workspace_id"), Some(fixture.workspace_id.as_str()));    // And the write is DISCOVERABLE as this writer's. There is no log to look    // in — `_ops` stopped being written at version 8 — so the fact lives where    // a cursor reads it: a stamp ENDS in its author's device id, and    // `substr(_hlc, 20)` is what the author index and `changes_since` compare.    let stamped = fixture        .db        .get(            "SELECT substr(_hlc, 20) AS author FROM cotton_todos WHERE id = ?",            &[SqlValue::Text("todo-1".to_string())],        )        .expect("a read")        .expect("the row");    assert_eq!(stamped.text("author"), Some(author.as_str()));}/// RULE: A Writer commits through mint: the first commit in a file mints the file's author and its cotton_authors fact ahead of the write, every op is stamped with that author and never with a job constant or the file's device id, and a served file queues nothing.#[test]fn the_first_commit_in_a_file_mints_its_author_first_and_a_served_file_queues_nothing() {    let fixture = fixture();    assert_eq!(        fixture.db.get("SELECT author_id FROM _meta", &[]).expect("a read").and_then(|r| r.text("author_id").map(str::to_string)),        None,        "a fresh file has no author"    );    let mut writer = writer(&fixture);    writer.upsert("cotton_todos", "todo-1", todo("todo-1", "one"));    let ops = writer.commit().expect("the commit lands");    let author = cotton_store::mint::file_author(&fixture.db).expect("minted on the first write");    assert!(author.starts_with("device:"), "{author}");    assert_ne!(author, "device:writer-fixture", "the author is not the file's device id");    assert_eq!(ops[0].device_id, author);    let fact = fixture        .db        .get("SELECT device_id, first_stamp FROM cotton_authors WHERE id = ?", &[SqlValue::Text(author.clone())])        .expect("a read")        .expect("the author fact");    assert_eq!(fact.text("device_id"), Some("device:writer-fixture"), "the fact names the device");    assert!(fact.text("first_stamp").expect("a stamp") < ops[0].hlc.as_str(), "the fact is ahead of the write");    let queued = fixture.db.get("SELECT COUNT(*) AS n FROM _outbox", &[]).expect("a read").and_then(|r| r.int("n"));    assert_eq!(queued, Some(0), "a served file queues nothing");}#[test]fn the_clock_is_seeded_from_the_file_and_written_through() {    // `_meta.last_hlc` is where the last stamp this file issued is recorded, so    // a restarted process continues the chain rather than re-issuing stamps    // that already happened.    let fixture = fixture();    let mut first = writer(&fixture);    first.upsert("cotton_todos", "todo-1", todo("todo-1", "one"));    let one = first.commit().expect("the first commit");    // The act's last op is its history row, stamped after the write.    let stamped = last_hlc_of(&fixture.db).expect("a read").expect("a stamp");    assert_eq!(stamped, one.last().expect("ops").hlc);    // A SECOND writer — a fresh process, as far as the file is concerned.    let mut second = writer(&fixture);    second.upsert("cotton_todos", "todo-2", todo("todo-2", "two"));    let two = second.commit().expect("the second commit");    assert!(two[0].hlc > one[0].hlc, "{} !> {}", two[0].hlc, one[0].hlc);}#[test]fn a_batch_stamps_each_op_after_the_last() {    let fixture = fixture();    let mut writer = writer(&fixture);    writer.upsert("cotton_todos", "todo-1", todo("todo-1", "one"));    writer.upsert("cotton_todos", "todo-2", todo("todo-2", "two"));    writer.upsert("cotton_todos", "todo-3", todo("todo-3", "three"));    let ops = writer.commit().expect("the commit");    // Three writes, then a history row for each (slice 6b).    assert_eq!(ops.len(), 6);    assert!(ops.windows(2).all(|pair| pair[0].hlc < pair[1].hlc), "each op stamped after the last");    // Every op id is distinct — the ULID source is monotonic within one    // millisecond rather than redrawn.    let mut ids: Vec<&str> = ops.iter().map(|op| op.op_id.as_str()).collect();    ids.sort_unstable();    ids.dedup();    assert_eq!(ids.len(), 6);}#[test]fn a_delete_carries_no_patch() {    let fixture = fixture();    let mut writer = writer(&fixture);    writer.upsert("cotton_todos", "todo-1", todo("todo-1", "one"));    writer.commit().expect("the insert");    let mut writer = writer_at(&fixture, now() + chrono::Duration::seconds(1));    writer.retract("cotton_todos", "todo-1", Retract::Relation);    let ops = writer.commit().expect("the delete");    assert_eq!(ops[0].kind, OpKind::Delete);    assert!(ops[0].patch.is_none());    assert!(fixture        .db        .get(            "SELECT id FROM cotton_todos WHERE id = ?",            &[SqlValue::Text("todo-1".to_string())]        )        .expect("a read")        .is_none());}#[test]fn a_write_behind_its_row_is_folded_forward_not_refused() {    // RULE (architect, 11 Oct 2026, with 99197f5ee): a write is made after the    // rows it writes, so it is stamped after them. A writer whose clock is    // behind a row it already holds is FOLDED FORWARD — its stamp starts past    // the newest clock that row holds — and the write stands and is queued.    // Until 99197f5ee the server refused such a write as "folded as stale",    // which dropped an approval the owner tapped on phone 242; this test    // asserted that refusal and lost its premise with the rule.    let fixture = fixture();    let mut writer = writer(&fixture);    writer.upsert("cotton_todos", "todo-1", todo("todo-1", "one"));    writer.commit().expect("the first write");    // A writer running an HOUR in the past: its own stamp would lose to the    // row's, so the mint lifts it past the row's clock instead.    let mut behind = writer_at(&fixture, now() - chrono::Duration::hours(1));    // Seed the clock from BEFORE the first write, which is what a wrong clock    // actually does — `_meta.last_hlc` is what a fresh writer would read.    fixture        .db        .run("UPDATE _meta SET last_hlc = NULL", &[])        .expect("the clock is reset");    behind.upsert("cotton_todos", "todo-1", todo("todo-1", "overwritten"));    behind        .commit()        .expect("a write behind its row is folded forward, never refused");    // The write made after reading the row stands.    let row = fixture        .db        .get(            "SELECT title FROM cotton_todos WHERE id = ?",            &[SqlValue::Text("todo-1".to_string())],        )        .expect("a read")        .expect("the row");    assert_eq!(row.text("title"), Some("overwritten"));}#[test]fn an_unknown_table_is_refused_by_name() {    let fixture = fixture();    let mut writer = writer(&fixture);    writer.upsert("cotton_nonsense", "row-1", Map::new());    let error = writer.commit().expect_err("an unknown table is refused");    assert!(error.to_string().contains("cotton_nonsense"), "{error}");}#[test]fn committing_nothing_writes_nothing() {    let fixture = fixture();    let mut writer = writer(&fixture);    assert_eq!(writer.pending(), 0);    assert!(writer.commit().expect("an empty commit").is_empty());    assert!(writer.ops().is_empty());    let before = last_hlc_of(&fixture.db).expect("a read");    assert_eq!(before, None);}