Cotton code
507 lines · 20.6 KB · RustRaw
//! The built-now set (slice 9a, part 2): every table and column the sync//! rebuild names is in a fresh file, EMPTY and read by nothing yet.//!//! - **`OWNING_REFS` / `SOFT_REFS` / `SERVER_ONLY_CHILD_REFS` ↔ the file's//!   foreign keys.** The three lists are hand-written, and this asks the file//!   whether they still say what its `FOREIGN KEY` clauses say — both//!   directions. An owning reference is a plain `REFERENCES` with no action; a//!   soft one is `SET NULL` (or a plain reference named in `SOFT_REFS`); a//!   server-only child has no constraint in the file at all, so its list is//!   held to NOT appear among the live keys.//! - **The signature columns** — `sig` is a nullable BLOB on every table that//!   will carry a signed write; `bytes` is NOT NULL where every row is a//!   receipt (`_outbox`, `_tombstones`) and nullable where a row may predate//!   one.//! - **`_born` on every replicated table** — every table with a `_hlc` has//!   one, nullable.//! - **The new tables' CHECKs refuse what they say they refuse**, and each//!   table takes one valid row.use std::collections::BTreeSet;use cotton_store::migrate::migrate_store;use cotton_store::schema::table_specs::{    OWNING_REFS, SERVER_ONLY_CHILD_REFS, SOFT_REFS, SOFT_REF_DATABASES, SERVER_ONLY_TABLES,    TABLE_SPECS,};use cotton_store::Driver;/// A real file at `SCHEMA_VERSION`, built the way a real one is.fn built() -> Driver {    let db = Driver::open_in_memory().expect("opens");    migrate_store(&db).expect("migrates");    db}/// `(child, column, parent, on_delete)` for every foreign key in the file,/// `workspace_id → cotton_workspaces` left out (every synced table has it, and/// the workspace is the file).fn live_foreign_keys(db: &Driver) -> Vec<(String, String, String, String)> {    db.all(        "SELECT m.name AS child, f.\"from\" AS col, f.\"table\" AS parent, f.on_delete AS on_delete \         FROM sqlite_master m, pragma_foreign_key_list(m.name) f \         WHERE m.type = 'table' ORDER BY m.name, f.\"from\", f.\"table\"",        &[],    )    .expect("reads")    .iter()    .map(|row| {        (            row.text("child").unwrap_or_default().to_string(),            row.text("col").unwrap_or_default().to_string(),            row.text("parent").unwrap_or_default().to_string(),            row.text("on_delete").unwrap_or_default().to_string(),        )    })    .filter(|(_, col, parent, _)| !(col == "workspace_id" && parent == "cotton_workspaces"))    .collect()}#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Class {    Owning,    Soft,    ServerOnlyChild,}/// A live key's class. `CASCADE` is no class at all any more: an owning/// reference is a plain `NO ACTION`, and so are the two money columns that/// were always plain, which `SOFT_REFS` names by hand — so a plain reference/// is soft only if that list already says so.fn classify(child: &str, col: &str, parent: &str, on_delete: &str) -> Class {    let soft_by_hand = SOFT_REFS        .iter()        .any(|(c, k, p)| *c == child && *k == col && *p == parent);    if SERVER_ONLY_TABLES.iter().any(|(name, _)| *name == child) {        Class::ServerOnlyChild    } else if on_delete == "SET NULL" || soft_by_hand {        Class::Soft    } else {        Class::Owning    }}/// The regeneration tool for the two lists the file can tell apart: prints/// them from a fresh file. Run with `cargo test -p cotton-store --test/// fresh_line_schema -- --ignored --nocapture print_the_ref_lists` and paste/// over the lists in `schema/table_specs.rs`. `SERVER_ONLY_CHILD_REFS` has no/// constraint in the file to print from; it is written by hand, and so are the/// `SOFT_REFS` entries of the `SOFT_REF_DATABASES` pairs, which have none.#[test]#[ignore = "a generator, run by hand when a foreign key changes"]fn print_the_ref_lists() {    let db = built();    let fks = live_foreign_keys(&db);    for (name, class) in [("OWNING_REFS", Class::Owning), ("SOFT_REFS", Class::Soft)] {        println!("pub const {name}: &[(&str, &str, &str)] = &[");        for (child, col, parent, on_delete) in &fks {            if classify(child, col, parent, on_delete) == class {                println!("    (\"{child}\", \"{col}\", \"{parent}\"),");            }        }        println!("];");    }}/// RULE: The hand-written owning, soft and server-only reference lists say exactly what the file's foreign keys say, and a soft pair that may name another database carries none.#[test]fn owning_refs_equal_the_live_schema_foreign_key_list() {    let db = built();    let fks: Vec<_> = live_foreign_keys(&db).into_iter().filter(|(child, _, parent, _)| !(child.starts_with('_') && parent.starts_with('_'))).collect();    assert!(!fks.is_empty(), "the file has no foreign keys at all — the query is wrong");    let key = |(child, col, parent): &(&str, &str, &str)| {        (child.to_string(), col.to_string(), parent.to_string())    };    let mut listed: BTreeSet<(String, String, String)> = BTreeSet::new();    let mut server_only: BTreeSet<(String, String, String)> = BTreeSet::new();    for list in [OWNING_REFS, SOFT_REFS, SERVER_ONLY_CHILD_REFS] {        for entry in list {            assert!(                listed.insert(key(entry)) && !server_only.contains(&key(entry)),                "{entry:?} is listed twice across OWNING_REFS / SOFT_REFS / SERVER_ONLY_CHILD_REFS"            );        }    }    for entry in SERVER_ONLY_CHILD_REFS {        listed.remove(&key(entry));        server_only.insert(key(entry));        assert!(            SERVER_ONLY_TABLES.iter().any(|(name, _)| *name == entry.0),            "{entry:?} is in SERVER_ONLY_CHILD_REFS but {} is not a server-only table",            entry.0        );    }    let live: BTreeSet<(String, String, String)> = fks        .iter()        .map(|(child, col, parent, _)| (child.clone(), col.clone(), parent.clone()))        .collect();    // A soft pair (SOFT_REF_DATABASES) may name a row in another database, so    // the file carries NO foreign key for it — a key would refuse that name —    // and must still carry both columns.    for (child, col, database) in SOFT_REF_DATABASES {        let parent = SOFT_REFS            .iter()            .find(|(c, k, _)| c == child && k == col)            .map(|(_, _, parent)| *parent)            .unwrap_or_else(|| panic!("{child}.{col} is in SOFT_REF_DATABASES but not in SOFT_REFS"));        let entry = (child.to_string(), col.to_string(), parent.to_string());        assert!(            !live.contains(&entry),            "{child}.{col} → {parent} is a soft pair with {database} and must have no FOREIGN KEY"        );        let columns = table_info(&db, child);        for column in [col, database] {            assert!(                columns.iter().any(|(name, _, _)| name == column),                "{child} has no column {column}, so SOFT_REF_DATABASES names a pair that is not there"            );        }        listed.remove(&entry);    }    // A server-only child's reference is a column, not a constraint: the file    // must carry NO foreign key for it, and must still carry the column.    for (child, col, parent) in &server_only {        assert!(            !live.contains(&(child.clone(), col.clone(), parent.clone())),            "{child}.{col} → {parent} is a server-only child reference and must have no FOREIGN KEY"        );        assert!(            table_info(&db, child).iter().any(|(name, _, _)| name == col),            "{child} has no column {col}, so SERVER_ONLY_CHILD_REFS names a reference that is not there"        );    }    // A soft reference is a column, not a constraint, since schema 81 (the    // few that were always a plain reference aside): it may carry no foreign    // key, and must still carry the column.    for entry in SOFT_REFS {        let entry = key(entry);        if !live.contains(&entry) {            assert!(                table_info(&db, &entry.0).iter().any(|(name, _, _)| *name == entry.1),                "{} has no column {}, so SOFT_REFS names a reference that is not there",                entry.0,                entry.1            );            listed.remove(&entry);        }    }    let missing: Vec<_> = live.difference(&listed).collect();    let stale: Vec<_> = listed.difference(&live).collect();    assert!(        missing.is_empty(),        "the file has foreign keys no list names: {missing:?} — run the ignored `print_the_ref_lists`"    );    assert!(        stale.is_empty(),        "the lists name foreign keys the file does not have: {stale:?}"    );    let in_list = |list: &[(&str, &str, &str)], child: &str, col: &str, parent: &str| {        list.iter()            .any(|(c, k, p)| *c == child && *k == col && *p == parent)    };    for (child, col, parent, on_delete) in &fks {        let class = classify(child, col, parent, on_delete);        let (list, name): (&[(&str, &str, &str)], &str) = match class {            Class::Owning => (OWNING_REFS, "OWNING_REFS"),            Class::Soft => (SOFT_REFS, "SOFT_REFS"),            Class::ServerOnlyChild => {                panic!("{child}.{col} → {parent}: a server-only child carries no FOREIGN KEY")            }        };        assert!(            in_list(list, child, col, parent),            "{child}.{col} → {parent} is ON DELETE {on_delete}, so it belongs in {name}"        );        if matches!(class, Class::Soft) {            assert!(                TABLE_SPECS.iter().any(|spec| spec.name == child),                "{child}.{col} is a soft reference from a table with no spec"            );        }    }}/// `(name, type, notnull)` per column.fn table_info(db: &Driver, table: &str) -> Vec<(String, String, i64)> {    db.all(&format!("PRAGMA table_info({table})"), &[])        .expect("reads")        .iter()        .map(|row| {            (                row.text("name").unwrap_or_default().to_string(),                row.text("type").unwrap_or_default().to_string(),                row.int("notnull").unwrap_or_default(),            )        })        .collect()}#[test]fn parked_counts_its_hand_over_offers_per_epoch_on_its_own_columns() {    // v61: the hand-over's offer count is not `tries`, which the sweep bumps.    let info = table_info(&built(), "_parked");    let column = |name: &str| {        info.iter()            .find(|(column, _, _)| column == name)            .map(|(_, kind, notnull)| (kind.clone(), *notnull))            .unwrap_or_else(|| panic!("_parked has no `{name}` column"))    };    assert_eq!(column("handover_epoch"), ("INTEGER".to_string(), 0));    assert_eq!(column("handover_offers"), ("INTEGER".to_string(), 1));}/// RULE: Every table that will carry a signed write has a nullable BLOB `sig` column, and a queued, retracting or erasing receipt's `bytes` is NOT NULL.#[test]fn sig_column_exists_nullable_on_writes_outbox_and_parked() {    let db = built();    // `_outbox` and `_tombstones` hold nothing but receipts, minted whole, so a    // row without bytes is a row that cannot travel and cannot be verified —    // refused at the table. So does `_gone` (v59): its one writer,    // `erase::apply`, keeps the erase's receipt. `_writes` and `_parked` may    // hold a row that predates its receipt, so their `bytes` stays nullable.    for (table, bytes_not_null) in [        ("_writes", 0),        ("_outbox", 1),        ("_parked", 0),        ("_tombstones", 1),        ("_gone", 1),    ] {        let info = table_info(&db, table);        let sig = info            .iter()            .find(|(name, _, _)| name == "sig")            .unwrap_or_else(|| panic!("{table} has no `sig` column"));        assert_eq!(sig.1, "BLOB", "{table}.sig is {}, not BLOB", sig.1);        assert_eq!(sig.2, 0, "{table}.sig is NOT NULL — an unsigned write could not be held");        let bytes = info            .iter()            .find(|(name, _, _)| name == "bytes")            .unwrap_or_else(|| panic!("{table} has no `bytes` column"));        assert_eq!(bytes.1, "BLOB", "{table}.bytes is {}, not BLOB", bytes.1);        assert_eq!(            bytes.2, bytes_not_null,            "{table}.bytes notnull is {}, expected {bytes_not_null}",            bytes.2        );    }}/// RULE: Every replicated table (every table with `_hlc`) carries a nullable `_born`, and no other table does.#[test]fn every_replicated_table_carries_born() {    let db = built();    let tables: Vec<String> = db        .all(            "SELECT name FROM sqlite_master WHERE type = 'table' AND sql NOT LIKE '%USING fts5%'",            &[],        )        .expect("reads")        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect();    let mut replicated = 0;    for table in &tables {        let info = table_info(&db, table);        let has = |column: &str| info.iter().find(|(name, _, _)| name == column);        match (has("_hlc"), has("_born")) {            (Some(_), Some(born)) => {                replicated += 1;                assert_eq!(born.1, "TEXT", "{table}._born is {}", born.1);                assert_eq!(born.2, 0, "{table}._born is NOT NULL");            }            (Some(_), None) => panic!("{table} is replicated (has `_hlc`) and has no `_born`"),            (None, Some(_)) => panic!("{table} has `_born` and is not replicated"),            (None, None) => {}        }    }    assert!(replicated > 100, "only {replicated} replicated tables — the walk is wrong");}const WS: &str = "11111111-1111-4111-8111-111111111111";fn refuses(db: &Driver, sql: &str, what: &str) {    let result = db.exec(sql);    let error = result.expect_err(&format!("{what} was accepted: {sql}"));    assert!(        error.to_string().contains("CHECK"),        "{what} was refused for another reason: {error}"    );}fn accepts_and_deletes(db: &Driver, table: &str, sql: &str) {    db.exec(sql)        .unwrap_or_else(|error| panic!("{table} refused a valid row: {error}\n{sql}"));    let count = db        .get(&format!("SELECT count(*) AS n FROM {table}"), &[])        .expect("counts")        .and_then(|row| row.int("n"))        .unwrap_or_default();    assert_eq!(count, 1, "{table} holds {count} rows after one insert");    db.exec(&format!("DELETE FROM {table}")).expect("deletes");}/// RULE: The built-now tables exist empty, refuse what their CHECKs refuse, and take one valid row.#[test]fn the_new_tables_exist_empty_with_their_checks() {    let db = built();    db.exec(&format!(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) \         VALUES ('{WS}', 'Home', 'owner-1', '2026-10-03T00:00:00.000Z')"    ))    .expect("a workspace");    for table in [        "_writes",        "_parked",        "_gone",        "_media_key_names",        "_media_unlinks",        "_computed",        "_on_demand",        "_keep_fetch",        "cotton_authors",        "cotton_revocations",        "cotton_serving_machine",        "cotton_vault_retired_keys",        "cotton_media_erasures",        "cotton_undos",        "cotton_grant_rotations",        "cotton_admissions",        "cotton_device_statements",        "cotton_invites",        "cotton_joined_places",        "cotton_imports",        "cotton_connections",        "cotton_person_handles",        "cotton_person_languages",        "cotton_msg_thread_filings",        "cotton_device_keep",        "cotton_msg_thread_marks",        "cotton_push_acks",        "cotton_device_relay_keys",    ] {        let count = db            .get(&format!("SELECT count(*) AS n FROM {table}"), &[])            .unwrap_or_else(|error| panic!("{table} is not in a fresh file: {error}"))            .and_then(|row| row.int("n"))            .unwrap_or_default();        assert_eq!(count, 0, "{table} is not empty in a fresh file");    }    let author = |reason: &str| {        format!(            "INSERT INTO cotton_authors (id, workspace_id, device_id, minted_at, reason, first_stamp) \             VALUES ('a1', '{WS}', 'device-1', '2026-10-03T00:00:00.000Z', '{reason}', '1:0:a1')"        )    };    refuses(&db, &author("guessed"), "cotton_authors.reason 'guessed'");    accepts_and_deletes(&db, "cotton_authors", &author("first"));    let revocation = |reason: &str| {        format!(            "INSERT INTO cotton_revocations (id, workspace_id, subject_table, subject_id, revoked_at, actor, reason) \             VALUES ('r1', '{WS}', 'cotton_devices', 'd1', '2026-10-03T00:00:00.000Z', 'owner', '{reason}')"        )    };    refuses(&db, &revocation("forgotten"), "cotton_revocations.reason 'forgotten'");    accepts_and_deletes(&db, "cotton_revocations", &revocation("lost"));    let parked = |class: &str| {        format!("INSERT INTO _parked (op_id, class, tbl, row_id) VALUES ('op-1', '{class}', 'cotton_todos', 't1')")    };    refuses(&db, &parked("rejected"), "_parked.class 'rejected'");    accepts_and_deletes(&db, "_parked", &parked("waiting"));    let writes = |kind: &str| {        format!(            "INSERT INTO _writes (tbl, row_id, hlc, op_id, kind) \             VALUES ('cotton_todos', 't1', '1:0:a1', 'op-1', '{kind}')"        )    };    refuses(&db, &writes("upsert"), "_writes.kind 'upsert'");    accepts_and_deletes(&db, "_writes", &writes("create"));    let device = |scope: &str| {        format!(            "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, approved_by_device, created_at, updated_at, scope) \             VALUES ('d1', '{WS}', 'device-1', 'Mac', '2026-10-03T00:00:00.000Z', 'device-0', \             '2026-10-03T00:00:00.000Z', '2026-10-03T00:00:00.000Z', '{scope}')"        )    };    refuses(&db, &device("half"), "cotton_devices.scope 'half'");    accepts_and_deletes(&db, "cotton_devices", &device("runner"));    db.exec(&format!(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, approved_by_device, created_at, updated_at) \         VALUES ('d1', '{WS}', 'device-1', 'Mac', '2026-10-03T00:00:00.000Z', 'device-0', \         '2026-10-03T00:00:00.000Z', '2026-10-03T00:00:00.000Z')"    ))    .expect("a device with no scope");    let scope = db        .get("SELECT scope FROM cotton_devices", &[])        .expect("reads")        .and_then(|row| row.text("scope").map(str::to_string));    assert_eq!(scope.as_deref(), Some("full"), "a device row with no scope is not 'full'");    db.exec("DELETE FROM cotton_devices").expect("deletes");    let serving = |positions: &str| {        format!(            "INSERT INTO cotton_serving_machine (id, workspace_id, epoch, device_credential_id, author_id, since, start_positions) \             VALUES ('s1', '{WS}', 1, 'd1', 'a1', '2026-10-03T00:00:00.000Z', {positions})"        )    };    refuses(&db, &serving("'[]'"), "cotton_serving_machine.start_positions as an array");    accepts_and_deletes(&db, "cotton_serving_machine", &serving("'{}'"));    for (table, sql) in [        (            "_gone",            "INSERT INTO _gone (tbl, row_id, hlc, bytes) VALUES ('cotton_todos', 't1', '1:0:a1', x'00')".to_string(),        ),        (            "_media_key_names",            "INSERT INTO _media_key_names (key, tbl, row_id) VALUES ('k', 'cotton_photos', 'p1')"                .to_string(),        ),        (            "_media_unlinks",            "INSERT INTO _media_unlinks (key, queued_at) VALUES ('k', '2026-10-03T00:00:00.000Z')".to_string(),        ),        (            "cotton_vault_retired_keys",            format!(                "INSERT INTO cotton_vault_retired_keys (id, workspace_id, version, under_version, under_kcv, wrapped, retired_at, actor) \                 VALUES ('v1', '{WS}', 1, 2, 'kcv', 'd3JhcHBlZA==', '2026-10-03T00:00:00.000Z', 'owner')"            ),        ),        (            "cotton_media_erasures",            format!(                "INSERT INTO cotton_media_erasures (id, workspace_id, key, record_table, record_id, erased_at, actor) \                 VALUES ('e1', '{WS}', 'k', 'cotton_photos', 'p1', '2026-10-03T00:00:00.000Z', 'owner')"            ),        ),        (            "cotton_undos",            format!(                "INSERT INTO cotton_undos (id, workspace_id, change_id, undo_change_id, at, actor) \                 VALUES ('u1', '{WS}', 'c1', 'c2', '2026-10-03T00:00:00.000Z', 'owner')"            ),        ),        (            "cotton_grant_rotations",            format!(                "INSERT INTO cotton_grant_rotations (id, workspace_id, grant_id, generation, digest, rotated_at, actor) \                 VALUES ('g1', '{WS}', 'grant-1', 2, 'digest', '2026-10-03T00:00:00.000Z', 'owner')"            ),        ),    ] {        accepts_and_deletes(&db, table, &sql);    }}