//! `read.you` — the owner's own person (Spec 10.3 "You"), and `read.account`'s //! `ownerName` read off that person once it is linked. //! //! Every case runs on `attached()`, the one synthetic paired phone. Every name //! is invented ([nothing-real-ever-goes-in-cotton-s-public-tree]). use serde_json::{json, Map, Value}; use crate::shell::client::phone_tests::attached; use crate::shell::client::ClientController; fn read(client: &ClientController, name: &str) -> Value { let entry = super::reads::read_for(name).unwrap_or_else(|| panic!("{name} is declared")); super::answer_read(client, entry, &Map::new()) .unwrap_or_else(|reason| panic!("{name} answered: {reason}")) } fn exec(client: &ClientController, sql: &str, params: &[&str]) { client .with_writer(|replica| { let bound: Vec = params .iter() .map(|value| rusqlite::types::Value::Text((*value).to_string())) .collect(); replica .driver .run(sql, &bound) .map_err(|error| error.to_string())?; crate::fixture::receipted(replica.driver, sql); Ok(()) }) .expect("the seed"); } fn one(client: &ClientController, sql: &str, params: &[&str]) -> Option { client .with_file(|replica| { let bound: Vec = params .iter() .map(|value| rusqlite::types::Value::Text((*value).to_string())) .collect(); Ok(replica .driver .get(sql, &bound) .map_err(|error| error.to_string())? .and_then(|row| row.text("value").map(str::to_string))) }) .expect("the read runs") } fn workspace(client: &ClientController) -> String { client .with_file(|replica| Ok(replica.workspace_id.to_string())) .expect("the workspace id") } fn named(client: &ClientController, name: &str) { let id = workspace(client); exec( client, "UPDATE cotton_workspaces SET name = ? WHERE id = ?", &[name, &id], ); } fn linked(client: &ClientController) -> Option { let id = workspace(client); one( client, "SELECT owner_person_id AS value FROM cotton_workspaces WHERE id = ?", &[&id], ) } /// The owner's person as the object serves it: a person row, and the link the /// object's meta lands on the copy's workspace row (`served_owner`). fn owner(client: &ClientController, name: &str) -> String { let id = "person-the-owner".to_string(); exec( client, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", &[&id, &workspace(client), name, "2026-09-01T00:00:00.000Z", "2026-09-01T00:00:00.000Z"], ); exec( client, "UPDATE cotton_workspaces SET owner_person_id = ? WHERE id = ?", &[&id, &workspace(client)], ); id } fn people(client: &ClientController) -> i64 { one(client, "SELECT CAST(COUNT(*) AS TEXT) AS value FROM cotton_people", &[]) .and_then(|n| n.parse().ok()) .unwrap_or(0) } // ── the contract ────────────────────────────────────────────────────────── #[test] fn read_you_answers_exactly_the_contract_keys_and_no_account_facts() { let (_dir, client) = attached(); owner(&client, "Tarun Invented"); let answer = read(&client, "read.you"); let mut keys: Vec<&str> = answer .as_object() .expect("an object") .keys() .map(String::as_str) .collect(); keys.sort_unstable(); assert_eq!( keys, [ "database_id", "devices_count", "name", "owner", "person_id", "print", "sign_in" ] ); assert_eq!(answer["database_id"], json!(workspace(&client))); assert_eq!(answer["owner"], json!(super::you::OWNER_LINKED)); // No GoTrue, session or email fact anywhere in what is said. let said = answer.to_string().to_lowercase(); for word in ["email", "@", "session", "gotrue", "password", "token"] { assert!(!said.contains(word), "read.you says `{word}`: {said}"); } } // ── the owner person ────────────────────────────────────────────────────── /// RULE: A phone's You opens from its own file with no Mac: read.you answers cotton_workspaces.owner_person_id and nothing else, so renaming the person, the owner or the database never loses You, and no server is asked. #[test] fn a_phones_you_opens_from_its_own_file_with_no_mac() { // `attached()` is a paired phone and its file; nothing serves it and // nothing here dials. let (_dir, client) = attached(); named(&client, "Personal"); let person = owner(&client, "Tarun Invented"); let answer = read(&client, "read.you"); assert_eq!(answer["person_id"], json!(person)); assert_eq!(answer["name"], json!("Tarun Invented")); assert_eq!(answer["database_id"], json!(workspace(&client))); // Every name there is changes, and a namesake appears: the same person. exec(&client, "UPDATE cotton_people SET full_name = 'Somebody Renamed' WHERE id = ?", &[&person]); named(&client, "A Renamed Database"); exec( &client, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", &["person-namesake", &workspace(&client), "Tarun Invented", "2026-09-02T00:00:00.000Z", "2026-09-02T00:00:00.000Z"], ); let again = read(&client, "read.you"); assert_eq!(again["person_id"], json!(person)); assert_eq!(again["name"], json!("Somebody Renamed")); } /// RULE: Until the copy holds the link the object serves and the person it names, read.you ANSWERS the typed `owner: "none_yet"` with no person — an ordinary state the next pass ends, never a failure — and it never guesses from a name, never makes a person and never writes the link: the object alone names the owner. #[test] fn a_database_with_no_owner_link_answers_no_owner_yet_and_guesses_nobody() { let (_dir, client) = attached(); // Every name a guess could go by is here, on a person and on the owner. named(&client, "Tarun Invented"); exec( &client, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", &["person-namesake", &workspace(&client), "Tarun Invented", "2026-09-01T00:00:00.000Z", "2026-09-01T00:00:00.000Z"], ); exec( &client, "INSERT INTO cotton_msg_owner_settings (workspace_id, handle, display_name, created_at, updated_at) \ VALUES (?, 'an-invented-handle', 'Tarun Invented', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')", &[&workspace(&client)], ); let before = people(&client); let answer = read(&client, "read.you"); assert_eq!(answer["owner"], json!(super::you::NO_OWNER_YET)); assert_eq!(answer["person_id"], Value::Null, "nobody is guessed"); assert_eq!(answer["name"], Value::Null); assert_eq!(answer["database_id"], json!(workspace(&client))); assert_eq!(linked(&client), None, "nothing was linked"); assert_eq!(people(&client), before, "nobody was made"); // A link to a person the copy does not hold yet, or holds in the bin (the // object follows a binned owner by number; its next answer moves the // link), is nobody yet: nothing is guessed meanwhile. let id = workspace(&client); exec(&client, "UPDATE cotton_workspaces SET owner_person_id = 'person-not-here-yet' WHERE id = ?", &[&id]); assert_eq!(read(&client, "read.you")["owner"], json!(super::you::NO_OWNER_YET)); let person = owner(&client, "Tarun Invented"); exec(&client, "UPDATE cotton_people SET trashed_at = '2026-09-03T00:00:00.000Z' WHERE id = ?", &[&person]); let binned = read(&client, "read.you"); assert_eq!(binned["owner"], json!(super::you::NO_OWNER_YET)); assert_eq!(binned["person_id"], Value::Null); // An archived owner is still you. exec(&client, "UPDATE cotton_people SET trashed_at = NULL, archived_at = '2026-09-03T00:00:00.000Z' WHERE id = ?", &[&person]); assert_eq!(read(&client, "read.you")["person_id"], json!(person)); } /// RULE: A fresh copy the object has not named its owner on yet is not a failure: through the full dispatch read.you answers `owner: "none_yet"` (never a refusal, so no Debug failure line on a fresh phone — rigbyfix-c, 22 Oct 2026), and no method on a phone writes the link. #[test] fn no_owner_yet_is_answered_through_the_dispatch_and_no_method_links_you() { let (_dir, handle) = crate::fixture::synthetic_phone(); let client = handle.client(); exec(&client, "UPDATE cotton_workspaces SET owner_person_id = NULL", &[]); let answer = crate::methods::dispatch(&handle, "read.you", &json!({})).expect("read.you answers"); assert_eq!(answer["owner"], json!(super::you::NO_OWNER_YET)); assert_eq!(answer["person_id"], Value::Null); assert!( crate::methods::dispatch(&handle, "you.choose", &json!({"person_id": "person-chosen"})).is_err(), "nothing on a phone says who you are" ); } #[test] fn a_linked_person_is_answered_by_its_own_name_and_print() { let (_dir, client) = attached(); named(&client, "Tarun Invented"); let person = owner(&client, "Tarun Invented"); assert_eq!( read(&client, "read.you")["print"], Value::Null, "no print yet" ); // A print lives under the database's own `{file id}/` prefix. let print = format!("{}/prints/invented-face.jpg", workspace(&client)); exec( &client, "UPDATE cotton_people SET full_name = ?, avatar_key = ? WHERE id = ?", &["Tarun Renamed", &print, &person], ); let answer = read(&client, "read.you"); assert_eq!(answer["person_id"], json!(person)); assert_eq!(answer["name"], json!("Tarun Renamed")); assert_eq!(answer["print"], json!(print)); } // ── read.account ────────────────────────────────────────────────────────── #[test] fn read_account_owner_name_is_the_owner_persons_once_linked_and_the_database_name_stays() { let (_dir, client) = attached(); named(&client, "Tarun Invented"); let person = owner(&client, "Tarun Invented"); exec( &client, "UPDATE cotton_people SET full_name = ? WHERE id = ?", &["Tarun Renamed", &person], ); assert_eq!( read(&client, "read.account")["ownerName"], json!("Tarun Renamed"), "a rename of the owner person is the owner's name" ); let id = workspace(&client); assert_eq!( one( &client, "SELECT name AS value FROM cotton_workspaces WHERE id = ?", &[&id] ) .as_deref(), Some("Tarun Invented"), "the database's own name is not touched" ); } #[test] fn read_account_owner_name_falls_back_to_the_workspace_name_while_unlinked() { let (_dir, client) = attached(); named(&client, "Tarun Invented"); assert_eq!( read(&client, "read.account")["ownerName"], json!("Tarun Invented") ); assert_eq!(linked(&client), None, "read.account links nobody"); } // ── sign_in ─────────────────────────────────────────────────────────────── #[test] fn sign_in_says_this_devices_admission_how_many_are_admitted_and_who_serves() { let (_dir, client) = attached(); named(&client, "Tarun Invented"); owner(&client, "Tarun Invented"); let id = workspace(&client); // No serving fact yet: said so. let answer = read(&client, "read.you"); assert_eq!(answer["devices_count"], json!(1)); assert_eq!( answer["sign_in"], json!([ "This device, An invented phone, was admitted on 8 Sep 2026.", "1 device is admitted.", "No Mac serves this database yet.", ]) ); // A second device, a revoked third, and the second serves. for (row, key, name, revoked) in [ ("device-row-mac", "BBBB", "An invented Mac", None), ( "device-row-old", "CCCC", "An old invented phone", Some("2026-09-20T00:00:00.000Z"), ), ] { exec( &client, "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \ approved_by_device, created_at, updated_at, revoked_at) \ VALUES (?, ?, ?, ?, '2026-09-10T09:00:00.000Z', 'self', \ '2026-09-10T09:00:00.000Z', '2026-09-10T09:00:00.000Z', ?)", &[row, &id, key, name, revoked.unwrap_or("")], ); } exec( &client, "UPDATE cotton_devices SET revoked_at = NULL WHERE revoked_at = ''", &[], ); exec( &client, "INSERT INTO cotton_serving_machine (id, workspace_id, epoch, device_credential_id, \ author_id, since) VALUES ('serving-1', ?, 1, 'BBBB', 'author-mac', \ '2026-09-10T09:00:00.000Z')", &[&id], ); let answer = read(&client, "read.you"); assert_eq!(answer["devices_count"], json!(2)); assert_eq!( answer["sign_in"], json!([ "This device, An invented phone, was admitted on 8 Sep 2026.", "2 devices are admitted.", "An invented Mac serves this database now.", ]) ); } #[test] fn sign_in_says_when_this_device_serves_and_when_it_is_not_admitted() { let (_dir, client) = attached(); named(&client, "Tarun Invented"); owner(&client, "Tarun Invented"); let id = workspace(&client); exec( &client, "INSERT INTO cotton_serving_machine (id, workspace_id, epoch, device_credential_id, \ author_id, since) VALUES ('serving-1', ?, 1, ?, 'author-self', \ '2026-09-10T09:00:00.000Z')", &[&id, crate::fixture::SELF_DEVICE_ID], ); assert_eq!( read(&client, "read.you")["sign_in"][2], json!("This device serves this database now.") ); exec( &client, "UPDATE cotton_devices SET revoked_at = '2026-09-30T00:00:00.000Z' WHERE device_id = ?", &[crate::fixture::SELF_DEVICE_ID], ); let answer = read(&client, "read.you"); assert_eq!( answer["sign_in"][0], json!("This device, An invented phone, was cut off on 30 Sep 2026.") ); assert_eq!(answer["sign_in"][1], json!("No device is admitted.")); assert_eq!(answer["devices_count"], json!(0)); } // ── read.databases ──────────────────────────────────────────────────────── /// RULE: one database whose file cannot be read never empties the Databases sheet; it is listed with its reason. /// /// 12 Oct 2026, the owner's phone (build 253) after a fresh copy of its /// personal database: the sheet came up empty, because one failing read of /// one file was a `?` that failed the whole `read.databases`, and the app /// keeps the list it had — none, at launch. The personal database is always /// on the sheet while the connection record names it. #[test] fn read_databases_lists_a_database_whose_file_cannot_be_read() { let (_dir, client) = attached(); // The personal file's own name cannot be read: its workspace table is gone. client .with_writer(|replica| { replica .driver .exec("ALTER TABLE cotton_workspaces RENAME TO cotton_workspaces_away") .map_err(|error| error.to_string()) }) .expect("the file is broken on purpose"); let answer = read(&client, "read.databases"); let rows = answer["databases"].as_array().expect("a list"); let personal = rows .iter() .find(|row| row["kind"] == "personal") .expect("the personal database is still listed"); assert!( personal["unreadable"].as_str().is_some_and(|reason| reason.contains("cotton_workspaces")), "the row says why it could not be read: {personal}" ); } /// The personal database is listed under its own name IN FULL, and renaming /// the owner person does not rename the database (a walk at 07:52Z: a two-word /// name listed as its first word, which made the cap read like a person). #[test] fn read_databases_lists_the_whole_database_name_and_an_owner_rename_leaves_it() { let (_dir, client) = attached(); named(&client, "Garden Three"); let listed = |client: &ClientController| { let answer = read(client, "read.databases"); answer["databases"] .as_array() .expect("a list") .iter() .find(|row| row["kind"] == "personal") .expect("the personal database is listed")["name"] .clone() }; assert_eq!(listed(&client), json!("Garden Three")); let person = owner(&client, "Garden Owner"); exec( &client, "UPDATE cotton_people SET full_name = ? WHERE id = ?", &["Someone Renamed", &person], ); assert_eq!( read(&client, "read.account")["ownerName"], json!("Someone Renamed") ); assert_eq!( listed(&client), json!("Garden Three"), "the database keeps its own name" ); } // ── a copy being put in place ───────────────────────────────────────────── /// RULE: while an arrived copy is being checked, unpacked and claimed, the open answers at once and never opens the file beside it. /// /// 12 Oct 2026, the owner's phone: the boot's open met the bootstrap thread's /// claim on the same file and waited out SQLite's busy timeout statement after /// statement, holding the controller's lock — the card said "Opening your /// database" for minutes and the bootstrap's own attach queued behind it. #[test] fn the_open_answers_at_once_while_a_copy_is_being_put_in_place() { let (_dir, client) = attached(); client.detach(); client.set_placing(true); let status = client.sync_status(); assert_eq!(status["connected"], json!(false), "{status}"); assert_eq!(status["reason"], json!(crate::shell::client::PLACING_A_COPY)); // The thread that placed it attaches it, and the file opens. client.attach_now().expect("the copy opens once it is in place"); assert_eq!(client.sync_status()["connected"], json!(true)); } /// RULE: an open of this device's database never holds the controller's state lock — a detach answers while an open runs, and an open overtaken by a detach installs nothing. /// /// 12 Oct 2026: `attach` held the state lock from its first line to its last, /// so a ladder, a log replay or a heal on the owner's 732 MB copy held every /// reader of it for as long as the open ran, and a re-hydrate's detach before /// its swap queued behind an open of the very file it was letting go. #[test] fn an_open_in_flight_holds_nobody_on_the_state_lock() { use std::sync::mpsc::channel; use std::time::Duration; let (_dir, client) = attached(); client.detach(); let (entered, opened) = channel::<()>(); let (release, released) = channel::<()>(); let released = std::sync::Mutex::new(released); *client.during_open.lock().expect("the hook slot") = Some(std::sync::Arc::new(move || { let _ = entered.send(()); let _ = released.lock().expect("the release").recv(); })); let opener = { let client = std::sync::Arc::clone(&client); std::thread::spawn(move || client.attach_now()) }; opened .recv_timeout(Duration::from_secs(10)) .expect("the open started"); // The state lock is free while the open runs: a detach answers at once. let (detached, said) = channel::<()>(); { let client = std::sync::Arc::clone(&client); std::thread::spawn(move || { client.detach(); let _ = detached.send(()); }); } said.recv_timeout(Duration::from_secs(5)) .expect("a detach answers while an open is in flight"); // What the detach was for — a copy being put in its place — and then the // open goes on. The handle it opened is not installed over the detach. client.set_placing(true); *client.during_open.lock().expect("the hook slot") = None; release.send(()).expect("the open is waiting"); assert_eq!( opener.join().expect("the opener"), Err(crate::shell::client::PLACING_A_COPY.to_string()), "an open overtaken by a detach looks again and finds the copy being placed" ); assert_eq!(client.sync_status()["connected"], json!(false)); client.attach_now().expect("the placed copy opens"); assert_eq!(client.sync_status()["connected"], json!(true)); } // ── opening the other held databases ────────────────────────────────────── /// Two databases held beside this device's own: places on the connection /// record and an invented file each. fn holding(client_dir: &std::path::Path, ids: &[&str]) { let layout = cotton_client::layout::Layout::new(client_dir); let record = layout.connection_json(); let mut connection: Value = serde_json::from_slice(&std::fs::read(&record).expect("the record")).expect("json"); connection["places"] = Value::Array( ids.iter() .map(|id| json!({ "id": id, "name": id, "available": true, "unavailableSince": null })) .collect(), ); std::fs::write(&record, serde_json::to_vec_pretty(&connection).expect("json")).expect("the record"); for id in ids { let path = layout.replica(id); if path.exists() { continue; } std::fs::create_dir_all(path.parent().expect("a parent")).expect("the replica folder"); let db = cotton_store::test_template::create_workspace_for_test( &path, &cotton_store::meta::Meta { workspace_id: (*id).to_string(), owner_id: crate::fixture::OWNER.to_string(), device_id: crate::fixture::DEVICE.to_string(), last_server_seq: 0, last_hlc: None, }, ) .expect("an invented database"); drop(db); } } /// RULE: an open of one held database never holds the set of open databases — a question about one already open answers while another opens, and an open overtaken by its database being let go installs nothing. /// /// 12 Oct 2026: `open_other` held the whole set's lock across a heal, a log /// replay and a ladder, so after an update — when every held copy climbs a /// ladder on its first open — a read of an open database waited for each of /// the others in turn; and the set's lock was also what kept a leave from /// racing an open of the file it deletes, which the let-go count now does. #[test] fn an_open_of_one_held_database_holds_nobody_on_the_others() { use std::sync::mpsc::channel; use std::time::Duration; const OPEN: &str = "00000000-0000-4000-8000-0000000000a1"; const OPENING: &str = "00000000-0000-4000-8000-0000000000b2"; let (dir, client) = attached(); holding(dir.path(), &[OPEN, OPENING]); client.open_database(OPEN).expect("the first held database opens"); let (entered, opened) = channel::<()>(); let (release, released) = channel::<()>(); let released = std::sync::Mutex::new(released); *client.other_opens.during_open.lock().expect("the hook slot") = Some(std::sync::Arc::new(move |database: &str| { if database == OPENING { let _ = entered.send(()); let _ = released.lock().expect("the release").recv(); } })); let opener = { let client = std::sync::Arc::clone(&client); std::thread::spawn(move || client.open_database(OPENING).map(|_| ())) }; opened.recv_timeout(Duration::from_secs(10)).expect("the open started"); // The set is free while the other opens: the open one answers at once. let (answered, said) = channel::(); { let client = std::sync::Arc::clone(&client); std::thread::spawn(move || { let _ = answered.send(client.open_database(OPEN).is_ok()); }); } assert_eq!( said.recv_timeout(Duration::from_secs(5)), Ok(true), "an open database answers while another opens" ); // Let go while it opens — detached, and no longer on the record, as a // leave leaves it. The handle it opened is not put in the set. client.detach(); holding(dir.path(), &[OPEN]); *client.other_opens.during_open.lock().expect("the hook slot") = None; release.send(()).expect("the open is waiting"); assert!( opener.join().expect("the opener").is_err(), "an open overtaken by a let-go looks again and finds the database no longer held" ); assert!(!client.open_databases().iter().any(|id| id == OPENING)); } /// RULE: a short read (Home's catalogue, read.home, read.day) of a held /// database nothing has opened yet answers while that database's open is /// held — it reads the file directly, never through the open's turn, ladder /// and rebuild. After a switch on 290 the fan stood on Me and Tools for /// 1.5–1.8 s while the database opened (readpool, 16 Oct 2026). #[test] fn a_short_read_of_a_database_still_opening_answers_from_its_file() { use std::sync::mpsc::channel; use std::time::Duration; const OPENING: &str = "00000000-0000-4000-8000-0000000000c3"; let (dir, client) = attached(); holding(dir.path(), &[OPENING]); let (entered, opened) = channel::<()>(); let (release, released) = channel::<()>(); let released = std::sync::Mutex::new(released); *client.other_opens.during_open.lock().expect("the hook slot") = Some(std::sync::Arc::new(move |database: &str| { if database == OPENING { let _ = entered.send(()); let _ = released.lock().expect("the release").recv(); } })); let opener = { let client = std::sync::Arc::clone(&client); std::thread::spawn(move || client.open_database(OPENING).map(|_| ())) }; opened.recv_timeout(Duration::from_secs(10)).expect("the open started"); let (answered, said) = channel::>(); { let client = std::sync::Arc::clone(&client); std::thread::spawn(move || { let _named = client.name_database_unopened(OPENING).expect("a held database is named"); let read = crate::shell::client::on_short_lane(crate::shell::client::ShortRead::Catalogue, || { crate::phone::catalogue::call(&client, &serde_json::json!({})).map(|_| ()).map_err(|error| error.message) }); let _ = answered.send(read); }); } let read = said.recv_timeout(Duration::from_secs(5)); *client.other_opens.during_open.lock().expect("the hook slot") = None; release.send(()).expect("the open is waiting"); opener.join().expect("the opener").expect("the open finishes"); assert_eq!(read, Ok(Ok(())), "the catalogue answered from the file while its open was held"); } /// RULE: a personal database whose copy is not in place — still coming in, or being checked, unpacked and claimed — is listed as arriving with how far its copy is, never as a database with nothing in it, and never as unreadable. /// /// 12 Oct 2026, the owner's phone (build 253): an empty Personal page with /// "only you" under its cap, an hour after the update, over a 732 MB copy /// that had not been put in place yet. #[test] fn a_personal_database_mid_copy_is_listed_as_arriving_never_as_empty() { let (_dir, client) = attached(); let mine = workspace(&client); client.detach(); client.note_own_copy(&mine, Some((202 * 1024 * 1024, Some(732 * 1024 * 1024))), None); client.set_placing(true); let answer = read(&client, "read.databases"); let personal = answer["databases"] .as_array() .expect("a list") .iter() .find(|row| row["kind"] == "personal") .cloned() .expect("the personal database is listed mid-copy"); assert_eq!(personal["arrival"]["state"], json!("arriving"), "{personal}"); assert_eq!(personal["arrival"]["totalBytes"], json!(732 * 1024 * 1024_u64)); assert!(personal.get("unreadable").is_none(), "{personal}"); // In place and claimed: the copy's figures go, and the row is plain again. client.attach_now().expect("the copy opens"); client.note_own_copy(&mine, None, None); let answer = read(&client, "read.databases"); let personal = answer["databases"] .as_array() .expect("a list") .iter() .find(|row| row["kind"] == "personal") .cloned() .expect("listed"); assert!(personal.get("arrival").is_none(), "{personal}"); } /// RULE: a person's local read never takes a database's writer and never waits on its open — the Devices page's reads (`read.devices`' household copies, the keep-fetch status, the databases' appearance) read every other database on its read pool or a read-only connection (`glance_in`), so a catch-up holding the writers across its folds, or an open in flight, never holds a screen. /// /// 13 Oct 2026, the owner's phone (build 269) mid catch-up: Settings › Devices /// ran out its six seconds and said the Mac did not answer — it never asked /// the Mac. `keep_fetch_status` took every household database's writer for a /// whole-file scan, so it queued behind each fold batch, and `read.devices` /// opened every held database through its turn. #[test] fn a_local_read_answers_while_a_catch_up_holds_the_writers_and_an_open() { use std::sync::mpsc::channel; use std::time::Duration; const OPEN: &str = "00000000-0000-4000-8000-0000000000c1"; const CLOSED: &str = "00000000-0000-4000-8000-0000000000d2"; let (dir, client) = attached(); holding(dir.path(), &[OPEN, CLOSED]); let layout = cotton_client::layout::Layout::new(dir.path()); for id in [OPEN, CLOSED] { std::fs::create_dir_all(layout.client_media_dir().join(id)).expect("a media folder"); } // This phone is live in every database, so the keep-fetch status reads // each one rather than refusing at the first. // An invented held file names no workspace row, so the row goes in with // the file's own keys off. for id in [crate::fixture::WORKSPACE, OPEN, CLOSED] { let file = rusqlite::Connection::open(layout.replica(id)).expect("the file"); file.pragma_update(None, "foreign_keys", false).expect("keys off"); file.execute( "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, approved_at, \ approved_by_device, created_at, updated_at) VALUES (?1, ?2, ?3, 'The invented phone', 'ios', \ '2026-01-01T00:00:00.000Z', 'owner', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')", rusqlite::params![format!("phone-{id}"), id, crate::fixture::DEVICE], ) .expect("the phone's row"); } // And a Mac of the owner's, whose row offers "Serve from this Mac" — the // part of `read.devices` that reads every household database. rusqlite::Connection::open(layout.replica(crate::fixture::WORKSPACE)) .expect("the file") .execute( "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, approved_at, \ approved_by_device, created_at, updated_at) VALUES ('a-mac', ?1, 'device:the-invented-mac', \ 'The invented studio', 'mac', '2026-01-01T00:00:00.000Z', 'owner', '2026-01-01T00:00:00.000Z', \ '2026-01-01T00:00:00.000Z')", rusqlite::params![crate::fixture::WORKSPACE], ) .expect("the Mac's row"); // The closed one's file is in WAL, as every copy the writer ever opened is. client.open_database(CLOSED).expect("the closed database opens once"); client.close_idle_databases(); assert!(!client.open_databases().iter().any(|id| id == CLOSED), "the closed database is closed"); // THE CATCH-UP: a fold holds the device's own writer and the open // database's, and the sync loop's open of the closed one is in flight. client.attach_now().expect("the device's own opens"); let own = client.replica().expect("the device's own writer"); let other = client.open_database(OPEN).expect("the open database").replica; let (held, holding_them) = channel::<()>(); let (release, released) = channel::<()>(); let folder = std::thread::spawn(move || { let _own = own.lock().expect("the own writer"); let _other = other.lock().expect("the other writer"); held.send(()).expect("the test waits"); let _ = released.recv(); }); holding_them.recv_timeout(Duration::from_secs(10)).expect("the writers are held"); let (opening, open_started) = channel::<()>(); let (let_open, open_released) = channel::<()>(); let open_released = std::sync::Mutex::new(open_released); *client.other_opens.during_open.lock().expect("the hook slot") = Some(std::sync::Arc::new(move |database: &str| { if database == CLOSED { let _ = opening.send(()); let _ = open_released.lock().expect("the release").recv(); } })); let opener = { let client = std::sync::Arc::clone(&client); std::thread::spawn(move || client.open_database(CLOSED).map(|_| ())) }; open_started.recv_timeout(Duration::from_secs(10)).expect("the open started"); // THE PERSON'S READS answer while all of that is held. let (answered, said) = channel::<(&'static str, bool)>(); { let client = std::sync::Arc::clone(&client); std::thread::spawn(move || { let count = |driver: &cotton_store::driver::Driver, _: &str| { driver.get("SELECT 1 AS one", &[]).map(|_| ()).map_err(|e| e.to_string()) }; let _ = answered.send(("open", client.glance_in(OPEN, count).is_ok())); let _ = answered.send(("closed", client.glance_in(CLOSED, count).is_ok())); let _ = answered.send(("keep fetch", client.keep_fetch_status(crate::fixture::DEVICE).is_ok())); let _ = answered.send(("devices", crate::phone::reads_work::devices(&client, &Default::default()).is_ok())); let _ = answered.send(("appearance", crate::phone::database_appearance::listed(&client).is_ok())); }); } for read in ["open", "closed", "keep fetch", "devices", "appearance"] { assert_eq!( said.recv_timeout(Duration::from_secs(5)), Ok((read, true)), "{read} answers while a catch-up holds the writers and an open" ); } *client.other_opens.during_open.lock().expect("the hook slot") = None; let_open.send(()).expect("the open is waiting"); release.send(()).expect("the fold is waiting"); folder.join().expect("the fold"); let _ = opener.join().expect("the opener"); }