//! 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::ValueasSqlValue;use serde_json::{json, Map, ValueasJsonValue};usecrate::actor::Actor;usecrate::driver::Driver;usecrate::error::{Result, StoreError};usecrate::mint::{changes_of, mint, Act, Held, History};usecrate::outbox::{IdSource, LocalChange};usecrate::protocol::types::{CottonOp, OpKind};usecrate::protocol::{derived_id, js};usecrate::schema::specs::spec_for;usecrate::schema::table_specs::{is_handed_over, OWNING_REFS};/// The rules' own table.pubconst TABLE: &str = "cotton_device_keep";/// How long a row opened from outside the rules stays on the device unopened.pubconst ON_DEMAND_DAYS: i64 = 30;/// How many rows one answer of [`open`] restates.pubconst OPEN_PAGE_ROWS: usize = 500;/// What an [`open`] of a row that is never kept is refused with.pubconst 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`]).pubconst STATUS_MEDIA_FOLDER: &str = "statuses";/// Is `key` a status's media — `{file}/messages/statuses/…`?pubfn is_status_media(key: &str) -> bool {letmut 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.pubfn 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.pubstatic 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.pubfn 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.pubstatic 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.pubconst 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`).pubconst 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)]pubenumTableRule {/// 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),}implTableRule {/// `all`, `none` or `days:N` (N a whole number of days, one or more).pubfn 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()) {returnNone; } days.parse().ok().map(TableRule::Days) } } }/// The text the `rule` column holds.pubfn as_text(self) -> String {matchself {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.pubconst KIND_TABLE: &str = "table";pubconst KIND_GROUP: &str = "group";pubconst KIND_RECORD: &str = "record";/// The rule a GROUP or a RECORD carries.pubconst ALWAYS: &str = "always";/// One stored rule, as a list shows it.#[derive(Debug, Clone, PartialEq, Eq)]pubstructRuleRow {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)]pubenumVerdict {/// 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).pubfn 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.pubfn 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.pubfn 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.pubfn 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`.pubfn 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)]pubstructKeep {/// 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,}implKeep {/// A device that keeps everything: a Mac, or a phone with no narrowing rule.pubfn 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).pubfn new_phone() -> Keep {letmut 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.pubfn 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.returnOk(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() };letmut keep = Keep { holds, ..start };letmut pinned: Vec<(String, String)> = Vec::new();for row in rules_of(db, device_id)? {match row.kind.as_str() { KIND_TABLE => matchTableRule::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 => {ifletSome((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.pubfn pinned_by_anyone(db: &Driver) -> Result<Keep> {letmut 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()); } elseifletSome((table, row_id)) = record_target(target) { keep.records.insert((table.to_string(), row_id.to_string())); } }Ok(keep) }fn pin_with_parents(&mutself, db: &Driver, table: &str, row_id: &str, depth: usize) -> Result<()> {if depth > MAX_DEPTH || !self.pins.insert((table.to_string(), row_id.to_string())) {returnOk(()); }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.pubfn fingerprint(&self) -> String {use sha2::Digest;letmut hash = sha2::Sha256::new();for (table, rule) in &self.tables { hash.update(format!("t\u{1f}{table}\u{1f}{rule:?}\u{1e}")); }letmut 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?pubfn narrows(&self) -> bool { !self.tables.is_empty() }/// The rule `table` itself carries (not what its owners carry).pubfn 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.pubfn 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() {returnOk(ops); }letmut memo = Memo::new();letmut 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`.pubfn verdict(&self, db: &Driver, table: &str, row_id: &str, now_ms: i64) -> Result<Verdict> {ifself.holds.holds(db, table, row_id, None)? {returnOk(Verdict::Never); }self.judge(db, table, row_id, None, now_ms, &mutMemo::new(), 0) }/// What this device may not hold at all (`crate::audience`).pubfn 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: &mutMemo, depth: usize, ) -> Result<Verdict> {if !self.governed.contains(table) || depth > MAX_DEPTH {returnOk(Verdict::Inside); }let key = (table.to_string(), row_id.to_string());ifletSome(known) = memo.get(&key) {returnOk(*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 = matchself.table_rule(table) {TableRule::All => Verdict::Inside,TableRule::None => Verdict::Never,TableRule::Days(days) => {ifself.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, } } } };letmut 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.pubfn pins_key(&self, db: &Driver, key: &str) -> Result<bool> {ifself.groups.is_empty() && self.records.is_empty() {returnOk(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; };ifself.kept_always(db, table, row_id, 0)? {returnOk(true); } }Ok(false) }/// Named pins for rule-fetch progress; uses the same pin judge as eviction.pubfn byte_pin_scopes(db: &Driver, device: &str) -> Result<Vec<(String, String, Keep)>> {letmut answer = Vec::new();for row in rules_of(db, device)? {letmut scope = Keep::default();if row.kind == KIND_GROUP { scope.groups.push(row.target.clone()); } elseif row.kind == KIND_RECORD {ifletSome((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 {returnOk(false); }ifself.records.contains(&(table.to_string(), row_id.to_string())) || self.in_a_kept_group(db, row_id)? {returnOk(true); }for (child, column, parent) in OWNING_REFS {if *child != table {continue; }ifletSome(parent_id) = column_text(db, table, row_id, column, None)? {ifself.kept_always(db, parent, &parent_id, depth + 1)? {returnOk(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> {ifself.groups.is_empty() || row_id.contains('"') {returnOk(false); }let marks = vec!["?"; self.groups.len()].join(", ");letmut 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" ), ¶ms, )? .is_some() {returnOk(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" ), ¶ms, )? .is_some()) }}typeMemo = 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: implIterator<Item = &'a str>) -> BTreeSet<&'static str> {letmut governed: BTreeSet<&'static str> = BTreeSet::new();for table in narrowed {ifletSome(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>> {letSome(spec) = spec_for(table) else {returnOk(None); };if !spec.columns.iter().any(|(name, _)| *name == column) {returnOk(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>> {letSome(column) = age_column(table) else {returnOk(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)>> {letmut parents = Vec::new();for (child, column, parent) in OWNING_REFS {if *child != table || !governed.contains(parent) {continue; }ifletSome(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.pubfn check_rule(db: &Driver, workspace_id: &str, device_id: &str, kind: &str, target: &str, rule: &str) -> Result<()> {ifcrate::media_holdings::device_standing(db, workspace_id, device_id)? != crate::media_holdings::DeviceStanding::Live {returnErr(StoreError::refused("a keep rule needs a live device of this database")); }if !is_phone(db, device_id)? {returnErr(StoreError::refused("a Mac keeps everything: it may take over serving, so what it keeps cannot be narrowed or changed", )); }match kind { KIND_TABLE => {ifTableRule::parse(rule).is_none() {returnErr(StoreError::refused("a table's keep rule is all, none or days:N")); }if age_column(target).is_none() {returnErr(StoreError::refused(format!("{target} is not a table a keep rule may narrow (keep::NARROWABLE)" ))); } } KIND_GROUP => {if rule != ALWAYS {returnErr(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 {returnErr(StoreError::refused(format!("{target} is no group of this database"))); } } KIND_RECORD => {if rule != ALWAYS {returnErr(StoreError::refused("a record is kept always, or has no rule")); }letSome((table, _row_id)) = record_target(target) else {returnErr(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)) {returnErr(StoreError::refused(format!("{table} is no table a device is sent"))); }ifKeep::of_device(db, device_id)?.table_rule(table) == TableRule::None {returnErr(StoreError::refused(format!("{table} {NEVER_REFUSAL}, so no record of it is kept"))); } } _ => returnErr(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)]pubfn set_rule( db: &Driver, workspace_id: &str, device_id: &str, kind: &str, target: &str, rule: &str, actor: Actor, now_ms: i64, ids: &mutdynIdSource, 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"))?;letmut 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)]pubfn clear_rule( db: &Driver, device_id: &str, kind: &str, target: &str, actor: Actor, now_ms: i64, ids: &mutdynIdSource, 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() {returnOk(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: &mutdynIdSource, 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)]pubstructOpened {/// 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.pubfn 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).letSome(spec) = crate::schema::package_shape::spec_on(db, table)?.filter(|spec| is_handed_over(spec.name)) else {returnErr(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 {returnErr(StoreError::refused(format!("{table} {row_id} {NEVER_REFUSAL}"))); }letmut 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();letmut 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: &mutVec<(String, String)>) -> Result<()> { owning_chain(db, &keep.governed, table, row_id, 0, rows)?;letmut 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: &mutVec<(String, String)>,) -> Result<()> {let key = (table.to_string(), row_id.to_string());if depth > MAX_DEPTH || rows.contains(&key) {returnOk(()); }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>> {letmut 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.pubfn 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.pubfn 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.pubfn fold_fetched(db: &Driver, ops: &[CottonOp], now_ms: i64) -> Result<crate::fold::FoldResult> {usecrate::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 {ifletSome(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)]pubstructOpenedTable {/// 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.pubconst 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.pubfn open_table(db: &Driver, keep: &Keep, table: &str, after: &str, now_ms: i64) -> Result<OpenedTable> {letSome(spec) = spec_for(table).filter(|spec| is_handed_over(spec.name) && age_column(spec.name).is_some()) else {returnErr(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 {returnErr(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))], )?;letmut answer = OpenedTable { reached: after.to_string(), ..OpenedTable::default() };letmut 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)]pubstructWidening {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.pubfn widenings(db: &Driver, keep: &Keep) -> Result<Vec<Widening>> {letmut owed = Vec::new();for (table, _age) in NARROWABLE {let rule = keep.table_rule(table);let said = rule.as_text();letSome(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; }letmut 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.pubfn 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.pubfn 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)]pubstructLeft {/// 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> {letSome(spec) = spec_for(table) else {returnOk(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).pubfn 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() {returnOk(()); } 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`]).pubfn 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.pubfn cut_copy(db: &Driver, keep: &Keep, now_ms: i64) -> Result<usize> {Ok(leave_from(db, keep, now_ms, usize::MAX, false)?.dropped)}pubconst KEEP_WRITES_PAGE: &str = "SELECT row_id FROM _writes WHERE tbl = ?1 AND row_id > ?2 ORDER BY row_id, hlc LIMIT 64";pubconst 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.structTaking<'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;implTaking<'_> {/// `table`'s `row_id` leaves; false once the pass is at its limit.fn take(&mutself, db: &Driver, table: &str, row_id: &str) -> Result<bool> {ifself.left.more {returnOk(false); }self.judged.push((table.to_string(), row_id.to_string()));let room = self.limit.saturating_sub(self.left.dropped).clamp(1, TAKE_BATCH);ifself.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(&mutself, db: &Driver) -> Result<()> {let judged = std::mem::take(&mutself.judged);if judged.is_empty() {returnOk(()); }let owned = crate::erase::Owned::of(db, &judged)?;letmut batch = Vec::new();for (table, row_id) in judged {ifself.taken.contains(&(table.clone(), row_id.clone())) {continue; }ifself.left.dropped >= self.limit {self.left.more = true;break; }letSome(spec) = spec_for(&table) else {continue; };letmut 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));ifself.guard_owed {letmut 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)?;letmut taking = Taking { keep, limit, guard_owed, judged: Vec::new(), taken: BTreeSet::new(), left: Left::default() };letmut 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)}implTaking<'_> {/// 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(&mutself, db: &Driver, keep: &Keep, now_ms: i64, fresh_from: &str) -> Result<Left> {letmut 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;letmut take = |db: &Driver, _left: &mutLeft, 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 {letSome(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] {letmut after = String::new();loop {let held = db.all(sql, &[text(table), text(&after)])?;letSome(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)? { returnOk(left); } } } } }TableRule::Days(days) => {letSome(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)?;letmut 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)], )?;letSome(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)? {returnOk(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.letmut 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)? {returnOk(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)? {returnOk(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() {returnOk(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`]).pubfn wanted(db: &Driver, keep: &Keep, limit: usize) -> Result<Vec<(String, String)>> {letmut wanted: BTreeSet<(String, String)> = BTreeSet::new();if !keep.narrows() || limit == 0 {returnOk(Vec::new()); }let ask = |db: &Driver, wanted: &mut BTreeSet<(String, String)>, table: &str, row_id: &str| -> Result<()> {if wanted.len() < limit {ifletSome(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" ), ¶ms, )? {let (Some(of), Some(member)) = (member.text("of"), member.text("member")) else {continue; };letSome((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; }letSome(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;