Cotton code
448 lines · 19.3 KB · RustRaw
//! The real files' way across: a file of an older fresh DDL moved in place to//! this build's. `fixtures/schema-v141.json` is the shape of the oldest file a//! shipped build wrote (`LEDGER_BASE`), and every stamp from it moves.use cotton_store::create::{apply_schema, schema_objects, SchemaObject};use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::shape_move::{crossing, left, move_step, move_to_current, LEDGER_BASE, MOVES_FROM, MOVE_TABLE};use cotton_store::Driver;use rusqlite::types::Value;fn v141_file() -> Driver {    frozen_file(141, include_str!("fixtures/schema-v141.json"))}fn frozen_file(version: u32, snapshot: &str) -> Driver {    let objects: Vec<SchemaObject> = serde_json::from_str(snapshot).unwrap();    let db = Driver::open_in_memory().unwrap();    let phase = |o: &SchemaObject| match o.kind.as_str() {        "table" if o.is_fts5_virtual() => 1,        "table" => 0,        "index" => 2,        _ => 3,    };    let mut ordered = objects.clone();    ordered.sort_by_key(|o| phase(o));    for object in &ordered {        db.exec(&object.sql).unwrap();    }    db.exec(&format!("PRAGMA user_version = {version}"))        .unwrap();    db}/// One row with every NOT NULL column filled by its type, `set` on top. CHECKs/// are off: the test is about carrying values, not about them.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 text(s: &str) -> Value {    Value::Text(s.into())}/// A row in Money, notes, todos, events and the widgets 144 drops: the tables/// the rises above 141 rebuild, one they leave alone, and one they retire.fn seed(db: &Driver) {    db.exec("PRAGMA foreign_keys = OFF; PRAGMA ignore_check_constraints = ON").unwrap();    insert(db, "cotton_money_accounts", 7, &[("id", text("acct")), ("kind", text("bank")), ("subtype", text("bank")), ("currency", text("EUR"))]);    insert(db, "cotton_notes", 42, &[("id", text("note")), ("title", text("a findable title"))]);    insert(db, "cotton_todos", 43, &[("id", text("todo")), ("status", text("open"))]);    insert(db, "cotton_events", 44, &[("id", text("event"))]);    insert(db, "cotton_widgets", 45, &[("id", text("widget"))]);}// RULE: A file of the 141 flat DDL — the oldest a shipped build wrote — moves in place to exactly a fresh file of this build: the tables the rises above it rebuild keep every row and rowid, the search index still finds a note through its carried rowid, and the one table a rise drops goes with its rows.#[test]fn a_141_file_moves_in_place_to_this_builds_schema() {    let db = v141_file();    seed(&db);    let report = move_to_current(&db).unwrap();    assert_eq!((report.from, report.to), (LEDGER_BASE, SCHEMA_VERSION));    assert_eq!(report.dropped, ["cotton_widgets"]);    assert!(report.kept.is_empty(), "{report}");    // 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() {}    let fresh = Driver::open_in_memory().unwrap();    apply_schema(&fresh).unwrap();    assert_eq!(schema_objects(&fresh).unwrap(), schema_objects(&db).unwrap());    let one = |sql: &str| db.get(sql, &[]).unwrap().unwrap();    for (table, id, rowid) in [("cotton_money_accounts", "acct", 7), ("cotton_notes", "note", 42), ("cotton_todos", "todo", 43), ("cotton_events", "event", 44)] {        assert_eq!(one(&format!("SELECT rowid AS r FROM {table} WHERE id = '{id}'")).int("r"), Some(rowid), "{table}");    }    let found = one("SELECT n.id AS id FROM fts_notes f JOIN cotton_notes n ON n.rowid = f.rowid WHERE fts_notes MATCH 'findable'");    assert_eq!(found.text("id"), Some("note"));    assert_eq!(        one("PRAGMA user_version").int("user_version"),        Some(i64::from(SCHEMA_VERSION))    );}// RULE: The shape move refuses a stamp the shape ledger cannot map up to this build — below its base, 141, or above this build — with its one sentence, before it writes anything: no rule carries a file from before the oldest one a shipped build wrote.#[test]fn a_stamp_the_move_does_not_know_is_refused() {    for stamp in [LEDGER_BASE - 1, SCHEMA_VERSION + 1] {        let db = v141_file();        db.exec(&format!("PRAGMA user_version = {stamp}")).unwrap();        assert!(!MOVES_FROM.contains(&stamp));        let before = schema_objects(&db).unwrap();        let refused = move_to_current(&db).unwrap_err().to_string();        assert!(            refused.contains(&format!(                "this file is stamped {stamp}; this build moves files from"            )),            "{refused}"        );        assert_eq!(schema_objects(&db).unwrap(), before);        assert_eq!(left(&db).unwrap(), None, "and has no move to run");    }}// RULE: Every stamp from the oldest shipped file's, 141, up to this build is admitted without a hand-kept list, and none below it.#[test]fn every_stamp_the_ledger_maps_up_is_admitted() {    assert_eq!(LEDGER_BASE, 141);    assert_eq!(MOVES_FROM, LEDGER_BASE..SCHEMA_VERSION);    assert!(!MOVES_FROM.contains(&140));    for stamp in [141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151] {        assert!(MOVES_FROM.contains(&stamp), "{stamp}");    }}// RULE: Every frozen shape from the floor up crosses to this build by the plan alone, before a statement runs: no lost column, no unfillable one and no undeclared loss refuses it, because a file at any of those stamps may be on a device.#[test]fn every_frozen_shape_from_the_floor_is_planned() {    let fresh = Driver::open_in_memory().unwrap();    apply_schema(&fresh).unwrap();    let target = schema_objects(&fresh).unwrap();    for (stamp, shape) in [        (141, include_str!("fixtures/schema-v141.json")),        (142, include_str!("fixtures/schema-v142.json")),        (143, include_str!("fixtures/schema-v143.json")),        (144, include_str!("fixtures/schema-v144.json")),        (145, include_str!("fixtures/schema-v145.json")),        (146, include_str!("fixtures/schema-v146.json")),        (147, include_str!("fixtures/schema-v147.json")),        (148, include_str!("fixtures/schema-v148.json")),        (149, include_str!("fixtures/schema-v149.json")),        (150, include_str!("fixtures/schema-v150.json")),        (151, include_str!("fixtures/schema-v151.json")),        (152, include_str!("fixtures/schema-v152.json")),        (153, include_str!("fixtures/schema-v153.json")),        (154, include_str!("fixtures/schema-v154.json")),        (155, include_str!("fixtures/schema-v155.json")),        (156, include_str!("fixtures/schema-v156.json")),    ] {        let had: Vec<SchemaObject> = serde_json::from_str(shape).unwrap();        crossing(&had, &target).unwrap_or_else(|e| panic!("v{stamp}: {e}"));        let db = frozen_file(stamp, shape);        let report = move_to_current(&db).unwrap_or_else(|e| panic!("v{stamp}: {e}"));        assert_eq!(report.from, stamp);        while cotton_store::index_later::step(&db).unwrap().is_some() {}        assert_eq!(schema_objects(&db).unwrap(), target, "v{stamp}");    }}/// RULE: An in-place move of a device copy keeps every sync cursor — each author's first lane and its `@late:` mail lane, value for value — and writes none, so the next pass owes only what arrived since; a move that lost or lowered a cursor would have every device re-pull its history (13 Oct 2026: a phone's move was suspected of exactly that; the cursors had held).#[test]fn an_in_place_move_keeps_every_sync_cursor() {    let db = v141_file();    // A copy mid-history: a few thousand authors' positions, both lanes.    db.exec(        "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 3000) \         INSERT INTO _cursors (author_device_id, hlc_seen, updated_at) \         SELECT CASE WHEN i % 2 = 0 THEN '@late:device:synthetic' || (i / 2) \         ELSE 'device:synthetic' || (i / 2) END, printf('%013d:0000:device:synthetic%d', 1700000000000 + i * 997, i / 2), \         '2026-10-12T00:00:00.000Z' FROM n",    )    .unwrap();    let cursors = |db: &Driver| {        db.all(            "SELECT author_device_id, hlc_seen, updated_at FROM _cursors ORDER BY 1",            &[],        )        .unwrap()    };    let before = cursors(&db);    assert_eq!(before.len(), 3000);    move_to_current(&db).unwrap();    assert_eq!(        cursors(&db),        before,        "every cursor, both lanes, value for value"    );    let version = db.get("PRAGMA user_version", &[]).unwrap().unwrap();    assert_eq!(version.int("user_version"), Some(i64::from(SCHEMA_VERSION)));}/// RULE: Place companions are nullable additions: the real mover uses native ADD COLUMN and preserves all existing person/location/event values, rowids and receipt stamps; no world rows are invented.#[test]fn place_companions_preserve_kept_rows() {    let fresh = Driver::open_in_memory().unwrap();    apply_schema(&fresh).unwrap();    let target = schema_objects(&fresh).unwrap();    // Synthetic prior shape: this build's unrelated objects, without the place companions.    // This isolates our crossing; the coordinator proves the batched rise on device copies.    let additions: &[(&str, &[&str])] = &[        ("cotton_people", &["city_place", "country"]),        (            "cotton_locations",            &["place", "place_id", "country", "timezone", "near"],        ),        ("cotton_events", &["event_place", "country", "timezone"]),    ];    let mut prior = target.clone();    for (table, columns) in additions {        let object = prior            .iter_mut()            .find(|o| o.kind == "table" && o.name == *table)            .unwrap();        for column in *columns {            let declaration = format!(", {column} TEXT");            assert!(                object.sql.contains(&declaration),                "{table}.{column} remains a nullable text fact"            );            object.sql = object.sql.replace(&declaration, "");        }    }    let plan = crossing(&prior, &target).unwrap();    assert!(plan.rebuild.is_empty(), "{plan:?}");    assert!(plan.absent.is_empty(), "{plan:?}");    assert!(plan.not_additive().is_empty(), "{plan:?}");    assert!(        plan.create_tables.is_empty(),        "world facts never create personal tables"    );    for (table, columns) in additions {        for column in *columns {            assert!(                plan.add_columns                    .iter()                    .any(|(t, sql)| t == table && sql == &format!("{column} TEXT")),                "{plan:?}"            );        }    }    let db = frozen_file(SCHEMA_VERSION - 1, &serde_json::to_string(&prior).unwrap());    db.exec("PRAGMA foreign_keys = OFF; PRAGMA ignore_check_constraints = ON")        .unwrap();    insert(        &db,        "cotton_people",        71,        &[            ("id", text("invented-person")),            ("city", text("Unlisted village")),            ("timezone", text("Europe/London")),            ("_hlc", text("kept-person-stamp")),        ],    );    insert(        &db,        "cotton_locations",        72,        &[            ("id", text("invented-location")),            ("name", text("Invented courtyard")),            ("_hlc", text("kept-location-stamp")),        ],    );    insert(        &db,        "cotton_events",        73,        &[            ("id", text("invented-event")),            ("location", text("Unlisted hall")),            ("_hlc", text("kept-event-stamp")),        ],    );    let kept: Vec<_> = additions        .iter()        .map(|(table, _)| {            let columns = db.all(&format!("PRAGMA table_info({table})"), &[]).unwrap();            let names = columns                .iter()                .map(|c| format!("\"{}\"", c.text("name").unwrap()))                .collect::<Vec<_>>()                .join(",");            let query = format!("SELECT rowid,{names} FROM {table}");            let row = db.get(&query, &[]).unwrap().unwrap().columns().to_vec();            (query, row)        })        .collect();    let _report = move_to_current(&db).unwrap();    for (query, before) in kept {        assert_eq!(db.get(&query, &[]).unwrap().unwrap().columns(), before);    }    for (table, columns) in additions {        for column in *columns {            assert_eq!(                db.get(                    &format!("SELECT count(*) AS n FROM {table} WHERE {column} IS NOT NULL"),                    &[]                )                .unwrap()                .unwrap()                .int("n"),                Some(0)            );        }    }}/// A 141 file with a row in Money, notes, todos, events and widgets, written/// to a fresh path of its own.fn seeded_v141_at(name: &str) -> std::path::PathBuf {    let db = v141_file();    seed(&db);    let path = std::env::temp_dir().join(format!("shape-move-{name}-{}.db", std::process::id()));    let _ = std::fs::remove_file(&path);    db.exec(&format!("VACUUM INTO '{}'", path.display())).unwrap();    path}/// The file at `path` opened as a new process would: nothing of an earlier/// open carried over.fn reopened(path: &std::path::Path) -> Driver {    let db = Driver::open(path).unwrap();    // The seeded rows break CHECKs on purpose (as above).    db.exec("PRAGMA ignore_check_constraints = ON").unwrap();    db}fn stamp(db: &Driver) -> i64 {    db.get("PRAGMA user_version", &[]).unwrap().unwrap().int("user_version").unwrap()}fn every_count(db: &Driver) -> Vec<(String, i64)> {    schema_objects(db).unwrap().into_iter()        .filter(|o| o.kind == "table" && !o.is_fts5_virtual() && !o.name.starts_with("sqlite_"))        .map(|o| {            let n = db.get(&format!("SELECT count(*) AS n FROM \"{}\"", o.name), &[]).unwrap().unwrap().int("n").unwrap();            (o.name, n)        })        .collect()}/// RULE: A STAMP N SAYS NO TABLE IS BELOW N (architect's ruling, 18 Oct 2026)./// A move run one step at a time — each step its own transaction, the file/// closed and opened again between steps as a phone killed mid-move is —/// keeps the file stamped where it began until the LAST step, reopens to/// exactly the steps it has left, finishes them, and ends in the very file the/// one-transaction move makes: the same objects in the same bytes, the same/// rows, the search index whole.#[test]fn a_move_cut_off_between_tables_finishes_them_on_the_next_open_and_only_then_stamps() {    let whole = seeded_v141_at("whole");    let stepped = seeded_v141_at("stepped");    move_to_current(&reopened(&whole)).unwrap();    let first = left(&reopened(&stepped)).unwrap().expect("a 141 file has a move to run");    assert_eq!((first.from, first.begun), (141, false));    assert!(first.holds("cotton_notes"), "before the first step every table is in its old shape");    let mut seen = vec![];    loop {        let db = reopened(&stepped);        let before = left(&db).unwrap();        let Some(step) = move_step(&db).unwrap() else { break };        seen.push(step.clone());        let after = left(&db).unwrap();        if step.finished {            assert_eq!(stamp(&db), i64::from(SCHEMA_VERSION), "the last step stamps");            assert_eq!(after, None);            break;        }        assert_eq!(stamp(&db), 141, "a step before the last leaves the stamp where the move began");        let after = after.expect("a move under way is left");        assert!(after.begun && after.done == step.done && after.total == step.total);        for table in &step.tables {            assert!(!after.holds(table), "{table} was moved by its step and no longer waits");        }        if let Some(before) = before.filter(|b| b.begun) {            assert_eq!(before.tables.len(), after.tables.len() + step.tables.len(), "one table per later step");        }        // Killed here: the handle goes, nothing in memory survives.        drop(db);    }    assert!(seen.len() > 2, "141 → this build is more than a first and a last step");    assert_eq!(seen.iter().map(|s| s.done).collect::<Vec<_>>(), (1..=seen[0].total).collect::<Vec<_>>());    let (whole, stepped) = (reopened(&whole), reopened(&stepped));    assert_eq!(schema_objects(&stepped).unwrap(), schema_objects(&whole).unwrap());    assert_eq!(every_count(&stepped), every_count(&whole));    assert!(stepped.get("SELECT 1 AS n FROM sqlite_master WHERE name = ?", &[text(MOVE_TABLE)]).unwrap().is_none());    let one = |sql: &str| stepped.get(sql, &[]).unwrap().unwrap();    assert_eq!(one("SELECT rowid AS r FROM cotton_money_accounts WHERE id = 'acct'").int("r"), Some(7));    let found = one("SELECT n.id AS id FROM fts_notes f JOIN cotton_notes n ON n.rowid = f.rowid WHERE fts_notes MATCH 'findable'");    assert_eq!(found.text("id"), Some("note"));    assert_eq!(move_step(&stepped).unwrap(), None, "a moved file has nothing left to move");}/// RULE: The one-transaction move FINISHES a file a step-by-step move left/// part way (a Mac opening a copy a phone was moving), never refuses it for/// the stamp it still carries.#[test]fn the_whole_move_finishes_a_file_left_part_way() {    let path = seeded_v141_at("partway");    let db = reopened(&path);    move_step(&db).unwrap().unwrap();    move_step(&db).unwrap().unwrap();    assert_eq!(stamp(&db), 141);    move_to_current(&db).unwrap();    assert_eq!(stamp(&db), i64::from(SCHEMA_VERSION));    assert_eq!(left(&db).unwrap(), None);}// RULE (MEDIA DRAIN 1, schema 157): the upload queue's four new words are APPENDED to a 156 copy's _media by ADD COLUMN, as SQLite writes them: no row of the queue is copied and nothing is rebuilt.#[test]fn the_upload_queue_gains_its_words_in_place() {    let fresh = Driver::open_in_memory().unwrap();    apply_schema(&fresh).unwrap();    let had: Vec<SchemaObject> = serde_json::from_str(include_str!("fixtures/schema-v156.json")).unwrap();    let plan = crossing(&had, &schema_objects(&fresh).unwrap()).unwrap();    assert!(plan.rebuild.is_empty(), "{:?}", plan.rebuild);    let media: Vec<&str> = plan.add_columns.iter().filter(|(table, _)| table == "_media").map(|(_, column)| column.as_str()).collect();    assert_eq!(media, ["last_code TEXT", "network TEXT NOT NULL DEFAULT 'any'", "asked_by TEXT", "source TEXT"]);}