//! GUARD 4 of tools as packages (architect's brief, 12 Oct 2026): N−1 ↔ N//! interop on a synthetic database, before any package shape step touches a//! real file.//!//! The Mac holds a tool a person brought at revision N; a device holds it at//! N−1. The Mac moves the tool to N — a new column — and writes rows that use//! it, changes one, retracts one. The device takes those receipts in the worst//! order the exchange can hand them: every row first, the definition last. It//! must park what it cannot hold yet as `newer-shape` and nothing else, refuse//! nothing, take the shape when the definition arrives, fold what waited, and//! end holding exactly the Mac's rows and receipts — with no fresh copy.//!//! Only the store's public API is used: `mint` writes, `arrive` folds.use cotton_store::actor::{Actor, JobName};use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE};use cotton_store::fold::{arrive, Arrival, FoldResult};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource};use cotton_store::protocol::types::CottonOp;use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::Driver;use serde_json::{json, Map, Value};constT0: i64 = 1_760_300_000_000;const TOOL: &str = "cotton_lesson";structIds(u32, &'static str);implIdSourceforIds {fn next_op_id(&mutself, _now_ms: i64) -> cotton_store::Result<String> {self.0 += 1;Ok(format!("{}-{:05}", self.1, self.0)) }}structDev { db: Driver, ids: Ids, fact: CottonOp,}/// A file whose `_parked` can hold `newer-shape` (rise 136's CHECK): the/// class the guard is about. A file that already has it is left as it is.fn parks_newer_shape(db: &Driver) {if cotton_store::rejected::keeps_newer_shape(db).expect("reads") {return; }let sql = cotton_store::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(cotton_store::schema::ddl::PARKED_ROW_INDEX).expect("indexes");}fn device(tag: &'static str) -> Dev {let db = file_at_version(SCHEMA_VERSION); seed_meta( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: format!("device:{tag}"), last_server_seq: 0, last_hlc: None, }, SCHEMA_VERSION, ) .expect("seeds"); seed_workspace_row(&db); parks_newer_shape(&db);letmut ids = Ids(0, tag);let author = first_author(&db, &format!("key-{tag}"), Some(tag), AuthorReason::First, &Clock::wall(T0 - 10), &mut ids, Held::Served) .expect("the author");Dev { db, ids, fact: author.fact }}implDev {fn act(&mutself, at_ms: i64, changes: Vec<Change>) -> Vec<CottonOp> {let act = Act { actor: Actor::device_job(JobName::named("test").expect("a job name")), verb: "test".to_string(), history: History::None, changes, }; mint(&self.db, &act, &Clock::wall(at_ms), &mutself.ids, Held::Served).expect("mints").ops }fn take(&self, ops: &[CottonOp]) -> FoldResult { arrive(&self.db, ops, Arrival::Pulled).expect("folds") }/// Every row of the tool's table, every column, in id order: the row/// hash a comparison reads, as text.fn rows(&self) -> Vec<String> {self.db .all(&format!("SELECT * FROM {TOOL} ORDER BY id"), &[]) .expect("reads") .iter() .map(|row| format!("{row:?}")) .collect() }/// The tool's receipts and tombstones, by op id.fn receipts(&self) -> Vec<String> {self.db .all("SELECT op_id FROM _writes WHERE tbl = ?1 UNION ALL SELECT 'tomb:' || op_id FROM _tombstones WHERE tbl = ?1 ORDER BY 1", &[rusqlite::types::Value::Text(TOOL.into())], ) .expect("reads") .iter() .filter_map(|row| row.text("op_id").map(str::to_owned)) .collect() }fn parks(&self) -> Vec<(String, String)> {self.db .all("SELECT class, reason FROM _parked ORDER BY op_id", &[]) .expect("reads") .iter() .map(|row| (row.text("class").unwrap_or_default().to_owned(), row.text("reason").unwrap_or_default().to_owned())) .collect() }}fn obj(value: Value) -> Map<String, Value> { value.as_object().expect("an object").clone()}/// The tool a person brought, at a revision: `extra` columns follow `name`.fn lesson(extra: Value) -> Value {letmut 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 definition(change: fn(&str, &str, Map<String, Value>) -> Change, revision: Value) -> Change { change("cotton_table_definitions","lesson", obj(json!({"id": "lesson", "workspace_id": WORKSPACE, "definition": revision,"builtin": false, "instructions_edited": false, "created_at": NOW, "updated_at": NOW, })), )}fn row(id: &str, fields: Value) -> Change {letmut patch = obj(json!({"id": id, "workspace_id": WORKSPACE, "created_at": NOW, "updated_at": NOW})); patch.extend(obj(fields));Change::create(TOOL, id, patch)}fn quiet(result: &FoldResult, what: &str) { assert!(result.rejected.is_empty(), "{what}: refused {:?}", result.rejected); assert!(result.waiting.is_empty(), "{what}: waiting {:?}", result.waiting);}/// RULE: A device a package revision behind takes the newer definition and rows in any order — parking only newer-shape, refusing nothing — then steps, folds what waited and ends row- and receipt-equal to the Mac, no fresh copy (tools as packages GUARD 4).#[test]fn a_device_a_revision_behind_takes_the_newer_package_and_ends_equal_to_the_mac() {letmut mac = device("mac");let phone = device("phone"); quiet(&phone.take(std::slice::from_ref(&mac.fact)), "the Mac's author"); quiet(&mac.take(std::slice::from_ref(&phone.fact)), "the phone's author");// Revision N−1, everywhere: the tool and two rows.letmut first = mac.act(T0 + 1_000, vec![definition(Change::create, lesson(json!([])))]); first.extend(mac.act(T0 + 1_100, vec![row("one", json!({"name": "Scales"})), row("two", json!({"name": "Arpeggios"}))])); quiet(&phone.take(&first), "revision N−1"); assert_eq!(phone.rows(), mac.rows(), "level at N−1");// Revision N on the Mac: a new column, used by a change and a create; a// retract beside them that needs no new shape.let second = mac.act(T0 + 2_000, vec![definition(Change::update, lesson(json!([{"key": "fee", "type": "amount", "default": 0}])))]);letmut rows = mac.act(T0 + 2_100, vec![Change::update(TOOL, "one", obj(json!({"fee": 1500, "updated_at": NOW})))]); rows.extend(mac.act(T0 + 2_200, vec![row("three", json!({"name": "Sight reading", "fee": 2500}))])); rows.extend(mac.act(T0 + 2_300, vec![Change::retract(TOOL, "two")])); assert!(mac.parks().is_empty(), "the Mac took its own revision: {:?}", mac.parks());// The device, rows first: what it cannot hold waits, newer-shape only. quiet(&phone.take(&rows), "the rows before their shape");let parks = phone.parks(); assert_eq!(parks.len(), 2, "the change and the create wait: {parks:?}"); assert!(parks.iter().all(|(class, _)| class == "newer-shape"), "{parks:?}"); assert!(cotton_store::rejected::board(&phone.db, NOW).expect("board").is_empty(), "nothing on the owner's board");// The definition lands: the shape steps, what waited folds.let landed = phone.take(&second); quiet(&landed, "the definition"); assert!(landed.board.is_empty(), "the step was taken: {:?}", landed.board); assert!(phone.parks().is_empty(), "nothing still waits: {:?}", phone.parks()); assert_eq!(phone.rows(), mac.rows(), "row-equal to the Mac"); assert_eq!(phone.receipts(), mac.receipts(), "receipt-equal to the Mac");// And the other way: a row the device writes at N reaches the Mac.letmut phone = phone;let back = phone.act(T0 + 3_000, vec![row("four", json!({"name": "Duets", "fee": 900}))]); quiet(&mac.take(&back), "the device's row at N"); assert_eq!(phone.rows(), mac.rows(), "level both ways");}/// RULE: The exchange hands over a package table's receipts like a compiled table's, because a tool's rows that never leave the Mac are rows every other device silently lacks.#[test]fn the_exchange_hands_over_a_package_tables_rows() {letmut mac = device("mac"); mac.act(T0 + 1_000, vec![definition(Change::create, lesson(json!([])))]); mac.act(T0 + 1_100, vec![row("one", json!({"name": "Scales"})), row("two", json!({"name": "Arpeggios"}))]); mac.act(T0 + 1_200, vec![Change::retract(TOOL, "two")]);let answered = cotton_store::exchange::answer(&mac.db, &std::collections::BTreeMap::new(), 1_000).expect("answers");let sent: Vec<_> = answered.ops.iter().filter(|op| op.table == TOOL).map(|op| op.kind.clone()).collect(); assert_eq!(sent.len(), 2, "the live row's create and the other's retract travel: {sent:?}");}/// RULE: Added own_<key> columns travel with definitions, park until the step adds them, and survive shape moves, because reordering sync must never drop a value.#[test]fn a_column_a_person_adds_to_a_shipped_table_is_a_real_column_everywhere() {let (_, tables) = cotton_store::schema::package_tables::builtin_shapes() .expect("the shipped shapes") .into_iter() .find(|(id, _)| id == "todo") .expect("todos ship");let store = tables[0].name.clone();letmut mac = device("mac");let phone = device("phone"); quiet(&phone.take(std::slice::from_ref(&mac.fact)), "the Mac's author");// The person adds "Met at" to Todos on the Mac: the shipped definition's// row in this database names it.let todo_row = |columns: Value| { obj(json!({"id": "todo", "workspace_id": WORKSPACE, "builtin": true, "instructions_edited": false,"definition": {"id": "todo", "builtin": true, "engine": "todos", "columns": columns},"created_at": NOW, "updated_at": NOW, })) };let defined = mac.act(T0 + 1_000, vec![Change::create("cotton_table_definitions", "todo", todo_row(json!([{"key": "own_met_at", "type": "text"}])))]);let has = |db: &Driver| db.all(&format!("SELECT name FROM pragma_table_info('{store}') WHERE name = 'own_met_at'"), &[]).expect("reads").len(); assert_eq!(has(&mac.db), 1, "the step made the column on the Mac");// A todo with a value under it: every NOT NULL column the build ships.letmut fields = obj(json!({"id": "t1", "workspace_id": WORKSPACE, "created_at": NOW, "updated_at": NOW, "own_met_at": "the station"}));for column in tables[0].columns.iter().filter(|c| !c.nullable && c.default.is_none() && !c.primary_key && !c.name.starts_with('_')) { fields.entry(column.name.clone()).or_insert_with(|| json!("synthetic")); }let written = mac.act(T0 + 2_000, vec![Change::create(&store, "t1", fields)]);// The phone takes the todo first: it waits for the column, newer-shape. quiet(&phone.take(&written), "the todo before its column"); assert_eq!(phone.parks().iter().filter(|(class, _)| class == "newer-shape").count(), 1, "{:?}", phone.parks()); quiet(&phone.take(&defined), "the definition"); assert!(phone.parks().is_empty(), "{:?}", phone.parks());let value = |db: &Driver| db.get(&format!("SELECT own_met_at FROM {store} WHERE id = 't1'"), &[]).expect("reads").and_then(|row| row.text("own_met_at").map(str::to_owned)); assert_eq!(value(&phone.db), Some("the station".to_owned()));// The start-up move sees the file as this build's shape: nothing rebuilt.let fresh = file_at_version(SCHEMA_VERSION);let crossing = cotton_store::shape_move::crossing( &cotton_store::create::schema_objects(&phone.db).expect("objects"), &cotton_store::create::schema_objects(&fresh).expect("objects"), ) .expect("a crossing");// (`_parked` differs here only by this test's 136 CHECK.) assert!(!crossing.rebuild.contains(&store) && crossing.add_columns.is_empty(), "rebuild {:?} add {:?}", crossing.rebuild, crossing.add_columns);}/// RULE: A record of an imported tool's table opens on a phone copy that lacks it — the serving Mac's keep::open answers its row's receipts and the phone folds them — because keep has no table list and a tool's record must be reachable like a built-in's (architect, 13 Oct 2026).#[test]fn an_imported_tools_record_opens_on_a_phone_copy() {letmut mac = device("mac");let phone = device("phone"); quiet(&phone.take(std::slice::from_ref(&mac.fact)), "the Mac's author");let defined = mac.act(T0 + 1_000, vec![definition(Change::create, lesson(json!([])))]); mac.act(T0 + 1_100, vec![row("one", json!({"name": "Scales"}))]);// The phone holds the tool, not the record. quiet(&phone.take(&defined), "the definition"); assert!(phone.rows().is_empty());let keep = cotton_store::keep::Keep::of_device(&mac.db, "device:phone").expect("the phone's rules");let opened = cotton_store::keep::open(&mac.db, &keep, TOOL, "one", 0, T0 + 2_000).expect("a made table's record opens"); assert_eq!(opened.rows, vec![(TOOL.to_owned(), "one".to_owned())]); assert!(!opened.ops.is_empty(), "with its receipts");let folded = cotton_store::keep::fold_opened(&phone.db, &opened.ops, &opened.rows, T0 + 2_000).expect("folds"); quiet(&folded, "the opened record"); assert_eq!(phone.rows(), mac.rows(), "the phone holds the record the Mac holds"); assert_eq!(phone.receipts(), mac.receipts(), "and its receipts");}