Cotton code
314 lines · 15.0 KB · RustRaw
//! A copy shaped for a PHONE, rather than a copy of everything.//!//! A cut empties server-local tables and rows outside the asking device's//! keep rules, together with their receipts. Dormant receipts on the Mac do//! not become orphan receipts on the phone. Retracts remain in `_tombstones`.//!//! Before filtering, the copy records the full file's per-author ceilings in//! `_cursors`. Claim and replacement checks read those recorded positions://! recomputing from the filtered receipts would rewind sync or reject a cut//! whose newest writes belong to rows the phone does not keep.//!//! [`strip_for_phone`] runs over the temp COPY, never the live file, and the//! caller `VACUUM`s afterwards to give the pages back.//!//! ## What is deliberately KEPT//!//! The `fts_*` shadow tables stay, and the brief that asked for this wanted//! them dropped and rebuilt on the phone after the claim. Measured against the//! wire they are not worth it: the body is gzipped now, and a search index of//! mostly-text compresses about as well as the text did, so dropping them saves//! a seventh of the body and costs a full FTS5 `'rebuild'` over tens of//! thousands of messages on a phone that is trying to paint its first screen.//! Since version 3 the indexes are EXTERNAL-CONTENT, which only sharpens the//! argument: they no longer hold a second copy of the text, so there is less//! there to drop. The measurement is a guard rather than a number in a comment//! — `cotton-server/tests/it/export_routes.rs`'s//! `the_search_index_is_cheap_once_the_body_is_gzipped` prints both sizes on//! every run and fails if the saving ever passes a quarter. If it does,//! `fts_reindex` is right there and this is the paragraph to delete.use crate::driver::Driver;use crate::error::Result;use rusqlite::types::Value as SqlValue;/// A consistent, unfiltered SQLite file, made through an independent WAL/// reader. READ_ONLY protects the live database; query_only is deliberately/// absent because SQLite must write the separate VACUUM INTO destination.pub fn copy_file(source: &std::path::Path, destination: &std::path::Path) -> Result<()> {    use rusqlite::OpenFlags;    let reader = rusqlite::Connection::open_with_flags(source,        OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX)?;    reader.busy_timeout(std::time::Duration::from_secs(30))?;    // not a copy: VACUUM INTO writes only a new file (SQLite refuses one that exists and is not empty).    reader.execute("VACUUM INTO ?", [destination.display().to_string()])?;    Ok(())}/// The tables emptied out of a phone's copy, each with the reason it is not/// missed.////// A NAMED LIST. An unknown table is kept, because a snapshot that silently/// dropped something nobody had thought about would be a phone quietly missing/// rows — the failure this whole file is trying not to cause on a bigger scale.pub static NOT_ON_A_PHONE: &[(&str, &str)] = &[    (        "_parked",        "device-local: what the SERVER could not apply yet. A copy that kept its push parks would be a device that owes a hand-over it never wrote",    ),    (        "_outbox",        "device-local: a queued op of the SERVER's would be pushed back up as this device's write. Emptied HERE and not by the claim — a claim that emptied an outbox would be a claim that could destroy writes",    ),    (        "_media",        "device-local, and the claim empties it anyway: a media row is an upload of bytes this device does not have",    ),    (        "_media_unlinks",        "device-local: the SERVER's queue of dead keys to take out of its own store. A fresh phone holds none of those bytes, and the erasures it folds from here on fill its own queue",    ),    (        "_computed",        "device-local: what the SERVER worked out for its computed columns. The phone derives its own from the rows it holds, at its first open and at every fold after",    ),    (        "_on_demand",        "device-local: what THIS device opened from outside its keep rules, and when. A phone that started with the Mac's list would count rows it never fetched",    ),    (        "_keep_fetch",        "device-local: what the SERVER's own copy is complete for — everything. The strip writes the asking device's lines afresh, after the cut: complete for the rules it was cut by (`keep::cover_copy`)",    ),    (        "_media_feature_prints",        "server-local, RETIRING: the old home of a photo's image print, folded onto `cotton_photos.image_embedding` a page per pass and dropped when empty (`cotton-server/src/media/analyze/prints.rs`)",    ),    (        "_media_face_embeddings",        "server-local, RETIRING: the old home of a face's print, folded onto `cotton_media_faces.embedding` the same way",    ),    (        "cotton_ai_calls",        "server-only metering ([`crate::schema::table_specs::METERING_TABLES`]) — the serving Mac's own record of model calls; the AI-usage screen asks the serving Mac for it live",    ),    (        "_ai_batches",        "server-only metering — the serving Mac's own batch bookkeeping beside `cotton_ai_calls`",    ),    (        "cotton_mcp_audit",        "server-only ([`crate::schema::table_specs::SERVER_ONLY_TABLES`]) — about two hundred thousand rows answering a question no screen on a phone asks. The stream already refuses to hand one over; this is what keeps a FRESH phone from starting with the back catalogue",    ),    (        "cotton_repo_vars",        "server-only — an input to a process on a machine, stored in the clear beside the workflow that reads it",    ),    (        "cotton_repo_merge_queue",        "the serving Mac's own bookkeeping of which pulls asked to land and which train they ride (`table_specs::SERVER_ONLY_TABLES`); the phone reads the queue off the pull's own checks",    ),];/// What one strip emptied.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct StripCounts {    /// Table name and rows removed, for the tables that were there.    pub emptied: Vec<(String, usize)>,}/// Empty the tables a phone does not read, on a COPY.////// Every delete is guarded on the table EXISTING: two of these are created/// lazily by a server worker and a file whose owner has never had a photo/// analysed has neither.pub fn strip_for_phone(db: &Driver) -> Result<StripCounts> {    strip(db, None)}/// [`strip_for_phone`] for the device that asked, at `now_ms`: the copy is/// also CUT BY THAT DEVICE'S KEEP RULES ([`crate::keep::cut_copy`]), so a/// phone's first copy holds what its exchange pages would have carried and/// nothing its rules leave out. A Mac's copy is cut of nothing — a Mac keeps/// everything.pub fn strip_for_device(db: &Driver, device_id: &str, now_ms: i64) -> Result<StripCounts> {    strip(db, Some((&|db: &Driver| crate::keep::Keep::of_device(db, device_id), now_ms)))}/// [`strip_for_device`] cut to `keep` rather than to a device's rules read off/// the copy — what the serving Mac prepares ahead of any device (the warm/// copy): a device whose rules have the same fingerprint gets these bytes.pub fn strip_for_keep(db: &Driver, keep: &crate::keep::Keep, now_ms: i64) -> Result<StripCounts> {    strip(db, Some((&|_: &Driver| Ok(keep.clone()), now_ms)))}/// Who a copy is cut for: the rules, read when the cut needs them, and when.type Asker<'a> = (&'a dyn Fn(&Driver) -> Result<crate::keep::Keep>, i64);fn strip(db: &Driver, asker: Option<Asker<'_>>) -> Result<StripCounts> {    db.transaction(|db| {        let mut emptied = Vec::new();        // Record the full cut, including positions already folded whose        // receipts lost. Filtering must never rewind either position.        for (author, top) in crate::cursors::seen_ceiling(db)? {            // Without a caller clock (strip_for_phone), date the copied            // cursor from its receipt's stamp, rather than inventing a time.            let ms = asker                .map(|(_, ms)| ms)                .or_else(|| top.split(':').next()?.parse().ok());            let at = ms                .and_then(crate::protocol::js::to_iso_string)                .unwrap_or_default();            crate::cursors::advance_cursor(db, &author, &top, &at)?;        }        // FIRST, before the derived history is emptied: setting a held        // receipt aside re-assembles its row, and the triggers write history.        let held = set_held_receipts_aside(db)?;        if held > 0 {            emptied.push(("_writes (held)".to_string(), held));        }        // Then the rules, for the same reason: a cut re-assembles its rows.        if let Some((rules, now_ms)) = asker {            let keep = rules(db)?;            let cut = crate::keep::cut_copy(db, &keep, now_ms)?;            if cut > 0 {                emptied.push(("rows outside the device's keep rules".to_string(), cut));                optimize_search(db)?;            }        }        for (table, _why) in NOT_ON_A_PHONE.iter().chain(crate::schema::table_specs::DEVICE_LOCAL_TABLES) {            if !table_exists(db, table)? {                continue;            }            let rows = db.run(&format!("DELETE FROM {table}"), &[])?;            emptied.push(((*table).to_string(), rows));        }        let removed = drop_receipts_without_rows(db)?;        if removed > 0 {            emptied.push(("_writes (rows outside the copy)".to_string(), removed));        }        // LAST, after the server's own lines are gone: the copy says what it        // is complete for — the rules it was just cut by — so a rule widened        // between this copy and the device's first look is still fetched.        if let Some((rules, _)) = asker {            let keep = rules(db)?;            crate::keep::cover_copy(db, &keep)?;        }        Ok(StripCounts { emptied })    })}/// Merge every full-text index down to one segment. A cut takes a set of/// rows out a table at a time, and FTS5 keeps each delete as a marker in a/// segment of its own until a merge: on the owner's file the mail indexes held/// 270 MB for 8,500 emails after the cut, 16 MB once merged (23 Oct 2026).fn optimize_search(db: &Driver) -> Result<()> {    let indexes: Vec<String> = db        .all(            "SELECT name FROM sqlite_master WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%USING fts5%'",            &[],        )?        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect();    for index in indexes {        db.exec(&format!("INSERT INTO \"{index}\" (\"{index}\") VALUES ('optimize')"))?;    }    // Merged whole: no erased row's words are left for the background purge (`crate::fts_purge`).    if db.get("SELECT 1 AS n FROM sqlite_master WHERE type = 'table' AND name = ?", &[rusqlite::types::Value::Text(crate::fts_purge::TABLE.into())])?.is_some() {        db.exec(&format!("DELETE FROM {}", crate::fts_purge::TABLE))?;    }    Ok(())}/// Remove receipts for rows absent from the cut, including dormant rows and/// emptied server-only tables. Table names come from the file and are quoted;/// package tables use their declared primary key just as built-ins do.fn drop_receipts_without_rows(db: &Driver) -> Result<usize> {    let mut removed = 0;    let quote = |name: &str| format!("\"{}\"", name.replace('"', "\"\""));    for row in db.all("SELECT DISTINCT tbl FROM _writes", &[])? {        let Some(table) = row.text("tbl") else {            continue;        };        let key = [SqlValue::Text(table.to_string())];        if !table_exists(db, table)? {            // not a copy: a snapshot made to travel: receipts of tables or rows it does not hold, and held ones, which never travel; the phone's own copy keeps them.            removed += db.run("DELETE FROM _writes WHERE tbl = ?", &key)?;            continue;        }        let columns = db.all(&format!("PRAGMA table_info({})", quote(table)), &[])?;        let primary: Vec<_> = columns            .iter()            .filter(|col| col.int("pk").unwrap_or(0) > 0)            .collect();        if primary.len() != 1 {            return Err(crate::error::StoreError::refused(format!(                "snapshot receipt table {table} needs a single primary key"            )));        }        let pk = primary[0].text("name").ok_or_else(|| {            crate::error::StoreError::refused("snapshot receipt table has no primary key name")        })?;        removed += db.run(            // not a copy: a snapshot made to travel: receipts of tables or rows it does not hold, and held ones, which never travel; the phone's own copy keeps them.            &format!("DELETE FROM _writes WHERE tbl = ? AND NOT EXISTS (SELECT 1 FROM {} r WHERE r.{} = _writes.row_id)", quote(table), quote(pk)),            &key,        )?;    }    Ok(removed)}/// Take every HELD receipt out of the copy and re-assemble the rows they/// showed in (design 3.8). A held receipt applies on its writer but never/// travels — not in a page, not in `seen`, and not in a snapshot — so the copy/// keeps neither the receipt nor the value it put in its row: each such row is/// assembled again from the receipts that do travel (a receipt that lost only/// to the held one is still there to take its place), and a row whose only/// create was held leaves its table. A held delete is a held receipt too./// Returns how many receipts were set aside.fn set_held_receipts_aside(db: &Driver) -> Result<usize> {    if !table_exists(db, "_writes")? {        return Ok(0);    }    let rows: Vec<(String, String)> = db        .all(            // A set-aside receipt (`rejected::SET_ASIDE`) is stripped as a held one is (QUEUE BAD OP 3), and one an            // earlier build marked let go (held = 2, QUEUE BAD OP 4).            "SELECT tbl, row_id FROM _writes WHERE held IN (1, 2, 3) \             UNION SELECT tbl, row_id FROM _tombstones WHERE held IN (1, 2, 3) ORDER BY tbl, row_id",            &[],        )?        .iter()        .filter_map(|row| {            Some((                row.text("tbl")?.to_string(),                row.text("row_id")?.to_string(),            ))        })        .collect();    // A held delete is set aside too: the copy shows the row as the    // receipts that travel leave it.    // not a copy: a snapshot made to travel: receipts of tables or rows it does not hold, and held ones, which never travel; the phone's own copy keeps them.    let removed = db.run("DELETE FROM _writes WHERE held IN (1, 2, 3)", &[])?        // not a copy: a snapshot made to travel: held receipts never travel; the phone's own copy keeps them.        + db.run("DELETE FROM _tombstones WHERE held IN (1, 2, 3)", &[])?;    for (table, row_id) in &rows {        crate::fold::reassemble_row(db, table, row_id)?;    }    Ok(removed)}/// Is this table in the file at all?fn table_exists(db: &Driver, table: &str) -> Result<bool> {    Ok(db        .get(            "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",            &[SqlValue::Text(table.to_string())],        )?        .is_some())}#[cfg(test)]#[path = "snapshot_tests.rs"]mod tests;