//! Offline sync facts for one database; no transport is consulted. use std::collections::BTreeSet; use std::path::Path; use cotton_core::rules::sync_state::{ Behind, Device, DeviceCopy, DeviceKind, DoingNow, Keeps, SyncState, ThisDevice, }; use cotton_store::driver::Driver; use rusqlite::types::Value as Sql; use serde_json::{json, Map, Value}; use crate::shell::client::ClientController; use crate::shell::file::ReadFile; // Reports may be ten minutes apart. Like Devices, allow twenty minutes // before a Mac's own contact report expires. const SERVING_CONTACT_WITHIN_MS: i64 = 20 * 60 * 1000; /// `read.sync_state { database?: string }`: the usual top-level database id, /// defaulting to the selected/personal database. Unknown ids are refused. /// /// Contract (snake_case JSON; u64 values are nonnegative integers): /// - database: string, the file's database id; read_at: RFC3339 UTC, read time. /// - as_of: RFC3339 UTC|null, last answer from this database's serving copy; /// the serving copy says read_at. Null means no exchange was observed. /// - devices: array of DeviceCopy, one per locally known active full device: /// - device: {id:string (credential id), name:string, kind:phone|tablet|mac| /// linux|windows|other, serving:bool (the stored serving fact)}. /// - as_of: RFC3339 UTC|null, the observation that supplies this row. /// - keeps: records_only|records_and_media|whole_file|null, retention policy. /// - behind: {changes:u64|null, at_least:bool, /// oldest_age_seconds:u64|null}. Incoming serving-copy receipts remaining /// at as_of, excluding this device's unsent writes; at_least marks the /// exchange's count cap. Oldest age is unknown: no stored stamp exists. /// - doing_now: idle|pulling_changes|fetching_bytes|sending|catching_up| /// paused|null. The local loop only distinguishes syncing as a whole, /// so it says catching_up; it never guesses a direction from prose. /// - last_heard_at: RFC3339 UTC|null, last locally stored contact evidence. /// - reachable: bool|null, observed reachability, as of this row's stamp; /// unreachable_since: RFC3339 UTC|null, first observed failure. /// - this_device: {id:string|null, synced_at:RFC3339 UTC|null (last observed /// level exchange), changes_waiting:u64 (outbox plus held writes), /// storage_bytes:u64|null (database, WAL and distinct local media files), /// bytes_wanted:u64|null (known-sized missing originals requested by keep /// rules, as the keep-fetch sweep last stored them; null until it has)}. /// /// All facts come from this device's file and its persisted sync observations. /// Remote activity and receipt positions are not replicated; their columns /// remain null, never idle/zero. The serving copy's reachability uses recent /// device contact or local exchanges; an old failure cannot erase newer /// contact. Peer names and retention rules are replicated; a reported_state /// supplies contact evidence only. /// `copy_as_of` is device-wide and must not stand in for a shared file's stamp. /// Storage is a local measurement, not an atomic filesystem snapshot. Media /// with unknown size and renditions are not counted in bytes_wanted. /// /// Three synthetic answers (serving Mac, synced phone, behind offline phone) /// are executable typed fixtures at `sync_state_tests/answers.json`. pub fn read(client: &ClientController, args: &Map) -> Result { let database = args .get("database") .map(|value| { value .as_str() .filter(|id| !id.is_empty() && *id != "all") .ok_or_else(|| "database must name one database".to_string()) }) .transpose()?; let _named = database .map(|id| client.name_database(Some(id))) .transpose()?; // SINGLE-FLIGHT: HomeSync asks every 20 s and a cancelled ask does not stop // the read it started, so a slow run was stacked beside the next tick's, // and the next — on 16 Oct 2026 four of them held every read connection // of the owner's Personal (readpool). One run walks the file at a time per // database; an ask that arrives while it runs JOINS it and is answered // with its answer, holding no connection while it waits. Joining, not // refusing: the `copy` rows (`records.get`/`records.list {table:"copy"}`) // are this same read, and a refusal there was a Debug failure on every // fresh phone whose first open overlapped Home's first tick (rigbyfix-c, // 22 Oct 2026). Keyed by this controller and the database it reads. let reads = database.map(str::to_string).or_else(|| client.attached_database()); let reading = format!("{:p}#{}", client, reads.as_deref().unwrap_or("")); let run = match InFlight::claim(&reading) { Claim::Join(flight) => return flight.answer(), Claim::Run(run) => run, }; let answer = walk(client); run.finish(&answer); answer } /// One run of [`read`]: the walk over this database's file a joined ask shares. fn walk(client: &ClientController) -> Result { let now_at = client.now(); let now = cotton_client::seams::iso(now_at); // Each Mac heard as Devices and Machines say it (295 rule 8): the one row // it writes about itself, read before this database's snapshot is taken. let presence = super::presence::household(client); client.with_file(|file| { let (facts, status) = client.database_sync_facts(file.workspace_id); let serving_id = serving_id(file)?; // This device as its Devices row names it: the key the server admitted // (`self_device_id`). On a phone `file.device_id` is the replica's // author id, a different id for the same phone, which drew it twice — // "A device · This device" beside its own named row (walker pass 4 // offline, row 2). A device not yet paired has only the author id. let this_id = client.self_device_id().unwrap_or_else(|| file.device_id.to_string()); let this_id = this_id.as_str(); let iso = |at| cotton_store::protocol::js::to_iso_string(at); let heard = facts.answered_at.and_then(iso); // The serving Mac's contact is one fact per Mac (295 rule 16). let mac_heard = facts.mac_answered_at.and_then(iso); let mut devices = known_devices(file, serving_id.as_deref())?; for copy in &mut devices { if let Some(reading) = presence.get(©.device.id) { copy.last_heard_at = cotton_core::device::presence::later(copy.last_heard_at.as_deref(), reading.heard_at.as_deref()); copy.as_of.clone_from(©.last_heard_at); } } if let Some(id) = serving_id .as_ref() .filter(|id| !devices.iter().any(|copy| ©.device.id == *id)) { devices.push(DeviceCopy { device: Device { id: id.clone(), name: String::new(), kind: DeviceKind::Other, serving: true, }, as_of: None, keeps: Some(Keeps::WholeFile), behind: Behind::default(), doing_now: None, last_heard_at: None, reachable: None, unreachable_since: None, }); } // A shared database can have device statements without approval rows. // Include the local identity even before its own approval row arrives. if !devices.iter().any(|copy| copy.device.id == this_id) { devices.push(DeviceCopy { device: Device { id: this_id.into(), name: String::new(), kind: DeviceKind::Other, serving: false, }, as_of: None, keeps: None, behind: Behind::default(), doing_now: None, last_heard_at: None, reachable: None, unreachable_since: None, }); } let changes_waiting = cotton_client::sync::cycle::current_pending(file.driver) .and_then(|n| u64::try_from(n).ok()) .ok_or("local pending changes could not be read")?; for copy in &mut devices { if copy.device.serving { copy.behind = Behind { changes: Some(0), ..Behind::default() }; // The device row survives a relaunch and can have newer // contact than this phone's last sync-loop observation. // Only this serving device supplies that evidence. let contact = latest_contact_at(copy.last_heard_at.as_deref(), mac_heard.as_deref()); copy.last_heard_at = contact.map(cotton_client::seams::iso); let failed = facts.mac_silent_since.and_then(chrono::DateTime::from_timestamp_millis); copy.reachable = heard_now(contact, failed, now_at); copy.unreachable_since = if copy.reachable == Some(false) { // The first pass that failed after the last contact; // a contact past the window with no failure seen // (no pass ran) is away from when the window closed. failed.filter(|at| contact.is_none_or(|heard| *at > heard)) .or_else(|| contact.map(|at| at + chrono::Duration::milliseconds(SERVING_CONTACT_WITHIN_MS))) .map(cotton_client::seams::iso) } else { None }; copy.as_of = copy.unreachable_since.clone().or_else(|| copy.last_heard_at.clone()); } if copy.device.id != this_id { continue; } copy.as_of = Some(now.clone()); copy.last_heard_at = Some(now.clone()); copy.reachable = Some(true); // This process is reading its own copy. copy.unreachable_since = None; copy.device.serving = false; copy.behind = Behind { // A catch-up still under way is not level, whatever its last // page counted: Me said "Up to date" while the cap over the // same copy said "syncing · 4 %" (walker 291). The one state // is the line's own. changes: if facts.catching_up || facts.copying { facts.remaining.filter(|left| *left > 0) } else { facts.remaining }, at_least: facts .remaining .is_some_and(|n| n >= cotton_core::constants::BEHIND_BY_CAP), oldest_age_seconds: None, }; copy.doing_now = Some(match status.as_ref().map(|status| status.state) { Some(cotton_client::sync::SyncState::Syncing) => DoingNow::CatchingUp, Some(cotton_client::sync::SyncState::Idle) => DoingNow::Idle, _ => DoingNow::Paused, }); } devices.sort_by(|a, b| a.device.id.cmp(&b.device.id)); let answer = SyncState { database: file.workspace_id.into(), as_of: heard.clone(), read_at: now.clone(), devices, this_device: ThisDevice { id: Some(this_id.to_string()), synced_at: facts.synced_at.and_then(iso), changes_waiting, storage_bytes: storage_bytes(file.driver, client.disk().as_ref())?, // No keep-fetch sweep asks a Mac for originals. bytes_wanted: None, }, }; let words = cotton_core::definitions::board::notice_words(); let template = words.get("sync_not_answering").and_then(Value::as_str).ok_or("missing sync reading")?; let line = cotton_core::rules::sync_state::not_answering_line(&answer.devices, template); let mut value = serde_json::to_value(answer).map_err(|e| e.to_string())?; value["line"] = line.map(Value::from).unwrap_or(Value::Null); Ok(value) }) } fn word(value: &impl serde::Serialize) -> Value { serde_json::to_value(value).unwrap_or(Value::Null) } /// `records.list {table:"copy"}`: this read's answer as one `copy` row per /// device holding the named database (definitions/copy.json says every /// word). This device's row also carries its own facts; a fact nobody /// observed is left out of the row, never filled in. pub fn copies( client: &ClientController, request: &Value, ) -> Result, crate::methods::MethodError> { // Me's one line while this run's schema moves go on (passivemove rule // 2): the database moving now, and how many of how many are done — typed // counts; copy.json says the words. let moving = cotton_client::moves::progress().map(|progress| MoveLine { database: super::databases::name_of(client, &progress.now).ok().flatten(), moved: progress.moved, of: progress.of, }); copies_said(client, request, moving.as_ref()) } /// `records.list {table:"schema_move"}` — what Me's move line opens: one row /// per database with a schema move to make in this run, in the order they /// move, with its state (`moving` the one now, `waiting` the ones after it, /// `moved` the ones done) and the tables it has left; schema_move.json says /// every word (passivemove rule 2). pub fn schema_moves(client: &ClientController) -> Vec { let mut now_said = false; cotton_client::moves::this_run_list() .into_iter() .map(|(id, done, left)| { let state = if done { "moved" } else if !now_said { now_said = true; "moving" } else { "waiting" }; let mut data = Map::new(); if let Some(name) = super::databases::name_of(client, &id).ok().flatten() { data.insert("name".into(), Value::from(name)); } data.insert("state".into(), Value::from(state)); if let Some(left) = left.filter(|left| left.begun && !left.tables.is_empty()) { data.insert("tables_left".into(), Value::from(left.tables.len())); } json!({ "id": id, "data": data, "deleted_at": Value::Null }) }) .collect() } /// Where this run's schema moves stand, as this device's copy row says it. #[derive(Debug, Clone, PartialEq, Eq)] struct MoveLine { database: Option, moved: usize, of: usize, } fn copies_said( client: &ClientController, request: &Value, moving: Option<&MoveLine>, ) -> Result, crate::methods::MethodError> { let unreadable = |error: String| crate::methods::MethodError::new("unreadable", error); // One database's copies: the list's `where.database`, a page's id // (`#`), else the shown database. let mut args = Map::new(); let from_id = request["ids"][0].as_str().and_then(|id| id.split_once('#')).map(|(database, _)| database); if let Some(database) = request["where"]["database"].as_str().or(from_id) { args.insert("database".into(), Value::from(database)); } let reading = read(client, &args).map_err(unreadable)?; let line = reading["line"].clone(); let answer: SyncState = serde_json::from_value(reading) .map_err(|error| unreadable(error.to_string()))?; Ok(copy_rows(&answer, &line, moving)) } fn copy_rows(answer: &SyncState, line: &Value, moving: Option<&MoveLine>) -> Vec { let here = answer.this_device.id.as_deref(); answer .devices .iter() .map(|copy| { let mut data = Map::new(); let mut put = |key: &str, value: Value| { if !value.is_null() { data.insert(key.into(), value); } }; let this = Some(copy.device.id.as_str()) == here; put("database", Value::from(answer.database.as_str())); put("name", Some(copy.device.name.trim()).filter(|name| !name.is_empty()).into()); put("kind", word(©.device.kind)); put( "role", Value::from(match (this, copy.device.serving) { (true, _) => "this_device", (false, true) => "serving", (false, false) => "copy", }), ); put("keeps", word(©.keeps)); if this { // This device's line is ONE state from typed sync/contact // evidence, never two joined. Me and the sync page say it // alike, through copy.json's slip. While a schema move is // under way that one state is the move: the database moving // now, and the count only when there is more than one. if let Some(moving) = moving { put("moving_database", moving.database.clone().into()); if moving.of > 1 { put("databases_moved", Value::from(moving.moved)); put("databases_to_move", Value::from(moving.of)); } } else { for (key, value) in ambient(answer, copy).columns() { put(key, value); } } } else { let behind = if copy.behind.at_least { "behind_at_least" } else { "behind" }; put(behind, copy.behind.changes.into()); // Idle is nothing to say on a line; any work is said. put("doing_now", word(©.doing_now.filter(|now| *now != DoingNow::Idle))); if copy.device.serving { put("not_answering", line.clone()); } } // This device is heard as it reads; its row says when it synced. if !this { put( "reach", copy.reachable .map(|up| if up { "reachable" } else { "unreachable" }) .into(), ); put("unreachable_since", copy.unreachable_since.clone().into()); put("last_heard_at", copy.last_heard_at.clone().into()); } if this { let own = &answer.this_device; if ambient(answer, copy) == Ambient::UpToDate { put("synced_at", own.synced_at.clone().into()); } put("bytes_wanted", own.bytes_wanted.into()); } json!({"id": format!("{}#{}", answer.database, copy.device.id), "data": data, "deleted_at": Value::Null}) }) .collect() } /// This device's one sync state. #[derive(Debug, PartialEq, Eq)] enum Ambient { /// Level, synced and the Mac heard now — the only time it is said. UpToDate, /// The Mac's last contact, said with its age ("Mac heard 13 min ago"): /// heard now but not level, or not heard now but within the window. MacHeard { at: String }, WaitingToSend(u64), /// Not heard within the window: since its last contact ("Mac not heard /// since 10:02 am"), or never heard at all. WaitingForMac { since: Option }, } impl Ambient { /// The one typed column that says this state; the definitions say it /// (copy.json, device.json, storage.json) under the same keys. fn columns(&self) -> [(&'static str, Value); 1] { match self { Ambient::WaitingForMac { since: Some(since) } => [("waiting_since", Value::from(since.as_str()))], Ambient::WaitingForMac { since: None } => [("ambient", Value::from("waiting_for_mac"))], Ambient::WaitingToSend(n) => [("changes_waiting", Value::from(*n))], Ambient::UpToDate => [("ambient", Value::from("up_to_date"))], Ambient::MacHeard { at } => [("mac_heard_at", Value::from(at.as_str()))], } } } /// This device's one sync state for the shown database, as its Devices card /// and page say it: the same state, wanted bytes and selected sync stamp as /// its Copy row and Me. An unreadable copy is refused rather than allowing /// an older local overlay to survive as a new answer. pub fn this_device_state(client: &ClientController) -> Result, crate::methods::MethodError> { // The sync state itself, never Me's move line: a card says the copy. let rows = copies_said(client, &json!({}), None)?; let own = rows.iter().find(|row| row["data"]["role"] == "this_device"); // Include nulls: a live overlay must clear an earlier state when the // next observation selects another one, including its historical stamp. let mut state: Map = AMBIENT_COLUMNS.iter() .chain(["bytes_wanted"].iter()) .map(|key| ((*key).into(), own.map(|row| row["data"][*key].clone()).unwrap_or(Value::Null))) .collect(); state.insert("last_synced".into(), own.map(|row| row["data"]["synced_at"].clone()).unwrap_or(Value::Null)); Ok(state) } /// The columns one of which says this device's state. pub const AMBIENT_COLUMNS: [&str; 4] = ["ambient", "changes_waiting", "waiting_since", "mac_heard_at"]; /// Only the serving copy's typed reachability proves it is unavailable. A /// paused local loop can mean a relaunch, not failed contact. "Up to date" /// is said only while the Mac is heard now; otherwise the Mac's contact is /// said with its age, and past the window as not heard since that contact /// (architect's offline-truth ruling, 17 Oct 2026, from the 293 walk) — /// never the read, failure-start or sync stamp. fn ambient(answer: &SyncState, own: &DeviceCopy) -> Ambient { let waiting = answer.this_device.changes_waiting; if own.device.serving { return if waiting == 0 { Ambient::UpToDate } else { Ambient::WaitingToSend(waiting) }; } let serving = answer.devices.iter().find(|copy| copy.device.serving && copy.device.id != own.device.id); let heard_at = serving.and_then(|copy| copy.last_heard_at.clone()); let within = heard_at.as_deref().is_some_and(|at| within_window(at, &answer.read_at)); match serving.and_then(|copy| copy.reachable) { Some(false) if within => Ambient::MacHeard { at: heard_at.unwrap_or_default() }, Some(false) => Ambient::WaitingForMac { since: heard_at }, _ if waiting > 0 => Ambient::WaitingToSend(waiting), Some(true) if own.behind.changes == Some(0) && answer.this_device.synced_at.is_some() => Ambient::UpToDate, Some(true) => heard_at.map_or(Ambient::WaitingForMac { since: None }, |at| Ambient::MacHeard { at }), // Nothing ever observed of the Mac: not heard yet — said, never left // blank and never "Up to date". None => Ambient::WaitingForMac { since: None }, } } /// Whether a contact stamp is within the heard window of `now`. fn within_window(at: &str, now: &str) -> bool { let parse = |stamp: &str| chrono::DateTime::parse_from_rfc3339(stamp).ok().map(|at| at.timestamp_millis()); matches!((parse(at), parse(now)), (Some(at), Some(now)) if now.saturating_sub(at) <= SERVING_CONTACT_WITHIN_MS) } /// Whether this device's own copy says the shown database's serving Mac is /// not reachable — `read.sync_state`'s `reachable` flag on the serving copy, /// the one source `media.ensure` asks. False when nothing was read. pub(crate) fn serving_away(client: &ClientController) -> bool { serving_not_heard(client).is_some() } /// The serving Mac this device does not hear now, as its last-heard instant /// (`Some(None)`: never heard) — the same `reachable` fact as /// [`serving_away`], so a failed pass after the last contact is not heard at /// once (`heard_now`). `None` when the Mac is heard, this device serves, or /// nothing could be read; a read that needs the Mac then asks it. pub(crate) fn serving_not_heard(client: &ClientController) -> Option> { let answer = read(client, &Map::new()).ok().and_then(|reading| serde_json::from_value::(reading).ok())?; let this = answer.this_device.id; answer .devices .into_iter() .find(|copy| copy.device.serving && copy.reachable == Some(false) && Some(copy.device.id.as_str()) != this.as_deref()) .map(|copy| copy.last_heard_at) } /// The outage this device sees now: the database's serving Mac stopped /// answering at `unreachable_since` and has not answered since. The Mac /// writes its own outages only once it is back, so while it is away this /// device's observation is the only row there is (walker's offline pass). /// Typed values only; outage.json says them. pub fn outage_now(client: &ClientController) -> Option { let rows = copies(client, &json!({})).ok()?; let serving = rows.into_iter().find(|row| { row["data"]["role"] == "serving" && row["data"]["reach"] == "unreachable" })?; outage_of(&serving["data"]) } /// The outage row for a serving copy row this device cannot reach. fn outage_of(data: &Value) -> Option { let since = data["unreachable_since"].as_str()?; // Typed values only: the Mac's name heads it and outage.json's // `phone_sees` says what it means, so the card is never a bare host and // a date (293 walk). `machine` is where a stored row was recorded; this // one was recorded nowhere but here. let mut out = Map::new(); out.insert("kind".into(), Value::from("unreachable")); out.insert("started_at".into(), Value::from(since)); out.insert("phone_sees".into(), Value::from("mac_not_heard")); if let Some(name) = data["name"].as_str() { out.insert("title".into(), Value::from(name)); } Some(json!({"id": format!("{OUTAGE_NOW}{}", data["database"].as_str().unwrap_or_default()), "table": "outage", "data": out, "deleted_at": Value::Null})) } /// The id prefix of [`outage_now`]'s row; no stored outage has it. pub const OUTAGE_NOW: &str = "now:"; /// The serving copy's credential id: the stored serving fact. pub(crate) fn serving_id(file: &ReadFile<'_>) -> Result, String> { Ok(cotton_store::serving::serving_fact(file.driver, file.workspace_id) .map_err(|e| e.to_string())? .map(|fact| fact.device_credential_id)) } /// The serving Mac's name, as `read.sync_state` names its serving device, /// inside a read the caller already holds. `None` when no serving device has /// a name. pub(crate) fn serving_name_in(file: &ReadFile<'_>) -> Option { let id = serving_id(file).ok()??; known_devices(file, Some(&id)) .ok()? .into_iter() .find(|copy| copy.device.serving) .map(|copy| copy.device.name.trim().to_string()) .filter(|name| !name.is_empty()) } /// Compare instants, not ISO spellings, and leave unreadable contact unknown. fn latest_contact_at( first: Option<&str>, second: Option<&str>, ) -> Option> { [first, second] .into_iter() .flatten() .filter_map(|at| chrono::DateTime::parse_from_rfc3339(at).ok()) .max() .map(|at| at.with_timezone(&chrono::Utc)) } /// Whether the serving Mac is HEARD now: its latest contact is within the /// window and no pass has failed since it. A failed pass after the last /// contact is the Mac not heard, at once — never a 20-minute-old answer /// standing for a Mac the relay cannot reach (293 walk, rows 13 and 149). /// Unknown when nothing was ever observed. fn heard_now( contact: Option>, failed: Option>, now: chrono::DateTime, ) -> Option { match (contact, failed) { (None, None) => None, (None, Some(_)) => Some(false), (Some(heard), failed) => Some( now.timestamp_millis().saturating_sub(heard.timestamp_millis()) <= SERVING_CONTACT_WITHIN_MS && failed.is_none_or(|at| at <= heard), ), } } fn known_devices(file: &ReadFile<'_>, serving: Option<&str>) -> Result, String> { let rows = file .driver .all( "SELECT d.device_id,d.name,d.platform,d.sampled_at,d.reported_state \ FROM cotton_devices d WHERE d.workspace_id=? AND d.scope='full' AND d.revoked_at IS NULL \ ORDER BY d.device_id,d.approved_at DESC,d.id DESC", &[Sql::Text(file.workspace_id.into())], ) .map_err(|e| e.to_string())?; let mut seen = BTreeSet::new(); let mut devices = Vec::new(); for row in rows { let id = row.text("device_id").unwrap_or_default(); if !seen.insert(id.to_string()) { continue; } let kind = DeviceKind::of_platform(row.text("platform").unwrap_or_default()); let report: Option = row .text("reported_state") .and_then(|raw| serde_json::from_str(raw).ok()); let heard = latest_contact_at( report.as_ref().and_then(|report| report.last_exchange_at.as_deref()), row.text("sampled_at"), ).map(cotton_client::seams::iso); let keeps = retention(file, id, kind, Some(id) == serving)?; devices.push(DeviceCopy { device: Device { id: id.into(), name: row.text("name").unwrap_or_default().into(), kind, serving: Some(id) == serving, }, as_of: heard.clone(), keeps, behind: Behind::default(), doing_now: None, last_heard_at: heard, reachable: None, unreachable_since: None, }); } let statements = file.driver.all( "SELECT device_key,device_name FROM cotton_device_statements ORDER BY _hlc DESC,id DESC", &[], ).map_err(|e| e.to_string())?; for row in statements { let id = row.text("device_key").unwrap_or_default(); if seen.contains(id) || cotton_store::membership::device(file.driver, id) .map_err(|e| e.to_string())? .is_none() { continue; } seen.insert(id.to_string()); devices.push(DeviceCopy { device: Device { id: id.into(), name: row.text("device_name").unwrap_or_default().into(), kind: DeviceKind::Other, serving: Some(id) == serving, }, as_of: None, keeps: None, behind: Behind::default(), doing_now: None, last_heard_at: None, reachable: None, unreachable_since: None, }); } Ok(devices) } fn retention( file: &ReadFile<'_>, id: &str, kind: DeviceKind, serving: bool, ) -> Result, String> { use cotton_store::storage_rules::{self, KeepRule, MacKeeps}; if serving { return Ok(Some(Keeps::WholeFile)); } Ok(match kind { DeviceKind::Mac | DeviceKind::Linux | DeviceKind::Windows => Some( match storage_rules::mac_keeps(file.driver, file.workspace_id, id) .map_err(|e| e.to_string())? { MacKeeps::Everything => Keeps::WholeFile, MacKeeps::RowsOnly => Keeps::RecordsOnly, MacKeeps::PerTool => Keeps::RecordsAndMedia, }, ), DeviceKind::Phone | DeviceKind::Tablet => { let mut opened_only = true; for tool in storage_rules::BYTE_TOOLS .iter() .chain(storage_rules::MESSAGE_SOURCES.iter()) { opened_only &= storage_rules::byte_rule(file.driver, file.workspace_id, id, tool) .map_err(|e| e.to_string())? == KeepRule::OnlyOpened; } Some(if opened_only { Keeps::RecordsOnly } else { Keeps::RecordsAndMedia }) } DeviceKind::Other => None, }) } fn storage_bytes(db: &Driver, disk: &dyn super::disk::Disk) -> Result, String> { let paths = db .all("PRAGMA database_list", &[]) .map_err(|e| e.to_string())?; let Some(path) = paths .iter() .find(|row| row.text("name") == Some("main")) .and_then(|row| row.text("file")) .filter(|path| !path.is_empty()) else { return Ok(None); }; let mut total = Some(0u64); let media = db .all( "SELECT DISTINCT local_path FROM _media WHERE local_path IS NOT NULL", &[], ) .map_err(|e| e.to_string())?; let mut files: BTreeSet = [path.to_string(), format!("{path}-wal")] .into_iter() .collect(); files.extend( media .iter() .filter_map(|row| row.text("local_path").map(str::to_string)), ); for path in files { total = total .zip(disk.file_size(Path::new(&path))) .map(|(sum, bytes)| sum.saturating_add(bytes)); } Ok(total) } #[cfg(test)] #[path = "sync_state_tests.rs"] mod tests; /// The runs of [`read`] in flight, by database — see [`read`]. static IN_FLIGHT: std::sync::Mutex>> = std::sync::Mutex::new(std::collections::BTreeMap::new()); /// One run in flight: the answer its joiners wait for. struct Flight { /// The thread walking the file: an ask on that same thread runs its own /// walk rather than wait on itself for ever. walker: std::thread::ThreadId, answer: std::sync::Mutex>, done: std::sync::Condvar, /// How many asks are waiting on it now — a test waits for its joiner. waiting: std::sync::atomic::AtomicUsize, } /// A run's answer, with the read pool's reason when the pool refused it, so a /// joiner's refusal is typed the way the run's was (`methods::could_not_read`). #[derive(Clone)] struct Answer { result: Result, refused: Option, } impl Flight { /// Wait for the run to end and answer what it answered. fn answer(&self) -> Result { self.waiting.fetch_add(1, std::sync::atomic::Ordering::SeqCst); let mut answer = self.answer.lock().unwrap_or_else(|e| e.into_inner()); while answer.is_none() { answer = self.done.wait(answer).unwrap_or_else(|e| e.into_inner()); } self.waiting.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); let Answer { result, refused } = answer.clone().expect("the run answered"); if let Some(refused) = refused { cotton_client::replica::note_read_refusal(refused); } result } } /// What an ask does: walk the file itself, or join the run already walking it. enum Claim { Run(InFlight), Join(std::sync::Arc), } /// One run's claim on its database in [`IN_FLIGHT`]; it answers its joiners /// when it finishes, and lets go when it drops — a run that panicked answers /// them with that, never leaving one waiting. struct InFlight { reading: String, flight: std::sync::Arc, } impl InFlight { fn claim(database: &str) -> Claim { let mut running = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner()); if let Some(flight) = running.get(database) { if flight.walker != std::thread::current().id() { return Claim::Join(flight.clone()); } // The walker asking again from inside its own walk: walking it // again is slow, waiting on itself is a hang. It walks, unshared. let flight = std::sync::Arc::new(Flight::new()); return Claim::Run(InFlight { reading: String::new(), flight }); } let flight = std::sync::Arc::new(Flight::new()); running.insert(database.to_owned(), flight.clone()); Claim::Run(InFlight { reading: database.to_owned(), flight }) } /// The run's answer: handed to every ask that joined it. fn finish(&self, result: &Result) { let refused = result .is_err() .then(cotton_client::replica::peek_read_refusal) .flatten(); self.answer(Answer { result: result.clone(), refused }); } fn answer(&self, answer: Answer) { let mut slot = self.flight.answer.lock().unwrap_or_else(|e| e.into_inner()); slot.get_or_insert(answer); self.flight.done.notify_all(); } } impl Flight { fn new() -> Flight { Flight { walker: std::thread::current().id(), answer: std::sync::Mutex::new(None), done: std::sync::Condvar::new(), waiting: std::sync::atomic::AtomicUsize::new(0), } } } impl Drop for InFlight { fn drop(&mut self) { if !self.reading.is_empty() { let mut running = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner()); if running.get(&self.reading).is_some_and(|flight| std::sync::Arc::ptr_eq(flight, &self.flight)) { running.remove(&self.reading); } } // A run that ended without an answer (a panic in its walk). self.answer(Answer { result: Err("read.sync_state ended without an answer".into()), refused: None, }); } } #[cfg(test)] mod single_flight { use serde_json::{json, Map, Value}; use super::{Claim, InFlight}; fn running(reading: &str) -> InFlight { match InFlight::claim(reading) { Claim::Run(run) => run, Claim::Join(_) => panic!("nothing else runs for this database"), } } /// Hold `run` until an ask on another thread is waiting on it. fn until_joined(run: &InFlight) { while run.flight.waiting.load(std::sync::atomic::Ordering::SeqCst) == 0 { std::thread::yield_now(); } } /// RULE: an ask for `read.sync_state` that arrives while a run for the same /// database is in flight JOINS that run and is answered with its answer — /// never a second walk beside it (16 Oct 2026, HomeSync's 20 s ticks stacked /// four walks on every read connection of the owner's Personal), and never a /// refusal (22 Oct 2026, every fresh phone's Debug listed the refused ask). #[test] fn an_ask_while_a_run_is_in_flight_joins_it() { let (_dir, client) = crate::shell::client::phone_tests::attached(); let reading = format!("{:p}#{}", &*client, client.attached_database().unwrap_or_default()); let run = running(&reading); let joiner = { let client = client.clone(); std::thread::spawn(move || super::read(&client, &Map::new())) }; until_joined(&run); // The run's answer, and nothing a walk of the file could have made: // the joiner answering it proves it walked nothing itself. run.finish(&Ok(json!({ "the_run": true }))); drop(run); assert_eq!(joiner.join().unwrap(), Ok(json!({ "the_run": true }))); assert!(super::read(&client, &Map::new()).unwrap()["devices"].is_array(), "the next ask after it walks"); } /// RULE: `records.get {table:"copy"}` answers its row while Home's /// `read.sync_state` runs for the same database. The copy rows are that /// same read, so its single-flight refused them — "records.get failed: /// could_not_read: read.sync_state is still running" on a fresh phone's /// Debug page, whenever the first open overlapped Home's first tick /// (rigbyfix-c, 22 Oct 2026). A first-launch read never fails. #[test] fn a_copy_row_is_read_while_the_sync_state_runs() { let (_dir, client) = crate::shell::client::phone_tests::attached(); let listed = crate::phone::records::settings_tables::call(&client, "records.list", &json!({ "table": "copy" })) .expect("copy is a settings table") .expect("the copy rows are read"); let id = listed["records"][0]["id"].as_str().expect("this phone's copy row").to_string(); let reading = format!("{:p}#{}", &*client, client.attached_database().unwrap_or_default()); let run = running(&reading); let ask = { let client = client.clone(); let id = id.clone(); std::thread::spawn(move || { crate::phone::records::settings_tables::call(&client, "records.get", &json!({ "table": "copy", "id": id })) .expect("copy is a settings table") }) }; until_joined(&run); let answer = super::walk(&client); run.finish(&answer); drop(run); let row = ask.join().unwrap().expect("a copy row read while sync_state runs"); assert_eq!(row["id"], Value::from(id)); } }