Cotton code
335 lines · 19.1 KB · RustRaw
//! A package's shape by data: the step is add-only, and a receipt for a//! shape this file does not hold yet waits for it instead of being refused.use super::*;use crate::mint::Change;use crate::protocol::types::CottonOp;use crate::test_support::{seeded_file, WORKSPACE as WS};use serde_json::json;const NOW: &str = "2026-10-13T10:00:00.000Z";const PEER: &str = "device:peer";/// A synthetic imported tool, at a revision: `extra` columns follow `name`.fn lesson(extra: serde_json::Value) -> serde_json::Value {    let mut columns = vec![json!({"key": "name", "type": "text", "required": true})];    columns.extend(extra.as_array().cloned().unwrap_or_default());    json!({        "id": "lesson", "name": "Lesson", "plural": "Lessons", "builtin": false,        "title": "name", "search": ["name"], "columns": columns,    })}fn tables_of(definition: &serde_json::Value) -> Vec<PackageTable> {    declared(definition).expect("derives").expect("not built in").into_iter().map(|t| t.table).collect()}fn count(db: &Driver, sql: &str) -> i64 {    db.get(sql, &[]).expect("reads").and_then(|row| row.int("n")).unwrap_or(-1)}fn columns_of(db: &Driver, table: &str) -> Vec<String> {    file_columns(db, table).expect("columns").into_iter().map(|c| c.name).collect()}/// RULE: A package step only grows the file — creates what is missing, adds a new column, keeps a column an older revision lacks, refuses a changed type, key, nullability or default and leaves the file as it was — so a kept value never meets a shape arriving by data.#[test]fn a_package_step_only_grows_the_file() {    let db = seeded_file("device:mine");    let first = tables_of(&lesson(json!([])));    let made = step(&db, &first).expect("steps");    assert!(made.created.contains(&"table cotton_lesson".to_owned()), "{made:?}");    assert!(made.created.iter().any(|o| o.starts_with("search index ")), "{made:?}");    db.exec("INSERT INTO cotton_lesson (id, name) VALUES ('one', 'Scales')").expect("a row");    assert!(!step(&db, &first).expect("steps again").changed(), "a second step is a no-op");    let second = tables_of(&lesson(json!([{"key": "fee", "type": "amount", "default": 0}, {"key": "notes", "type": "longtext"}])));    let grown = step(&db, &second).expect("grows");    assert_eq!(grown.added, vec!["cotton_lesson.fee".to_owned(), "cotton_lesson.notes".to_owned()]);    assert_eq!(count(&db, "SELECT count(*) AS n FROM cotton_lesson WHERE id = 'one' AND name = 'Scales' AND fee IS NULL"), 1);    // The older revision arriving after the newer one takes nothing away.    let late = step(&db, &first).expect("an older revision steps");    assert!(!late.changed());    assert_eq!(late.ahead, vec!["cotton_lesson.fee".to_owned(), "cotton_lesson.notes".to_owned()]);    assert!(columns_of(&db, "cotton_lesson").contains(&"fee".to_owned()));    // A narrowed column is refused, and nothing of the step stays.    let mut narrowed = second.clone();    narrowed[0].columns.iter_mut().find(|c| c.name == "notes").expect("notes").sql_type = "INTEGER".into();    narrowed[0].columns.push(PackageColumn {        name: "late".into(), sql_type: "TEXT".into(), default: None, nullable: true,        primary_key: false, declaration: None, position: None,    });    let refused = step(&db, &narrowed).expect_err("a changed type is refused");    assert!(refused.to_string().contains("not add-only"), "{refused}");    assert!(!columns_of(&db, "cotton_lesson").contains(&"late".to_owned()), "the step rolled back whole");}/// RULE: Between revisions of a package, a dropped table, a dropped or renamed column, a changed type or a column made required is refused at import and seed — add-only is all an older device can take by data; an unwanted column is marked retired.#[test]fn a_revision_that_drops_renames_or_narrows_is_refused() {    let base = tables_of(&lesson(json!([{"key": "fee", "type": "amount"}])));    check_add_only(&base, &tables_of(&lesson(json!([{"key": "fee", "type": "amount"}, {"key": "room", "type": "text"}]))))        .expect("adding is allowed");    let mut retiring = lesson(json!([]));    retiring["retired"] = json!([{"key": "fee", "type": "amount"}]);    check_add_only(&base, &tables_of(&retiring)).expect("retiring keeps the column in storage");    check_add_only(&base, &tables_of(&lesson(json!([{"key": "fee", "type": "amount", "default": 5}]))))        .expect("a default is the engine's and changes freely");    for (next, says) in [        (tables_of(&lesson(json!([]))), "drops or renames"),        (tables_of(&lesson(json!([{"key": "price", "type": "amount"}]))), "drops or renames"),        (tables_of(&lesson(json!([{"key": "fee", "type": "number"}]))), "type"),        (Vec::new(), "drops the table"),    ] {        let refused = check_add_only(&base, &next).expect_err("refused");        assert!(refused.to_string().contains(says), "{refused} should say {says}");    }    let mut narrower = base.clone();    narrower[0].columns.iter_mut().find(|c| c.name == "fee").expect("fee").nullable = false;    narrower[0].columns.iter_mut().find(|c| c.name == "fee").expect("fee").default = None;    assert!(check_add_only(&base, &narrower).expect_err("refused").to_string().contains("empty"));}// ── the fold: a receipt for a shape this file does not hold yet ────────────/// `_parked` as rise 136 builds it (the CHECK admits `newer-shape`).fn at_rise_136(db: &Driver) {    let sql = crate::schema::ddl::PARKED_TABLE        .replace("'unverified'))", "'unverified','newer-shape'))")        .replace("IF NOT EXISTS ", "");    db.exec("ALTER TABLE _parked RENAME TO _parked_before").expect("renames");    db.exec(&sql).expect("the 136 _parked");    db.exec("INSERT INTO _parked SELECT * FROM _parked_before").expect("copies");    db.exec("DROP TABLE _parked_before").expect("drops");    db.exec(crate::schema::ddl::PARKED_ROW_INDEX).expect("indexes");}fn obj(value: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {    value.as_object().cloned().expect("an object")}/// A receipt minted on `on` by the peer at `ms`.fn minted(on: &Driver, change: Change, ms: i64, op_id: &str) -> CottonOp {    crate::wire::op_of_change(on, &change, &format!("{ms:013}:0000:{PEER}"), PEER, &crate::fixtures::fixture_actor(), op_id.into())        .expect("a receipt")}fn definition_row(on: &Driver, definition: &serde_json::Value, ms: i64, op_id: &str) -> CottonOp {    minted(        on,        Change::create(            "cotton_table_definitions",            "lesson",            obj(json!({                "id": "lesson", "workspace_id": WS, "definition": definition,                "builtin": false, "instructions_edited": false, "created_at": NOW, "updated_at": NOW,            })),        ),        ms,        op_id,    )}/// The peer's file: it holds `definition` and its tables.fn peer_holding(definition: &serde_json::Value) -> Driver {    let peer = seeded_file(PEER);    let row = definition_row(&peer, definition, 1_000, "op-peer-definition");    let folded = crate::fold::fold_ops(&peer, &[row]).expect("folds");    assert!(folded.rejected.is_empty() && folded.parked.is_empty() && folded.waiting.is_empty(), "{:?} {:?}", folded.rejected, folded.parked);    let (_, refused) = step_file(&peer).expect("steps");    assert!(refused.is_empty(), "{refused:?}");    peer}/// RULE (copy-installer-store, 8 Nov 2026): a fold that writes definitions steps the tables whose storage it changed and no other — a definition whose looks alone changed steps none — because stepping every declared table on every definition fold made a fresh copy's install O(all tables) per tool; the launch path still steps the whole file.#[test]fn a_definition_fold_steps_only_the_storage_it_changed() {    let db = peer_holding(&lesson(json!([])));    // A second definition's row is here and its table is not: only a step of    // the whole file would make it.    let mut chore = lesson(json!([]));    chore["id"] = json!("chore");    db.run(        "INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) VALUES ('chore', ?, ?, 0, 0, ?, ?)",        &[SqlValue::Text(WS.into()), SqlValue::Text(chore.to_string()), SqlValue::Text(NOW.into()), SqlValue::Text(NOW.into())],    )    .expect("a definition row");    let _ = crate::spans::take();    // The lesson gains a column: its table steps, the chore's is not made.    let grown = lesson(json!([{"key": "fee", "type": "amount"}]));    let folded = crate::fold::fold_ops(&db, &[definition_row(&db, &grown, 2_000, "op-grown")]).expect("folds");    assert!(folded.rejected.is_empty(), "{:?}", folded.rejected);    assert!(columns_of(&db, "cotton_lesson").contains(&"fee".to_owned()), "the lesson stepped");    assert!(columns_of(&db, "cotton_chore").is_empty(), "the chore's table is not this fold's");    assert_eq!(crate::spans::take().iter().find(|(name, _, _)| *name == "package_shape::step").map(|s| s.2), Some(1));    // Its looks change and its storage does not: nothing steps.    let mut renamed = grown.clone();    renamed["plural"] = json!("Lessons, all of them");    let folded = crate::fold::fold_ops(&db, &[definition_row(&db, &renamed, 3_000, "op-renamed")]).expect("folds");    assert!(folded.applied.contains(&"op-renamed".to_owned()), "the new looks landed");    assert!(crate::spans::take().iter().all(|(name, _, _)| *name != "package_shape::step"), "no step for looks alone");    // The launch path steps the whole file: the chore's table is made.    assert!(step_file(&db).expect("steps").0.created.contains(&"table cotton_chore".to_owned()));}/// RULE (copy-installer-store, 8 Nov 2026): a package spec read for one table is the spec the whole file's read gives that table — a package table, a shipped table, one the file does not know — because a miss now reads only the table asked.#[test]fn one_tables_spec_is_the_whole_reads_spec_of_it() {    let db = peer_holding(&lesson(json!([{"key": "fee", "type": "amount"}])));    let whole = package_specs(&db).expect("the whole read");    let mut asked: Vec<String> = whole.keys().cloned().collect();    asked.extend(["cotton_todos", "cotton_people", "cotton_nothing_here"].map(str::to_owned));    assert!(asked.iter().any(|table| table == "cotton_lesson"), "{asked:?}");    for table in asked {        let one = package_spec_of(&db, &table).expect("one read");        assert_eq!(one.map(|spec| spec as *const TableSpec), whole.get(&table).map(|spec| *spec as *const TableSpec), "{table}");    }}/// RULE: A receipt for a package table or column this file lacks parks newer-shape — never refused, off the owner's board — and folds once the definition arrives and steps the shape, because definition and rows travel separately and a row must not be lost.#[test]fn a_row_waits_for_its_package_shape_and_folds_after_the_step() {    let v1 = lesson(json!([]));    let v2 = lesson(json!([{"key": "fee", "type": "amount", "default": 0}]));    let peer = peer_holding(&v2);    let row = minted(        &peer,        Change::create(            "cotton_lesson",            "one",            obj(json!({"id": "one", "workspace_id": WS, "name": "Scales", "fee": 1500, "created_at": NOW, "updated_at": NOW})),        ),        2_000,        "op-row",    );    // A file that holds nothing of the package: the row waits for its table.    let db = seeded_file("device:mine");    at_rise_136(&db);    let folded = crate::exchange::fold_incoming(&db, std::slice::from_ref(&row)).expect("folds");    assert!(folded.rejected.is_empty(), "not refused: {:?}", folded.rejected);    let parked = crate::rejected::select(&db, None).expect("parks");    assert_eq!((parked.len(), parked[0].class.as_str()), (1, "newer-shape"));    assert!(crate::rejected::board(&db, NOW).expect("board").is_empty(), "off the owner's board");    // The first revision arrives: the table, but not yet its `fee`.    let first = definition_row(&peer, &v1, 1_500, "op-v1");    // The fold steps the file itself when a definition lands.    crate::exchange::fold_incoming(&db, &[first]).expect("folds");    assert_eq!(count(&db, "SELECT count(*) AS n FROM cotton_lesson"), 0, "fee is not this file's yet");    let parked = crate::rejected::select(&db, None).expect("parks");    assert_eq!(parked[0].class, "newer-shape", "{}", parked[0].reason);    assert!(parked[0].reason.contains("cotton_lesson.fee"), "{}", parked[0].reason);    // The second revision: the step adds `fee` and the row folds.    let second = definition_row(&peer, &v2, 3_000, "op-v2");    crate::exchange::fold_incoming(&db, &[second]).expect("folds");    assert!(columns_of(&db, "cotton_lesson").contains(&"fee".to_owned()), "the fold stepped the shape");    let again = step_file(&db).expect("steps").0;    assert!(        again.created.iter().chain(&again.added).chain(&again.replaced).all(|made| !made.contains("cotton_lesson")),        "a second step of the lesson is a no-op: {again:?}"    );    assert_eq!(count(&db, "SELECT count(*) AS n FROM cotton_lesson WHERE id = 'one' AND fee = 1500 AND name = 'Scales'"), 1);    assert!(crate::rejected::select(&db, None).expect("parks").is_empty(), "the park ended");}/// RULE: A package table's receipts are minted and its erasures take its rows on the file that holds it, as any table's are, because a tool a person brought is the same kind as a built-in.#[test]fn a_package_table_is_written_and_read_like_any_table() {    let db = peer_holding(&lesson(json!([])));    let spec = spec_on(&db, "cotton_lesson").expect("reads").expect("a package table");    assert_eq!(spec.pk, "id");    assert!(spec.columns.iter().any(|(c, codec)| *c == "created_at" && *codec == Codec::Timestamp));    assert!(!spec.columns.iter().any(|(c, _)| c.starts_with('_')), "bookkeeping is not a field");    assert!(spec_on(&db, "cotton_nothing_here").expect("reads").is_none());    assert!(may_arrive("cotton_nothing_here") && !may_arrive("_parked") && !may_arrive("cotton_todos"));}/// RULE (26 Oct 2026): a column holding several values is kept as one JSON/// list, whatever its type, so a made table's list (a token's scopes, a/// client's redirect addresses) is written and read whole, never refused as/// "not a string".#[test]fn a_column_of_several_values_is_kept_as_a_json_list() {    let definition = lesson(json!([        {"key": "tags", "type": "text", "multiple": true},        {"key": "room", "type": "text"},    ]));    let held = declared(&definition).expect("derives").expect("not built in").remove(0);    assert_eq!(held.codecs.get("tags"), Some(&Codec::Json));    assert_eq!(held.codecs.get("room"), Some(&Codec::Text));}// ── a copy's columns for the object's definition ───────────────────────────const MONEY: &str = "cotton_money_transactions";fn statement_of(db: &Driver, table: &str) -> String {    db.get("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(table.into())])        .expect("reads")        .and_then(|row| row.text("sql").map(str::to_owned))        .expect("the table")}/// RULE (owner, 27 Oct 2026): a column the object's definition names on a shipped table that the build's table lacks is added to the copy's table in place — nullable, typed from the definition, once — so the fold writes it; one of another type, one of the build's own and a type this build does not know are refused by name, and nothing of a refused call stays.#[test]fn a_served_column_is_added_in_place_once_and_the_fold_writes_it() {    let db = seeded_file("device:mine");    let before = columns_of(&db, MONEY);    let balance = served_column("balance_after_minor", "amount", false).expect("an amount");    assert_eq!((balance.sql_type, balance.codec), ("INTEGER", Codec::MoneyMinor));    let state = served_column("balance_state", "choice", false).expect("a choice");    assert_eq!((state.sql_type, state.codec), ("TEXT", Codec::Text));    assert_eq!(served_column("tags", "text", true).expect("a list").codec, Codec::Json);    let unknown = served_column("mood", "colour", false).expect_err("a type this build does not know");    assert!(unknown.to_string().contains("mood") && unknown.to_string().contains("colour"), "{unknown}");    assert!(served_column("_hlc", "text", false).is_err() && served_column("Bad Key", "text", false).is_err());    let added = add_served(&db, MONEY, &[balance.clone(), state.clone()]).expect("adds");    assert_eq!(added, vec![format!("{MONEY}.balance_after_minor"), format!("{MONEY}.balance_state")]);    let after = columns_of(&db, MONEY);    assert_eq!(after.len(), before.len() + 2);    assert!(add_served(&db, MONEY, &[balance.clone(), state]).expect("again").is_empty(), "a second pass adds nothing");    // The fold knows the column from the file, as it knows a made table's.    let spec = spec_on(&db, MONEY).expect("reads").expect("a shipped table");    assert!(spec.columns.iter().any(|(c, _)| *c == "balance_after_minor"));    assert!(spec.columns.iter().any(|(c, _)| *c == "balance_state"));    assert_eq!(spec.pk, "id");    let retyped = ServedColumn { sql_type: "TEXT", codec: Codec::Text, ..balance };    let refused = add_served(&db, MONEY, &[served_column("note_line", "text", false).expect("text"), retyped]).expect_err("a column only adds");    assert!(refused.to_string().contains("balance_after_minor"), "{refused}");    assert!(!columns_of(&db, MONEY).contains(&"note_line".to_owned()), "the refused call rolled back whole");    let own = add_served(&db, MONEY, &[served_column("amount_minor", "amount", false).expect("an amount")]).expect_err("the build's own");    assert!(own.to_string().contains("amount_minor"), "{own}");    assert!(add_served(&db, "cotton_nothing_here", &[]).is_err());}/// RULE: a column a copy added for the object's definition is carried as a person's added column is — the file's statement less it is this build's statement, so a shape move neither rebuilds the table nor loses the column.#[test]fn a_served_column_is_carried_and_never_a_difference_from_the_build() {    let db = seeded_file("device:mine");    let built = statement_of(&db, MONEY);    db.exec(&format!("ALTER TABLE \"{MONEY}\" ADD COLUMN \"own_met_at\" TEXT")).expect("a person's column");    add_served(&db, MONEY, &[served_column("balance_before_minor", "amount", false).expect("an amount"), served_column("own_mark", "text", false).expect("text")]).expect("adds");    let (kept, added) = without_added(&statement_of(&db, MONEY));    assert_eq!(kept, built, "less its added columns, the statement is the build's");    let names: Vec<String> = added.iter().filter_map(|declared| added_name(declared)).collect();    assert_eq!(names.len(), 3, "{added:?}");    for name in ["own_met_at", "balance_before_minor", "own_mark"] {        assert!(names.iter().any(|n| n == name), "{name} in {names:?}");    }    let had = crate::create::schema_objects(&db).expect("the file's objects");    let plan = crate::shape_move::crossing(&had, &crate::create::fresh_schema().expect("the build's")).expect("plans");    assert!(!plan.rebuild.contains(&MONEY.to_owned()), "{:?}", plan.rebuild);    assert!(!plan.add_columns.iter().any(|(table, _)| table == MONEY), "{:?}", plan.add_columns);}