//! An ERASE ends a record for good, in every file. //! //! No table is cascaded away with a bin row (store v52, guard //! `no_table_a_bin_row_cascades_into`): the fold takes owning children out //! itself rather than SQLite removing them behind it. //! //! ## The ERASE kind (design 6.2, slice 5a-ii) //! //! A retract whose receipt names an `erase` reason ([`crate::mint::Delete`]) //! ends its record for good, wherever it is folded: [`apply`] takes out the //! row, its owned descendants ([`owned_descendants`]: owning children by //! `OWNING_REFS`, present or dormant, and the rows [`OWNED_BY`] declares), //! their receipts, queued pushes, history and search rows, and keeps one //! `_gone` row per erased row holding the erase's receipt byte for byte. The //! erase's own receipt stays the row's tombstone too, so it travels on the //! paths a retract already travels (the exchange, the hand-over, the //! snapshot), and every device that folds it does the same. A later write //! at an erased id, or under an erased parent, is refused with a //! [`GONE_REFUSAL`] reason, which parks `gone`. //! //! It is reached from the fold only through `fact_hooks::arriving`, which //! every receipt the file does not hold passes before it is stored. use std::cell::RefCell; use std::collections::{BTreeMap, BTreeSet}; use rusqlite::types::Value as SqlValue; use crate::canonical::{Kind, Receipt}; use crate::driver::Driver; use crate::error::Result; use crate::protocol::types::CottonOp; use crate::schema::specs::spec_for; use crate::schema::table_specs::OWNING_REFS; /// Every table whose rows wait in the bin: `(table, the column set while a /// row is in the bin, the record_kind its history rows carry)`. /// /// The store knows tables, not kinds, so this is the bin engine's list /// restated; the guard `the_store_bin_tables_are_the_engine_bin_sources` /// (cotton-core) holds it equal to `rules::bin::bin_source` over every /// `BinKind`, so a new binnable kind cannot skip it. pub static BIN_TABLES: &[(&str, &str, &str)] = &[ ("cotton_money_transactions", "trashed_at", "transaction"), ("cotton_emails", "trashed_at", "email"), ("cotton_email_threads", "trashed_at", "email_thread"), ("cotton_secrets", "trashed_at", "secret"), ("cotton_decisions", "trashed_at", "decision"), ("cotton_notes", "trashed_at", "note"), ("cotton_events", "trashed_at", "event"), ("cotton_goals", "trashed_at", "goal"), ("cotton_moods", "trashed_at", "mood"), ("cotton_alarms", "trashed_at", "alarm"), ("cotton_meetings", "trashed_at", "meeting"), ("cotton_photos", "trashed_at", "photo"), ("cotton_videos", "trashed_at", "video"), ("cotton_documents", "trashed_at", "document"), ("cotton_msg_messages", "trashed_at", "message"), ("cotton_screenplay_characters", "trashed_at", "screenplay_character"), ("cotton_news_topics", "trashed_at", "news_topic"), ("cotton_todos", "trashed_at", "todo"), ]; /// How a refusal of a write at an erased id begins: `rejected::Class:: /// of_refusal` reads it as `gone`. pub const GONE_REFUSAL: &str = "gone:"; /// The rows that name a record without a foreign key and leave with it when /// it is erased (design 6.2's `OWNED_BY`): `(table, column naming the /// record, extra condition)`. A record is named by its id alone — every id /// here is a uuid, so an id names one record whatever its kind. A link names /// a row in this database only while `to_database` is NULL. pub static OWNED_BY: &[(&str, &str, &str)] = &[ ("cotton_links", "from_id", ""), ("cotton_links", "to_id", " AND to_database IS NULL"), ("cotton_project_links", "record_id", ""), ("cotton_media_album_items", "record_id", ""), ("cotton_media_faces", "record_id", ""), ("cotton_media_sightings", "record_id", ""), ("cotton_note_attachments", "record_id", ""), ("cotton_thought_attachments", "record_id", ""), // Server-only: a repository's variables are no row of any other file. ("cotton_repo_vars", "repo_id", ""), ]; /// Whether this file erased the row: `_gone` holds it. pub fn is_gone(db: &Driver, table: &str, row_id: &str) -> Result { Ok(db .get( "SELECT 1 AS gone FROM _gone WHERE tbl = ? AND row_id = ?", &[SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())], )? .is_some()) } /// The erase of the record `record_id`, when this file erased it — its /// `(stamp, author)`, by the record's id alone, as an erase takes the record's /// history (every id is a uuid, and a history row may name its table by its /// definition id). fn erase_of_record(db: &Driver, record_id: &str) -> Result> { Ok(db .get( "SELECT hlc, author FROM _gone WHERE row_id = ? AND tbl <> ? ORDER BY hlc LIMIT 1", &[SqlValue::Text(record_id.to_string()), SqlValue::Text(HISTORY_TABLE.to_string())], )? .map(|row| { let text = |c: &str| row.text(c).unwrap_or_default().to_string(); (text("hlc"), text("author")) })) } /// Why `receipt` may not apply here, when it writes at an erased id or names /// an erased owning parent. `None` for every other receipt. pub(crate) fn refusal(db: &Driver, op: &CottonOp, receipt: &Receipt) -> Result> { if is_gone(db, &op.table, &op.row_id)? { return Ok(Some(format!( "{GONE_REFUSAL} {} {} was erased, and a later write at its id is never applied", op.table, op.row_id ))); } if let Some(reason) = crate::mint::history::of_gone(op, receipt, |id| erase_of_record(db, id))? { return Ok(Some(reason)); } if receipt.kind == Kind::Retract { return Ok(None); } for (child, column, parent) in OWNING_REFS { if *child != op.table { continue; } let Some(parent_id) = receipt.fields.get(*column).and_then(|v| v.as_str()) else { continue; }; if is_gone(db, parent, parent_id)? { return Ok(Some(format!( "{GONE_REFUSAL} {} {} names {parent} {parent_id}, which was erased, so it is never applied", op.table, op.row_id ))); } } Ok(None) } /// A search index's delete leaves a row's words in its earlier pages until they are merged. An erase deletes plainly /// and the background purge merges the index after (`crate::fts_purge`, DELETE FAST, 24 Nov 2026; before it, every /// erase deleted securely, minutes on a phone for a sender's mail). pub fn secure_search(db: &Driver, table: &str) -> Result<()> { crate::fts_purge::mark(db, table) } /// Apply an erase: `receipt` is a retract naming an `erase` reason. Takes /// out the row and its owned descendants — table rows, receipts, queued /// pushes, history, search rows, media-key names — and keeps a `_gone` row /// for each, holding this receipt. The fold then stores the receipt as the /// row's tombstone, as it stores any retract. pub(crate) fn apply(db: &Driver, op: &CottonOp, receipt: &Receipt, owned: &Owned) -> Result<()> { let Some(reason) = receipt.erase.as_deref() else { return Ok(()); }; let mut rows = owned.descendants(db, &op.table, &op.row_id)?; rows.push((op.table.clone(), op.row_id.clone())); // ITS HISTORY GOES WITH IT (slice 6): each history row is a fact, taken // out and kept `_gone` like the row, so no device holds or takes it back. let history = history_rows(db, &rows, owned)?; rows.splice(0..0, history); let tables: BTreeSet<&str> = rows.iter().map(|(table, _)| table.as_str()).collect(); for table in tables { secure_search(db, table)?; } // Children before parents, so no owning foreign key is left dangling. for (table, row_id) in &rows { if let Some(spec) = crate::schema::package_shape::spec_on(db, table)? { if owned.table_exists(db, table)? { db.run( &format!("DELETE FROM {table} WHERE \"{}\" = ?", spec.pk), &[SqlValue::Text(row_id.clone())], )?; } } } // The keys these rows name leave the index with them — each by the whole // of its primary key, which begins with the key. let mut named = BTreeSet::new(); for (table, row_id) in &rows { for key in owned.key_names(db, table, row_id)? { db.run( // not a copy: _media_key_names, which rows name which media key, derived. "DELETE FROM _media_key_names WHERE key = ? AND tbl = ? AND row_id = ?", &[SqlValue::Text(key.clone()), SqlValue::Text(table.clone()), SqlValue::Text(row_id.clone())], )?; named.insert(key); } } let sig = crate::receipts::sig_value(op); for (table, row_id) in &rows { let key = [SqlValue::Text(table.clone()), SqlValue::Text(row_id.clone())]; // A write of it parked here holds what it said (its bytes): it goes too. for place in ["_writes", "_tombstones", "_outbox", "_parked"] { db.run(&format!("DELETE FROM {place} WHERE tbl = ? AND row_id = ?"), &key)?; } db.run( "INSERT INTO _gone (tbl, row_id, hlc, reason, op_id, author, actor, bytes, sig) \ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(tbl, row_id) DO NOTHING", &[ SqlValue::Text(table.clone()), SqlValue::Text(row_id.clone()), SqlValue::Text(receipt.stamp.clone()), SqlValue::Text(reason.to_string()), SqlValue::Text(op.op_id.clone()), SqlValue::Text(receipt.author.clone()), SqlValue::Text(receipt.actor.clone()), SqlValue::Blob(op.receipt.as_bytes().to_vec()), sig.clone(), ], )?; } // A key these rows were the last to name, which an erasure already names, // is dead now: it enters the unlink queue (slice 7). crate::media_erasure::names_dropped(db, &named, &receipt.stamp)?; Ok(()) } /// One ownership rule: the rows of `child` whose `column` names a row — an /// owning reference (`OWNING_REFS`, for rows of its parent table) or an /// [`OWNED_BY`] row (for a row of any table). type Rule = (&'static str, &'static str, &'static str); /// The rules that apply to a row of `table`, each with its place in the one /// list of them all: the owning references into `table`, then [`OWNED_BY`]. fn rules_for(table: &str) -> impl Iterator + '_ { let owning = OWNING_REFS .iter() .enumerate() .filter(move |(_, (_, _, parent))| *parent == table) .map(|(at, (child, column, _))| (at, (*child, *column, ""))); let named = OWNED_BY.iter().enumerate().map(|(at, rule)| (OWNING_REFS.len() + at, *rule)); owning.chain(named) } /// The child table of the rule at `at` in that list. fn child_of(at: usize) -> &'static str { match OWNING_REFS.get(at) { Some((child, _, _)) => child, None => OWNED_BY[at - OWNING_REFS.len()].0, } } /// WHAT AN ACT'S ERASED ROWS OWN, READ ONCE FOR THE ACT. /// /// Whether a row owns others is asked of every row an erase takes: a read of /// the child table and a read of the child's receipts (a dormant child is in /// no table), for each rule. Asked one erased row at a time that is a pass /// over every receipt of every child table PER ERASED ROW, inside the file — /// two thousand pruned runs over twenty-two thousand job receipts held the /// owner's file for more than ten minutes (11 Oct 2026). So an act asks once: /// [`Owned::of`] reads each rule ONCE for every row the act erases, and then /// once more per level of what those own, and the walk reads the answers. /// /// A row not asked about here is asked of the file as before ([`naming`]), and /// so is every row of a child table something has since written into /// ([`Owned::wrote`]) — an answer read before a write is not the answer after. #[derive(Default)] pub(crate) struct Owned { /// The rows of the rule's child that name the parent. named: RefCell>>, /// The parents each rule was asked about: for one of these, no entry in /// `named` means no row names it. asked: RefCell>>, /// The media keys `_media_key_names` holds for a row, for every row read /// here — `(table, row id)`, a row naming none included. That index is /// keyed by the KEY, so asking it by row is a pass over all of it. keys: RefCell>>, /// Whether a table exists, asked of the schema once. tables: RefCell>, } impl Owned { /// What `roots` own, and what those own, to the leaves — one read of the /// table and one of the receipts per rule and level, whatever the number /// of roots. pub(crate) fn of(db: &Driver, roots: &[(String, String)]) -> Result { let owned = Owned::default(); let mut seen: BTreeSet<(String, String)> = roots.iter().cloned().collect(); let mut level: Vec<(String, String)> = seen.iter().cloned().collect(); while !level.is_empty() { let mut asks: BTreeMap)> = BTreeMap::new(); for (table, row_id) in &level { for (at, rule) in rules_for(table) { asks.entry(at).or_insert_with(|| (rule, BTreeSet::new())).1.insert(row_id.clone()); } } let mut next = Vec::new(); for (at, ((child, column, extra), parents)) in asks { for (parent, id) in naming_many(db, child, column, extra, &parents)? { if seen.insert((child.to_string(), id.clone())) { next.push((child.to_string(), id.clone())); } owned.named.borrow_mut().entry((at, parent)).or_default().insert(id); } owned.asked.borrow_mut().entry(at).or_default().extend(parents); } level = next; } owned.read_key_names(db, &seen)?; Ok(owned) } /// The keys the index holds for each of `rows`, in one pass over it. fn read_key_names(&self, db: &Driver, rows: &BTreeSet<(String, String)>) -> Result<()> { let ids: BTreeSet<&str> = rows.iter().map(|(_, row_id)| row_id.as_str()).collect(); let list = serde_json::to_string(&ids).map_err(|e| crate::error::StoreError::encode(e.to_string()))?; let mut keys = self.keys.borrow_mut(); for row in rows { keys.entry(row.clone()).or_default(); } for row in db.all( "SELECT tbl, row_id, key FROM _media_key_names WHERE row_id IN (SELECT value FROM json_each(?))", &[SqlValue::Text(list)], )? { if let (Some(table), Some(row_id), Some(key)) = (row.text("tbl"), row.text("row_id"), row.text("key")) { if let Some(held) = keys.get_mut(&(table.to_string(), row_id.to_string())) { held.insert(key.to_string()); } } } Ok(()) } /// The keys `_media_key_names` holds for `table`'s `row_id`: read already, /// or asked of the index — never, for a table that holds no media key. pub(crate) fn key_names(&self, db: &Driver, table: &str, row_id: &str) -> Result> { if let Some(keys) = self.keys.borrow().get(&(table.to_string(), row_id.to_string())) { return Ok(keys.clone()); } if !crate::media_keys::names_keys(table) { return Ok(BTreeSet::new()); } crate::media_keys::index_names(db, table, row_id) } fn table_exists(&self, db: &Driver, table: &str) -> Result { if let Some(exists) = self.tables.borrow().get(table) { return Ok(*exists); } let exists = table_exists(db, table)?; self.tables.borrow_mut().insert(table.to_string(), exists); Ok(exists) } /// What the erases among `ops` own — the fold's reading, before it applies /// any of them. pub(crate) fn of_erases(db: &Driver, ops: &[CottonOp]) -> Result { let roots: Vec<(String, String)> = ops .iter() .filter(|op| { // The text first: a batch is mostly not erases, and decoding // every receipt twice is the fold's whole cost again. op.receipt.contains("\"erase\"") && crate::canonical::decode(op.receipt.as_bytes()).is_ok_and(|receipt| receipt.erase.is_some()) }) .map(|op| (op.table.clone(), op.row_id.clone())) .collect(); if roots.is_empty() { return Ok(Owned::default()); } Owned::of(db, &roots) } /// A row of `table` was written since the reading: what was read of the /// rules whose child it is no longer holds, and is asked of the file again. pub(crate) fn wrote(&self, table: &str) { self.asked.borrow_mut().retain(|at, _| child_of(*at) != table); self.keys.borrow_mut().retain(|(held, _), _| held != table); } /// Every row owned by `table`'s `row_id`, deepest first: its owning /// children by `OWNING_REFS`, present (in their table) or dormant (named /// only by a receipt), and the rows [`OWNED_BY`] declares, each with its /// own. pub(crate) fn descendants(&self, db: &Driver, table: &str, row_id: &str) -> Result> { let mut out = Vec::new(); let mut seen = BTreeSet::from([(table.to_string(), row_id.to_string())]); self.walk(db, table, row_id, &mut seen, &mut out)?; Ok(out) } fn walk( &self, db: &Driver, table: &str, row_id: &str, seen: &mut BTreeSet<(String, String)>, out: &mut Vec<(String, String)>, ) -> Result<()> { for (at, (child, column, extra)) in rules_for(table) { for id in self.naming(db, at, (child, column, extra), row_id)? { if seen.insert((child.to_string(), id.clone())) { self.walk(db, child, &id, seen, out)?; out.push((child.to_string(), id)); } } } Ok(()) } /// The rows of the rule's child that name `row_id`: read already, or asked /// of the file. fn naming(&self, db: &Driver, at: usize, (child, column, extra): Rule, row_id: &str) -> Result> { if self.asked.borrow().get(&at).is_some_and(|parents| parents.contains(row_id)) { return Ok(self.named.borrow().get(&(at, row_id.to_string())).cloned().unwrap_or_default()); } naming(db, child, column, extra, row_id) } } /// Every row owned by `table`'s `row_id`, deepest first — one row's asking /// ([`Owned`] is an act's). pub fn owned_descendants(db: &Driver, table: &str, row_id: &str) -> Result> { Owned::default().descendants(db, table, row_id) } /// Ownership candidates come from the normalized index. A cross-database /// link is still excluded by the same canonical receipt's to_database field. fn receipts_naming(table: &str, column: &str, extra: &str, names: &str) -> String { let also = if extra.contains("to_database IS NULL") { format!(" AND ({}) IS NULL", crate::receipts::implied::field_sql("w", table, "to_database")) } else { String::new() }; format!("{}{also}", crate::receipts::owners_naming_sql(table,column,names)) } /// The ids of `table`'s rows whose `column` names `row_id`: in the table, and /// in the receipts of rows the table does not hold (dormant ones). fn naming(db: &Driver, table: &str, column: &str, extra: &str, row_id: &str) -> Result> { let mut ids = BTreeSet::new(); let Some(spec) = spec_for(table) else { return Ok(ids); }; let key = [SqlValue::Text(row_id.to_string())]; if table_exists(db, table)? { for row in db.all(&format!("SELECT \"{}\" AS id FROM {table} WHERE {column} = ?{extra}", spec.pk), &key)? { if let Some(id) = row.text("id") { ids.insert(id.to_string()); } } } for row in db.all(&receipts_naming(table, column, extra, "= ?"), &key)? { if let Some(id) = row.text("row_id") { ids.insert(id.to_string()); } } Ok(ids) } /// [`naming`] for many rows in the same two reads: `(the row named, the id /// naming it)` for every row of `table` — present or dormant — whose `column` /// names one of `parents`. fn naming_many( db: &Driver, table: &str, column: &str, extra: &str, parents: &BTreeSet, ) -> Result> { let mut found = Vec::new(); let Some(spec) = spec_for(table) else { return Ok(found); }; let list = [SqlValue::Text( serde_json::to_string(parents).map_err(|e| crate::error::StoreError::encode(e.to_string()))?, )]; const AMONG: &str = "IN (SELECT value FROM json_each(?))"; if table_exists(db, table)? { for row in db.all( &format!("SELECT \"{}\" AS id, {column} AS parent FROM {table} WHERE {column} {AMONG}{extra}", spec.pk), &list, )? { if let (Some(parent), Some(id)) = (row.text("parent"), row.text("id")) { found.push((parent.to_string(), id.to_string())); } } } for row in db.all(&receipts_naming(table, column, extra, AMONG), &list)? { if let (Some(parent), Some(id)) = (row.text("parent"), row.text("row_id")) { found.push((parent.to_string(), id.to_string())); } } Ok(found) } /// The `cotton_changes` rows of `rows`, by record id alone (every id is a /// uuid, and the history names a record's table by its definition id). fn history_rows(db: &Driver, rows: &[(String, String)], owned: &Owned) -> Result> { if !owned.table_exists(db, HISTORY_TABLE)? { return Ok(Vec::new()); } let mut history = Vec::new(); for (_, row_id) in rows.iter().filter(|(table, _)| table != HISTORY_TABLE) { for row in db.all( &format!("SELECT id FROM {HISTORY_TABLE} WHERE record_id = ?"), &[SqlValue::Text(row_id.clone())], )? { if let Some(id) = row.text("id") { history.push((HISTORY_TABLE.to_string(), id.to_string())); } } } Ok(history) } const HISTORY_TABLE: &str = crate::fact_hooks::HISTORY_TABLE; fn table_exists(db: &Driver, table: &str) -> Result { db.table_exists(table) } /// The id a content-keyed importer gives its record (design 6.2): the /// derived id of `parts`, or, when that one was erased here, the next /// generation's, `derived_id(table, [parts…, "gen", n])` with the lowest /// `n ≥ 1` not in `_gone`. Every device holding the same erasures picks the /// same generation. pub fn generation_id(db: &Driver, table: &str, parts: &[&str]) -> Result { let first = crate::protocol::derived_id::derived_id(table, parts); if !is_gone(db, table, &first)? { return Ok(first); } let mut n: u64 = 1; loop { let generation = n.to_string(); let mut named: Vec<&str> = parts.to_vec(); named.push("gen"); named.push(&generation); let id = crate::protocol::derived_id::derived_id(table, &named); if !is_gone(db, table, &id)? { return Ok(id); } n += 1; } } #[cfg(test)] #[path = "erase_tests.rs"] mod tests;