Cotton code
151 lines · 8.4 KB · RustRaw
//! Schema 143: an event is the database's, never its calendar's. The object//! keeps no calendars, yet 151 of the 154 events it serves name the one the//! owner's old Mac filed them in; the copy's `cotton_events.collection_id`//! foreign key made that an OWNING reference, so each one was stored as its//! receipts and held out of its table — dormant, never parked, never shown//! (27 Oct 2026). The rise drops the reference by rebuilding `cotton_events`//! with every row and rowid, and the move's finish settles every event it//! held out.use std::collections::BTreeMap;use cotton_store::{    create::{apply_schema, SchemaObject},    fold::fold_pulled,    mint::{served, Actor, JobName, ServedRow},    schema::{        move_intents::{rebuilt_above, released_above, INTENTS},        table_specs::OWNING_REFS,    },    shape_move::{crossing, move_to_current},    Driver,};use serde_json::{json, Value};fn actor() -> Actor {    Actor::job(JobName::named("object-sync").expect("a job name"))}fn event(title: &str, starts_at: &str, calendar: Option<&str>, trashed_at: Option<&str>) -> BTreeMap<String, Value> {    BTreeMap::from([        ("collection_id".to_string(), calendar.map_or(Value::Null, |id| json!(id))),        ("title".to_string(), json!(title)),        ("starts_at".to_string(), json!(starts_at)),        ("ends_at".to_string(), json!(starts_at)),        ("all_day".to_string(), json!(false)),        ("on_google".to_string(), json!(true)),        ("sync_state".to_string(), json!("synced")),        ("organizer_is_self".to_string(), json!(true)),        ("trashed_at".to_string(), trashed_at.map_or(Value::Null, |at| json!(at))),        ("created_at".to_string(), json!("2026-10-20T09:00:00.000Z")),        ("updated_at".to_string(), json!("2026-10-20T09:00:00.000Z")),    ])}/// A file of this build whose `cotton_events` is 142's, stamped 142, holding/// the object's events as a 142 copy held them: the receipts of each, and in/// the table only the ones that named no calendar.fn at_142_with_served_events() -> (Driver, Vec<SchemaObject>) {    let had: Vec<SchemaObject> = serde_json::from_str(include_str!("fixtures/schema-v142.json")).unwrap();    let db = Driver::open_in_memory().unwrap();    apply_schema(&db).unwrap();    let ops = vec![        served("op-in-a-calendar".into(), "cotton_events", "e-calendar", "1792456264079:0185:object", &actor(),            ServedRow::Live(event("A synthetic meeting", "2026-10-30T09:00:00.000Z", Some("a-calendar-never-served"), None)), None).unwrap(),        served("op-binned".into(), "cotton_events", "e-binned", "1792456264080:0185:object", &actor(),            ServedRow::Live(event("A synthetic binned meeting", "2026-10-21T09:00:00.000Z", Some("a-calendar-never-served"), Some("2026-10-22T09:00:00.000Z"))), None).unwrap(),        served("op-no-calendar".into(), "cotton_events", "e-google", "1792456264081:0185:object", &actor(),            ServedRow::Live(event("A synthetic Google event", "2026-10-31T09:00:00.000Z", None, None)), None).unwrap(),        served("op-gone-create".into(), "cotton_events", "e-gone", "1792456264082:0185:object", &actor(),            ServedRow::Live(event("A synthetic deleted event", "2026-10-29T09:00:00.000Z", Some("a-calendar-never-served"), None)), None).unwrap(),        served("op-gone".into(), "cotton_events", "e-gone", "1792456264083:0185:object", &actor(), ServedRow::Retracted, None).unwrap(),    ];    let folded = fold_pulled(&db, &ops).unwrap();    assert!(folded.rejected.is_empty(), "{:?}", folded.rejected);    // The 142 table, with what that copy showed of these events: only the    // one that named no calendar. The receipts stay, as they did there.    let kept: Vec<Value> = db        .all("SELECT rowid AS rowid, * FROM cotton_events WHERE collection_id IS NULL", &[])        .unwrap()        .iter()        .map(|row| json!(row.int("rowid")))        .collect();    assert_eq!(kept.len(), 1);    // A 142 copy kept every receipt whole: none was implied before 151 (receipts::implied).    for row in db.all("SELECT DISTINCT row_id FROM _writes WHERE tbl = 'cotton_events'", &[]).unwrap() {        cotton_store::receipts::implied::materialize_row(&db, "cotton_events", row.text("row_id").unwrap()).unwrap();    }    db.exec("PRAGMA foreign_keys=OFF").unwrap();    db.exec("DELETE FROM cotton_events WHERE collection_id IS NOT NULL").unwrap();    db.exec("CREATE TEMP TABLE kept AS SELECT rowid AS r, * FROM cotton_events").unwrap();    let old = had.iter().find(|o| o.kind == "table" && o.name == "cotton_events").unwrap();    db.exec("DROP TABLE cotton_events").unwrap();    db.exec(&old.sql).unwrap();    for object in had.iter().filter(|o| o.tbl_name == "cotton_events" && o.kind != "table") {        let _ = db.exec(&object.sql);    }    let columns: Vec<String> = db        .all("SELECT name FROM pragma_table_info('cotton_events')", &[])        .unwrap()        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect();    db.exec(&format!(        "INSERT INTO cotton_events (rowid, {0}) SELECT r, {0} FROM kept",        columns.join(", ")    ))    .unwrap();    db.exec("DROP TABLE kept").unwrap();    // The put-back fired the insert trigger over an index that still held the    // row: rebuilt whole from its content, as a 142 copy's was.    db.exec("INSERT INTO fts_events(fts_events) VALUES('rebuild')").unwrap();    db.exec("PRAGMA foreign_keys=ON").unwrap();    db.exec("PRAGMA user_version=142").unwrap();    (db, had)}fn ids(db: &Driver, sql: &str) -> Vec<String> {    db.all(sql, &[]).unwrap().iter().filter_map(|row| row.text("id").map(str::to_string)).collect()}/// RULE: The 143 rise drops cotton_events' foreign key to a calendar by rebuilding the table in place — every row and rowid kept — and its finish settles every event the owning reference held out: an event naming a calendar this copy never holds is in its table, a binned one in its table binned, a retracted one out, and nothing is parked.#[test]fn every_event_the_calendar_held_out_comes_in_and_every_row_stays() {    let (db, had) = at_142_with_served_events();    assert_eq!(ids(&db, "SELECT id FROM cotton_events ORDER BY id"), ["e-google"]);    let before = db.all("SELECT rowid, * FROM cotton_events ORDER BY rowid", &[]).unwrap();    let plan = crossing(&had, &cotton_store::create::fresh_schema().unwrap()).unwrap();    let rebuilt: std::collections::BTreeSet<&str> = plan.rebuild.iter().map(String::as_str).collect();    assert_eq!(rebuilt_above(142), rebuilt, "REBUILDS says so");    assert_eq!(        rebuilt.difference(&rebuilt_above(143)).copied().collect::<Vec<_>>(),        ["cotton_events"],        "cotton_events, and beside it only a later rise's rebuilds"    );    move_to_current(&db).unwrap();    let kept = db.all("SELECT rowid, * FROM cotton_events WHERE id = 'e-google'", &[]).unwrap();    assert_eq!(kept, before, "the row the copy showed stays, with its rowid");    assert_eq!(ids(&db, "SELECT id FROM cotton_events ORDER BY id"), ["e-binned", "e-calendar", "e-google"]);    assert_eq!(ids(&db, "SELECT id FROM cotton_events WHERE trashed_at IS NOT NULL"), ["e-binned"]);    assert_eq!(        db.get("SELECT collection_id FROM cotton_events WHERE id = 'e-calendar'", &[]).unwrap().unwrap().text("collection_id"),        Some("a-calendar-never-served"),        "the event keeps the calendar it names, which nothing reads as its owner"    );    assert!(db.all("SELECT * FROM _parked", &[]).unwrap().is_empty());    assert!(db.all("SELECT * FROM _writes_owners WHERE tbl = 'cotton_events'", &[]).unwrap().is_empty());    assert!(db.all("PRAGMA foreign_key_check", &[]).unwrap().is_empty());    // Its search index carries the events that came in.    assert_eq!(db.get("SELECT count(*) AS n FROM fts_events WHERE fts_events MATCH 'synthetic'", &[]).unwrap().unwrap().int("n"), Some(3));}/// RULE: 143 is one rise and not additive: it rebuilds cotton_events, releases its owning reference to a calendar (which OWNING_REFS no longer names), and discards no stored value.#[test]fn the_143_rise_releases_the_calendar_and_discards_nothing() {    let rises: Vec<_> = INTENTS.iter().filter(|intent| intent.version == 143).collect();    assert_eq!(rises.len(), 1);    assert!(!rises[0].additive && rises[0].losses.is_empty());    assert_eq!(released_above(142).collect::<Vec<_>>(), [("cotton_events", "collection_id")]);    assert!(released_above(142).all(|(table, column)| !OWNING_REFS.iter().any(|(t, c, _)| *t == table && *c == column)));}