//! `apps/cotton/__tests__/client/replica.test.ts`, transliterated. //! //! Two of its cases change shape and say so here: "brings the file to //! SCHEMA_VERSION" becomes two cases — a file BEHIND this build is walked //! forward by the ladder (`migrate_tests.rs` in `cotton-store` holds the rungs //! themselves) and a file AHEAD of it is refused untouched — and "gives the //! store context this Mac's own device id" becomes an assertion on //! `Replica::device_id`, because there is no store context to give: the driver //! is a value. use super::*; use crate::seams::{FixedClock, SeededRandom}; use crate::test_support::{bootstrap_from, temp_layout, write_snapshot, WORKSPACE}; use cotton_store::schema::ddl::SCHEMA_VERSION; fn clock() -> FixedClock { FixedClock::default_start() } fn never_bootstrap(_: &Path) -> Result<(), String> { panic!("this test must not need a snapshot") } // ── the device id ─────────────────────────────────────────────────────────── #[test] fn the_device_id_is_device_ulid_and_is_the_same_on_the_next_launch() { let (_dir, layout) = temp_layout(); let random = SeededRandom::default(); let first = resolve_device_id(&layout, &clock(), &random).expect("an id"); let second = resolve_device_id(&layout, &clock(), &random).expect("an id"); assert!(first.starts_with("device:"), "{first}"); assert_eq!(first.len(), "device:".len() + 26); assert_eq!(first, second); } #[test] fn it_mints_a_new_one_when_the_file_holds_something_that_is_not_a_device_id() { let (_dir, layout) = temp_layout(); let path = device_file_path(&layout); std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder"); std::fs::write(&path, r#"{"deviceId":"not-a-device"}"#).expect("the file"); let id = resolve_device_id(&layout, &clock(), &SeededRandom::default()).expect("an id"); assert!(id.starts_with("device:"), "{id}"); } // ── openReplica ───────────────────────────────────────────────────────────── #[test] fn it_fetches_the_snapshot_on_a_first_open_and_reports_that_it_bootstrapped() { let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); let mut asked = 0usize; let mut bootstrap = |destination: &Path| { asked += 1; std::fs::copy(&snapshot, destination) .map(|_| ()) .map_err(|error| error.to_string()) }; let replica = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap, ) .expect("an open replica"); assert!(replica.bootstrapped); assert_eq!(replica.workspace_id, WORKSPACE); assert_eq!(replica.path, layout.replica(WORKSPACE)); drop(replica); assert_eq!(asked, 1); } #[test] fn it_takes_an_in_process_bootstrap_instead_of_an_http_one_because_the_seam_is_a_path() { // Embedded mode hands the SAME closure an in-process backup of the // server's own file; nothing in this crate knows which it got. let (dir, layout) = temp_layout(); let source = dir.path().join("served.db"); write_snapshot(&source); let replica = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(source), ) .expect("an open replica"); assert!(replica.bootstrapped); } /// RULE: An open replica reads its file identity once, so media keys and derived ids use that identity instead of a caller-built string. #[test] fn an_open_replica_carries_the_identity_its_file_names() { let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); let replica = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(snapshot), ) .expect("an open replica"); assert_eq!(replica.file_id().as_str(), WORKSPACE); assert_eq!(replica.namespace().as_str(), WORKSPACE); assert_eq!(replica.open_reader().expect("a reader").identity, replica.identity); } #[test] fn it_refuses_a_bootstrap_that_wrote_nothing() { let (_dir, layout) = temp_layout(); let error = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut |_: &Path| Ok(()), ) .expect_err("a refusal"); assert!(matches!(error, ReplicaError::Bootstrap(_)), "{error}"); assert!(error.to_string().contains("nothing to open")); } #[test] fn it_refuses_an_empty_snapshot_rather_than_opening_a_zero_byte_file() { let (_dir, layout) = temp_layout(); let error = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut |destination: &Path| { std::fs::write(destination, b"").map_err(|error| error.to_string()) }, ) .expect_err("a refusal"); assert!(error.to_string().contains("nothing to open")); assert!(!layout.replica(WORKSPACE).exists()); } #[test] fn it_opens_the_file_it_already_has_without_asking_the_server_again() { let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); let first = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(snapshot), ) .expect("an open replica"); drop(first); let again = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut never_bootstrap, ) .expect("an open replica"); assert!(!again.bootstrapped); } #[test] fn it_refuses_a_file_written_by_a_newer_build_without_changing_its_stamp() { // The dev baseline must match exactly. Refusing it cannot change the file // or its newer stamp; the matching build must still find its own data. let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); { let db = Driver::open(&snapshot).expect("the file"); db.exec(&format!("PRAGMA user_version = {}", SCHEMA_VERSION + 1)) .expect("a stamp"); } let error = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(snapshot.clone()), ) .expect_err("a newer baseline is refused"); assert!(error.to_string().contains("does not match this build")); let file = Driver::open(layout.replica(WORKSPACE)).expect("the refused file remains"); assert_eq!( cotton_store::migrate::current_version(&file).expect("a version"), SCHEMA_VERSION + 1, "the newer build's stamp is untouched" ); } #[test] fn an_ordinary_launch_at_this_builds_version_reports_no_migration_at_all() { // The screen must paint NOTHING on a launch that has nothing to do: a // start event with no steps behind it is a frame held for no reason. let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); let mut seen: Vec = Vec::new(); let replica = open_replica_with(OpenReplicaInput { layout: &layout, workspace_id: WORKSPACE, clock: &clock(), random: &SeededRandom::default(), judge: None, bootstrap: &mut bootstrap_from(snapshot), on_migration: Some(&mut |event| seen.push(event)), on_bootstrapped: None, receipt_signer: cotton_store::signed::SignerSlot::default(), }) .expect("an open replica"); drop(replica); assert!(seen.is_empty(), "{seen:?}"); } #[test] fn the_replica_carries_this_macs_own_device_id_not_the_files() { let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); let replica = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(snapshot), ) .expect("an open replica"); // The snapshot was seeded as `device:snapshot`; this Mac authors as itself. assert_ne!(replica.device_id, "device:snapshot"); assert_eq!( replica.meta().expect("meta").expect("some").device_id, "device:snapshot" ); } #[test] fn a_file_that_names_no_database_is_refused_and_kept() { let (dir, layout) = temp_layout(); let headless = dir.path().join("headless.db"); { let db = Driver::open(&headless).expect("a file"); cotton_store::create::apply_schema(&db).expect("the schema"); db.exec(&format!("PRAGMA user_version = {SCHEMA_VERSION}")) .expect("a stamp"); } let error = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(headless), ) .expect_err("a refusal"); assert!(matches!(error, ReplicaError::NoIdentity)); assert!(layout.replica(WORKSPACE).exists(), "a file that is there is kept"); } // ── the ingest cursors ────────────────────────────────────────────────────── #[test] fn the_cursors_live_in_the_replica_so_deleting_the_file_forgets_where_each_source_got_to() { let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); let replica = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(snapshot.clone()), ) .expect("an open replica"); assert_eq!( read_ingest_cursor(&replica.driver, "ingest:messages:cursor").expect("a read"), None ); write_ingest_cursor( &replica.driver, "ingest:messages:cursor", "42", "2026-09-08T10:00:00.000Z", ) .expect("a write"); assert_eq!( read_ingest_cursor(&replica.driver, "ingest:messages:cursor").expect("a read"), Some("42".to_string()) ); // Written twice is updated, not duplicated. write_ingest_cursor( &replica.driver, "ingest:messages:cursor", "99", "2026-09-08T10:01:00.000Z", ) .expect("a write"); assert_eq!( read_ingest_cursor(&replica.driver, "ingest:messages:cursor").expect("a read"), Some("99".to_string()) ); let path = replica.path.clone(); drop(replica); std::fs::remove_file(&path).expect("the file goes"); let fresh = open_replica( &layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(snapshot), ) .expect("an open replica"); assert_eq!( read_ingest_cursor(&fresh.driver, "ingest:messages:cursor").expect("a read"), None, "a re-bootstrapped file forgets the cursors with it" ); } // ── the read pool ─────────────────────────────────────────────────────────── /// RULE: a read that cannot get a connection is refused after a bounded wait, /// and the refusal names the line and thread holding every connection — on a /// standby on 12 Oct 2026 reads queued on four held connections for hours, /// the quit with them, and nothing said who held them (standbyhang). #[test] fn a_read_behind_held_connections_is_refused_naming_the_holders() { let (_dir, _layout, replica) = crate::test_support::open_test_replica(); let mut pool = replica.open_read_pool().expect("a pool"); pool.shared.wait_limit = Duration::from_millis(200); let held: Vec<_> = (0..READERS_PER_DATABASE) .map(|_| pool.take().expect("a free connection")) .collect(); let this_file = file!(); let refused = std::thread::scope(|scope| { scope.spawn(|| pool.take().err()).join().unwrap() }) .expect("refused once every connection is held"); let said = refused.to_string(); assert!(said.contains("every read connection of this file is busy"), "{said}"); assert!(said.contains(this_file), "names the holders' line: {said}"); assert_eq!(pool.holders().len(), READERS_PER_DATABASE); drop(held); assert!(pool.holders().is_empty(), "a returned lease is no longer named"); assert!(pool.take().is_ok()); } /// RULE: a read connection is a hold of the file — a network call, dial or /// child process inside one is the debug panic `held` makes of a wait inside /// the writer, so no read keeps a connection across the network. #[test] fn a_lease_marks_its_thread_as_holding_the_file() { let (_dir, _layout, replica) = crate::test_support::open_test_replica(); let pool = replica.open_read_pool().expect("a pool"); assert_eq!(cotton_store::held::held(), None); let lease = pool.take().expect("a connection"); assert_eq!(cotton_store::held::held(), Some("a read connection")); drop(lease); assert_eq!(cotton_store::held::held(), None); } /// RULE: the SHORT lane admits only short reads — a read on it that runs past /// SHORT_READ_DEADLINE is stopped inside its statement and refused as too /// long (`ReadRefused::TooLong`), so no read can grow into the lane later and /// starve Home the way four long reads starved the shared lane on 16 Oct 2026 /// (readpool; architect's check 21:22 IST). #[test] fn a_long_read_on_the_short_lane_is_cut_at_its_deadline() { let (_dir, _layout, replica) = crate::test_support::open_test_replica(); let pool = replica.open_read_pool().expect("a pool"); let _ = take_read_refusal(); let lease = pool.take_short().expect("the short lane"); let began = std::time::Instant::now(); let walked = lease.driver.get( "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT COUNT(*) AS c FROM n", &[], ); let took = began.elapsed(); assert!(walked.is_err(), "an endless read on the short lane answered"); assert!(lease.past_deadline()); assert!(took < SHORT_READ_DEADLINE + Duration::from_secs(1), "cut after {took:?}"); assert_eq!(take_read_refusal(), Some(ReadRefused::TooLong)); drop(lease); // The connection goes back without the deadline: the next short read runs. let next = pool.take_short().expect("the short lane again"); assert!(next.driver.get("SELECT 1 AS one", &[]).is_ok()); assert_eq!(take_read_refusal(), None); } /// RULE: a read refused because every connection of its lane is held says so /// as `ReadRefused::Busy` — a file that is fine, never one that cannot be read /// (readpool). #[test] fn a_read_refused_for_a_connection_is_marked_busy() { let (_dir, _layout, replica) = crate::test_support::open_test_replica(); let mut pool = replica.open_read_pool().expect("a pool"); pool.short.wait_limit = Duration::from_millis(100); let _ = take_read_refusal(); let held: Vec<_> = (0..SHORT_READERS_PER_DATABASE).map(|_| pool.take_short().expect("free")).collect(); let refused = pool.take_short().err().expect("refused while the lane is held"); assert!(is_busy(&refused), "{refused}"); assert_eq!(take_read_refusal(), Some(ReadRefused::Busy)); drop(held); } /// RULE: the short lane never waits behind the shared lane — Home's read takes /// a connection while every shared one is held (readpool, 16 Oct 2026). #[test] fn the_short_lane_answers_while_the_shared_lane_is_held() { let (_dir, _layout, replica) = crate::test_support::open_test_replica(); let mut pool = replica.open_read_pool().expect("a pool"); pool.shared.wait_limit = Duration::from_millis(100); let held: Vec<_> = (0..READERS_PER_DATABASE).map(|_| pool.take().expect("free")).collect(); assert!(pool.take().is_err(), "the shared lane is full"); let short = pool.take_short().expect("the short lane is its own"); assert!(short.driver.get("SELECT 1 AS one", &[]).is_ok()); drop(held); } /// RULE: The open never rebuilds the computed index — a copy whose index another build stamped opens as it is, and the rebuild runs after, in the background (`bring_index_current`), because the rebuild reads every record and on a large copy it held phone 296 on "Opening your database" for 2:28 (17 Oct 2026). #[test] fn the_open_leaves_a_stale_index_for_the_background_and_never_rebuilds_it() { let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); let first = open_replica(&layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(snapshot)) .expect("an open replica"); assert!(first.bring_index_current().is_ok()); // Another build's stamp: an install whose computed columns moved. cotton_store::derived::mark_rebuilt(&first.driver, "0:sha256:another-build").expect("stamped"); drop(first); let again = open_replica(&layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut never_bootstrap) .expect("the copy opens as it is"); assert!(!cotton_tools::derive::is_current(&again.driver).expect("reads"), "the open rebuilt the index"); assert!(again.bring_index_current().expect("rebuilds"), "the background pass rebuilds it"); assert!(cotton_tools::derive::is_current(&again.driver).expect("reads")); assert!(!again.bring_index_current().expect("current"), "a current index is left alone"); } /// RULE: A device's fold never rebuilds a stale index — it leaves the rows it changed for the background rebuild, which works the index out beside the folds and swaps it in with them patched, because a rebuild inside the fold ran inside the sync pass with the copy's mutex and write lock held, and on the 304 phone (20 Oct 2026) no pass sent an exchange for hours. #[test] fn a_devices_fold_leaves_a_stale_index_to_the_background_and_the_swap_patches_its_rows() { use cotton_store::derived::Derive; let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); let replica = open_replica(&layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(snapshot)) .expect("an open replica"); assert!(replica.driver.indexes_beside(), "a device's copy leaves its index to the background"); replica.bring_index_current().expect("rebuilt"); cotton_store::derived::mark_rebuilt(&replica.driver, "0:sha256:another-build").expect("stamped"); let rows = [("cotton_people".to_string(), "person-1".to_string())]; cotton_tools::derive::CoreDerive.derive(&replica.driver, &rows).expect("the fold's pass"); let pending = |replica: &Replica| { replica .driver .get("SELECT count(*) AS n FROM _computed WHERE table_id = '' AND key = 'pending'", &[]) .expect("reads") .and_then(|row| row.int("n")) .unwrap_or(0) }; assert!(!cotton_tools::derive::is_current(&replica.driver).expect("reads"), "the fold did not rebuild"); assert_eq!(pending(&replica), 1, "the row the fold changed waits for the rebuild"); assert!(replica.bring_index_current().expect("rebuilds")); assert!(cotton_tools::derive::is_current(&replica.driver).expect("reads")); assert_eq!(pending(&replica), 0, "the swap patched it and let it go"); } /// RULE: A fold that redefines a table on a device marks the index stale and leaves it to the background, never rebuilding inside the fold. #[test] fn a_devices_fold_that_redefines_a_table_leaves_the_rebuild_to_the_background() { use cotton_store::derived::Derive; let (dir, layout) = temp_layout(); let snapshot = dir.path().join("snapshot.db"); write_snapshot(&snapshot); let replica = open_replica(&layout, WORKSPACE, &clock(), &SeededRandom::default(), &mut bootstrap_from(snapshot)) .expect("an open replica"); replica.bring_index_current().expect("rebuilt"); // The fold lands a table with a computed column: the file's derivation moves. let definition = serde_json::json!({ "id": "movement", "name": "Movement", "plural": "Movements", "picture": null, "builtin": false, "engine": null, "columns": [ {"key": "name", "type": "text"}, {"key": "amount", "type": "amount"}, {"key": "balance", "type": "amount", "computed": {"running": {"column": "amount", "opening": 0}}} ], "title": "name", "date": null, "project": null, "order": null, "sort": {"column": "name", "descending": false}, "slip": {"title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null}, "tile": {"face": "slip-list"}, "page": [{"heading": null, "columns": ["name"]}], "instructions": "A synthetic table with one computed column." }); replica .driver .run( "INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES ('movement', ?, ?, 0, ?, ?)", &[ rusqlite::types::Value::Text(WORKSPACE.into()), rusqlite::types::Value::Text(definition.to_string()), rusqlite::types::Value::Text("2026-01-01T00:00:00.000Z".into()), rusqlite::types::Value::Text("2026-01-01T00:00:00.000Z".into()), ], ) .expect("the fold's definition"); cotton_store::schema::package_shape::step_file(&replica.driver).expect("its table"); let rows = [("cotton_table_definitions".to_string(), "movement".to_string())]; cotton_tools::derive::CoreDerive.derive(&replica.driver, &rows).expect("the fold's pass"); assert!(!cotton_tools::derive::is_current(&replica.driver).expect("reads"), "the fold rebuilt the index"); assert!(replica.bring_index_current().expect("rebuilds")); assert!(cotton_tools::derive::is_current(&replica.driver).expect("reads")); }