Cotton code
610 lines · 21.3 KB · RustRaw
//! `cotton_store::mint`: the one place this file's own writes are made.//! What it refuses, what it queues, and what it leaves behind.use cotton_store::actor::{Actor, AutomationId, DeviceId, JobName, RunId, SessionId};use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE};use cotton_store::fold::{actor_may_be_named_by, arrive, Arrival};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource};use cotton_store::file_identity::read_file_identity;use cotton_store::protocol::derived_id::{link_id_for, record_link_id, LinkRow};use cotton_store::protocol::hlc::next_hlc;use cotton_store::protocol::types::OpKind;use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::wire::op_of_change;use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};const DEVICE: &str = "device:01JTESTDEVICE000000000000000";const PEER: &str = "device:01JPEERDEVICE000000000000000";const T0: i64 = 1_759_480_000_000;fn fresh() -> Driver {    let db = file_at_version(SCHEMA_VERSION);    seed_meta(        &db,        &Meta {            workspace_id: WORKSPACE.to_string(),            owner_id: OWNER.to_string(),            device_id: DEVICE.to_string(),            last_server_seq: 0,            last_hlc: None,        },        SCHEMA_VERSION,    )    .expect("seeds the identity");    seed_workspace_row(&db);    first_author(&db, "key-of-this-device", Some("Test phone"), AuthorReason::First, &Clock::wall(T0 - 1), &mut Ids(900), Held::Served)        .expect("the file's author");    db}/// Ids a test can predict.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-{:04}", self.0))    }}fn todo(row_id: &str, title: &str) -> Map<String, Value> {    json!({        "id": row_id,        "workspace_id": WORKSPACE,        "title": title,        "created_at": NOW,        "updated_at": NOW,    })    .as_object()    .expect("an object")    .clone()}fn session_actor(db: &Driver) -> Actor {    db.run(        "INSERT INTO cotton_sessions (id, workspace_id, tool, last_active_at, created_at, updated_at) \         VALUES ('s1', ?, 'claude-code', ?, ?, ?)",        &[            SqlValue::Text(WORKSPACE.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),        ],    )    .unwrap_or_else(|e| panic!("a session row: {e}"));    Actor::session(SessionId::in_file(db, "s1").expect("the session row"))}fn act(actor: Actor, changes: Vec<Change>) -> Act {    Act {        actor,        verb: "test_write".to_string(),        history: History::None,        changes,    }}fn text(db: &Driver, sql: &str) -> Option<String> {    db.get(sql, &[]).expect("reads").and_then(|row| {        row.columns().first().and_then(|(_, value)| match value {            SqlValue::Text(text) => Some(text.clone()),            _ => None,        })    })}fn count(db: &Driver, sql: &str) -> i64 {    db.get(sql, &[])        .expect("reads")        .and_then(|row| row.int("n"))        .unwrap_or(0)}/// RULE: A local write made while this file's clock is behind a row it writes is FOLDED FORWARD — stamped past the newest clock that row holds, applied and queued — never refused and never lost to a row the writer was looking at (architect, 11 Oct 2026; phone 242's approval "That wasn't kept"). The mint's stale check stays behind it: a write that still loses is an error, never a silent success.#[test]fn local_write_behind_its_row_is_folded_forward() {    let db = fresh();    let actor = session_actor(&db);    // A peer's write already in the file, stamped a day AHEAD of this clock.    let ahead = next_hlc(PEER, None, T0 + 86_400_000).expect("a stamp");    let peer = op_of_change(        &db,        &Change::create("cotton_todos", "t1", todo("t1", "from the peer")),        &ahead,        PEER,        &Actor::device_job(JobName::named("test").expect("a job name")),        "peer-1".to_string(),    )    .expect("the peer's receipt");    // The peer has announced itself here, so its write is not held back.    db.run(        "INSERT INTO cotton_authors (id, workspace_id, device_id, minted_at, reason, first_stamp) VALUES (?, ?, 'peer-key', ?, 'first', ?)",        &[SqlValue::Text(PEER.to_string()), SqlValue::Text(WORKSPACE.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(peer.hlc.clone())],    )    .expect("the peer's fact");    let folded = arrive(&db, &[peer], Arrival::Handed).expect("folds");    assert_eq!(folded.applied.len(), 1, "{folded:?}");    // The fold moved the file's clock up to the peer's stamp, as it should; a    // correct hybrid clock then never loses to a row it has seen. The case    // the rule is for is a file whose clock fell BEHIND its rows — `_meta`    // restored from an older copy than the tables — so plant exactly that.    db.run("UPDATE _meta SET last_hlc = NULL", &[])        .expect("a clock behind its rows");    let before = count(&db, "SELECT COUNT(*) AS n FROM _outbox");    mint(        &db,        &act(            actor,            vec![Change::update(                "cotton_todos",                "t1",                todo("t1", "from here"),            )],        ),        &Clock::wall(T0),        &mut Ids(0),        Held::Replica,    )    .expect("a write behind its row is folded forward, not refused");    assert_eq!(        text(&db, "SELECT title FROM cotton_todos WHERE id = 't1'").as_deref(),        Some("from here"),        "the write made after reading the row stands"    );    assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), before + 1, "and is queued");    let queued = text(&db, "SELECT MAX(hlc) FROM _outbox WHERE tbl = 'cotton_todos'").expect("a stamp");    assert!(queued > ahead, "stamped past the row it wrote: {queued} vs {ahead}");}/// RULE: A receipt's actor is one its author's device may name: a replica mints for its owner, its sessions and its own jobs, never for a token, a job of the serving Mac or a take-over.#[test]fn receipt_actor_must_belong_to_its_authors_device() {    let db = fresh();    let job = Actor::job(JobName::named("usage").expect("a job name"));    for (n, (held, actor, refused)) in [        (Held::Replica, job.clone(), true),        (Held::Replica, Actor::takeover(), true),        (Held::Served, job.clone(), false),        (Held::Served, Actor::takeover(), false),        (            Held::Replica,            Actor::device_job(JobName::named("backup").expect("a name")),            false,        ),        (Held::Offline, job.clone(), true),    ]    .into_iter()    .enumerate()    {        let row = format!("t-{n}");        let outcome = mint(            &db,            &act(                actor.clone(),                vec![Change::create("cotton_todos", &row, todo(&row, "x"))],            ),            &Clock::wall(T0),            // An op id of its own per write: the same id again is a replay.            &mut Ids(u32::try_from(n).expect("a few") * 10),            held,        );        assert_eq!(            outcome.is_err(),            refused,            "{held:?} naming {actor}: {outcome:?}"        );        if let Err(reason) = outcome {            assert!(reason.to_string().contains("may not name"), "{reason}");        }    }    // An automation is allowed exactly where the actor it acts for is.    db.run(        "INSERT INTO cotton_tool_definitions (id, workspace_id, definition, created_at, updated_at) VALUES ('tool-1', ?, '{}', ?, ?)",        &[            SqlValue::Text(WORKSPACE.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),        ],    )    .unwrap_or_else(|e| panic!("a tool definition row: {e}"));    let automation = || AutomationId::in_file(&db, "tool-1").expect("the row");    let session = session_actor(&db);    assert!(        actor_may_be_named_by(Held::Replica, &Actor::automation(automation(), session)).is_ok()    );    assert!(actor_may_be_named_by(Held::Replica, &Actor::automation(automation(), job)).is_err());}#[test]fn a_replica_queues_its_mint_and_a_served_file_does_not() {    for (held, queued) in [(Held::Replica, 2), (Held::Served, 0)] {        let db = fresh();        let actor = session_actor(&db);        let minted = mint(            &db,            &act(                actor,                vec![                    Change::create("cotton_todos", "t1", todo("t1", "one")),                    Change::create("cotton_todos", "t2", todo("t2", "two")),                ],            ),            &Clock::wall(T0),            &mut Ids(0),            held,        )        .unwrap_or_else(|e| panic!("{held:?}: {e}"));        assert_eq!(minted.ops.len(), 2);        assert_eq!(minted.ops[0].op_id, "op-0001");        assert_eq!(            minted.ops[0].device_id,            cotton_store::mint::file_author(&db).expect("an author"),            "stamped with the file's author"        );        assert_ne!(minted.ops[0].device_id, DEVICE, "the author is the minted one, not the device id");        assert!(            minted.ops[1].hlc > minted.ops[0].hlc,            "one running stamp across the act"        );        assert_eq!(            minted.applied_rows,            vec![                ("cotton_todos".to_string(), "t1".to_string()),                ("cotton_todos".to_string(), "t2".to_string())            ]        );        assert_eq!(            count(&db, "SELECT COUNT(*) AS n FROM _outbox"),            queued,            "{held:?}"        );        assert_eq!(            text(&db, "SELECT last_hlc FROM _meta").as_deref(),            Some(minted.ops[1].hlc.as_str()),            "the file's clock continues from the act"        );        assert_eq!(            text(                &db,                &format!(                    "SELECT hlc_seen FROM _cursors WHERE author_device_id = '{}'",                    cotton_store::mint::file_author(&db).expect("an author")                )            )            .as_deref(),            Some(minted.ops[1].hlc.as_str()),            "this file has seen its own writes"        );    }}#[test]fn a_retract_is_a_delete_and_a_change_without_a_patch_is_refused() {    let db = fresh();    let actor = session_actor(&db);    mint(        &db,        &act(            actor.clone(),            vec![Change::create("cotton_todos", "t1", todo("t1", "one"))],        ),        &Clock::wall(T0),        &mut Ids(0),        Held::Served,    )    .expect("creates");    let minted = mint(        &db,        &act(actor.clone(), vec![Change::retract("cotton_todos", "t1")]),        &Clock::wall(T0 + 1),        &mut Ids(10),        Held::Served,    )    .expect("retracts");    assert_eq!(minted.ops[0].kind, OpKind::Delete);    assert!(minted.ops[0].patch.is_none());    assert_eq!(        count(            &db,            "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't1'"        ),        0    );    let mut no_patch = Change::create("cotton_todos", "t2", todo("t2", "two"));    no_patch.patch = None;    let refused = mint(        &db,        &act(actor.clone(), vec![no_patch]),        &Clock::wall(T0 + 2),        &mut Ids(20),        Held::Served,    )    .expect_err("a create names its columns");    assert!(refused.to_string().contains("names no column"), "{refused}");    let refused = mint(        &db,        &act(actor, vec![]),        &Clock::wall(T0 + 3),        &mut Ids(30),        Held::Served,    )    .expect_err("an empty act");    assert!(refused.to_string().contains("changes nothing"), "{refused}");}#[test]fn a_rejected_write_is_an_error_and_leaves_nothing_behind() {    let db = fresh();    let actor = session_actor(&db);    let refused = mint(        &db,        &act(            actor,            vec![Change::create("cotton_todos", "x", {                // A workspace this file does not hold: the fold refuses the row.                let mut orphan = todo("x", "x");                orphan.insert("workspace_id".into(), json!("22222222-2222-4222-8222-222222222222"));                orphan            })],        ),        &Clock::wall(T0),        &mut Ids(0),        Held::Replica,    )    .expect_err("a row the fold refuses is refused");    assert!(        refused.to_string().contains("refused by the fold"),        "{refused}"    );    assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), 0);    assert_eq!(        text(&db, "SELECT last_hlc FROM _meta"),        text(&db, "SELECT first_stamp FROM cotton_authors"),        "the clock did not move past the author fact"    );}#[test]fn the_owner_at_a_device_is_an_actor_of_that_device_row() {    let db = fresh();    db.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, approved_by_device, created_at, updated_at) \         VALUES ('dev-row', ?, 'key-1', 'Phone', ?, 'owner', ?, ?)",        &[            SqlValue::Text(WORKSPACE.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),        ],    )    .expect("a device row");    let owner = Actor::owner(DeviceId::in_file(&db, "dev-row").expect("the row"));    assert_eq!(owner.to_wire(), "owner:dev-row");    assert!(DeviceId::in_file(&db, "dev-missing").is_err());    mint(        &db,        &act(            owner,            vec![Change::create("cotton_todos", "t1", todo("t1", "tapped"))],        ),        &Clock::wall(T0),        &mut Ids(0),        Held::Replica,    )    .expect("the owner writes on a replica");}fn patch(value: Value) -> Map<String, Value> {    value.as_object().expect("an object").clone()}/// RULE: A file's `kind`, `namespace` and `owner_user_id` never change after its workspace row is created, with no exception: mint refuses a change to any of them, from empty too, and a change naming the value already there is not a change.#[test]fn workspace_kind_namespace_owner_are_immutable_after_creation() {    let db = fresh();    let actor = session_actor(&db);    let mut ids = Ids(0);    let mut write = |db: &Driver, change: Change| {        mint(db, &act(actor.clone(), vec![change]), &Clock::wall(T0), &mut ids, Held::Served)    };    let row = |id: &str, identity: Value| {        let mut row = patch(json!({            "id": id,            "name": "A database",            // One workspace row per owner in a file: each its own owner.            "owner_user_id": format!("owner-of-{id}"),            "created_at": NOW,        }));        row.extend(patch(identity));        row    };    write(&db, Change::create("cotton_workspaces", "bare", row("bare", json!({}))))        .expect("a row made without its identity, as today's seed makes it");    write(        &db,        Change::create(            "cotton_workspaces",            "made",            row("made", json!({ "kind": "shared", "namespace": "made" })),        ),    )    .expect("a row made with its identity");    // From empty is a change too: a database's kind is decided where its row    // is made, or never.    for (id, column, value) in [        ("bare", "kind", json!("shared")),        ("bare", "namespace", json!("bare")),        ("bare", "owner_user_id", json!("someone-else")),        ("made", "kind", json!("personal")),        ("made", "kind", Value::Null),        ("made", "namespace", json!("another-database")),        ("made", "owner_user_id", json!("someone-else")),    ] {        let refused = write(            &db,            Change::update("cotton_workspaces", id, patch(json!({ column: value }))),        )        .expect_err("an identity column is never changed");        assert!(refused.to_string().contains(column), "{id}.{column}: {refused}");    }    // The same values, beside a real change, are written.    write(        &db,        Change::update(            "cotton_workspaces",            "made",            patch(json!({                "name": "Renamed",                "kind": "shared",                "namespace": "made",                "owner_user_id": "owner-of-made",            })),        ),    )    .expect("a change that keeps the identity");    assert_eq!(        text(&db, "SELECT name || ' ' || kind || ' ' || namespace || ' ' || owner_user_id AS row FROM cotton_workspaces WHERE id = 'made'"),        Some("Renamed shared made owner-of-made".to_string())    );    assert_eq!(text(&db, "SELECT kind FROM cotton_workspaces WHERE id = 'bare'"), None);}/// One person key row, every value invented.fn person_key(id: &str) -> Map<String, Value> {    patch(json!({        "id": id,        "workspace_id": WORKSPACE,        "public_key": "an-invented-public-half",        "name": "Nobody Invented",        "sealed_private": "an-invented-sealed-half",        "vmk_version": 1,        "created_at": NOW,    }))}/// RULE: A fresh file holds an empty cotton_person_keys, and a person key is written once, when it is made: mint refuses a change of one, and the fold refuses a peer's change receipt naming one.#[test]fn person_keys_table_exists_empty_and_insert_only() {    const SENTENCE: &str = "a person key is written once, when it is made";    let db = fresh();    assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_person_keys"), 0);    let actor = Actor::job(JobName::named("vault").expect("a job name"));    let mut ids = Ids(0);    mint(        &db,        &act(actor.clone(), vec![Change::create("cotton_person_keys", "fp-1", person_key("fp-1"))]),        &Clock::wall(T0),        &mut ids,        Held::Served,    )    .expect("a person key is made");    // This file's own change is refused by mint.    let refused = mint(        &db,        &act(            actor,            vec![Change::update(                "cotton_person_keys",                "fp-1",                patch(json!({ "sealed_private": "another-sealed-half" })),            )],        ),        &Clock::wall(T0 + 1_000),        &mut ids,        Held::Served,    )    .expect_err("a person key is never changed");    assert!(refused.to_string().contains(SENTENCE), "{refused}");    // A peer's change receipt is refused by the fold.    let stamp = next_hlc(PEER, None, T0 + 2_000).expect("a stamp");    let peer = op_of_change(        &db,        &Change::update(            "cotton_person_keys",            "fp-1",            patch(json!({ "public_key": "another-public-half" })),        ),        &stamp,        PEER,        &Actor::device_job(JobName::named("test").expect("a job name")),        "peer-1".to_string(),    )    .expect("the peer's receipt");    db.run(        "INSERT INTO cotton_authors (id, workspace_id, device_id, minted_at, reason, first_stamp) VALUES (?, ?, 'peer-key', ?, 'first', ?)",        &[SqlValue::Text(PEER.to_string()), SqlValue::Text(WORKSPACE.to_string()), SqlValue::Text(NOW.to_string()), SqlValue::Text(stamp.clone())],    )    .expect("the peer's fact");    let folded = arrive(&db, &[peer], Arrival::Handed).expect("folds");    assert!(folded.applied.is_empty(), "{folded:?}");    assert!(        folded.rejected.iter().chain(folded.parked.iter()).any(|r| r.reason.contains(SENTENCE)),        "{folded:?}"    );    assert_eq!(        text(&db, "SELECT public_key || ' ' || sealed_private AS row FROM cotton_person_keys WHERE id = 'fp-1'"),        Some("an-invented-public-half an-invented-sealed-half".to_string())    );}/// RULE: A link that names its own database as `to_database` is the link that names none: `link_id_for` derives the same id, and mint stores the column as null.#[test]fn link_to_own_file_named_explicitly_has_the_same_id_as_with_none() {    let db = fresh();    let named = LinkRow {        from_kind: "note",        from_id: "n1",        to_kind: "person",        to_id: "p1",        to_database: Some(WORKSPACE),    };    let none = LinkRow { to_database: None, ..named };    let file = read_file_identity(&db).expect("reads").expect("the file is seeded");    let id = link_id_for(&named, file.id());    assert_eq!(id, link_id_for(&none, file.id()));    assert_eq!(id, record_link_id("note", "n1", "person", "p1"), "the id every link has today");    assert_ne!(        id,        link_id_for(&LinkRow { to_database: Some("another-database"), ..named }, file.id()),        "a link into another database is another link"    );    let actor = session_actor(&db);    mint(        &db,        &act(            actor,            vec![Change::create(                "cotton_links",                &id,                patch(json!({                    "id": id,                    "workspace_id": WORKSPACE,                    "from_kind": "note",                    "from_id": "n1",                    "to_kind": "person",                    "to_id": "p1",                    "to_database": WORKSPACE,                    "created_at": NOW,                })),            )],        ),        &Clock::wall(T0),        &mut Ids(0),        Held::Served,    )    .expect("the link");    assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_links WHERE to_database IS NULL"), 1);    assert_eq!(text(&db, "SELECT id FROM cotton_links").as_deref(), Some(id.as_str()));}