//! Read each local replica's own stamp without attaching, migrating or writing it.use cotton_client::layout::Layout;use cotton_core::device::reported_state::{DatabaseFileState, DiskHolding, NotCounted, Parked};use std::path::Path;pub(crate) fn sqlite_header(path: &Path) -> bool {use std::io::Read;letmut header=[0;16]; std::fs::File::open(path).and_then(|mut file|file.read_exact(&mut header)).is_ok() && &header==b"SQLite format 3\0"}fn open_read(path: &Path) -> Result<rusqlite::Connection, String> {// SQLite may recover or discard an invalid WAL while opening. A file// without even its header must be diagnosed without touching sidecars.if !sqlite_header(path) { returnErr("The file has no readable SQLite header.".into()); }let database = rusqlite::Connection::open_with_flags( path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, ).map_err(|error| error.to_string())?; database.busy_timeout(std::time::Duration::ZERO).map_err(|error| error.to_string())?;Ok(database)}fn stamp_of(database: &rusqlite::Connection) -> Result<u32, String> {let version = database.query_row("PRAGMA user_version", [], |row| row.get::<_, i64>(0)) .map_err(|error| error.to_string())?; u32::try_from(version).map_err(|error| error.to_string())}pub(crate) fn stamp(path: &Path) -> Result<u32, String> { stamp_of(&open_read(path)?)}/// The bytes a file holds, `0` when there is none.fn file_bytes(path: &Path) -> u64 { std::fs::symlink_metadata(path).map_or(0, |meta| meta.len())}/// The bytes everything under `path` holds; a link is never followed.fn tree_bytes(path: &Path) -> u64 {letOk(meta) = std::fs::symlink_metadata(path) else { return0 };if !meta.is_dir() {returnif meta.file_type().is_symlink() { 0 } else { meta.len() }; } std::fs::read_dir(path) .map(|entries| entries.flatten().map(|entry| tree_bytes(&entry.path())).sum()) .unwrap_or(0)}/// What the database's own media ledger records this device holds: the/// originals in the media store and the thumbnails in the cache. Both stores/// are shared by every database, so the ledger is what divides them.fn ledger_bytes(database: &rusqlite::Connection) -> Option<(u64, u64)> { database .query_row("SELECT COALESCE(SUM(CASE WHEN tier IS NOT 'thumb' THEN size_bytes END), 0), COALESCE(SUM(CASE WHEN tier = 'thumb' THEN size_bytes END), 0) FROM _media WHERE local_path IS NOT NULL", [], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)), ) .ok() .map(|(media, thumbs)| (u64::try_from(media).unwrap_or(0), u64::try_from(thumbs).unwrap_or(0)))}/// WHAT ONE DATABASE HOLDS ON THIS DEVICE'S DISK: its file and log measured,/// everything else in its folder and its removed refused copies as retained/// copies, and its media as its ledger records them.fn holding(layout: &Layout, id: &str, path: &Path, ledger: Option<(u64, u64)>) -> DiskHolding {let own = |name: &std::ffi::OsStr| ["replica.db", "replica.db-wal", "replica.db-shm"].iter().any(|own| name == *own);let beside: u64 = path .parent() .and_then(|folder| std::fs::read_dir(folder).ok()) .map(|entries| entries.flatten().filter(|entry| !own(&entry.file_name())).map(|entry| tree_bytes(&entry.path())).sum()) .unwrap_or(0);letmut wal = path.as_os_str().to_os_string(); wal.push("-wal");DiskHolding { replica_bytes: file_bytes(path), wal_bytes: file_bytes(Path::new(&wal)),// Copies kept aside whole because they held changes not yet sent (QUEUE BAD OP 4) count here too. retained_copy_bytes: beside + tree_bytes(&layout.refused_copies_dir(id)) + cotton_client::copy_keep::kept_bytes(layout, Some(id)), media_bytes: ledger.map(|(media, _)| media), thumbnail_bytes: ledger.map(|(_, thumbs)| thumbs), }}/// The sealed rows a copy holds parked, by why, off the parks' keys alone; `None` when it holds none, and/// [`Parked::Unknown`] while they cannot be counted cheaply (FIRST SYNC 8: the parks' keys an older build left are/// still being filled), or could not be read: never a false zero.pub(crate) fn parked_rows(db: &rusqlite::Connection) -> Option<Parked> {let unknown = Some(Parked::Unknown(NotCounted::Unknown));letOk(Some(counts)) = cotton_client::seal::parked_by_code(db) else { return unknown };letmut parked = cotton_core::device::reported_state::ParkedRows::default();for (code, n) in counts {let slot = match code.as_str() { cotton_client::seal::SEAL_KEY_MISSING => &mut parked.waiting_key, cotton_client::seal::WAITING_PARENT => &mut parked.waiting_parent, cotton_client::seal::FOLD_REFUSED => &mut parked.refused,"seal_does_not_open" => &mut parked.former_database, _ => &mut parked.other, }; *slot += n; } (parked != Default::default()).then_some(Parked::Counted(parked))}/// EVERY PARK THIS COPY HOLDS, by its code (PHONE MEASURES), kinds and counts only: a sealed row's by its seal code,/// off the parks' keys (none while they are not counted yet: [`parked_rows`] says `unknown` then), and a change the/// sync set aside by `<direction>_<code>`: the code its reason begins with, else its class (`newer-shape` for a/// newer schema). Never a reason's words.pub(crate) fn parked_by_code(db: &rusqlite::Connection) -> std::collections::BTreeMap<String, u64> {letmut counts = std::collections::BTreeMap::new();ifletOk(Some(sealed)) = cotton_client::seal::parked_by_code(db) {for (code, n) in sealed { *counts.entry(code).or_insert(0) += n; } }let set_aside = db.prepare("SELECT coalesce(direction, 'pull'), class, CASE WHEN instr(coalesce(reason, ''), ':') > 0 THEN substr(reason, 1, instr(reason, ':') - 1) END, count(*) FROM _parked GROUP BY 1, 2, 3", );ifletOk(mut statement) = set_aside {let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, Option<String>>(2)?, row.get::<_, i64>(3)?)));for (direction, class, code, n) in rows.into_iter().flatten().flatten() {let named = |text: &str| !text.is_empty() && text.len() <= 40 && text.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');let code = code.map(|code| code.trim().to_string()).filter(|code| named(code)).unwrap_or_else(|| class.replace('-', "_")); *counts.entry(format!("{}_{code}", direction.replace('-', "_"))).or_insert(0) += u64::try_from(n).unwrap_or(0); } } counts}pub(crate) fn states(layout: &Layout) -> Vec<DatabaseFileState> {letOk(entries) = std::fs::read_dir(layout.client_dir()) else { returnVec::new() };letmut states = Vec::new();for entry in entries.flatten() {let path = entry.path().join("replica.db");if !path.is_file() { continue; }letSome(id) = entry.file_name().to_str().map(str::to_string) else { continue };let opened = open_read(&path);let (schema_version, problem) = match opened.as_ref().map_err(String::clone).and_then(stamp_of) {Ok(version) => (Some(version), None),Err(reason) => (None, Some(reason)), };let ledger = opened.as_ref().ok().and_then(ledger_bytes);let parked = opened.as_ref().ok().and_then(|db| parked_rows(db));let by_code = opened.as_ref().ok().map(parked_by_code).unwrap_or_default();let first_sync = cotton_client::first_sync::kept(&path); drop(opened); states.push(DatabaseFileState { database_id: id.clone(), filename: format!("{id}/replica.db"), schema_version, problem, disk: Some(holding(layout, &id, &path, ledger)), check: crate::phone::file_check::kept(&path), parked, park_fill: crate::phone::seal::fill_holds(&path), parked_by_code: by_code, first_sync, }); } states.sort_by(|left, right| left.database_id.cmp(&right.database_id)); states}pub(crate) fn repositories(_: &Layout) -> Option<cotton_core::device::reported_state::RepositoryReadiness> { None }#[cfg(test)]mod tests {usesuper::*;/// RULE: Report every replica's own WAL-aware schema stamp, including a lagging or unreadable file, without moving it; one build's schema number cannot describe all copies on a phone. #[test]fn reports_each_files_stamp_without_creating_or_moving_files() {let dir = tempfile::tempdir().unwrap();let layout = Layout::new(dir.path());let current = layout.replica("current");let old = layout.replica("old");let corrupt = layout.replica("corrupt");for path in [¤t, &old, &corrupt] { std::fs::create_dir_all(path.parent().unwrap()).unwrap(); }let current_db = rusqlite::Connection::open(¤t).unwrap(); current_db.execute_batch(&format!("PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; PRAGMA user_version={}", cotton_store::migrate::SCHEMA_VERSION)).unwrap();let old_db = rusqlite::Connection::open(&old).unwrap(); old_db.execute_batch("PRAGMA user_version=93").unwrap(); std::fs::write(&corrupt, b"a synthetic unreadable file").unwrap();let before = std::fs::read(&old).unwrap();let reported = states(&layout); assert_eq!(reported.iter().find(|file| file.database_id == "current").unwrap().schema_version, Some(cotton_store::migrate::SCHEMA_VERSION)); assert_eq!(reported.iter().find(|file| file.database_id == "old").unwrap().schema_version, Some(93));let refused = reported.iter().find(|file| file.database_id == "corrupt").unwrap(); assert!(refused.schema_version.is_none() && refused.problem.is_some()); assert_eq!(std::fs::read(&old).unwrap(), before, "reporting did not move the old copy"); assert!(stamp(&layout.replica("missing")).is_err()); assert!(!layout.replica("missing").exists(), "diagnostics never creates a replica"); drop((current_db, old_db)); }/// RULE: Each database's state says what it holds on this device's disk — its replica and its write-ahead log measured, the copy set aside for an update, a download and its removed refused copies as retained copies, and its originals and thumbnails as its own media ledger records them — so the serving Mac says what a phone holds without guessing (row 8, 22 Oct 2026). #[test]fn each_database_says_what_it_holds_on_disk() {let dir = tempfile::tempdir().unwrap();let layout = Layout::new(dir.path());let path = layout.replica("synthetic"); std::fs::create_dir_all(path.parent().unwrap()).unwrap();let db = rusqlite::Connection::open(&path).unwrap(); db.execute_batch("PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; CREATE TABLE _media(key TEXT PRIMARY KEY, size_bytes INTEGER NOT NULL, local_path TEXT, tier TEXT); INSERT INTO _media VALUES ('a', 3000, '/synthetic/media/a', 'original'), ('b', 500, '/synthetic/media/b', NULL), ('c', 70, '/synthetic/thumbs/c', 'thumb'), ('d', 9999, NULL, 'original');", ).unwrap(); std::fs::write(path.with_file_name("replica.db.before-update"), vec![0; 1234]).unwrap(); std::fs::write(path.with_file_name("replica.db.download"), vec![0; 66]).unwrap();let refused = layout.refused_copies_dir("synthetic").join("synthetic-token"); std::fs::create_dir_all(&refused).unwrap(); std::fs::write(refused.join("replica.db"), vec![0; 4000]).unwrap(); std::fs::write(refused.join("replica.db-wal"), vec![0; 100]).unwrap();let reported = states(&layout);let disk = reported[0].disk.clone().expect("measured"); assert_eq!(disk.replica_bytes, std::fs::metadata(&path).unwrap().len());let wal = std::fs::metadata(path.with_file_name("replica.db-wal")).unwrap().len(); assert!(wal > 0, "the writes sit in the log"); assert_eq!(disk.wal_bytes, wal); assert_eq!(disk.retained_copy_bytes, 1234 + 66 + 4000 + 100); assert_eq!(disk.media_bytes, Some(3500), "originals held; one not on this device"); assert_eq!(disk.thumbnail_bytes, Some(70));// A file whose ledger cannot be read still says its files.let unreadable = layout.replica("unreadable"); std::fs::create_dir_all(unreadable.parent().unwrap()).unwrap(); std::fs::write(&unreadable, b"a synthetic unreadable file").unwrap();let unreadable = states(&layout).into_iter().find(|file| file.database_id == "unreadable").unwrap();let disk = unreadable.disk.expect("measured"); assert_eq!((disk.replica_bytes, disk.media_bytes, disk.thumbnail_bytes), (27, None, None)); drop(db); }}#[cfg(test)]mod parked_tests {/// RULE (FIRST SYNC 6): a copy's parked sealed rows are counted by why, rows waiting for their parent apart from/// the refused, so a device's reported state never reads a waiting mail as an error. #[test]fn parked_rows_count_waiting_for_a_parent_apart_from_refused() {use cotton_client::seal::Note;let db = rusqlite::Connection::open_in_memory().expect("a file"); assert_eq!(super::parked_rows(&db), None, "no seal state: nothing parked");let park = |id: &str, code: &str| Note::Parked { table: "email".into(), id: id.into(), code: code.into(), reason: "invented".into(), row: serde_json::json!({}), at: "2026-11-26T10:00:00Z".into() }; cotton_client::seal::write_notes(&db, &[ park("e-1", cotton_client::seal::SEAL_KEY_MISSING), park("e-2", "seal_does_not_open"), park("e-3", "x"), park("e-4", "x"), park("e-5", "x"), ]).expect("parked"); cotton_client::seal::write_notes(&db, &[Note::Waiting { table: "email".into(), id: "e-3".into(), mark: 0 },Note::Waiting { table: "email".into(), id: "e-4".into(), mark: 0 },Note::Refused { table: "email".into(), id: "e-5".into() }, ]).expect("noted");letSome(super::Parked::Counted(parked)) = super::parked_rows(&db) else { panic!("counted") };// A former database's key (`seal_does_not_open`) is counted apart since PHONE MEASURES. assert_eq!((parked.waiting_key, parked.waiting_parent, parked.refused, parked.former_database, parked.other), (1, 2, 1, 1, 0)); assert_eq!(serde_json::to_value(&parked).expect("json"), serde_json::json!({"waitingKey": 1, "waitingParent": 2, "refused": 1, "formerDatabase": 1, "other": 0})); }/// RULE (FIRST SYNC 8, the coordinator's review of FIRST SYNC 7 (1)): a copy whose parks an older build made and/// whose parks' keys are still being filled reports its parks as `"unknown"`, a value of its own, never as none/// (a phone holding 280,000 parks read as holding none); once filled, they are counted. #[test]fn parks_not_yet_counted_are_reported_unknown_never_none() {let dir = tempfile::tempdir().expect("a folder");let path = dir.path().join("replica.db"); {let db = rusqlite::Connection::open(&path).expect("a file");// The seal state as an older build left it: parks, and no parks' keys. db.execute_batch("CREATE TABLE _seal (tbl TEXT NOT NULL, row_id TEXT NOT NULL, sealed INTEGER NOT NULL, dek_enc TEXT, seal_v INTEGER, version INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID; CREATE TABLE _seal_parked (tbl TEXT NOT NULL, row_id TEXT NOT NULL, code TEXT NOT NULL, reason TEXT NOT NULL, row TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID;", ) .expect("old state");letmut put = db.prepare("INSERT INTO _seal_parked VALUES ('email', ?1, 'seal_key_missing', 'invented', '{}', '2026-11-26T10:00:00Z')").expect("insert");for n in0..(cotton_client::seal::PARKS_INLINE + 10) { put.execute([format!("invented-{n:06}")]).expect("a park"); } }let read = || rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).expect("read"); assert_eq!(super::parked_rows(&read()), Some(super::Parked::Unknown(super::NotCounted::Unknown)), "an older build's parks, not counted: unknown"); assert_eq!(serde_json::to_value(super::parked_rows(&read())).expect("json"), serde_json::json!("unknown"));// This build's first note makes the keys; too many parks to fill at once, so still unknown until the slices.let db = rusqlite::Connection::open(&path).expect("write"); cotton_client::seal::write_notes(&db, &[]).expect("state"); assert_eq!(super::parked_rows(&read()), Some(super::Parked::Unknown(super::NotCounted::Unknown)), "being filled: unknown");while !cotton_client::seal::fill_park_keys(&db, std::time::Duration::from_secs(5)).expect("fill") {}letSome(super::Parked::Counted(parked)) = super::parked_rows(&read()) else { panic!("counted once filled") }; assert_eq!(parked.waiting_key, (cotton_client::seal::PARKS_INLINE + 10) as u64); }/// RULE (PHONE MEASURES): every park a copy holds is counted by its code, kinds and counts only: a sync's set-aside/// change by direction and the code its reason begins with, else its class (a newer schema), never its words. #[test]fn every_park_is_counted_by_its_code() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("replica.db");let db = cotton_store::Driver::open(&path).unwrap(); cotton_store::create::apply_schema(&db).unwrap(); db.exec("INSERT INTO _parked (op_id, direction, class, reason, tbl, row_id) VALUES ('a', 'pull', 'waiting', 'author_unknown: an invented author', 'cotton_notes', 'n-1'), ('b', 'pull', 'waiting', 'author_unknown: another', 'cotton_notes', 'n-2'), ('c', 'pull', 'newer-shape', 'WordsOf A NewerBuild', 'cotton_notes', 'n-3'), ('d', 'push', 'conflict', 'bad_column: no such column', 'cotton_notes', 'n-4')", ) .unwrap(); drop(db);let read = rusqlite::Connection::open(&path).unwrap();let counts = super::parked_by_code(&read); assert_eq!(counts.get("pull_author_unknown"), Some(&2), "{counts:?}"); assert_eq!(counts.get("pull_newer_shape"), Some(&1), "{counts:?}"); assert_eq!(counts.get("push_bad_column"), Some(&1), "{counts:?}"); assert!(counts.keys().all(|code| code.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')), "codes only: {counts:?}"); }}