Cotton code
333 lines · 12.7 KB · RustRaw
//! Totality, both directions (step 5, R5).//!//! Two of the four guards that replace `gen:check`. They are stronger than what//! they replace: the generator only ever emitted what it read, so a byte diff//! against its own output could not tell a coherent declaration from an//! incoherent one. These ask the FILE.//!//! - **`TABLE_SPECS` ↔ the schema.** Every table the ladder creates has a spec,//!   or is one of the twelve system tables, or is an FTS5 index — and every spec//!   names a real table with the columns it declares, in the file's own order.//! - **`FTS_SOURCES` ↔ the schema.** Every source names a table the ladder//!   creates, every indexed column is a real column of it, and the index itself//!   exists.//!//! A "no" is never a missing entry here: the three exemptions are derived//! (`meta::SYSTEM_TABLE_NAMES`, the FTS5 virtual tables, their shadow tables),//! never a hand list somebody could grow.use std::collections::BTreeSet;use cotton_store::meta::SYSTEM_TABLE_NAMES;use cotton_store::migrate::migrate_store;use cotton_store::schema::fts::FTS_SOURCES;use cotton_store::schema::table_specs::{DROPPED_TABLES, TABLE_NAMES, 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}/// Every ordinary table in the file — FTS5 virtual tables, their shadows and/// SQLite's own bookkeeping left out.fn ordinary_tables(db: &Driver) -> BTreeSet<String> {    let virtuals: BTreeSet<String> = db        .all(            "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE '%USING fts5%'",            &[],        )        .expect("reads")        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect();    const SHADOWS: [&str; 5] = ["_data", "_idx", "_docsize", "_config", "_content"];    db.all("SELECT name FROM sqlite_master WHERE type = 'table'", &[])        .expect("reads")        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .filter(|name| name != "sqlite_sequence")        .filter(|name| !virtuals.contains(name))        .filter(|name| {            !SHADOWS.iter().any(|suffix| {                name.strip_suffix(suffix)                    .is_some_and(|stem| virtuals.contains(stem))            })        })        .collect()}fn columns_of(db: &Driver, table: &str) -> BTreeSet<String> {    db.all(&format!("PRAGMA table_info({table})"), &[])        .expect("reads")        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect()}/// RULE: Every table the database creates is either declared as a record type or carries a written reason it is not.#[test]fn every_table_the_schema_creates_has_a_spec_or_a_written_reason_not_to() {    let db = built();    let specs: BTreeSet<&str> = TABLE_SPECS.iter().map(|spec| spec.name).collect();    let system: BTreeSet<&str> = SYSTEM_TABLE_NAMES.iter().copied().collect();    let mut unaccounted: Vec<String> = Vec::new();    for table in ordinary_tables(&db) {        if specs.contains(table.as_str()) || system.contains(table.as_str()) {            continue;        }        unaccounted.push(table);    }    assert!(        unaccounted.is_empty(),        "the schema creates {unaccounted:?}, which no `TABLE_SPECS` entry names and which is not \         one of the twelve system tables — a table with no spec is a table the fold rejects every op \         for, silently, for ever"    );}#[test]fn every_spec_names_a_real_table_with_the_columns_it_declares() {    let db = built();    let tables = ordinary_tables(&db);    for spec in TABLE_SPECS {        assert!(            tables.contains(spec.name),            "`{}` has a spec and the schema never creates it — the fold would write into nothing",            spec.name        );        let real = columns_of(&db, spec.name);        for (column, _) in spec.columns {            assert!(                real.contains(*column),                "`{}`.`{column}` is in the spec and not in the table",                spec.name            );        }        assert!(            real.contains(spec.pk),            "`{}`'s primary key `{}` is not one of its columns",            spec.name,            spec.pk        );        for key in spec.natural_key {            assert!(                real.contains(*key),                "`{}`'s natural key names `{key}`, which the table does not have",                spec.name            );        }        // The spec is the CODEC: a column the table has and the spec does not        // is a column no op can ever carry. TWO exemptions, and they are        // written rather than absent — `_hlc` is the newest stamp among the        // row's current receipts and `_born` (version 49) the stamp it was        // created under. Both are set by the fold from the receipts and never        // by a patch, so a spec entry for either would let a client overwrite        // the clock that decides which client wins.        const NOT_IN_A_SPEC: [&str; 2] = ["_hlc", "_born"];        let declared: BTreeSet<&str> = spec.columns.iter().map(|(name, _)| *name).collect();        let uncarryable: Vec<&String> = real            .iter()            .filter(|name| !declared.contains(name.as_str()))            .filter(|name| !NOT_IN_A_SPEC.contains(&name.as_str()))            .collect();        assert!(            uncarryable.is_empty(),            "`{}` has {uncarryable:?} in the file and not in its spec — no op could ever carry them",            spec.name        );    }    assert_eq!(TABLE_NAMES.len(), TABLE_SPECS.len());    for dropped in DROPPED_TABLES {        assert!(            !tables.contains(*dropped),            "`{dropped}` is dropped and the schema still creates it"        );        assert!(            !TABLE_SPECS.iter().any(|spec| spec.name == *dropped),            "`{dropped}` is dropped and still has a spec"        );    }}#[test]fn every_fts_source_names_a_real_table_and_real_columns_and_a_real_index() {    let db = built();    let tables = ordinary_tables(&db);    let indexes: BTreeSet<String> = db        .all(            "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE '%USING fts5%'",            &[],        )        .expect("reads")        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect();    for source in FTS_SOURCES {        assert!(            indexes.contains(source.fts),            "`{}` is a source and the schema never creates the index",            source.fts        );        assert!(            tables.contains(source.source),            "`{}` mirrors `{}`, which the schema never creates",            source.fts,            source.source        );        assert!(!source.columns.is_empty(), "{} indexes nothing", source.fts);        let real = columns_of(&db, source.source);        for column in source.columns {            assert!(                real.contains(*column),                "`{}` indexes `{}`.`{column}`, which the table does not have — the index would be \                 created wide and filled narrow, and the search would silently never match",                source.fts,                source.source            );        }        // And the index carries exactly the indexed columns — no `row_id`, and        // nothing else. It is external-content: the source row is found by        // rowid, not by a copy of its TEXT id stored in the index.        let indexed = columns_of(&db, source.fts);        assert!(            !indexed.contains("row_id"),            "{} still carries a `row_id` column — an external-content index finds its row by \             rowid, and a `row_id` column is what made a delete scan the whole index",            source.fts        );        assert_eq!(            indexed.len(),            source.columns.len(),            "{} carries {indexed:?} but FTS_SOURCES declares {:?}",            source.fts,            source.columns        );        for column in source.columns {            assert!(                indexed.contains(*column),                "`{}` declares `{column}` and the index does not carry it",                source.fts            );        }    }    // The other direction: an FTS5 index in the file that no source names would    // be an index nothing ever fills.    for index in &indexes {        assert!(            FTS_SOURCES.iter().any(|source| source.fts == index),            "the schema creates `{index}` and no `FTS_SOURCES` entry names it — nothing would \             ever fill it"        );    }    // And each spec's `fts_into` agrees with the source list, both ways.    for spec in TABLE_SPECS {        let Some(fts) = spec.fts_into else { continue };        let source = FTS_SOURCES            .iter()            .find(|source| source.fts == fts)            .unwrap_or_else(|| panic!("{} points at {fts}, which is not a source", spec.name));        assert_eq!(source.source, spec.name, "{fts} mirrors a different table");    }    for source in FTS_SOURCES {        let spec = TABLE_SPECS            .iter()            .find(|spec| spec.name == source.source)            .unwrap_or_else(|| {                panic!(                    "{} mirrors {}, which has no spec",                    source.fts, source.source                )            });        // A table may be mirrored by two indexes while a wider one is filled        // beside the one that answers (v122: fts_mail beside fts_emails); the        // spec names the one that answers, and must name one.        assert!(            spec.fts_into.is_some(),            "{} mirrors {} and the spec does not say so",            source.fts,            source.source        );    }}/// RULE: Every table and column several databases name is in a fresh file and in `TABLE_SPECS` with a codec, and a link's ends are unique per target database.////// The two tests above hold `TABLE_SPECS` and the file equal in both/// directions for every table. This one names the eight shapes P1 of several/// databases adds, empty and unused, so a later slice that starts writing/// into one finds it in every file already — and the links' uniqueness, which/// has to admit one edge to the same id in two databases.#[test]fn table_specs_match_the_live_schema() {    let db = built();    let tables = ordinary_tables(&db);    let columns: [(&str, &str); 6] = [        ("cotton_workspaces", "kind"),        ("cotton_workspaces", "namespace"),        ("cotton_mcp_tokens", "minted_by_device"),        ("cotton_links", "to_database"),        ("cotton_sessions", "todo_database"),        ("cotton_meetings", "event_database"),    ];    for (table, column) in columns {        assert!(            columns_of(&db, table).contains(column),            "`{table}`.`{column}` is not in a fresh file"        );        let spec = TABLE_SPECS            .iter()            .find(|spec| spec.name == table)            .unwrap_or_else(|| panic!("`{table}` has no spec"));        assert!(            spec.columns.iter().any(|(name, _)| *name == column),            "`{table}`.`{column}` has no codec in `TABLE_SPECS` — no op could carry it"        );    }    for table in ["cotton_databases", "cotton_database_departures"] {        assert!(tables.contains(table), "`{table}` is not in a fresh file");        assert!(            TABLE_SPECS.iter().any(|spec| spec.name == table),            "`{table}` has no spec"        );    }    // The ends of a link are unique per target database, not per ends alone:    // the table-level UNIQUE is gone, and one index holds the five.    let links: String = db        .get("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'cotton_links'", &[])        .expect("reads")        .and_then(|row| row.text("sql").map(str::to_string))        .expect("the links table");    assert!(        !links.contains("UNIQUE"),        "cotton_links still carries a table-level UNIQUE, which refuses a second link to the same \         id in another database"    );    let unique: Vec<String> = db        .all(            "SELECT sql FROM sqlite_master WHERE type = 'index' AND tbl_name = 'cotton_links' \             AND sql LIKE 'CREATE UNIQUE INDEX%'",            &[],        )        .expect("reads")        .iter()        .filter_map(|row| row.text("sql").map(str::to_string))        .collect();    assert!(        unique.iter().any(|sql| sql.ends_with(            "(from_kind, from_id, to_kind, to_id, coalesce(to_database, ''))"        )),        "no unique index on the links' ends and their target database: {unique:?}"    );}