//! Two builds on either side of an additive rise exchange both ways, and the //! older one, once it moves, holds exactly what the newer one holds. //! //! The floor rule (`exchange::admission`) says a build serves any stamp from //! its floor to its own schema, because every rise between only added. This is //! that rule run end to end on a synthetic database: for every stamp `s` in //! `[floor(), SCHEMA_VERSION)` with a frozen shape, a file at `s` and a file at //! this build's schema share one history written at `s`, each writes once more //! at its own schema, and they exchange — the older as a phone with a newer //! Mac, and the newer as a phone with an older Mac. Within one binary a build's //! stamp is the receipt's (`Receipt::schema`), so the older side's writes are //! minted at `s` and carry only the columns `s` holds. use std::collections::{BTreeMap, BTreeSet}; use cotton_store::canonical; use cotton_store::create::{apply_schema, schema_objects, SchemaObject}; use cotton_store::cursors::read_cursors; use cotton_store::exchange::{ admission, answer_excluding, fold_answer, fold_incoming, handled, Admission, Handed, Handled, Handover, }; use cotton_store::fixtures::{dump, fixture_actor, owner_file_at}; use cotton_store::meta::{read_meta, seed_meta, Meta}; use cotton_store::mint::Change; use cotton_store::protocol::types::{CottonOp, ExchangeResponse}; use cotton_store::rejected::{keeps_newer_shape, refold_newer_shape}; use cotton_store::schema::ddl::SCHEMA_VERSION; use cotton_store::schema::move_intents::{floor, floor_of}; use cotton_store::shape_move::{is_local, move_to_current}; use cotton_store::Driver; use serde_json::{json, Map}; const NOW: &str = "2026-10-13T00:00:00.000Z"; fn fresh_shape() -> Vec { let fresh = Driver::open_in_memory().unwrap(); apply_schema(&fresh).unwrap(); schema_objects(&fresh).unwrap() } /// The frozen shape at `stamp`, if this tree keeps one. fn frozen(stamp: u32) -> Option> { let path = cotton_store::manifest_dir().join(format!("tests/fixtures/schema-v{stamp}.json")); std::fs::read(path).ok().map(|bytes| serde_json::from_slice(&bytes).unwrap()) } /// A file of exactly this shape, stamped: tables, search indexes, indexes, /// then triggers. fn build(shape: &[SchemaObject], stamp: u32) -> Driver { 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 = 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(); db } /// The older file's `_parked` as this build makes it, so the older build in /// this test parks a newer shape the way every build from rise 136 does. fn parks_like_this_build(db: &Driver) { // This binary folds through its device-local ownership projection; only // synced shapes and receipt stamps represent the old peer in this harness. db.exec(cotton_store::schema::ddl::WRITES_OWNERS_TABLE).unwrap(); db.exec(cotton_store::schema::ddl::WRITES_OWNERS_INDEX).unwrap(); db.exec("DROP TABLE _parked").unwrap(); db.exec(cotton_store::schema::ddl::PARKED_TABLE).unwrap(); db.exec(cotton_store::schema::ddl::PARKED_ROW_INDEX).unwrap(); } fn columns(db: &Driver) -> BTreeMap> { let mut out = BTreeMap::new(); for row in db .all("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'", &[]) .unwrap() { let table = row.text("name").unwrap().to_string(); let names = db .all(&format!("SELECT name FROM pragma_table_info('{table}')"), &[]) .unwrap() .iter() .map(|row| row.text("name").unwrap().to_string()) .collect(); out.insert(table, names); } out } /// `op` as a build at `stamp` would have minted it: its receipt says `stamp` /// and names only the columns a file at `stamp` holds. `None` for a table /// that file does not have. fn minted_at(op: &CottonOp, stamp: u32, held: &BTreeMap>) -> Option { let mut receipt = canonical::decode(op.receipt.as_bytes()).unwrap(); let names = held.get(&receipt.table)?; receipt.fields.retain(|name, _| names.contains(name)); receipt.schema = stamp; let bytes = canonical::encode(&receipt).unwrap(); Some(cotton_store::wire::from_bytes(op.op_id.clone(), &bytes).unwrap()) } /// Every receipt `source` holds, page by page, as its answer hands them over. fn every_receipt(source: &Driver) -> Vec { let mut cursors = BTreeMap::new(); let mut ops = Vec::new(); for _ in 0..10_000 { let answered = answer_excluding(source, &cursors, 2_000, &Handled::default()).unwrap(); ops.extend(answered.ops); cursors = answered.cursors; if !answered.has_more { return ops; } } panic!("the answer never ran out of pages"); } fn response(workspace_id: &str, answered: cotton_store::exchange::Answered, schema: u32, epoch: Option) -> ExchangeResponse { ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: workspace_id.to_string(), ops: answered.ops, cursors: answered.cursors, has_more: answered.has_more, schema_version: Some(schema), applied_rows: BTreeMap::new(), rejected: Vec::new(), seen: answered.seen, serving_epoch: epoch, server_time: None, restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, } } /// One exchange as the route runs it: the phone's write is admitted on the /// floor rule and folded by the Mac, then the phone pulls every page and folds /// it — the Mac never offers a fresh copy, so nothing but receipts moves. fn exchange(phone: &Driver, phone_stamp: u32, mac: &Driver, mac_stamp: u32, sent: &CottonOp, workspace_id: &str) { let keeps = keeps_newer_shape(mac).unwrap(); assert_eq!( admission(mac_stamp, phone_stamp, Some(floor_of(phone_stamp)), keeps), Admission::Serve, "a phone at {phone_stamp} is served by a Mac at {mac_stamp}" ); let folded = fold_incoming(mac, std::slice::from_ref(sent)).unwrap(); assert!(folded.rejected.is_empty(), "the Mac refused the phone's write: {:?}", folded.rejected); let already = handled(std::slice::from_ref(sent)); for _ in 0..10_000 { let answered = answer_excluding(mac, &read_cursors(phone).unwrap(), 500, &already).unwrap(); let epoch = cotton_store::serving::heard_epoch(mac, workspace_id).unwrap(); let page = response(workspace_id, answered, mac_stamp, epoch); fold_answer(phone, &Handed::nothing(workspace_id), &page, NOW, &mut Handover::shut()).unwrap(); if !page.has_more { return; } } panic!("the Mac's answer never ran out of pages"); } /// `(class, count)` of every park a file holds. fn parks(db: &Driver) -> BTreeMap { db.all("SELECT class, COUNT(*) AS n FROM _parked GROUP BY class", &[]) .unwrap() .iter() .map(|row| (row.text("class").unwrap().to_string(), row.int("n").unwrap())) .collect() } /// Every synced row of a file, column by column, as text. fn rows(db: &Driver) -> BTreeMap>> { let synced = cotton_store::fixtures::synced_tables(db); let held: BTreeMap> = columns(db) .into_iter() .filter(|(table, _)| synced.contains(table)) .map(|(table, names)| (table, names.into_iter().collect())) .collect(); dump(db, &held) } fn todo(id: &str, title: &str, workspace_id: &str) -> Change { let mut patch = Map::new(); for (key, value) in [ ("id", json!(id)), ("title", json!(title)), ("status", json!("open")), ("priority", json!(0)), ("workspace_id", json!(workspace_id)), ("created_at", json!(NOW)), ("updated_at", json!(NOW)), ] { patch.insert(key.to_string(), value); } Change::create("cotton_todos", id, patch) } /// One side of the pair: a file at `stamp`, holding the shared history. fn side(shape: &[SchemaObject], stamp: u32, meta: &Meta, device: &str, history: &[CottonOp]) -> Driver { let db = build(shape, stamp); parks_like_this_build(&db); seed_meta(&db, &Meta { device_id: device.to_string(), ..meta.clone() }, stamp).unwrap(); // The workspace row first, as a join brings it: the fold reads which kind // of database it is folding into once per batch. let (workspace, rest): (Vec, Vec) = history.iter().cloned().partition(|op| op.table == "cotton_workspaces"); for batch in [workspace, rest] { let folded = fold_incoming(&db, &batch).unwrap(); assert!(folded.rejected.is_empty(), "the history folds at {stamp}: {:?}", folded.rejected); } assert!(parks(&db).is_empty(), "the history parks nothing at {stamp}: {:?}", parks(&db)); db } /// RULE: Two builds on either side of an additive rise exchange both ways on a synthetic database — the older as a phone with a newer Mac and the newer as a phone with an older Mac — with nothing refused and nothing parked outside newer-shape; the older side's move rebuilds no synced table; and after it moves and refolds it is statement-equal to a fresh file of this build and row-equal to the other side, with no fresh copy fetched. This is the floor rule's whole promise (schema programme, 12 Oct 2026): a phone a cut behind its Mac, or ahead of it, keeps syncing and loses nothing. #[test] fn builds_across_an_additive_rise_exchange_both_ways_and_converge() { let scratch = owner_file_at(SCHEMA_VERSION); let meta = read_meta(&scratch).unwrap().expect("the synthetic owner file has an identity"); let author = meta.device_id.clone(); let fresh = fresh_shape(); let newer_shape_parks = keeps_newer_shape(&build(&fresh, SCHEMA_VERSION)).unwrap(); let stamps: Vec = (floor()..SCHEMA_VERSION).filter(|stamp| frozen(*stamp).is_some()).collect(); assert!(!stamps.is_empty() || floor() == SCHEMA_VERSION, "no frozen shape between the floor and this build"); for stamp in stamps { let shape = frozen(stamp).unwrap(); let held = columns(&build(&shape, stamp)); let history: Vec = every_receipt(&scratch).iter().filter_map(|op| minted_at(op, stamp, &held)).collect(); assert!(!history.is_empty()); let write = |id: &str, ms: i64, at: u32| -> CottonOp { let op = cotton_store::wire::op_of_change( &scratch, &todo(id, id, &meta.workspace_id), &format!("{ms:013}:0000:{author}"), &author, &fixture_actor(), format!("op-{id}"), ) .unwrap(); minted_at(&op, at, &held).unwrap() }; for older_is_phone in [true, false] { let older = side(&shape, stamp, &meta, if older_is_phone { "device:phone" } else { "server:mac" }, &history); let newer = side(&shape, stamp, &meta, if older_is_phone { "server:mac" } else { "device:phone" }, &history); let moved = move_to_current(&newer).unwrap(); assert!(moved.rebuilt.iter().all(|table| is_local(table)), "{stamp}: the newer side rebuilt {:?}", moved.rebuilt); // Each writes once more, at its own schema. let old_write = write(&format!("older-{stamp}-{older_is_phone}"), 4_000_000_000_000, stamp); let new_write = write(&format!("newer-{stamp}-{older_is_phone}"), 4_000_000_000_001, SCHEMA_VERSION); assert!(fold_incoming(&older, std::slice::from_ref(&old_write)).unwrap().rejected.is_empty()); assert!(fold_incoming(&newer, std::slice::from_ref(&new_write)).unwrap().rejected.is_empty()); if !newer_shape_parks { // Before rise 136's CHECK: only the older phone's write reaching // the newer Mac is this build's to promise. if older_is_phone { exchange(&older, stamp, &newer, SCHEMA_VERSION, &old_write, &meta.workspace_id); assert!(parks(&newer).is_empty(), "{stamp}: the Mac parked {:?}", parks(&newer)); } continue; } if older_is_phone { exchange(&older, stamp, &newer, SCHEMA_VERSION, &old_write, &meta.workspace_id); } else { exchange(&newer, SCHEMA_VERSION, &older, stamp, &new_write, &meta.workspace_id); } assert!(parks(&newer).is_empty(), "{stamp}: the newer side parked {:?}", parks(&newer)); let waiting = parks(&older); assert!( waiting.keys().all(|class| class == "newer-shape") && waiting.get("newer-shape").copied().unwrap_or(0) > 0, "{stamp}: the older side parks only the newer write, as newer-shape: {waiting:?}" ); // The older side updates: its move, then the refold. let moved = move_to_current(&older).unwrap(); assert!(moved.rebuilt.iter().all(|table| is_local(table)), "{stamp}: the older side rebuilt {:?}", moved.rebuilt); let refolded = refold_newer_shape(&older, NOW).unwrap(); assert!(refolded.still_rejected.is_empty(), "{stamp}: {:?}", refolded.still_rejected); assert!(parks(&older).is_empty(), "{stamp}: {:?}", parks(&older)); if !older_is_phone { // The newer phone's next exchange brings what the older Mac // wrote while it was behind (it already has its own write). exchange(&newer, SCHEMA_VERSION, &older, SCHEMA_VERSION, &new_write, &meta.workspace_id); } else { exchange(&older, SCHEMA_VERSION, &newer, SCHEMA_VERSION, &old_write, &meta.workspace_id); } // Package tables created by the received definitions also stay in the file; // the store shape/move guards hold the declared core statements. let (a, b) = (rows(&older), rows(&newer)); for table in a.keys().chain(b.keys()).collect::>() { assert_eq!(a.get(table), b.get(table), "{stamp}: {table} differs after the move"); } } } }