Cotton code
311 lines · 16.4 KB · RustRaw
//! A schema rise is additive or it is not, and the answer is the move's own//! diff over the frozen shapes (`fixtures/schema-vNN.json`, each the flat DDL//! of its stamp; this build's own shape stands for its own stamp).//!//! Additive is said of the EXCHANGE shape — the rows of the synced tables,//! which is what one build serves another — because that is what `floor()` is//! for. A rise that rebuilds only local tables (`_parked`, `_outbox` and kin)//! is additive: no peer is sent a row of them.use std::collections::{BTreeMap, BTreeSet};use std::time::Instant;use cotton_store::create::{apply_schema, schema_objects, SchemaObject};use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::schema::move_intents::{floor, floor_of, INTENTS};use cotton_store::schema::table_specs::TABLE_SPECS;use cotton_store::shape_move::{crossing, is_local, move_to_current};use cotton_store::Driver;use rusqlite::types::Value;fn fresh_shape() -> Vec<SchemaObject> {    let fresh = Driver::open_in_memory().unwrap();    apply_schema(&fresh).unwrap();    schema_objects(&fresh).unwrap()}/// Every frozen shape by its stamp, and this build's own.fn shapes() -> BTreeMap<u32, Vec<SchemaObject>> {    let dir = cotton_store::manifest_dir().join("tests/fixtures");    let mut shapes = BTreeMap::new();    for entry in std::fs::read_dir(&dir).unwrap() {        let name = entry.unwrap().file_name().to_string_lossy().into_owned();        let stamp = name.strip_prefix("schema-v").and_then(|rest| rest.strip_suffix(".json")).and_then(|stamp| stamp.parse::<u32>().ok());        if let Some(stamp) = stamp {            shapes.insert(stamp, serde_json::from_slice(&std::fs::read(dir.join(&name)).unwrap()).unwrap());        }    }    shapes.insert(SCHEMA_VERSION, fresh_shape());    shapes}/// A file of exactly this shape, stamped: tables, search indexes, indexes,/// then triggers.fn build(db: &Driver, shape: &[SchemaObject], stamp: u32) {    let phase = |o: &SchemaObject| match o.kind.as_str() {        "table" if o.is_fts5_virtual() => 1,        "table" => 0,        "index" => 2,        _ => 3,    };    let mut ordered = shape.to_vec();    ordered.sort_by_key(|o| phase(o));    for object in &ordered {        db.exec(&object.sql).unwrap();    }    db.exec(&format!("PRAGMA user_version = {stamp}")).unwrap();}/// One row with every NOT NULL column filled by its type, `set` on top. The/// caller turns CHECKs off: these rows are about being carried, not about/// what they say.fn insert(db: &Driver, table: &str, rowid: i64, set: &[(&str, Value)]) {    let columns = db.all(&format!("SELECT name, type, \"notnull\" AS nn, dflt_value FROM pragma_table_info('{table}')"), &[]).unwrap();    let (mut names, mut values) = (vec!["rowid".to_string()], vec![Value::Integer(rowid)]);    for column in &columns {        let name = column.text("name").unwrap();        if let Some((_, value)) = set.iter().find(|(n, _)| *n == name) {            names.push(format!("\"{name}\""));            values.push(value.clone());        } else if column.int("nn") == Some(1) && column.get("dflt_value").is_none_or(|v| *v == Value::Null) {            names.push(format!("\"{name}\""));            values.push(match column.text("type").unwrap_or("").to_ascii_uppercase().as_str() {                t if t.contains("INT") => Value::Integer(rowid),                t if t.contains("REAL") => Value::Real(1.0),                _ => Value::Text(format!("{table}-{name}-{rowid}")),            });        }    }    let marks = vec!["?"; names.len()].join(", ");    db.run(&format!("INSERT INTO \"{table}\" ({}) VALUES ({marks})", names.join(", ")), &values).unwrap();}fn column_names(db: &Driver, table: &str) -> Vec<String> {    db.all(&format!("SELECT name FROM pragma_table_info('{table}')"), &[]).unwrap().iter().map(|row| row.text("name").unwrap().to_string()).collect()}fn int(db: &Driver, sql: &str) -> i64 {    db.get(sql, &[]).unwrap().unwrap().columns()[0].1.clone().try_into_int()}trait IntoInt {    fn try_into_int(self) -> i64;}impl IntoInt for Value {    fn try_into_int(self) -> i64 {        match self {            Value::Integer(n) => n,            other => panic!("expected an integer, read {other:?}"),        }    }}/// The stamps below this build that reach it additively and gain a column on/// the way, each with the tables that gain one.fn additive_starts(shapes: &BTreeMap<u32, Vec<SchemaObject>>) -> Vec<(u32, BTreeSet<String>)> {    let fresh = &shapes[&SCHEMA_VERSION];    shapes        .range(floor()..SCHEMA_VERSION)        .filter_map(|(stamp, had)| {            let gaining: BTreeSet<String> = crossing(had, fresh).unwrap().add_columns.into_iter().map(|(table, _)| table).collect();            (!gaining.is_empty()).then_some((*stamp, gaining))        })        .collect()}/// RULE: A rise is declared additive exactly when crossing its two frozen shapes only adds to the exchange shape — on the synced tables it creates tables and appends columns by ADD COLUMN, rebuilds and removes none, and changes no UNIQUE index or rule trigger over rows a peer may send; what it does to a local table (leading underscore: never synced), a search index or a plain index does not count, because no peer is served a row of those and a rebuild of _parked must not raise floor(). A rise with no frozen shape on both sides to prove it is declared not additive. floor() is read off these flags, and one wrong flag has a build serve a peer whose rows mean something else, or refuse one it could serve./// A frozen CHECK is never edited: a new typed word uses an additive column or a rows table, so peers keep the same rules over their existing rows.#[test]fn every_rise_is_classified_as_its_frozen_shapes_say() {    let shapes = shapes();    for intent in INTENTS {        match (shapes.get(&(intent.version - 1)), shapes.get(&intent.version)) {            (Some(had), Some(fresh)) => {                let plan = crossing(had, fresh).unwrap();                let why = plan.not_additive();                assert_eq!(intent.additive, why.is_empty(), "v{} against its frozen shapes: {why:?}", intent.version);            }            _ => assert!(                !intent.additive,                "v{} is declared additive, and no frozen shape of it and of v{} proves it",                intent.version,                intent.version - 1            ),        }    }}/// RULE: A local table is one named with a leading underscore and no synced table is, because the classification leaves local tables out by that name alone and a synced table taken for a local one could be rebuilt under a peer without floor() rising.#[test]fn no_synced_table_is_taken_for_a_local_one() {    for spec in TABLE_SPECS {        assert!(!is_local(spec.name), "{} is synced and named like a local table", spec.name);    }    for local in ["_parked", "_outbox", "_writes", "_meta"] {        assert!(is_local(local));    }}/// RULE: A crossing that rebuilds only a local table is additive and one that rebuilds a synced table is not, whatever else it does — the same CHECK widened on _parked and on a synced table are opposite answers — because the floor is the exchange shape's, not the file's.#[test]fn a_rebuild_of_a_local_table_alone_is_additive() {    let table = |name: &str, check: &str| SchemaObject {        kind: "table".into(),        name: name.into(),        tbl_name: name.into(),        sql: format!("CREATE TABLE {name} (id TEXT PRIMARY KEY, class TEXT NOT NULL CHECK (class IN ({check})))"),    };    let had = [table("_parked", "'a'"), table("cotton_notes", "'a'")];    let local = crossing(&had, &[table("_parked", "'a', 'newer-shape'"), table("cotton_notes", "'a'")]).unwrap();    assert_eq!(local.rebuild, ["_parked"]);    assert_eq!(local.not_additive(), Vec::<String>::new());    let synced = crossing(&had, &[table("_parked", "'a'"), table("cotton_notes", "'a', 'b'")]).unwrap();    assert_eq!(synced.not_additive(), ["table cotton_notes is rebuilt"]);}/// RULE: Between any two frozen shapes floor_of calls an additive crossing, the move's plan rebuilds no synced table and finds none gone — several additive rises crossed at once are still one additive crossing, because a peer can sit any number of stamps behind the build that serves it.#[test]fn every_additive_crossing_of_frozen_shapes_rebuilds_no_synced_table() {    let shapes = shapes();    for (to, fresh) in &shapes {        for (from, had) in shapes.range(floor_of(*to)..*to) {            let plan = crossing(had, fresh).unwrap();            assert!(plan.rebuild.iter().all(|table| is_local(table)), "v{from} to v{to} rebuilds {:?}", plan.rebuild);            assert_eq!(plan.not_additive(), Vec::<String>::new(), "v{from} to v{to}");        }    }}/// RULE: A file at any frozen stamp from floor() up moves to this build with no synced table rebuilt and nothing retired, every row of a table that gained a column keeps its rowid and every value, and each new column is born as its declared default — because the move must not rewrite or invent a value on a crossing the build calls additive.#[test]fn a_file_at_or_above_the_floor_moves_without_a_synced_table_rebuilt() {    let shapes = shapes();    for (stamp, gaining) in additive_starts(&shapes) {        let db = Driver::open_in_memory().unwrap();        build(&db, &shapes[&stamp], stamp);        db.exec("PRAGMA foreign_keys = OFF; PRAGMA ignore_check_constraints = ON").unwrap();        let mut before = BTreeMap::new();        for table in &gaining {            insert(&db, table, 41, &[]);            insert(&db, table, 42, &[]);            let held = column_names(&db, table);            let query = format!("SELECT rowid, {} FROM \"{table}\" ORDER BY rowid", held.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", "));            before.insert(table.clone(), (held, query.clone(), db.all(&query, &[]).unwrap()));        }        let report = move_to_current(&db).unwrap();        assert_eq!((report.from, report.to), (stamp, SCHEMA_VERSION));        assert!(report.rebuilt.iter().all(|table| is_local(table)), "v{stamp} rebuilt {:?}", report.rebuilt);        assert!(report.dropped.is_empty(), "v{stamp}: {report}");        assert!(gaining.iter().all(|table| !report.rebuilt.contains(table)));        // The indexes a move leaves to the background (SCHEMA 155) are made as the phone's background pass makes them.        while cotton_store::index_later::step(&db).unwrap().is_some() {}        assert_eq!(schema_objects(&db).unwrap(), shapes[&SCHEMA_VERSION], "v{stamp} is not this build's shape after the move");        for (table, (held, query, rows)) in &before {            assert_eq!(&db.all(query, &[]).unwrap(), rows, "v{stamp}: {table}");            for column in db.all(&format!("SELECT name, dflt_value FROM pragma_table_info('{table}')"), &[]).unwrap() {                let name = column.text("name").unwrap();                if !held.iter().any(|c| c == name) {                    let born = column.text("dflt_value").unwrap_or("NULL");                    assert_eq!(int(&db, &format!("SELECT count(*) FROM \"{table}\" WHERE \"{name}\" IS NOT ({born})")), 0, "v{stamp}: {table}.{name}");                }            }        }    }}/// Deleted with its journal files when the test ends, passed or not.struct Scratch(std::path::PathBuf);impl Drop for Scratch {    fn drop(&mut self) {        for suffix in ["", "-wal", "-shm", "-journal"] {            let _ = std::fs::remove_file(format!("{}{suffix}", self.0.display()));        }    }}/// The size of the owner's Mac file when the schema programme began/// (12 Oct 2026): what a move must not rewrite to add a column.const FILE_BYTES: i64 = 732 * 1024 * 1024;/// RULE: On a 732 MB file whose weight is in the very table that gains a column, the move to this build leaves the file the size it was and frees no page — a rebuild would copy the table and double the file — because adding a column must cost the same on a year of data as on an empty file.////// MEASURED (a Mac, 12 Oct 2026, debug build, beside a release archive): 0.70 s to move a 742 MB file from v134 to v135, the whole-file integrity check included; the test prints its own `took` line.#[test]fn a_732_mb_file_gains_its_column_without_its_table_being_rewritten() {    let shapes = shapes();    // The newest stamp below this build that reaches it by adding a column.    // A build whose own rise is not additive has no such crossing to make.    let Some((stamp, gaining)) = additive_starts(&shapes).pop() else {        assert!(shapes.range(floor()..SCHEMA_VERSION).all(|(_, had)| crossing(had, &shapes[&SCHEMA_VERSION]).unwrap().add_columns.is_empty()));        return;    };    let table = gaining.iter().next().unwrap();    let scratch = Scratch(std::env::temp_dir().join(format!(        "cotton-shape-additive-{}-{}.sqlite",        std::process::id(),        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()    )));    // Written with no journal: the weight is synthetic and the write is not    // what is measured.    {        let conn = rusqlite::Connection::open(&scratch.0).unwrap();        conn.execute_batch("PRAGMA journal_mode = OFF; PRAGMA synchronous = OFF; PRAGMA foreign_keys = OFF; PRAGMA ignore_check_constraints = ON").unwrap();        let db = Driver::from_connection(conn, false).unwrap();        db.exec("PRAGMA foreign_keys = OFF; PRAGMA ignore_check_constraints = ON; BEGIN").unwrap();        build(&db, &shapes[&stamp], stamp);        // The weight goes in the first column a row may leave empty.        let heavy = db            .all(&format!("SELECT name FROM pragma_table_info('{table}') WHERE \"notnull\" = 0 AND pk = 0 AND upper(type) = 'TEXT'"), &[])            .unwrap()            .first()            .map(|row| row.text("name").unwrap().to_string())            .unwrap_or_else(|| panic!("{table} has no free text column to weigh down"));        // Written until the FILE is the size, not until the text is: a table        // whose text is also indexed or searched holds it twice, and a count        // from the text's length wrote 1,480 MB for v151's table, past the        // runner's 300 s cap at load (rust-main 17065, 24 Nov 2026).        let weight = "synthetic weight ".repeat(4096);        let size = |db: &Driver| int(db, "PRAGMA page_count") * int(db, "PRAGMA page_size");        let mut rowid = 0;        while size(&db) < FILE_BYTES {            for _ in 0..64 {                rowid += 1;                insert(&db, table, rowid, &[(heavy.as_str(), Value::Text(format!("{rowid} {weight}")))]);            }        }        db.exec("COMMIT").unwrap();    }    let db = Driver::open(&scratch.0).unwrap();    db.exec("PRAGMA foreign_keys = OFF; PRAGMA ignore_check_constraints = ON").unwrap();    let pages = |db: &Driver| (int(db, "PRAGMA page_count"), int(db, "PRAGMA freelist_count"));    let (page_count, free) = pages(&db);    assert!(page_count * int(&db, "PRAGMA page_size") >= FILE_BYTES);    let rows = int(&db, &format!("SELECT count(*) FROM \"{table}\""));    let started = Instant::now();    let report = move_to_current(&db).unwrap();    let took = started.elapsed();    eprintln!("took {took:?} to move a {} MB file from v{stamp}: {report}", page_count * int(&db, "PRAGMA page_size") / (1024 * 1024));    assert!(!report.rebuilt.contains(table), "{report}");    assert!(report.created.iter().any(|made| made.starts_with(&format!("column {table}."))), "{report}");    assert_eq!(int(&db, &format!("SELECT count(*) FROM \"{table}\"")), rows);    // A rebuild copies the table beside itself before it drops the old one. An index the move makes over the table's    // rows takes its own pages and copies no row (153's sender index, made inside the move from 151: 263 pages here    // against 187,929), so the pages of the indexes the move made are not counted as growth (SCHEMA 155 REVIEW).    let made_indexes: Vec<String> = report.created.iter().filter_map(|made| made.strip_prefix("index ")).map(str::to_string).collect();    let index_pages: i64 = made_indexes        .iter()        .map(|name| int(&db, &format!("SELECT count(*) FROM dbstat WHERE name = '{name}'")))        .sum();    let (after_pages, after_free) = pages(&db);    assert!(        after_pages - page_count - index_pages < 64 && after_free - free < 64,        "the file went from {page_count} pages ({free} free) to {after_pages} ({after_free} free), {index_pages} of them the move's indexes {made_indexes:?}"    );}