usesuper::*;use cotton_core::flavor::Flavor;use cotton_store::migrate::SCHEMA_VERSION;use cotton_store::Driver;const WORKSPACE: &str = "ws-dev-heal";/// A replica file stamped `version`, with a `-wal` beside it.fn stamped_file(layout: &Layout, version: u32) -> std::path::PathBuf {let path = layout.replica(WORKSPACE); std::fs::create_dir_all(path.parent().expect("a parent")).expect("the folder");let driver = Driver::open(&path).expect("a file"); driver.exec(&format!("PRAGMA user_version = {version}")).expect("the stamp"); driver.exec("CREATE TABLE kept (id INTEGER)").expect("a table"); drop(driver);letmut wal = path.as_os_str().to_owned(); wal.push("-wal"); std::fs::write(&wal, b"x").expect("a wal"); path}/// The local receipt stores, empty — in the old two-column shape a store/// counts before it reads. `_outbox` carries its `tbl` column because the/// pending count reads it: a device's own visits, samples and receipts queue/// there too and never count as the person's changes.fn with_receipt_stores(path: &std::path::Path) {Driver::open(path).expect("reopen").exec("CREATE TABLE _outbox (op_id TEXT PRIMARY KEY, tbl TEXT NOT NULL); CREATE TABLE _writes (op_id TEXT PRIMARY KEY, held INTEGER NOT NULL, tbl TEXT NOT NULL DEFAULT 'note'); CREATE TABLE _tombstones (op_id TEXT PRIMARY KEY, held INTEGER NOT NULL, tbl TEXT NOT NULL DEFAULT 'note'); CREATE TABLE _parked (op_id TEXT PRIMARY KEY, direction TEXT NOT NULL)").expect("local receipts");}/// RULE: a move that fails never renames, sets aside or deletes the copy, and is not run again by the open behind it: it stays where it was, its why is written down before anything else and told to the open's reporter, and the page at zero unsent names that why — never "kept until they are sent" (255, 12 Oct 2026: the move's reason was lost and the page said 0 changes were holding the copy).#[test]fn a_failed_move_leaves_the_copy_and_the_page_names_why() {let root = tempfile::tempdir().expect("a root");let layout = Layout::new(root.path().join("CottonDB"));let path = stamped_file(&layout, SCHEMA_VERSION - 1); with_receipt_stores(&path);letmut heard = Vec::new();let heal = heal_stale_replica(&layout, WORKSPACE, Some(Flavor::Real), Some(&mut |event| heard.push(event)));let why = "not a whole copy: it names no database".to_string(); assert_eq!(heal, Some(Heal::NotMoved { stamped: SCHEMA_VERSION - 1, why: why.clone() }));// The open's reporter hears the failure with the mover's own sentence, so// the boot page stops on it rather than waiting on a move that ended. assert_eq!( heard.last(),Some(&MigrationEvent::Failed { from: SCHEMA_VERSION - 1, to: SCHEMA_VERSION, message: why.clone() }) );// And the open that follows does not run the same move again.let stopped = Heal::stopped(&heal).expect("a failed move stops the open"); assert!(stopped.to_string().contains(&why), "{stopped}"); assert!(path.exists(), "the copy stays at its own name"); assert!(!crate::bootstrap::previous::path(&path).exists(), "nothing is set aside"); assert_eq!(crate::bootstrap::not_moved::why(&layout, WORKSPACE), Some(why.clone()));let words = Heal::explain(heal, "Refused.".to_string()); assert!(words.contains(&why), "{words}"); assert!(!words.contains("kept until"), "{words}"); assert!(!words.contains("0 changes"), "{words}");}/// RULE: unsent changes that cannot be read stop the move — whether one writes what the move loses cannot be told — and the copy stays.#[test]fn unreadable_unsent_changes_keep_the_copy_unmoved() {for flavor in [Flavor::Dev, Flavor::Real] {let root = tempfile::tempdir().unwrap();let layout = Layout::new(root.path().join("synthetic-device"));let path = stamped_file(&layout, SCHEMA_VERSION - 1); with_receipt_stores(&path);// A queued op in a store with no receipt bytes to read it by.Driver::open(&path).unwrap().exec("INSERT INTO _outbox (op_id, tbl) VALUES ('op-1', 'note')").unwrap(); assert_eq!( heal_stale_replica(&layout, WORKSPACE, Some(flavor), None),Some(Heal::Held { stamped: SCHEMA_VERSION - 1, unsent: None }) ); assert!(path.exists()); assert_eq!(crate::bootstrap::not_moved::why(&layout, WORKSPACE), None, "not a failed move"); }}/// An undeclared process (a crate's own test) is never healed.#[test]fn an_undeclared_process_keeps_its_file() {let root = tempfile::tempdir().expect("a root");let layout = Layout::new(root.path().join("CottonDB"));let path = stamped_file(&layout, SCHEMA_VERSION - 1); with_receipt_stores(&path); assert_eq!(heal_stale_replica(&layout, WORKSPACE, None, None), None); assert!(path.exists());}#[test]fn nothing_to_heal_without_a_file() {let root = tempfile::tempdir().expect("a root");let layout = Layout::new(root.path().join("CottonDev")); assert_eq!(heal_stale_replica(&layout, WORKSPACE, Some(Flavor::Dev), None), None);}#[test]fn refresh_refuses_held_writes_and_deletes_before_reading_a_snapshot() {for table in ["_writes", "_tombstones"] {let root = tempfile::tempdir().expect("root");let layout = Layout::new(root.path());let path = stamped_file(&layout, SCHEMA_VERSION); with_receipt_stores(&path);let db = Driver::open(&path).expect("file"); db.exec("CREATE TABLE _meta (workspace_id TEXT, handed_over_epoch INTEGER)").expect("no handover fact"); db.exec(&format!("INSERT INTO {table} (op_id, held) VALUES ('held', 1)")).expect("held receipt"); assert!(crate::bootstrap::owes_hand_over(&db).expect("read receipt stores").is_some()); }}/// RULE: the answer an open that must not run gives a page is typed — the `not_moved` code, and the copy's stamp and this build's schema as fields for the log — and the sentence it carries names no schema and no number: a version is the core's bookkeeping, never words on the "Opening your database" or not-moved card (passivemove rule 4, architect).#[test]fn a_stopped_open_answers_a_code_and_typed_versions_never_a_schema_sentence() {for stamp in [SCHEMA_VERSION - 1, SCHEMA_VERSION + 7] {let root = tempfile::tempdir().expect("a root");let layout = Layout::new(root.path().join("CottonDB"));let path = stamped_file(&layout, stamp); with_receipt_stores(&path);let heal = heal_stale_replica(&layout, WORKSPACE, Some(Flavor::Real), None);let stopped = Heal::stopped(&heal).expect("a failed move stops the open"); assert_eq!(stopped.code(), crate::bootstrap::NOT_MOVED); assert_eq!((stopped.stamped, stopped.reads), (stamp, SCHEMA_VERSION), "the numbers are typed");let page = stopped.to_string(); assert!(!page.to_lowercase().contains("schema"), "stamp {stamp}: {page}"); assert!(!page.chars().any(|c| c.is_ascii_digit()), "stamp {stamp}: {page}");let log = stopped.log_line(); assert!(log.contains(&stamp.to_string()) && log.contains(&SCHEMA_VERSION.to_string()), "{log}"); }}/// A whole copy of `workspace` stamped by the build before this one, whose/// `cotton_todos` is in an older shape: one of its columns (not the last, so/// the move REBUILDS the table rather than adding to it) is not there yet.fn copy_with_a_table_to_rebuild(layout: &Layout, workspace: &str) -> std::path::PathBuf {let path = crate::test_support::replica_with_rows(layout, workspace, 3);let db = Driver::open(&path).expect("the copy");let columns = db.all("SELECT name, \"notnull\" AS nn FROM pragma_table_info('cotton_todos') ORDER BY cid", &[]).expect("columns");let last = columns.last().and_then(|row| row.text("name")).expect("a last column").to_string();let dropped = columns.iter() .filter(|row| row.int("nn") == Some(0)) .filter_map(|row| row.text("name").map(str::to_string)) .filter(|name| *name != last && !name.starts_with('_')) .find(|name| db.exec(&format!("ALTER TABLE cotton_todos DROP COLUMN \"{name}\"")).is_ok()); assert!(dropped.is_some(), "a column of cotton_todos can be taken away"); db.exec(&format!("PRAGMA user_version = {}", SCHEMA_VERSION - 1)).expect("the stamp"); db.checkpoint_truncate().expect("a checkpoint"); path}/// RULE: A SCHEMA MOVE NEVER HOLDS THE OPEN (passivemove rule 1, architect's/// ruling 18 Oct 2026). The heal before an open runs only the move's first/// step and answers `Moving`; the open admits the copy as it is, still/// stamped by the build before, with the tables it has left written in the/// file and noted for every reader (`crate::moves`); a read of a table the/// move has done answers at once; and the steps left, run after the open one/// table per transaction, finish the move and only then stamp it.#[test]fn a_copy_another_build_stamped_opens_first_and_moves_its_tables_after() {let (_dir, layout) = crate::test_support::temp_layout();let workspace = "ws-moves-after-the-open";let path = copy_with_a_table_to_rebuild(&layout, workspace);let heal = heal_stale_replica_leaving_tables(&layout, workspace, Some(Flavor::Dev)); assert_eq!(heal, Some(Heal::Moving { stamped: SCHEMA_VERSION - 1 })); {let db = Driver::open(&path).unwrap(); assert_eq!(current_version(&db).unwrap(), SCHEMA_VERSION - 1, "the heal does not stamp");let left = cotton_store::shape_move::left(&db).unwrap().expect("a move under way"); assert!(left.begun && left.holds("cotton_todos") && !left.holds("cotton_workspaces"), "{left:?}"); }let replica = crate::open_replica( &layout, workspace, &crate::seams::FixedClock::default_start(), &crate::seams::SeededRandom::default(), &mut |_| Err("nothing downloads".to_string()), ) .expect("a copy mid-move opens as it is"); assert_eq!(current_version(&replica.driver).unwrap(), SCHEMA_VERSION - 1, "the open does not move it"); assert!(replica.moving()); assert_eq!(crate::moves::left(workspace).map(|left| left.tables), Some(vec!["cotton_todos".to_string()]));let workspaces = replica.driver.get("SELECT count(*) AS n FROM cotton_workspaces", &[]).unwrap().unwrap().int("n"); assert_eq!(workspaces, Some(1), "a table the move has done reads at once");letmut steps = vec![];whileletSome(stepped) = replica.move_step().expect("a step") { steps.push(stepped.clone());if !stepped.finished { assert_eq!(current_version(&replica.driver).unwrap(), SCHEMA_VERSION - 1, "no stamp before the last step"); } } assert!(steps.iter().any(|step| step.tables == vec!["cotton_todos".to_string()]), "{steps:?}"); assert!(steps.last().is_some_and(|step| step.finished)); assert_eq!(current_version(&replica.driver).unwrap(), SCHEMA_VERSION); assert!(!replica.moving() && crate::moves::left(workspace).is_none());let todos = replica.driver.get("SELECT count(*) AS n FROM cotton_todos", &[]).unwrap().unwrap().int("n"); assert_eq!(todos, Some(3), "every row of the rebuilt table is there");}/// RULE: a file at this database's address that names another database is not healed — no fold, no move writes into it; the open behind refuses it and it is kept byte for byte.#[test]fn a_copy_of_another_database_is_left_to_the_open_untouched() {let root = tempfile::tempdir().expect("a root");let layout = Layout::new(root.path().join("CottonDB"));let path = layout.replica(WORKSPACE); std::fs::create_dir_all(path.parent().expect("a parent")).expect("the folder");crate::test_support::write_snapshot_for(&path, "66666666-6666-4666-8666-666666666666");let bytes = std::fs::read(&path).expect("the bytes"); assert!(heal_stale_replica_leaving_tables(&layout, WORKSPACE, Some(Flavor::Real)).is_none()); assert_eq!(std::fs::read(&path).expect("still there"), bytes, "the heal wrote into another database's file");}