Cotton code
244 lines · 12.2 KB · RustRaw
//! A copy's own check, in the background (SCHEMA 155 REVIEW, 26 Nov 2026): since an additive move no longer reads//! the whole file at the open (`shape_move` `made_only`), each copy on this device is read whole here instead, by//! `PRAGMA quick_check` on a read-only connection beside the writer, so nothing a person does waits on it. It runs//! once for each build of this core and otherwise once a week, on the pass after a sync, and its verdict is kept//! beside the copy (`file-check.json`) for the device's reported state (`database_files::states`): what a support//! look reads to see whether a copy is whole.//!//! 2.2 s over 110,000 mails (1.7 GB) on the box (26 Nov 2026).use std::path::{Path, PathBuf};use std::time::Duration;use cotton_core::device::reported_state::{CopySizes, FileCheck};use crate::shell::client::ClientController;/// The file the verdict is kept in, beside the copy.pub const FILE: &str = "file-check.json";/// How long a verdict stands for one build of this core.pub const EVERY: Duration = Duration::from_secs(7 * 24 * 60 * 60);/// This core's build, as a verdict names it.pub fn this_build() -> &'static str {    env!("COTTON_BUILD_CRATES_TREE")}fn kept_at(replica: &Path) -> PathBuf {    replica.with_file_name(FILE)}/// The verdict kept for the copy at `replica`, if one was.pub fn kept(replica: &Path) -> Option<FileCheck> {    serde_json::from_slice(&std::fs::read(kept_at(replica)).ok()?).ok()}/// Whether the copy at `replica` is due a check at `now_ms`: never checked, checked by another build, or a week ago.pub fn due(replica: &Path, now_ms: i64) -> bool {    match kept(replica) {        None => true,        Some(check) => check.build != this_build() || now_ms - check.at_ms >= EVERY.as_millis() as i64,    }}/// Check the copy at `replica` now, on its own read-only connection, and keep the verdict: `ok`, SQLite's first/// words of what is wrong, or why the check itself could not run (`not checked: …`: a file that will not open, or/// SQLITE_CORRUPT as an error rather than a row). Each is kept, so a copy that fails is asked again on the weekly rule,/// never after every sync (INDEX LATER 2 REVIEW). Answers an error only when the verdict could not be kept.pub fn check(replica: &Path, now_ms: i64) -> Result<FileCheck, String> {    let started = std::time::Instant::now();    let verdict = match read(replica) {        Ok(said) if said == ["ok"] => "ok".to_string(),        Ok(said) => said.join("; "),        Err(why) => format!("{NOT_CHECKED}{why}"),    };    let took_ms = started.elapsed().as_millis() as u64;    // Measured only in a copy that is whole: a page the check refused may stop the read part way.    let sizes = (verdict == "ok").then(|| sizes(replica)).and_then(|measured| match measured {        Ok(sizes) => Some(sizes),        Err(why) => {            tracing::warn!("file check: the copy's sizes could not be read — {why}");            None        }    });    let check = FileCheck { build: this_build().to_string(), at_ms: now_ms, verdict: verdict.chars().take(400).collect(), took_ms, sizes };    // not a copy: the file check's verdict beside the copy.    std::fs::write(kept_at(replica), serde_json::to_vec(&check).map_err(|error| error.to_string())?).map_err(|error| error.to_string())?;    Ok(check)}/// How a verdict begins when the check itself could not run.pub const NOT_CHECKED: &str = "not checked: ";fn read(replica: &Path) -> Result<Vec<String>, String> {    let reader = cotton_store::Driver::open_reader(replica).map_err(|error| error.to_string())?;    let rows = reader.all("PRAGMA quick_check(8)", &[]).map_err(|error| error.to_string())?;    Ok(rows.iter().filter_map(|row| row.text("quick_check").map(str::to_string)).collect())}/// The parks' tables: their indexes count with them.const PARK_TABLES: &[&str] = &["_seal_parked", "_seal_park_keys", "_parked"];/// WHAT THE COPY AT `replica` HOLDS, by kind (PHONE MEASURES): every page read once (`dbstat`), each b-tree put/// with its kind by `sqlite_schema`: a search index's (`fts_*`) and a park's with their own indexes, `_writes` apart/// from its indexes, every other index together, the person's tables, the rest of the copy's bookkeeping, and the/// pages free. Names and sizes only; no row is read.pub fn sizes(replica: &Path) -> Result<CopySizes, String> {    let started = std::time::Instant::now();    let reader = cotton_store::Driver::open_reader(replica).map_err(|error| error.to_string())?;    let rows = reader        .all(            "SELECT d.name AS name, coalesce(s.type, '') AS type, coalesce(s.tbl_name, d.name) AS tbl, d.bytes AS bytes             FROM (SELECT name, sum(pgsize) AS bytes FROM dbstat GROUP BY name) d LEFT JOIN sqlite_schema s ON s.name = d.name",            &[],        )        .map_err(|error| error.to_string())?;    let mut sizes = CopySizes::default();    for row in &rows {        let (name, kind, table) = (row.text("name").unwrap_or_default(), row.text("type").unwrap_or_default(), row.text("tbl").unwrap_or_default());        let bytes = u64::try_from(row.int("bytes").unwrap_or(0)).unwrap_or(0);        let slot = if table.starts_with("fts_") {            &mut sizes.search        } else if PARK_TABLES.contains(&table) {            &mut sizes.parked        } else if kind == "index" || name.starts_with("sqlite_autoindex_") {            &mut sizes.indexes        } else if table == "_writes" {            &mut sizes.writes        } else if table.starts_with('_') || table.starts_with("sqlite_") {            &mut sizes.other        } else {            &mut sizes.rows        };        *slot += bytes;    }    let pragma = |name: &str| reader.get(&format!("PRAGMA {name}"), &[]).ok().flatten().and_then(|row| row.int(name)).unwrap_or(0);    sizes.free = u64::try_from(pragma("freelist_count") * pragma("page_size")).unwrap_or(0);    sizes.took_ms = started.elapsed().as_millis() as u64;    Ok(sizes)}/// The pass after a sync: the attached copy, checked when it is due, and only while the app is away (it reads the/// whole file: 2.2 s at his size, on a phone's disk beside a person's own reads, INDEX LATER 2 REVIEW).pub fn carry(client: &ClientController) -> Option<FileCheck> {    carry_when(client, crate::phone::trim::is_away())}/// [`carry`], with whether nobody is waiting on the copy (the processing job: always).pub fn carry_when(client: &ClientController, away: bool) -> Option<FileCheck> {    if !away {        return None;    }    let database = client.attached_database()?;    let replica = client.layout().replica(&database);    let now = chrono::Utc::now().timestamp_millis();    if !due(&replica, now) {        return None;    }    match check(&replica, now) {        Ok(check) => {            if check.verdict.starts_with(NOT_CHECKED) {                tracing::warn!("file check: {}", check.verdict);            } else if check.verdict == "ok" {                tracing::info!("file check: the copy is whole ({} ms)", check.took_ms);            } else {                tracing::warn!("file check: the copy is not whole — {}", check.verdict);            }            Some(check)        }        Err(refusal) => {            tracing::warn!("file check: its verdict could not be kept — {refusal}");            None        }    }}#[cfg(test)]mod tests {    use super::*;    /// RULE (SCHEMA 155 REVIEW): a copy is checked on a read-only connection once per build and otherwise weekly,    /// and the verdict is kept beside it.    #[test]    fn a_copy_is_checked_once_a_build_and_weekly() {        let dir = tempfile::tempdir().unwrap();        let replica = dir.path().join("replica.db");        let db = cotton_store::Driver::open(&replica).unwrap();        cotton_store::create::apply_schema(&db).unwrap();        drop(db);        assert!(due(&replica, 1_000));        let checked = check(&replica, 1_000).unwrap();        assert_eq!(checked.verdict, "ok");        assert!(checked.sizes.as_ref().is_some_and(|sizes| sizes.other > 0 && sizes.indexes > 0), "measured with the check: {checked:?}");        assert_eq!(kept(&replica), Some(checked));        assert!(!due(&replica, 1_000 + 60_000), "checked this build a minute ago");        assert!(due(&replica, 1_000 + EVERY.as_millis() as i64), "a week on");        let mut other = kept(&replica).unwrap();        other.build = "another build".into();        std::fs::write(replica.with_file_name(FILE), serde_json::to_vec(&other).unwrap()).unwrap();        assert!(due(&replica, 1_000 + 60_000), "another build's verdict");    }    /// RULE (INDEX LATER 2 REVIEW): the check reads beside a live writer (its own read-only connection over the    /// log), and a copy that is not whole says so in its verdict.    #[test]    fn a_copy_is_checked_beside_a_writer_and_a_bad_one_says_so() {        let dir = tempfile::tempdir().unwrap();        let replica = dir.path().join("replica.db");        let db = cotton_store::Driver::open(&replica).unwrap();        cotton_store::create::apply_schema(&db).unwrap();        db.exec("BEGIN IMMEDIATE; INSERT INTO cotton_workspaces(id,name,owner_user_id,created_at) VALUES ('synthetic','Synthetic','person','now')").unwrap();        assert_eq!(check(&replica, 1_000).unwrap().verdict, "ok", "beside a writer mid-transaction");        db.exec("COMMIT").unwrap();        drop(db);        // Not whole: a page of the file overwritten with noise.        let bad = dir.path().join("bad").join("replica.db");        std::fs::create_dir_all(bad.parent().unwrap()).unwrap();        std::fs::copy(&replica, &bad).unwrap();        let mut bytes = std::fs::read(&bad).unwrap();        let page = 4096;        for byte in &mut bytes[page * 3..page * 6] {            *byte = 0x5a;        }        std::fs::write(&bad, bytes).unwrap();        let checked = check(&bad, 1_000).unwrap();        assert_ne!(checked.verdict, "ok", "{checked:?}");        assert_eq!(kept(&bad), Some(checked.clone()), "kept, so asked again on the weekly rule");        assert!(!due(&bad, 1_000 + 60_000), "not again after every sync");        // One that will not open at all: the failure is the verdict.        let none = dir.path().join("none").join("replica.db");        std::fs::create_dir_all(none.parent().unwrap()).unwrap();        std::fs::write(&none, b"not a database, invented").unwrap();        let checked = check(&none, 1_000).unwrap();        assert!(checked.verdict.starts_with(NOT_CHECKED) || checked.verdict != "ok", "{checked:?}");        assert!(!due(&none, 1_000 + 60_000));    }    /// RULE (PHONE MEASURES): the copy's file is measured by kind, names and sizes only: the person's rows, the    /// receipts, the indexes, the search index, the parks, the rest, and the pages free, adding up to the file.    #[test]    fn a_copys_file_is_measured_by_kind() {        let dir = tempfile::tempdir().unwrap();        let replica = dir.path().join("replica.db");        let db = cotton_store::Driver::open(&replica).unwrap();        cotton_store::create::apply_schema(&db).unwrap();        db.exec("INSERT INTO cotton_workspaces(id,name,owner_user_id,created_at) VALUES ('synthetic','Synthetic','person','now')").unwrap();        let tables: Vec<String> = db.all("SELECT name FROM sqlite_schema WHERE type = 'table'", &[]).unwrap().iter().filter_map(|row| row.text("name").map(str::to_string)).collect();        for needed in ["_writes", "_parked", "cotton_workspaces"] {            assert!(tables.iter().any(|table| table == needed), "{needed} in the schema");        }        assert!(tables.iter().any(|table| table.starts_with("fts_")), "a search index in the schema");        drop(db);        let sizes = sizes(&replica).unwrap();        for (kind, bytes) in [("rows", sizes.rows), ("writes", sizes.writes), ("indexes", sizes.indexes), ("search", sizes.search), ("parked", sizes.parked), ("other", sizes.other)] {            assert!(bytes > 0, "{kind}: {sizes:?}");        }        let file = std::fs::metadata(&replica).unwrap().len();        let wal = std::fs::metadata(replica.with_extension("db-wal")).map(|meta| meta.len()).unwrap_or(0);        let counted = sizes.rows + sizes.writes + sizes.indexes + sizes.search + sizes.parked + sizes.other + sizes.free;        assert!(counted <= file + wal && counted + 4 * 4096 >= file, "{counted} counted of a {file} byte file: {sizes:?}");    }}