//! The template has to be a file `create_workspace` would have made. use std::collections::HashSet; use std::sync::{Arc, Barrier, Mutex}; use super::*; fn meta(id: &str) -> Meta { Meta { workspace_id: id.to_string(), owner_id: "owner-1".to_string(), device_id: "device:one".to_string(), last_server_seq: 7, last_hlc: Some("2026-09-12T00:00:00.000Z".to_string()), } } fn scratch() -> PathBuf { let dir = std::env::temp_dir().join(format!( "cotton-template-tests-{}-{:?}", std::process::id(), std::thread::current().id() )); std::fs::create_dir_all(&dir).expect("a scratch directory"); dir } #[test] fn a_copy_has_the_same_schema_as_a_file_built_from_zero() { let dir = scratch(); let built = dir.join("built.db"); let ladder = Driver::open(&built).expect("a file"); create_workspace(&ladder, &meta("ws-built")).expect("the ladder runs"); let copied = dir.join("copied.db"); let db = create_workspace_for_test(&copied, &meta("ws-copied")).expect("a copy"); // Object for object, in the comparison `schema_snapshot` uses. assert_eq!( crate::create::schema_objects(&db).expect("the copy's schema"), crate::create::schema_objects(&ladder).expect("the ladder's schema"), ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn the_copy_carries_the_identity_it_was_asked_for_and_not_the_templates() { let dir = scratch(); let path = dir.join("one.db"); let db = create_workspace_for_test(&path, &meta("ws-mine")).expect("a copy"); let found = crate::meta::read_meta(&db).expect("the read").expect("a row"); assert_eq!(found.workspace_id, "ws-mine"); assert_eq!(found.owner_id, "owner-1"); assert_eq!(found.device_id, "device:one"); assert_eq!(found.last_server_seq, 7); assert_eq!( found.last_hlc.as_deref(), Some("2026-09-12T00:00:00.000Z"), "a cursor the caller named is not the template's" ); assert_eq!( crate::meta::file_schema_version(&db).expect("the stamp"), crate::migrate::SCHEMA_VERSION, "a copy is stamped at this build's version, like a file the ladder made" ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn two_copies_are_separate_files() { let dir = scratch(); let first = create_workspace_for_test(&dir.join("a.db"), &meta("ws-a")).expect("a copy"); let second = create_workspace_for_test(&dir.join("b.db"), &meta("ws-b")).expect("a copy"); first .run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES \ ('ws-a','A','owner-1','2026-09-12T00:00:00.000Z')", &[], ) .expect("a row in the first"); let count = second .get("SELECT COUNT(*) AS n FROM cotton_workspaces", &[]) .expect("a count") .and_then(|row| row.int("n")); assert_eq!(count, Some(0), "a write to one copy is not in the other"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn the_fingerprint_is_this_builds_ladder() { // Sixteen hex characters, and the same answer every time it is asked — // a key that moved between two calls would rebuild the template per test. let once = ladder_fingerprint(); assert_eq!(once.len(), 16); assert!(once.chars().all(|c| c.is_ascii_hexdigit())); assert_eq!(once, ladder_fingerprint()); } #[test] fn no_two_builders_of_the_template_can_choose_the_same_name() { // The failure this holds shut: two THREADS of one `cargo test` process // reaching `template()` on a cold cache and picking the same `.building` // path, so the second one's ladder ran over the first one's file — // `table _meta already exists`, through whichever test was second. A pid // does not separate threads and the clock is microsecond-grained, so the // old name collided; every name here has to be its own. let template = scratch().join("template.db"); let threads = 16; let each = 64; let barrier = Arc::new(Barrier::new(threads)); let names: Arc>> = Arc::new(Mutex::new(Vec::new())); let mut running = Vec::new(); for _ in 0..threads { let barrier = Arc::clone(&barrier); let names = Arc::clone(&names); let template = template.clone(); running.push(std::thread::spawn(move || { // All of them at once, which is what the start of a suite is. barrier.wait(); let mine: Vec = (0..each).map(|_| building_path(&template)).collect(); names.lock().expect("the names").extend(mine); })); } for thread in running { thread.join().expect("a builder"); } let names = names.lock().expect("the names"); let distinct: HashSet<&PathBuf> = names.iter().collect(); assert_eq!(names.len(), threads * each, "every builder named a file"); assert_eq!( distinct.len(), names.len(), "two builders shared a path, and the second would run the ladder over the first's file" ); } #[test] fn a_build_that_does_not_reach_its_rename_leaves_nothing_behind() { let dir = scratch(); let path = dir.join("template.db"); let building = Building::at(building_path(&path)); std::fs::write(building.path(), b"half a ladder").expect("a half-built file"); let mut sidecar = building.path().to_path_buf().into_os_string(); sidecar.push("-wal"); let sidecar = PathBuf::from(sidecar); std::fs::write(&sidecar, b"a sidecar").expect("a sidecar"); let abandoned = building.path().to_path_buf(); drop(building); assert!(!abandoned.exists(), "the half-built file is gone"); assert!(!sidecar.exists(), "its sidecar is gone too"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn an_in_memory_copy_has_the_ladders_schema_and_the_identity_it_was_asked_for() { let ladder = Driver::open_in_memory().expect("a file"); create_workspace(&ladder, &meta("ws-built")).expect("the ladder runs"); let db = create_workspace_in_memory_for_test(&meta("ws-memory")).expect("a restore"); assert_eq!( crate::create::schema_objects(&db).expect("the copy's schema"), crate::create::schema_objects(&ladder).expect("the ladder's schema"), ); let found = crate::meta::read_meta(&db).expect("the read").expect("a row"); assert_eq!(found.workspace_id, "ws-memory"); assert_eq!(found.last_server_seq, 7); assert_eq!( crate::meta::file_schema_version(&db).expect("the stamp"), crate::migrate::SCHEMA_VERSION, ); } #[test] fn an_in_memory_copy_takes_writes_and_enforces_its_foreign_keys() { // The template on disk is a WAL file; restored into memory it must still // be a file a fixture can write, with the cascades the schema leans on. let db = create_workspace_in_memory_for_test(&meta("ws-writes")).expect("a restore"); db.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES \ ('ws-writes','W','owner-1','2026-09-12T00:00:00.000Z')", &[], ) .expect("a write lands"); let on = db .get("PRAGMA foreign_keys", &[]) .expect("the pragma") .and_then(|row| row.int("foreign_keys")); assert_eq!(on, Some(1)); let other = create_workspace_in_memory_for_test(&meta("ws-other")).expect("a restore"); let count = other .get("SELECT COUNT(*) AS n FROM cotton_workspaces", &[]) .expect("a count") .and_then(|row| row.int("n")); assert_eq!(count, Some(0), "a write to one copy is not in the other"); } /// RULE: A compiled package storage change invalidates cached test databases even when core DDL is unchanged; on 18 Oct a read credential hit an old cached scope CHECK. #[test] fn package_storage_changes_invalidate_the_template() { let shapes = crate::schema::package_tables::builtin_shapes().unwrap(); let before = ladder_fingerprint_with_shapes(&shapes); let mut changed = shapes.clone(); let column = changed.iter_mut().flat_map(|(_, tables)| tables) .find(|table| table.name == "cotton_code_credentials").unwrap() .columns.iter_mut().find(|column| column.name == "scope").unwrap(); column.declaration = Some("scope TEXT NOT NULL CHECK (scope IN ('synthetic'))".into()); assert_ne!(before, ladder_fingerprint_with_shapes(&changed)); assert_eq!(before, ladder_fingerprint()); }