Cotton code
1712 lines · 72.9 KB · RustRaw
//! What a device keeps: the KEEP RULES, and the one judge that reads them.//!//! Architect's brief, 12 Oct 2026: a phone must not hold every byte the//! household holds; a Mac always holds everything. A device's rules are rows//! of `cotton_device_keep` (`crate::schema::ddl::DEVICE_KEEP_TABLE`) — a TABLE//! with `all`, `none` or a horizon in days, a GROUP always, a RECORD always —//! and NO ROW IS `all`: a device nobody gave a rule keeps everything, which is//! what every device did before this file.//!//! ONE JUDGE, read by both sides (the owner's rule: one implementation of who//! wins): the serving Mac asks it which rows an exchange answer carries//! ([`Keep::leave_out`]) and which a device may open ([`open`]); the device//! asks it what it may drop again. Two would disagree, and a row one side//! thought kept would be a row the other never sent.//!//! What the judge says of a row://!//! - A device that is not a phone keeps EVERYTHING, whatever a row says//!   ([`is_phone`]): a Mac may take over serving and must hold the whole file,//!   so its rules cannot be narrowed — not by [`set_rule`], which refuses, and//!   not by a row written some other way, which is never read.//! - A table whose rule is `none` is NEVER on the device: not in a page, not//!   when opened, and no pin brings it back.//! - A table whose rule is `days:N` keeps the rows whose age column//!   ([`NARROWABLE`]) is within N days. An older row is simply absent — not a//!   stub — and is answered whole when its record is opened ([`open`]).//! - A RECORD rule, or membership of a group a GROUP rule names, brings a row//!   past its table's horizon; a pinned row keeps the rows it belongs to.//! - A rule on a table covers what that table OWNS (`OWNING_REFS`): a row//!   whose owning parent is outside is outside, so no child is ever left on a//!   phone waiting for a parent that will not come.//!//! WHAT A PHONE ALREADY HOLDS IS THE PHONE'S TO SETTLE, with the same judge://! [`leave`] drops from its own copy what its rules no longer keep — a local//! drop, no tombstone, nothing travels, never a row it still owes somebody a//! change to — and [`wanted`] names what the rules keep that it can see it//! lacks, to be opened like any record. [`cut_copy`] is the same drop over//! the snapshot a new phone starts from.//!//! A RULE THAT IS WIDENED BRINGS ITS ROWS BACK. The rows a narrower rule left//! out were never sent, so the phone holds no receipt it could name them by://! it keeps one line a narrowable table of what its copy is complete for//! (`_keep_fetch`), and when its rule comes to be wider than that it asks the//! serving Mac for the table itself, a page at a time ([`widenings`],//! [`open_table`], [`widened`]). Nobody may set a narrowing rule without this//! ([`NARROWING_GUARDED`]).//!//! A receipt left out of a page is still PASSED: the page's cursors move//! beyond it, so the device is never asked for it again and never reads as//! behind on it. A DELETE ALWAYS TRAVELS, except for a table that is never//! kept: a row a phone opened yesterday must still leave it when it is erased//! today, and a delete of a row the phone never held costs it one small//! receipt.use std::collections::{BTreeMap, BTreeSet, HashMap};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value as JsonValue};use crate::actor::Actor;use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::mint::{changes_of, mint, Act, Held, History};use crate::outbox::{IdSource, LocalChange};use crate::protocol::types::{CottonOp, OpKind};use crate::protocol::{derived_id, js};use crate::schema::specs::spec_for;use crate::schema::table_specs::{is_handed_over, OWNING_REFS};/// The rules' own table.pub const TABLE: &str = "cotton_device_keep";/// How long a row opened from outside the rules stays on the device unopened.pub const ON_DEMAND_DAYS: i64 = 30;/// How many rows one answer of [`open`] restates.pub const OPEN_PAGE_ROWS: usize = 500;/// What an [`open`] of a row that is never kept is refused with.pub const NEVER_REFUSAL: &str = "is never kept on this device";const DAY_MS: i64 = 24 * 60 * 60 * 1000;/// The folder of a file's message media a status's picture is kept under:/// `{file}/messages/statuses/…`. No thread id is `statuses`. The one spelling/// — `cotton_client::stories::STATUS_MEDIA_FOLDER` is this constant — because/// three readers must agree on what a status's bytes are: the thumbnail sweep,/// `media.ensure` and the Storage pass ([`status_bytes_never`]).pub const STATUS_MEDIA_FOLDER: &str = "statuses";/// Is `key` a status's media — `{file}/messages/statuses/…`?pub fn is_status_media(key: &str) -> bool {    let mut parts = key.split('/').skip(1);    parts.next() == Some("messages") && parts.next() == Some(STATUS_MEDIA_FOLDER)}/// A STATUS'S BYTES ARE NEVER ON A PHONE (architect's ruling, 12 Oct 2026:/// "never a thumbnail, never an original"): is `key` a status's media on a/// device whose rules never keep `cotton_stories`? The row's own rule and no/// second one — a phone a person gave `all` for the table keeps its statuses'/// bytes as it keeps its chats', and a Mac is never asked twice.pub fn status_bytes_never(db: &Driver, device_id: &str, key: &str) -> Result<bool> {    Ok(is_status_media(key) && Keep::of_device(db, device_id)?.table_rule("cotton_stories") == TableRule::None)}/// THE TABLES A RULE MAY NARROW, each with the column its age is read from.////// A NAMED LIST, and the safe direction: a rule on a table nobody thought/// about could hide the rows a device needs to sync at all (its own device/// row, the authors, the vault's keys), so a table takes a `none` or a horizon/// only once it is written here with the date a person would mean by "the/// last three months" of it.pub static NARROWABLE: &[(&str, &str)] = &[    // Mail: a thread is as old as its last message; its emails and    // participants are owned by it and follow it.    ("cotton_email_threads", "last_at"),    // Statuses: a status is as old as its posting.    ("cotton_stories", "posted_at"),    // Chats: a thread is as old as its last message; its messages (and    // their reactions) are owned by it and follow it.    ("cotton_msg_threads", "last_message_at"),    // Imports: a run of an import (a phone's messages, its call history) is    // as old as the day it ran.    ("cotton_imports", "created_at"),];/// The column `table`'s age is read from, when a rule may narrow it.pub fn age_column(table: &str) -> Option<&'static str> {    NARROWABLE.iter().find(|(name, _)| *name == table).map(|(_, column)| *column)}/// What a PHONE keeps of a table nobody gave it a rule for, where that is not/// `all`: `(table, rule, why)`. A stored rule for the table replaces it.////// A DEFAULT NARROWS EVERY REAL PHONE THE DAY IT LANDS, with no rule row and/// nobody choosing it, so a table is named here only once the FFI guard/// drives it — a phone's copy against a served Mac/// (`cotton-ffi/tests/phone_keep_end_to_end.rs`); `cotton-ffi/tests/keep_flags_need_the_end_to_end_guard.rs::a_default_/// narrows_a_phone_only_for_a_table_the_ffi_guard_drives` reads that test's/// source and fails a default it does not name. The statuses default was here/// for one landing before that test existed (87ca2cdba), was taken out/// (53ea58dd0) and returned with it.////// MAIL, CHATS AND IMPORTS KEEP SIX MONTHS (owner, 23 Oct 2026, 02:55/// IST): a phone's copy holds the last [`PHONE_KEEP_DAYS`] of email threads/// (their emails and participants follow them), of message threads (their/// messages follow them) and of import runs; older rows stay on the Mac and/// open on demand. Twelve years of mail is still searched — on the Mac, and/// opened from there.////// A DEFAULT IS A PHONE'S WITH A MAC BEHIND IT ([`Keep::of_device`]): a phone/// that is its database's only home (Rigby) keeps everything, since nothing/// would answer for a row it let go.////// Every other table is `all`; the media horizon is the byte fetcher's.pub static PHONE_DEFAULTS: &[(&str, TableRule, &str)] = &[    (        "cotton_stories",        TableRule::None,        "a status is watched for a day and kept on the Macs after the app forgets it; a phone holds none of them",    ),    (        "cotton_email_threads",        TableRule::Days(PHONE_KEEP_DAYS),        "a phone keeps six months of mail; older threads stay on the Mac and open on demand",    ),    (        "cotton_msg_threads",        TableRule::Days(PHONE_KEEP_DAYS),        "a phone keeps six months of chats; older threads stay on the Mac and open on demand",    ),    (        "cotton_imports",        TableRule::Days(PHONE_KEEP_DAYS),        "a phone keeps six months of import runs; older ones stay on the Mac",    ),];/// The days of mail, chats and imports a phone keeps by default.pub const PHONE_KEEP_DAYS: u32 = 180;/// MAY ANYBODY NARROW A REAL PHONE — the one flag every face and verb that/// writes a keep rule reads (the device row's "What this phone keeps", "Keep/// on this phone", `set_keep_rule`). While it is `false` a writer offers and/// accepts only what narrows nothing — a table's `all`, a group's or a/// record's `always` — and refuses `none` and `days:N`.////// TRUE, because both things the architect's ruling of 12 Oct 2026 asked for/// are on main, and it stays true only while both are:////// - finding 2, a test at the FFI driving a phone's copy against a served Mac///   — first copy, exchange, open, reconcile///   (`cotton-ffi/tests/phone_keep_end_to_end.rs`);/// - finding 1, the WIDEN PATH — "no rule can be set before it": a table rule///   later widened (`days:30` to `days:365`, `none` to `all`, or cleared)///   brings back the rows the narrower rule left out ([`widenings`],///   [`open_table`], [`widened`]; the same FFI test drives it).////// `cotton-ffi/tests/keep_flags_need_the_end_to_end_guard.rs::narrowing_is_allowed_only_with_the_ffi_guard_and_the_widen_/// path` holds the flag to both: it reads the FFI test's source for the widen/// step and fails a `true` without it.////// The judge itself does not read it: a rule row that is already in a file is/// obeyed whatever this says. Nor does a DEFAULT (`PHONE_DEFAULTS`).pub const NARROWING_GUARDED: bool = true;/// The table id a hand-picked group's `data.table` names a narrowable table/// by (the definition's id), so a kept group's member is asked for from the/// table it is a record of and from no other.static GROUPED_AS: &[(&str, &str)] = &[("cotton_email_threads", "email_thread")];/// A TABLE rule.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum TableRule {    /// Every row. What no rule means.    All,    /// Never on this device, not even when opened.    None,    /// The rows whose age column is within this many days; older on demand.    Days(u32),}impl TableRule {    /// `all`, `none` or `days:N` (N a whole number of days, one or more).    pub fn parse(text: &str) -> Option<TableRule> {        match text {            "all" => Some(TableRule::All),            "none" => Some(TableRule::None),            _ => {                let days = text.strip_prefix("days:")?;                if days.is_empty() || days.starts_with('0') || !days.bytes().all(|b| b.is_ascii_digit()) {                    return None;                }                days.parse().ok().map(TableRule::Days)            }        }    }    /// The text the `rule` column holds.    pub fn as_text(self) -> String {        match self {            TableRule::All => "all".to_string(),            TableRule::None => "none".to_string(),            TableRule::Days(days) => format!("days:{days}"),        }    }}/// The three kinds of rule, as the `kind` column spells them.pub const KIND_TABLE: &str = "table";pub const KIND_GROUP: &str = "group";pub const KIND_RECORD: &str = "record";/// The rule a GROUP or a RECORD carries.pub const ALWAYS: &str = "always";/// One stored rule, as a list shows it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct RuleRow {    pub id: String,    pub device_id: String,    pub kind: String,    pub target: String,    pub rule: String,}/// What the judge says of one row.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]pub enum Verdict {    /// Kept: in every page.    Inside,    /// Not kept, but answered when its record is opened.    Outside,    /// Never on this device.    Never,}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// Is `device_id` a phone, as this file's `cotton_devices` says it?////// Only `ios` and `android` are. A Mac, a Linux box, and a device whose/// platform the file does not say are NOT — unknown is a Mac's answer, because/// a Mac that may take over serving must hold the whole file. Where a key has/// several rows the live approval answers, then the newest (the order every/// reader of the table uses).pub fn is_phone(db: &Driver, device_id: &str) -> Result<bool> {    let platform = db        .get(            "SELECT platform FROM cotton_devices WHERE device_id = ? \             ORDER BY (revoked_at IS NULL) DESC, approved_at DESC, id ASC LIMIT 1",            &[text(device_id)],        )?        .and_then(|row| row.text("platform").map(str::to_string));    Ok(matches!(platform.as_deref(), Some("ios") | Some("android")))}/// Does this file name a live Mac besides `device_id` — one that holds the/// whole file and answers for what a phone lets go? A served file always/// does: the host that founded it is filed by the platform it runs on, `mac`/// or `linux` (a Linux host serves the same file a Mac does). An assistant's/// or a runner's row is not one: neither holds the whole file.pub fn has_a_mac(db: &Driver, device_id: &str) -> Result<bool> {    Ok(db        .get(            "SELECT 1 AS found FROM cotton_devices WHERE device_id <> ? AND revoked_at IS NULL \             AND platform IN ('mac', 'linux') AND COALESCE(scope, 'full') = 'full' LIMIT 1",            &[text(device_id)],        )?        .is_some())}/// The stored rules of one device, in the order a list shows them.pub fn rules_of(db: &Driver, device_id: &str) -> Result<Vec<RuleRow>> {    Ok(db        .all(            "SELECT id, device_id, kind, target, rule FROM cotton_device_keep \             WHERE device_id = ? ORDER BY kind, target",            &[text(device_id)],        )?        .iter()        .map(|row| RuleRow {            id: row.text("id").unwrap_or_default().to_string(),            device_id: row.text("device_id").unwrap_or_default().to_string(),            kind: row.text("kind").unwrap_or_default().to_string(),            target: row.text("target").unwrap_or_default().to_string(),            rule: row.text("rule").unwrap_or_default().to_string(),        })        .collect())}/// A RECORD rule's target, `<table>:<row id>`, taken apart.pub fn record_target(target: &str) -> Option<(&str, &str)> {    let (table, row_id) = target.split_once(':')?;    (!table.is_empty() && !row_id.is_empty()).then_some((table, row_id))}/// A RECORD rule's target for `table`'s `row_id`.pub fn record_target_of(table: &str, row_id: &str) -> String {    format!("{table}:{row_id}")}/// What one device keeps of one file: its rules, read once.#[derive(Debug, Clone, Default)]pub struct Keep {    /// The tables a rule narrows (`none` or a horizon); a table not here is `all`.    tables: BTreeMap<String, TableRule>,    /// The groups kept always.    groups: Vec<String>,    /// The rows kept always: every RECORD rule's row and the rows it belongs to.    pins: BTreeSet<(String, String)>,    /// The RECORD rules' own rows, without what they belong to: what a pin's    /// BYTES are read from ([`Keep::pins_key`]).    records: BTreeSet<(String, String)>,    /// The narrowed tables and every table they own: the only tables whose    /// rows cost the judge a read.    governed: BTreeSet<&'static str>,    /// What this device may not hold at all: the only-you records, when it is    /// not one of the owner's devices (`crate::audience`). Read before every    /// rule, Mac or phone — a member's Mac keeps everything but these.    holds: crate::audience::Holds,}impl Keep {    /// A device that keeps everything: a Mac, or a phone with no narrowing rule.    pub fn everything() -> Keep {        Keep::default()    }    /// What a phone keeps before it has a rule of its own or a hold: the    /// phone defaults. What the serving Mac keeps a first copy cut to for the    /// next phone to join (the warm copy, architect 17 Oct 2026).    pub fn new_phone() -> Keep {        let mut keep = Keep::default();        for (table, rule, _why) in PHONE_DEFAULTS {            keep.tables.insert((*table).to_string(), *rule);        }        keep.governed = governed_by(keep.tables.keys().map(String::as_str));        keep    }    /// What `device_id` keeps of this file.    pub fn of_device(db: &Driver, device_id: &str) -> Result<Keep> {        let holds = crate::audience::Holds::for_device(db, device_id)?;        if !is_phone(db, device_id)? {            // A MAC'S RULES CANNOT BE NARROWED: its rows are never read.            return Ok(Keep { holds, ..Keep::everything() });        }        // The defaults narrow a phone only where a Mac answers for what it        // lets go; a phone that is its file's only home starts from all.        let start = if has_a_mac(db, device_id)? { Keep::new_phone() } else { Keep::everything() };        let mut keep = Keep { holds, ..start };        let mut pinned: Vec<(String, String)> = Vec::new();        for row in rules_of(db, device_id)? {            match row.kind.as_str() {                KIND_TABLE => match TableRule::parse(&row.rule) {                    // Only a table a rule may narrow is narrowed, whatever a                    // row written past `set_rule` names.                    Some(TableRule::All) | None => {                        keep.tables.remove(&row.target);                    }                    Some(rule) if age_column(&row.target).is_some() => {                        keep.tables.insert(row.target, rule);                    }                    Some(_) => {}                },                KIND_GROUP => keep.groups.push(row.target),                KIND_RECORD => {                    if let Some((table, row_id)) = record_target(&row.target) {                        pinned.push((table.to_string(), row_id.to_string()));                    }                }                _ => {}            }        }        keep.governed = governed_by(keep.tables.keys().map(String::as_str));        // A pinned row keeps what it belongs to: its owning parents, upward.        for (table, row_id) in pinned {            keep.records.insert((table.clone(), row_id.clone()));            keep.pin_with_parents(db, &table, &row_id, 0)?;        }        Ok(keep)    }    /// The pins of EVERY live device of this file, merged: each GROUP and    /// RECORD rule a device that is not revoked keeps always. Asked only    /// through [`Keep::pins_key`]; it narrows no table.    ///    /// A MAC THAT KEEPS ROWS ONLY ASKS THIS before it lets an original go    /// (architect's ruling, 12 Oct 2026: "never a pinned record's or a kept    /// album's bytes"). A Mac holds no group or record rule of its own — the    /// keep verbs refuse one — so its [`Keep::of_device`] pins nothing, and    /// the album a person kept always on their phone is the pin it must honour.    pub fn pinned_by_anyone(db: &Driver) -> Result<Keep> {        let mut keep = Keep::default();        for row in db.all(            "SELECT kind, target FROM cotton_device_keep k \             WHERE kind IN (?, ?) AND EXISTS (SELECT 1 FROM cotton_devices d \               WHERE d.device_id = k.device_id AND d.revoked_at IS NULL) \             ORDER BY kind, target",            &[text(KIND_GROUP), text(KIND_RECORD)],        )? {            let (Some(kind), Some(target)) = (row.text("kind"), row.text("target")) else {                continue;            };            if kind == KIND_GROUP {                keep.groups.push(target.to_string());            } else if let Some((table, row_id)) = record_target(target) {                keep.records.insert((table.to_string(), row_id.to_string()));            }        }        Ok(keep)    }    fn pin_with_parents(&mut self, db: &Driver, table: &str, row_id: &str, depth: usize) -> Result<()> {        if depth > MAX_DEPTH || !self.pins.insert((table.to_string(), row_id.to_string())) {            return Ok(());        }        for (parent, parent_id) in governed_parents(db, &self.governed, table, row_id, None)? {            self.pin_with_parents(db, parent, &parent_id, depth + 1)?;        }        Ok(())    }    /// WHAT A COPY CUT BY THESE RULES HOLDS, as one short string: two    /// devices — or one device an hour apart — whose fingerprints are equal    /// are cut to the same rows. The serving Mac keeps a cut copy for an hour    /// per fingerprint (`cotton-server`'s snapshots), and a rule changed in    /// between is a different fingerprint and so a fresh cut. The pins are    /// in it with what they belong to, so a pinned row moved under another    /// parent is a fresh cut too. A Mac's — everything — is the empty rule    /// set's.    pub fn fingerprint(&self) -> String {        use sha2::Digest;        let mut hash = sha2::Sha256::new();        for (table, rule) in &self.tables {            hash.update(format!("t\u{1f}{table}\u{1f}{rule:?}\u{1e}"));        }        let mut groups = self.groups.clone();        groups.sort();        groups.dedup();        for group in &groups {            hash.update(format!("g\u{1f}{group}\u{1e}"));        }        for (table, row_id) in &self.pins {            hash.update(format!("p\u{1f}{table}\u{1f}{row_id}\u{1e}"));        }        hash.update(self.holds.fingerprint());        hex::encode(&hash.finalize()[..16])    }    /// Does any rule narrow what this device is sent?    pub fn narrows(&self) -> bool {        !self.tables.is_empty()    }    /// The rule `table` itself carries (not what its owners carry).    pub fn table_rule(&self, table: &str) -> TableRule {        self.tables.get(table).copied().unwrap_or(TableRule::All)    }    /// AN ANSWER'S OPS, LESS WHAT THIS DEVICE DOES NOT KEEP.    ///    /// An upsert travels when its row is [`Verdict::Inside`]; a delete travels    /// unless its table is never kept. Only the governed tables cost a read —    /// every other op passes untouched, and a device with no narrowing rule    /// is handed its ops back as they came.    pub fn leave_out(&self, db: &Driver, ops: Vec<CottonOp>, now_ms: i64) -> Result<Vec<CottonOp>> {        // What this device may never hold goes first, deletes and all.        let ops = self.holds.leave_out(db, ops)?;        if !self.narrows() {            return Ok(ops);        }        let mut memo = Memo::new();        let mut kept = Vec::with_capacity(ops.len());        for op in ops {            if !self.governed.contains(op.table.as_str()) {                kept.push(op);                continue;            }            let travels = match op.kind {                OpKind::Delete => self.table_rule(&op.table) != TableRule::None,                OpKind::Upsert => {                    self.judge(db, &op.table, &op.row_id, op.patch.as_ref(), now_ms, &mut memo, 0)?                        == Verdict::Inside                }            };            if travels {                kept.push(op);            }        }        Ok(kept)    }    /// What this device keeps of `table`'s `row_id`, at `now_ms`.    pub fn verdict(&self, db: &Driver, table: &str, row_id: &str, now_ms: i64) -> Result<Verdict> {        if self.holds.holds(db, table, row_id, None)? {            return Ok(Verdict::Never);        }        self.judge(db, table, row_id, None, now_ms, &mut Memo::new(), 0)    }    /// What this device may not hold at all (`crate::audience`).    pub fn holds(&self) -> &crate::audience::Holds {        &self.holds    }    /// The judge. `said` is what an op in hand says of the row, read where the    /// file's own row is gone (a row binned since) — and a row nothing can be    /// read of is SENT rather than guessed at.    #[allow(clippy::too_many_arguments)]    fn judge(        &self,        db: &Driver,        table: &str,        row_id: &str,        said: Option<&Map<String, JsonValue>>,        now_ms: i64,        memo: &mut Memo,        depth: usize,    ) -> Result<Verdict> {        if !self.governed.contains(table) || depth > MAX_DEPTH {            return Ok(Verdict::Inside);        }        let key = (table.to_string(), row_id.to_string());        if let Some(known) = memo.get(&key) {            return Ok(*known);        }        // Held as inside while its parents are asked, so a row that names        // itself through a chain ends rather than turning for ever.        memo.insert(key.clone(), Verdict::Inside);        let own = match self.table_rule(table) {            TableRule::All => Verdict::Inside,            TableRule::None => Verdict::Never,            TableRule::Days(days) => {                if self.pins.contains(&key) || self.in_a_kept_group(db, row_id)? {                    Verdict::Inside                } else {                    let oldest = now_ms - i64::from(days) * DAY_MS;                    match age_ms(db, table, row_id, said)? {                        Some(at) if at < oldest => Verdict::Outside,                        _ => Verdict::Inside,                    }                }            }        };        let mut verdict = own;        if verdict != Verdict::Never {            for (parent, parent_id) in governed_parents(db, &self.governed, table, row_id, said)? {                let of_parent = self.judge(db, parent, &parent_id, None, now_ms, memo, depth + 1)?;                verdict = verdict.max(of_parent);            }        }        memo.insert(key, verdict);        Ok(verdict)    }    /// A GROUP OR A RECORD KEEP PINS ITS BYTES: is `key` named by a row this    /// device keeps always — a RECORD rule's row, a member of a kept group (a    /// photo of a kept album), or a row one of those owns (a pinned chat's    /// messages)? Read from the file's own index of who names a key    /// (`_media_key_names`), so it costs a device with no such rule nothing    /// and any other a few indexed reads a key.    ///    /// The Storage pass asks this before releasing an original; the client's    /// keep-fetch queue asks the same judge to fetch missing pinned originals    /// within the phone's cap, on any network.    pub fn pins_key(&self, db: &Driver, key: &str) -> Result<bool> {        if self.groups.is_empty() && self.records.is_empty() {            return Ok(false);        }        for namer in db.all("SELECT tbl, row_id FROM _media_key_names WHERE key = ?", &[text(key)])? {            let (Some(table), Some(row_id)) = (namer.text("tbl"), namer.text("row_id")) else {                continue;            };            if self.kept_always(db, table, row_id, 0)? {                return Ok(true);            }        }        Ok(false)    }    /// Named pins for rule-fetch progress; uses the same pin judge as eviction.    pub fn byte_pin_scopes(db: &Driver, device: &str) -> Result<Vec<(String, String, Keep)>> {        let mut answer = Vec::new();        for row in rules_of(db, device)? {            let mut scope = Keep::default();            if row.kind == KIND_GROUP {                scope.groups.push(row.target.clone());            } else if row.kind == KIND_RECORD {                if let Some((table, id)) = record_target(&row.target) {                    scope.records.insert((table.into(), id.into()));                }            } else { continue; }            let name = db.get("SELECT title AS name FROM cotton_media_albums WHERE id=?", &[text(&row.target)])?                .and_then(|r|r.text("name").map(str::to_string))                .or_else(||db.get("SELECT name FROM cotton_groups WHERE id=?", &[text(&row.target)]).ok().flatten().and_then(|r|r.text("name").map(str::to_string)))                .unwrap_or_else(|| "Kept record".into());            answer.push((row.target, name, scope));        }        Ok(answer)    }    /// Is `table`'s `row_id` kept always by its own rule, by a kept group, or    /// by an owner that is?    fn kept_always(&self, db: &Driver, table: &str, row_id: &str, depth: usize) -> Result<bool> {        if depth > MAX_DEPTH {            return Ok(false);        }        if self.records.contains(&(table.to_string(), row_id.to_string())) || self.in_a_kept_group(db, row_id)? {            return Ok(true);        }        for (child, column, parent) in OWNING_REFS {            if *child != table {                continue;            }            if let Some(parent_id) = column_text(db, table, row_id, column, None)? {                if self.kept_always(db, parent, &parent_id, depth + 1)? {                    return Ok(true);                }            }        }        Ok(false)    }    /// Is `row_id` a member of a group this device keeps always? An album's    /// item, or a member of a hand-picked group (its `cotton_group_members`    /// row). A group that is a filter has no members to keep.    fn in_a_kept_group(&self, db: &Driver, row_id: &str) -> Result<bool> {        if self.groups.is_empty() || row_id.contains('"') {            return Ok(false);        }        let marks = vec!["?"; self.groups.len()].join(", ");        let mut params = vec![text(row_id)];        params.extend(self.groups.iter().map(|group| text(group)));        if db            .get(                &format!(                    "SELECT 1 AS x FROM cotton_media_album_items WHERE record_id = ? AND album_id IN ({marks}) LIMIT 1"                ),                &params,            )?            .is_some()        {            return Ok(true);        }        Ok(db            .get(                &format!(                    "SELECT 1 AS x FROM cotton_group_members m JOIN cotton_groups g ON g.id = m.group_id \                     WHERE m.record_id = ? AND g.deleted_at IS NULL AND g.id IN ({marks}) LIMIT 1"                ),                &params,            )?            .is_some())    }}type Memo = HashMap<(String, String), Verdict>;/// No chain of owners is this deep; a row that claims one is sent.const MAX_DEPTH: usize = 16;/// The narrowed tables and every table they own, transitively.fn governed_by<'a>(narrowed: impl Iterator<Item = &'a str>) -> BTreeSet<&'static str> {    let mut governed: BTreeSet<&'static str> = BTreeSet::new();    for table in narrowed {        if let Some(spec) = spec_for(table) {            governed.insert(spec.name);        }    }    loop {        let before = governed.len();        for (child, _column, parent) in OWNING_REFS {            if governed.contains(parent) {                governed.insert(*child);            }        }        if governed.len() == before {            return governed;        }    }}/// One column of `table`'s `row_id` as text: the file's own row first, then/// what the op in hand says.fn column_text(    db: &Driver,    table: &str,    row_id: &str,    column: &str,    said: Option<&Map<String, JsonValue>>,) -> Result<Option<String>> {    let Some(spec) = spec_for(table) else {        return Ok(None);    };    if !spec.columns.iter().any(|(name, _)| *name == column) {        return Ok(None);    }    let here = db        .get(            &format!("SELECT \"{column}\" AS v FROM {table} WHERE \"{pk}\" = ?", pk = spec.pk),            &[text(row_id)],        )?        .and_then(|row| row.text("v").map(str::to_string));    Ok(here.or_else(|| said.and_then(|patch| patch.get(column)).and_then(|v| v.as_str()).map(str::to_string)))}/// When `table`'s `row_id` is from, by its age column. `None` when the table/// has none, the row says nothing, or what it says is no date.fn age_ms(db: &Driver, table: &str, row_id: &str, said: Option<&Map<String, JsonValue>>) -> Result<Option<i64>> {    let Some(column) = age_column(table) else {        return Ok(None);    };    Ok(column_text(db, table, row_id, column, said)?.and_then(|at| js::parse_date_ms(&at)))}/// The governed owning parents `table`'s `row_id` names: `(parent table, id)`.fn governed_parents(    db: &Driver,    governed: &BTreeSet<&'static str>,    table: &str,    row_id: &str,    said: Option<&Map<String, JsonValue>>,) -> Result<Vec<(&'static str, String)>> {    let mut parents = Vec::new();    for (child, column, parent) in OWNING_REFS {        if *child != table || !governed.contains(parent) {            continue;        }        if let Some(parent_id) = column_text(db, table, row_id, column, said)? {            parents.push((*parent, parent_id));        }    }    Ok(parents)}// ── writing a rule ──────────────────────────────────────────────────────/// Refuse a rule nobody could keep. `set_rule` asks this; so does any other/// writer of the table before it mints.pub fn check_rule(db: &Driver, workspace_id: &str, device_id: &str, kind: &str, target: &str, rule: &str) -> Result<()> {    if crate::media_holdings::device_standing(db, workspace_id, device_id)?        != crate::media_holdings::DeviceStanding::Live    {        return Err(StoreError::refused("a keep rule needs a live device of this database"));    }    if !is_phone(db, device_id)? {        return Err(StoreError::refused(            "a Mac keeps everything: it may take over serving, so what it keeps cannot be narrowed or changed",        ));    }    match kind {        KIND_TABLE => {            if TableRule::parse(rule).is_none() {                return Err(StoreError::refused("a table's keep rule is all, none or days:N"));            }            if age_column(target).is_none() {                return Err(StoreError::refused(format!(                    "{target} is not a table a keep rule may narrow (keep::NARROWABLE)"                )));            }        }        KIND_GROUP => {            if rule != ALWAYS {                return Err(StoreError::refused("a group is kept always, or has no rule"));            }            let known = db                .get(                    "SELECT 1 AS x FROM cotton_media_albums WHERE id = ?1 \                     UNION ALL SELECT 1 FROM cotton_groups WHERE id = ?1 AND deleted_at IS NULL",                    &[text(target)],                )?                .is_some();            if !known {                return Err(StoreError::refused(format!("{target} is no group of this database")));            }        }        KIND_RECORD => {            if rule != ALWAYS {                return Err(StoreError::refused("a record is kept always, or has no rule"));            }            let Some((table, _row_id)) = record_target(target) else {                return Err(StoreError::refused("a record's keep rule names <table>:<row id>"));            };            // A made table's record lives in its own table, which only the            // file's definitions declare (`package_shape::spec_on`).            let spec = match spec_for(table) {                Some(spec) => Some(spec),                None => crate::schema::package_shape::spec_on(db, table)?,            };            if !spec.is_some_and(|spec| is_handed_over(spec.name)) {                return Err(StoreError::refused(format!("{table} is no table a device is sent")));            }            if Keep::of_device(db, device_id)?.table_rule(table) == TableRule::None {                return Err(StoreError::refused(format!("{table} {NEVER_REFUSAL}, so no record of it is kept")));            }        }        _ => return Err(StoreError::refused("a keep rule is of a table, a group or a record")),    }    Ok(())}/// Set one rule of one device: a minted write, so it reaches every device./// Returns the rule's id — derived, so the same rule set twice is one row.#[allow(clippy::too_many_arguments)]pub fn set_rule(    db: &Driver,    workspace_id: &str,    device_id: &str,    kind: &str,    target: &str,    rule: &str,    actor: Actor,    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<String> {    check_rule(db, workspace_id, device_id, kind, target, rule)?;    let id = derived_id::device_keep_id(device_id, kind, target);    let at = js::to_iso_string(now_ms).ok_or_else(|| StoreError::encode("keep rule date out of range"))?;    let mut patch = Map::new();    if db.get("SELECT id FROM cotton_device_keep WHERE id = ?", &[text(&id)])?.is_none() {        patch.insert("id".into(), json!(id));        patch.insert("workspace_id".into(), json!(workspace_id));        patch.insert("device_id".into(), json!(device_id));        patch.insert("kind".into(), json!(kind));        patch.insert("target".into(), json!(target));        patch.insert("created_at".into(), json!(at));    }    patch.insert("rule".into(), json!(rule));    patch.insert("updated_at".into(), json!(at));    let change = LocalChange {        kind: OpKind::Upsert,        table: TABLE.into(),        row_id: id.clone(),        patch: Some(patch),        delete: None,    };    write(db, actor, "set_keep_rule", change, now_ms, ids, held)?;    Ok(id)}/// Clear one rule of one device, back to `all`. `false` when there was none.#[allow(clippy::too_many_arguments)]pub fn clear_rule(    db: &Driver,    device_id: &str,    kind: &str,    target: &str,    actor: Actor,    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<bool> {    let id = derived_id::device_keep_id(device_id, kind, target);    if db.get("SELECT id FROM cotton_device_keep WHERE id = ?", &[text(&id)])?.is_none() {        return Ok(false);    }    write(db, actor, "clear_keep_rule", LocalChange::delete(TABLE, &id).retract(), now_ms, ids, held)?;    Ok(true)}fn write(    db: &Driver,    actor: Actor,    verb: &str,    change: LocalChange,    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<()> {    let clock = crate::mint::clock::writer_clock(db, now_ms, &mut *ids)?;    mint(        db,        &Act { actor, verb: verb.into(), history: History::None, changes: changes_of(db, &[change]) },        &clock,        ids,        held,    )?;    Ok(())}// ── on demand ───────────────────────────────────────────────────────────/// One answer of [`open`].#[derive(Debug, Clone, PartialEq, Default)]pub struct Opened {    /// The rows' receipts, as their authors' streams would carry them.    pub ops: Vec<CottonOp>,    /// The rows this answer restated.    pub rows: Vec<(String, String)>,    /// Where the next answer starts, when the record is more rows than one    /// answer holds.    pub next: Option<usize>,}/// A RECORD, WHOLE, FOR A DEVICE THAT OPENED IT: the receipts of `table`'s/// `row_id`, of the owning parents it could not land without, and of every/// row it owns — parents first, [`OPEN_PAGE_ROWS`] rows an answer, from/// `after`.////// This is how a row outside a device's rules reaches it: asked for by name,/// answered from the receipts the file holds, folded as a pulled arrival. The/// serving Mac keeps no memory of it — a device opens again to hear what/// changed. Refused for a row that is never kept ([`NEVER_REFUSAL`]); a row/// this file does not hold answers nothing.pub fn open(db: &Driver, keep: &Keep, table: &str, row_id: &str, after: usize, now_ms: i64) -> Result<Opened> {    // Any table a definition names opens: a made table's record by the same    // rules as a built-in's (architect, 13 Oct 2026: keep has no table list).    let Some(spec) = crate::schema::package_shape::spec_on(db, table)?.filter(|spec| is_handed_over(spec.name)) else {        return Err(StoreError::refused(format!("{table} is no table a device is sent")));    };    let table = spec.name;    if keep.verdict(db, table, row_id, now_ms)? == Verdict::Never {        return Err(StoreError::refused(format!("{table} {row_id} {NEVER_REFUSAL}")));    }    let mut rows: Vec<(String, String)> = Vec::new();    record_rows(db, keep, table, row_id, &mut rows)?;    let page: Vec<(String, String)> = rows.iter().skip(after).take(OPEN_PAGE_ROWS).cloned().collect();    let mut ops = Vec::new();    for (of_table, of_row) in &page {        ops.extend(receipts_of(db, of_table, of_row)?);    }    let reached = after + page.len();    Ok(Opened { ops, rows: page, next: (reached < rows.len()).then_some(reached) })}/// A record's rows, in the order a fold lands them, added to `rows`: the/// governed parents `table`'s `row_id` could not land without, the row, and/// every row it owns that a device is sent.fn record_rows(db: &Driver, keep: &Keep, table: &str, row_id: &str, rows: &mut Vec<(String, String)>) -> Result<()> {    owning_chain(db, &keep.governed, table, row_id, 0, rows)?;    let mut owned = crate::erase::owned_descendants(db, table, row_id)?;    // Deepest first as an erase wants them; parents first as a fold does.    owned.reverse();    for (owned_table, owned_id) in owned {        let sent = is_handed_over(&owned_table)            && keep.table_rule(&owned_table) != TableRule::None            && !keep.holds.holds(db, &owned_table, &owned_id, None)?;        if sent && !rows.contains(&(owned_table.clone(), owned_id.clone())) {            rows.push((owned_table, owned_id));        }    }    Ok(())}/// `table`'s `row_id` under the governed parents it names, topmost first.fn owning_chain(    db: &Driver,    governed: &BTreeSet<&'static str>,    table: &str,    row_id: &str,    depth: usize,    rows: &mut Vec<(String, String)>,) -> Result<()> {    let key = (table.to_string(), row_id.to_string());    if depth > MAX_DEPTH || rows.contains(&key) {        return Ok(());    }    for (parent, parent_id) in governed_parents(db, governed, table, row_id, None)? {        owning_chain(db, governed, parent, &parent_id, depth + 1, rows)?;    }    if !rows.contains(&key) {        rows.push(key);    }    Ok(())}/// Every receipt of one row that travels — its writes and its retract — in/// stamp order, signatures beside them. A held receipt never travels (3.8).fn receipts_of(db: &Driver, table: &str, row_id: &str) -> Result<Vec<CottonOp>> {    let mut ops = Vec::new();    for store in ["_writes", "_tombstones"] {        for row in db.all(            &format!(                "SELECT op_id, hlc, bytes, sig FROM {store} WHERE tbl = ? AND row_id = ? AND held = 0 ORDER BY hlc"            ),            &[text(table), text(row_id)],        )? {            ops.push(crate::stored::receipt_row(&row).map_err(StoreError::encode)?);        }    }    ops.sort_by(|a, b| a.hlc.cmp(&b.hlc));    Ok(ops)}/// Write down that this device opened `rows` now: the ledger the thirty-day/// drop reads (`_on_demand`). A row opened again keeps when it was first/// fetched and takes the new opening.pub fn record_opened(db: &Driver, rows: &[(String, String)], now_ms: i64) -> Result<()> {    let at = js::to_iso_string(now_ms).ok_or_else(|| StoreError::encode("opening date out of range"))?;    for (table, row_id) in rows {        db.run(            "INSERT INTO _on_demand (tbl, row_id, fetched_at, opened_at) VALUES (?, ?, ?, ?) \             ON CONFLICT (tbl, row_id) DO UPDATE SET opened_at = excluded.opened_at",            &[text(table), text(row_id), text(&at), text(&at)],        )?;    }    Ok(())}/// WHAT A DEVICE DOES WITH AN ANSWER OF [`open`]: fold the receipts as the/// pulled arrival they are — the answer of the peer this file syncs from —/// and write down that the rows were opened now.////// Parked exactly as an exchange answer's ops are (`exchange::fold_answer`):/// one held back for an author this file has no fact for waits for the fact,/// and one this file refuses is kept whole with its reason, never dropped.pub fn fold_opened(db: &Driver, ops: &[CottonOp], rows: &[(String, String)], now_ms: i64) -> Result<crate::fold::FoldResult> {    let result = fold_fetched(db, ops, now_ms)?;    record_opened(db, rows, now_ms)?;    Ok(result)}/// [`fold_opened`] for rows the rules KEEP ([`wanted`]): the same fold and no/// line in `_on_demand`, because a row a rule keeps is not dropped for being/// unopened.pub fn fold_fetched(db: &Driver, ops: &[CottonOp], now_ms: i64) -> Result<crate::fold::FoldResult> {    use crate::rejected::{park, park_waiting, retry_waiting_for, Class, Direction};    let now = js::to_iso_string(now_ms).ok_or_else(|| StoreError::encode("opening date out of range"))?;    let judge_ms = db.judge().and_then(|judge| judge.now());    let result = crate::fold::fold_pulled_judged(db, ops, judge_ms)?;    park_waiting(db, ops, &result.waiting, Direction::Pull, &now)?;    for author in &result.announced {        retry_waiting_for(db, author, &now)?;    }    for rejection in &result.rejected {        if let Some(op) = ops.iter().find(|op| op.op_id == rejection.op_id) {            park(db, op, Direction::Pull, Class::of_refusal(&rejection.reason), &rejection.reason, &now)?;        }    }    Ok(result)}// ── a rule that was widened ─────────────────────────────────────────────//// A narrower rule left rows out of every page and passed the cursors beyond// them: the phone holds no receipt of them and cannot ask for them by name.// When its rule widens it asks for the TABLE./// One answer of [`open_table`].#[derive(Debug, Clone, PartialEq, Default)]pub struct OpenedTable {    /// The receipts of the rows this answer restated.    pub ops: Vec<CottonOp>,    /// The rows this answer restated.    pub rows: Vec<(String, String)>,    /// The key this answer read up to: where the next one starts.    pub reached: String,    /// There are keys beyond `reached`.    pub more: bool,}/// How many keys of a table one answer of [`open_table`] reads at most. It/// also stops once it has restated [`OPEN_PAGE_ROWS`] rows, at the end of the/// record that crossed the line.pub const TABLE_PAGE_KEYS: usize = 500;/// A TABLE, FOR A DEVICE WHOSE RULE WAS WIDENED: the rows of `table` beyond/// the key `after` that the device's rules keep ([`Verdict::Inside`]), each/// whole as [`open`] answers a record — the parents it could not land/// without, and what it owns — in key order.////// Only a table a rule may narrow is answered this way ([`NARROWABLE`]);/// refused for a table that is never kept on the asking device. Rows the/// device already holds are restated too: the serving Mac keeps no memory of/// what a device has, and a receipt folded twice changes nothing.pub fn open_table(db: &Driver, keep: &Keep, table: &str, after: &str, now_ms: i64) -> Result<OpenedTable> {    let Some(spec) = spec_for(table).filter(|spec| is_handed_over(spec.name) && age_column(spec.name).is_some()) else {        return Err(StoreError::refused(format!("{table} is not a table a keep rule may narrow (keep::NARROWABLE)")));    };    let table = spec.name;    if keep.table_rule(table) == TableRule::None {        return Err(StoreError::refused(format!("{table} {NEVER_REFUSAL}")));    }    let keys = db.all(        &format!("SELECT \"{pk}\" AS id FROM {table} WHERE \"{pk}\" > ? ORDER BY \"{pk}\" LIMIT ?", pk = spec.pk),        &[text(after), SqlValue::Integer(i64::try_from(TABLE_PAGE_KEYS + 1).unwrap_or(i64::MAX))],    )?;    let mut answer = OpenedTable { reached: after.to_string(), ..OpenedTable::default() };    let mut read = 0;    for row_id in keys.iter().filter_map(|row| row.text("id")).take(TABLE_PAGE_KEYS) {        read += 1;        answer.reached = row_id.to_string();        if keep.verdict(db, table, row_id, now_ms)? != Verdict::Inside {            continue;        }        record_rows(db, keep, table, row_id, &mut answer.rows)?;        if answer.rows.len() >= OPEN_PAGE_ROWS {            break;        }    }    answer.more = read < keys.len();    for (of_table, of_row) in &answer.rows {        answer.ops.extend(receipts_of(db, of_table, of_row)?);    }    Ok(answer)}/// How much of a table a rule keeps, for comparing two rules: `none`, then a/// horizon by its days, then `all`.fn width(rule: TableRule) -> (u8, u32) {    match rule {        TableRule::None => (0, 0),        TableRule::Days(days) => (1, days),        TableRule::All => (2, 0),    }}/// A fetch a widened rule owes: ask [`open_table`] for `table` beyond `after`/// and hand the answer's end to [`widened`] with this `target`.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Widening {    pub table: String,    /// The rule the fetch is for, as its text.    pub target: String,    pub after: String,}/// WHAT THIS DEVICE'S WIDENED RULES OWE IT: each narrowable table whose rule/// now keeps more than this copy is complete for (`_keep_fetch`), with where/// its fetch got to. Writes the lines as it reads them:////// - a table with no line is taken as complete for the rule it has now — what///   every copy made before the line existed is, and what a first copy says///   of itself ([`cover_copy`]);/// - a rule that came to keep LESS, or the same: the copy is complete for it///   at once (what leaves is [`leave`]'s), and a fetch under way is dropped;/// - a rule that came to keep MORE: a fetch is owed, from the start when the///   rule is not the one the fetch under way was for.pub fn widenings(db: &Driver, keep: &Keep) -> Result<Vec<Widening>> {    let mut owed = Vec::new();    for (table, _age) in NARROWABLE {        let rule = keep.table_rule(table);        let said = rule.as_text();        let Some(line) = db.get("SELECT covered, target, after FROM _keep_fetch WHERE tbl = ?", &[text(table)])? else {            db.run("INSERT INTO _keep_fetch (tbl, covered) VALUES (?, ?)", &[text(table), text(&said)])?;            continue;        };        // A line nobody can read is the narrowest: the doubt fetches.        let covered = line.text("covered").and_then(TableRule::parse).unwrap_or(TableRule::None);        if width(rule) <= width(covered) {            if line.text("covered") != Some(said.as_str()) || line.text("target").is_some() {                db.run(                    "UPDATE _keep_fetch SET covered = ?, target = NULL, after = NULL WHERE tbl = ?",                    &[text(&said), text(table)],                )?;            }            continue;        }        let mut after = line.text("after").unwrap_or_default().to_string();        if line.text("target") != Some(said.as_str()) {            after.clear();            db.run("UPDATE _keep_fetch SET target = ?, after = '' WHERE tbl = ?", &[text(&said), text(table)])?;        }        owed.push(Widening { table: (*table).to_string(), target: said, after });    }    Ok(owed)}/// A page of a widening fetch was folded: the fetch for `target` has read up/// to `reached`, and with no `more` this copy is complete for `target`. A/// line whose target has changed since the page was asked for is left alone —/// the next [`widenings`] starts that fetch from the beginning.pub fn widened(db: &Driver, table: &str, target: &str, reached: &str, more: bool) -> Result<()> {    if more {        db.run(            "UPDATE _keep_fetch SET after = ? WHERE tbl = ? AND target = ?",            &[text(reached), text(table), text(target)],        )?;    } else {        db.run(            "UPDATE _keep_fetch SET covered = target, target = NULL, after = NULL WHERE tbl = ? AND target = ?",            &[text(table), text(target)],        )?;    }    Ok(())}/// A FIRST COPY SAYS WHAT IT IS COMPLETE FOR: the rules it was cut by/// ([`cut_copy`]), one line a narrowable table, replacing whatever the file it/// was copied from said of itself. So a rule widened between the copy and the/// device's first [`widenings`] is still fetched.pub fn cover_copy(db: &Driver, keep: &Keep) -> Result<()> {    db.run("DELETE FROM _keep_fetch", &[])?;    for (table, _age) in NARROWABLE {        db.run(            "INSERT INTO _keep_fetch (tbl, covered) VALUES (?, ?)",            &[text(table), text(&keep.table_rule(table).as_text())],        )?;    }    Ok(())}// ── the device's side: what leaves, and what the rules want back ────────//// The serving Mac only decides what it SENDS. What a phone already holds, and// what it was passed over on before a rule came to want it, are the phone's// to settle — with the same judge, so the two never disagree about a row./// What one pass of [`leave`] did.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct Left {    /// The rows that left this copy, the rows they own counted.    pub dropped: usize,    /// The tables they left, for the lists that show them to read again.    pub tables: BTreeSet<String>,    /// The rows passed over because this device still owes somebody a change    /// to them.    pub owed: usize,    /// The pass stopped at its limit: there is more to drop.    pub more: bool,}fn iso(ms: i64) -> Result<String> {    js::to_iso_string(ms).ok_or_else(|| StoreError::encode("keep date out of range"))}fn in_table(db: &Driver, table: &str, row_id: &str) -> Result<bool> {    let Some(spec) = spec_for(table) else {        return Ok(false);    };    Ok(db        .get(&format!("SELECT 1 AS x FROM {table} WHERE \"{pk}\" = ?", pk = spec.pk), &[text(row_id)])?        .is_some())}/// Does this device hold a change to `table`'s `row_id` that nobody else has/// yet: a push still queued, a held receipt, or a push its peer refused?fn owes(db: &Driver, table: &str, row_id: &str) -> Result<bool> {    let key = [text(table), text(row_id)];    Ok(db        .get(            "SELECT 1 AS x FROM _outbox WHERE tbl = ?1 AND row_id = ?2 \             UNION ALL SELECT 1 FROM _writes WHERE tbl = ?1 AND row_id = ?2 AND held = 1 \             UNION ALL SELECT 1 FROM _tombstones WHERE tbl = ?1 AND row_id = ?2 AND held = 1 \             UNION ALL SELECT 1 FROM _parked WHERE direction = 'push' AND tbl = ?1 AND row_id = ?2 LIMIT 1",            &key,        )?        .is_some())}/// THE LOCAL DROP: `table`'s `row_id` and the governed rows it owns leave/// THIS COPY — their receipts, their media-key names, their `_on_demand`/// lines, and their table rows by the fold's own presence rule (a row with no/// create is not present, so its search rows and its children follow). No/// tombstone and nothing minted: the row is not deleted, it is only not here,/// and nothing about it travels. The cursors do not move back, so the serving/// Mac never re-sends it; it returns when it is opened ([`open`]).////// The rows no rule governs that name it (`erase::OWNED_BY` — links, album/// items) stay: the serving Mac sends those to every device.////// A pass never drops a row this device still owes somebody a change to/// ([`owes`]): a drop never loses a write. A snapshot's COPY does not ask —/// its queue is the serving Mac's and is emptied with the copy.////// The drop of rows already listed is SET-BASED: each part of/// a row (its media-key names, receipts, tombstone, `_on_demand` line and/// table row, with the present rows that hang off it) leaves in one/// statement a table for all of them, in one transaction, whatever their/// number. A phone's first copy drops hundreds of thousands of rows; one at/// a time, each in its own savepoint, that was most of an hour on the/// owner's file (23 Oct 2026). The foreign keys are checked when the/// transaction commits, the set whole.////// `derive`: the computed values the rows fed are worked out again. A/// snapshot's copy passes `false` — the copy empties `_computed` whole and/// the device works it out from what it holds./// Drop `rows` (table, id) from this copy alone, as a keep rule drops them:/// the row and everything of it here — its receipts, its tombstone, its/// media-key names — and no retract minted, so nothing of it goes anywhere./// For rows this copy wrote for itself and never sent (TRIM: the shell's/// default lines).pub fn drop_here(db: &Driver, rows: &[(String, String)]) -> Result<()> {    db.transaction(|db| {        drop_listed(db, rows, true)?;        // A table a definition derives (a package's, the shell's lines) is not this build's to        // assemble: with its receipts gone, its row goes by its id.        for (table, id) in rows.iter().filter(|(table, _)| crate::schema::specs::spec_for(table).is_none()) {            if db.table_exists(table)? {                db.run(&format!("DELETE FROM \"{table}\" WHERE id = ?"), &[text(id)])?;            }        }        Ok(())    })}pub(crate) fn drop_listed(db: &Driver, rows: &[(String, String)], derive: bool) -> Result<()> {    if rows.is_empty() {        return Ok(());    }    db.transaction(|db| {        db.exec(            "CREATE TEMP TABLE IF NOT EXISTS _keep_cut (tbl TEXT NOT NULL, row_id TEXT NOT NULL, \             PRIMARY KEY (tbl, row_id)) WITHOUT ROWID",        )?;        db.run("DELETE FROM temp._keep_cut", &[])?;        for some in rows.chunks(10_000) {            let listed = serde_json::to_string(some).map_err(|e| StoreError::encode(e.to_string()))?;            db.run(                "INSERT OR IGNORE INTO temp._keep_cut (tbl, row_id) \                 SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?)",                &[text(&listed)],            )?;        }        db.exec("PRAGMA defer_foreign_keys = ON")?;        // A row that is not here names no key here: every name it holds goes.        for table in ["_media_key_names", "_writes", "_tombstones", "_on_demand"] {            db.run(                &format!("DELETE FROM {table} WHERE (tbl, row_id) IN (SELECT tbl, row_id FROM temp._keep_cut)"),                &[],            )?;        }        // With no receipt left no row is live: the fold's presence rule takes        // each out of its table, its present children with it.        crate::fold::remove_listed(db)?;        db.run("DELETE FROM temp._keep_cut", &[])?;        Ok(())    })?;    if derive {        crate::derived::after_fold(db, rows);    }    Ok(())}/// Was `table`'s `row_id` opened on this device since `fresh_from`?fn opened_since(db: &Driver, table: &str, row_id: &str, fresh_from: &str) -> Result<bool> {    Ok(db        .get(            "SELECT 1 AS x FROM _on_demand WHERE tbl = ? AND row_id = ? AND opened_at >= ?",            &[text(table), text(row_id), text(fresh_from)],        )?        .is_some())}/// WHAT THIS DEVICE HOLDS AND NO LONGER KEEPS, DROPPED ([`drop_listed`]), at/// most `limit` rows a pass:////// - every row of a table that is never kept;/// - a row past its table's horizon that the judge calls outside — so a pin or///   a kept group still holds it, and a record that LEFT a kept group goes;/// - a row opened from outside the rules and not opened again for///   [`ON_DEMAND_DAYS`]. One the rules have since come to keep only loses its///   line in `_on_demand`.////// A row opened within [`ON_DEMAND_DAYS`] is passed over, and so is a row/// this device still owes somebody a change to ([`Left::owed`]).pub fn leave(db: &Driver, keep: &Keep, now_ms: i64, limit: usize) -> Result<Left> {    leave_from(db, keep, now_ms, limit, true)}/// A PHONE'S FIRST COPY, CUT BY ITS RULES: everything [`leave`] would drop,/// dropped from the snapshot's COPY before the phone takes it, so a new phone/// never starts with what its rules leave out. Returns the rows cut.pub fn cut_copy(db: &Driver, keep: &Keep, now_ms: i64) -> Result<usize> {    Ok(leave_from(db, keep, now_ms, usize::MAX, false)?.dropped)}pub const KEEP_WRITES_PAGE: &str = "SELECT row_id FROM _writes WHERE tbl = ?1 AND row_id > ?2 ORDER BY row_id, hlc LIMIT 64";pub const KEEP_TOMBSTONES_PAGE: &str = "SELECT row_id FROM _tombstones WHERE tbl = ?1 AND row_id > ?2 ORDER BY row_id LIMIT 64";/// The rows a pass has judged to leave, taken a batch at a time: what each/// owns is read once for the batch ([`crate::erase::Owned::of`]) and the/// batch is dropped whole ([`drop_listed`]) — never a row at a time.struct Taking<'a> {    keep: &'a Keep,    limit: usize,    guard_owed: bool,    judged: Vec<(String, String)>,    /// Every row this pass dropped, so one an earlier row owned is not taken    /// twice.    taken: BTreeSet<(String, String)>,    left: Left,}/// The most rows judged before their batch is dropped.const TAKE_BATCH: usize = 20_000;impl Taking<'_> {    /// `table`'s `row_id` leaves; false once the pass is at its limit.    fn take(&mut self, db: &Driver, table: &str, row_id: &str) -> Result<bool> {        if self.left.more {            return Ok(false);        }        self.judged.push((table.to_string(), row_id.to_string()));        let room = self.limit.saturating_sub(self.left.dropped).clamp(1, TAKE_BATCH);        if self.judged.len() >= room {            self.flush(db)?;        }        Ok(!self.left.more)    }    /// Drop what is judged: each row with the governed rows it owns, unless    /// this device still owes somebody a change to one of them ([`owes`]).    fn flush(&mut self, db: &Driver) -> Result<()> {        let judged = std::mem::take(&mut self.judged);        if judged.is_empty() {            return Ok(());        }        let owned = crate::erase::Owned::of(db, &judged)?;        let mut batch = Vec::new();        for (table, row_id) in judged {            if self.taken.contains(&(table.clone(), row_id.clone())) {                continue;            }            if self.left.dropped >= self.limit {                self.left.more = true;                break;            }            let Some(spec) = spec_for(&table) else {                continue;            };            let mut rows: Vec<(String, String)> = owned                .descendants(db, spec.name, &row_id)?                .into_iter()                .filter(|row| self.keep.governed.contains(row.0.as_str()) && !self.taken.contains(row))                .collect();            rows.push((spec.name.to_string(), row_id));            if self.guard_owed {                let mut owed = false;                for (of_table, of_row) in &rows {                    owed |= owes(db, of_table, of_row)?;                }                if owed {                    self.left.owed += 1;                    continue;                }            }            self.left.dropped += rows.len();            self.left.tables.extend(rows.iter().map(|(table, _)| table.clone()));            self.taken.extend(rows.iter().cloned());            batch.extend(rows);        }        drop_listed(db, &batch, self.guard_owed)    }}fn leave_from(db: &Driver, keep: &Keep, now_ms: i64, limit: usize, guard_owed: bool) -> Result<Left> {    let fresh_from = iso(now_ms - ON_DEMAND_DAYS * DAY_MS)?;    let mut taking = Taking { keep, limit, guard_owed, judged: Vec::new(), taken: BTreeSet::new(), left: Left::default() };    let mut left = taking.judge(db, keep, now_ms, &fresh_from)?;    taking.flush(db)?;    left.dropped += taking.left.dropped;    left.owed += taking.left.owed;    left.more |= taking.left.more;    left.tables.extend(std::mem::take(&mut taking.left.tables));    Ok(left)}impl Taking<'_> {    /// What leaves, judged in the order a pass takes it; answers what left    /// outside the batches (the rows this device may never hold).    fn judge(&mut self, db: &Driver, keep: &Keep, now_ms: i64, fresh_from: &str) -> Result<Left> {    let mut left = Left::default();    let fresh_from = fresh_from.to_string();    // A copy's computed values are worked out on the device that takes it.    let derive = self.guard_owed;    let mut take = |db: &Driver, _left: &mut Left, table: &str, row_id: &str| -> Result<bool> { self.take(db, table, row_id) };    // WHAT THIS DEVICE MAY NEVER HOLD leaves first, whole: a member's copy    // starts without a single only-you row, receipt or tombstone. Never    // guarded by what the device owes — it may not hold the row at all.    if !keep.holds.is_empty() {        let rows = keep.holds.rows(db)?;        if !rows.is_empty() {            drop_listed(db, &rows, derive)?;            left.dropped += rows.len();            left.tables.extend(rows.into_iter().map(|(table, _)| table));        }    }    for (table, rule) in &keep.tables {        let Some(spec) = spec_for(table) else {            continue;        };        match rule {            TableRule::All => {}            TableRule::None => {                // Present or dormant, and a retract held from before the rule.                // Deleting a row removes its receipts on both sides. Advancing                // by row id also skips repeated receipts of an owed row.                for sql in [KEEP_WRITES_PAGE, KEEP_TOMBSTONES_PAGE] {                    let mut after = String::new();                    loop {                        let held = db.all(sql, &[text(table), text(&after)])?;                        let Some(last) = held.last().and_then(|row| row.text("row_id")) else { break; };                        after = last.to_string();                        let ids: BTreeSet<_> = held.iter().filter_map(|row| row.text("row_id")).collect();                        for row_id in ids {                            // An owed row kept its writes: it was already                            // judged on that side, as UNION did before paging.                            if sql == KEEP_TOMBSTONES_PAGE && db.get(                                "SELECT 1 AS present FROM _writes WHERE tbl = ?1 AND row_id = ?2 LIMIT 1",                                &[text(table), text(row_id)],                            )?.is_some() { continue; }                            if !take(db, &mut left, table, row_id)? { return Ok(left); }                        }                    }                }            }            TableRule::Days(days) => {                let Some(age) = age_column(table) else {                    continue;                };                // The dates are ISO text, so text order finds the old rows;                // the judge then reads each one's date properly.                let oldest = iso(now_ms - i64::from(*days) * DAY_MS)?;                let mut after = String::new();                loop {                    let page = db.all(                        &format!(                            "SELECT \"{pk}\" AS id FROM {table} WHERE \"{age}\" < ? AND \"{pk}\" > ? \                             ORDER BY \"{pk}\" LIMIT 500",                            pk = spec.pk                        ),                        &[text(&oldest), text(&after)],                    )?;                    let Some(last) = page.last().and_then(|row| row.text("id")) else {                        break;                    };                    after = last.to_string();                    for row_id in page.iter().filter_map(|row| row.text("id")) {                        if opened_since(db, table, row_id, &fresh_from)?                            || keep.verdict(db, table, row_id, now_ms)? == Verdict::Inside                        {                            continue;                        }                        if !take(db, &mut left, table, row_id)? {                            return Ok(left);                        }                    }                }            }        }    }    // What was opened from outside the rules and has sat unopened since.    let stale: Vec<(String, String)> = db        .all("SELECT tbl, row_id FROM _on_demand WHERE opened_at < ? ORDER BY opened_at, tbl, row_id", &[text(&fresh_from)])?        .iter()        .filter_map(|row| Some((row.text("tbl")?.to_string(), row.text("row_id")?.to_string())))        .collect();    for (table, row_id) in &stale {        if keep.verdict(db, table, row_id, now_ms)? == Verdict::Inside {            // Kept by a rule now: nothing to wait thirty days for.            db.run("DELETE FROM _on_demand WHERE tbl = ? AND row_id = ?", &[text(table), text(row_id)])?;            continue;        }        // A row fetched under a parent that is still being opened stays with it.        let mut under_open = false;        for (parent, parent_id) in governed_parents(db, &keep.governed, table, row_id, None)? {            under_open |= opened_since(db, parent, &parent_id, &fresh_from)?;        }        // Its line is gone when a row dropped earlier in this pass owned it.        let line = db.get("SELECT 1 AS x FROM _on_demand WHERE tbl = ? AND row_id = ?", &[text(table), text(row_id)])?;        if under_open || line.is_none() {            continue;        }        if !take(db, &mut left, table, row_id)? {            return Ok(left);        }    }    Ok(left)}}/// The topmost row this file must be handed for `table`'s `row_id` to be/// present: the row itself when this file holds no create of it, or the first/// governed owning parent that is not here, upward. `None` when the row is/// present, was retracted, is of a table never kept, or waits on something no/// rule governs.fn missing_root(db: &Driver, keep: &Keep, table: &str, row_id: &str, depth: usize) -> Result<Option<(String, String)>> {    if depth > MAX_DEPTH || keep.table_rule(table) == TableRule::None || in_table(db, table, row_id)? {        return Ok(None);    }    let receipts = crate::receipts::of_row(db, table, row_id)?;    let retract = crate::receipts::retract_stamp(db, table, row_id)?;    if retract.is_some() {        return Ok(None);    }    let life = crate::receipts::assemble_under(table, &receipts, None, false);    let said: Map<String, JsonValue> = life.fields.iter().map(|(name, current)| (name.clone(), current.value.clone())).collect();    for (parent, parent_id) in governed_parents(db, &keep.governed, table, row_id, Some(&said))? {        if !in_table(db, parent, &parent_id)? {            return missing_root(db, keep, parent, &parent_id, depth + 1);        }    }    Ok((!life.live).then(|| (table.to_string(), row_id.to_string())))}/// WHAT THE RULES KEEP THAT THIS DEVICE DOES NOT HOLD, as far as its own file/// can tell — at most `limit` rows, each to be fetched whole ([`open`]) and/// folded with [`fold_fetched`]:////// - a governed row this file holds receipts of and no create — an old thread///   a new message revived: the page carried the change, the fold keeps it///   dormant (a row is live only with its create), and here it is asked for;/// - a row whose governed owning parent is not here — the parent is asked for,///   and brings what it owns;/// - a pinned record that is not here;/// - a member of a kept group that is not here.////// Not what a TABLE rule widened later wants back: this file cannot name rows/// it never heard of. That is a fetch by table ([`widenings`]).pub fn wanted(db: &Driver, keep: &Keep, limit: usize) -> Result<Vec<(String, String)>> {    let mut wanted: BTreeSet<(String, String)> = BTreeSet::new();    if !keep.narrows() || limit == 0 {        return Ok(Vec::new());    }    let ask = |db: &Driver, wanted: &mut BTreeSet<(String, String)>, table: &str, row_id: &str| -> Result<()> {        if wanted.len() < limit {            if let Some(root) = missing_root(db, keep, table, row_id, 0)? {                wanted.insert(root);            }        }        Ok(())    };    for (table, row_id) in &keep.pins {        if keep.governed.contains(table.as_str()) {            ask(db, &mut wanted, table, row_id)?;        }    }    if !keep.groups.is_empty() {        let marks = vec!["?"; keep.groups.len()].join(", ");        let params: Vec<SqlValue> = keep.groups.iter().map(|group| text(group)).collect();        for member in db.all(            &format!(                "SELECT g.table_id AS of, m.record_id AS member FROM cotton_groups g \                 JOIN cotton_group_members m ON m.group_id = g.id \                 WHERE g.deleted_at IS NULL AND g.id IN ({marks}) ORDER BY g.id, m.record_id"            ),            &params,        )? {            let (Some(of), Some(member)) = (member.text("of"), member.text("member")) else {                continue;            };            let Some((table, _)) = GROUPED_AS.iter().find(|(_, id)| *id == of) else {                continue;            };            ask(db, &mut wanted, table, member)?;        }    }    // The governed rows this file holds receipts of and does not show.    for table in keep.governed.iter().copied() {        if wanted.len() >= limit {            break;        }        let Some(spec) = spec_for(table) else {            continue;        };        if keep.table_rule(table) == TableRule::None {            continue;        }        let dormant = db.all(            &format!(                "SELECT DISTINCT w.row_id AS id FROM _writes w WHERE w.tbl = ?1 \                 AND NOT EXISTS (SELECT 1 FROM {table} t WHERE t.\"{pk}\" = w.row_id) \                 AND NOT EXISTS (SELECT 1 FROM _tombstones d WHERE d.tbl = ?1 AND d.row_id = w.row_id) LIMIT ?2",                pk = spec.pk            ),            &[text(table), SqlValue::Integer(i64::try_from(limit).unwrap_or(i64::MAX))],        )?;        for row_id in dormant.iter().filter_map(|row| row.text("id")) {            ask(db, &mut wanted, table, row_id)?;        }    }    Ok(wanted.into_iter().collect())}#[cfg(test)]#[path = "keep_tests.rs"]mod tests;