//! Archive in one tap at his size (DECISIONS "Archive in one tap"; CONTRACT row 19's finding, 25 Nov 2026): archiving //! a whole sender writes ONE `email_cut` row, not a write per mail (13,750 mails took 52 s one by one). Every Post //! query that decides whether a mail is in the Inbox or Archived reads the rows through [`Know`], so the counts stay //! exact: //! //! - a row covers mail from its sender sent at or before `before` and landed here at or before `at`: mail that lands //! after the Archive is never covered, whatever its date says; //! - `except` lists the mails moved back to the Inbox since, which win over the row; //! - Undo deletes the row: one write. //! //! The values go into the SQL as quoted literals (addresses, times and ids, `'` doubled), so every query keeps its //! own parameters as they were. use super::super::*; use cotton_tools::mcp::handlers::tables; use cotton_core::rules::mail_predicate; use cotton_core::rules::mail_predicate::cuts as mail_cuts; const TABLE: &str = "email_cut"; /// What a move back to the Inbox past [`mail_cuts::EXCEPT_MAX`] of one Archive answers. pub(super) const EXCEPT_FULL: &str = "except_full"; #[derive(Debug, Clone, Default, PartialEq)] pub(crate) struct Cut { pub(crate) id: String, /// An address, or `@domain`. pub(crate) key: String, pub(crate) before: String, pub(crate) at: String, pub(crate) except: Vec, } /// The rows this copy holds; none where the copy has no such table. pub(super) fn read_cuts(ctx: &mut Ctx<'_>) -> Vec { let ask = json!({ "table": TABLE, "where": {}, "limit": 100000 }).as_object().cloned().unwrap_or_default(); let Ok(listed) = tables::list_records(ctx, &ask) else { return Vec::new() }; listed["records"] .as_array() .into_iter() .flatten() .filter_map(|r| { let data = r.get("data").unwrap_or(r); let field = |k: &str| data.get(k).and_then(Value::as_str).map(str::to_string); Some(Cut { id: r.get("id").and_then(Value::as_str)?.to_string(), // As stored: a key its writer did not normalise covers nothing (MAIL PREDICATE phase 2, rule 5). key: field("key")?, before: field("before")?, at: field("at")?, except: field("except").and_then(|e: String| serde_json::from_str::>(e.as_str()).ok()).unwrap_or_default(), }) }) .collect() } /// [`Know`] with the rows on it: what every Post read asks for. pub(super) fn know(ctx: &mut Ctx<'_>) -> Result { super::kept::kept(ctx, "know", |ctx| { let mut know = Know::read(ctx)?; know.cuts = read_cuts(ctx); Ok(know) }) } /// The SQL that is true of a mail (columns prefixed by `on`, `""` or `"e."`) an archived-sender row covers: the /// shared predicate over `_mail_cuts` (MAIL PREDICATE phase 2), the rows themselves no longer spelled into the SQL. pub(super) fn covered(_cuts: &[Cut], on: &str) -> String { mail_cuts::archive_covers(on) } /// A mail's Inbox, as SQL on columns prefixed by `on`. pub(super) fn inbox(know: &Know, on: &str) -> String { format!(" AND {live_mail} AND {on}archived_at IS NULL AND coalesce({on}in_inbox, 1) <> 0 AND NOT {}", covered(&know.cuts, on), live_mail = mail_predicate::live(on)) } /// Archived, as SQL on columns prefixed by `on`. pub(super) fn archived(know: &Know, on: &str) -> String { format!(" AND {live_mail} AND ({on}archived_at IS NOT NULL OR {on}in_inbox = 0 OR {})", covered(&know.cuts, on), live_mail = mail_predicate::live(on)) } /// The kit tables of the other cuts (MAIL PREDICATE phase 2): a Delete of a whole sender, and a Mark read of many. pub(super) const BIN: &str = "email_bin_cut"; pub(super) const READ: &str = "email_read_cut"; /// Archive's kit table, for [`keep_out_of`]. pub(super) const ARCHIVE: &str = TABLE; /// What a move back past [`mail_cuts::EXCEPT_MAX`] answers when the Delete is already being erased: Undo is no longer /// possible, so it is not offered. pub(super) const ERASING_FULL: &str = "erasing_full"; /// The newest server time this copy knows: the newest landing of any mail it holds (`_mail_landed_at`, one seek). pub(super) fn newest_landed(ctx: &mut Ctx<'_>) -> Result, String> { Ok(one(ctx, &format!("SELECT max(landed_at) AS n FROM {}", mail_cuts::LANDED), &[])?.and_then(|r| s(&r, "n"))) } /// When he tapped (PHASE 2 PHONE 2, item 1): the later of this phone's clock and the newest server time the copy /// knows, so a phone whose clock runs behind never makes a Delete due early. pub(super) fn made_at(ctx: &mut Ctx<'_>, now: &str) -> Result { let now = mail_cuts::normalise_time(now).ok_or("the phone's clock is not a time")?; Ok(match newest_landed(ctx)?.and_then(|n| mail_cuts::normalise_time(&n)) { Some(newest) if newest > now => newest, _ => now, }) } /// His own addresses as the predicate reads them (`_mail_own`): set from what Post knows of his accounts before any /// cut is written or erased, so no cut covers his own mail. pub(super) fn keep_own<'a>(ctx: &mut Ctx<'_>, own: impl IntoIterator) -> Result<(), String> { let mut keys: Vec = own.into_iter().map(mail_cuts::normalise_key).filter(|k| !k.is_empty()).collect(); keys.sort(); keys.dedup(); let held: Vec = rows(ctx, &format!("SELECT \"key\" FROM {} ORDER BY \"key\"", mail_cuts::OWN), &[])?.iter().filter_map(|r| s(r, "key")).collect(); if held == keys { return Ok(()); } ctx.db().run(&format!("DELETE FROM {}", mail_cuts::OWN), &[]).map_err(|e| e.to_string())?; for k in keys { ctx.db().run(&format!("INSERT OR IGNORE INTO {} (\"key\") VALUES (?)", mail_cuts::OWN), &[text(k)]).map_err(|e| e.to_string())?; } Ok(()) } /// Write a row: every mail from `key` sent up to `before` that landed by `at`, made at `made_at`. Its id. pub(super) fn cut(ctx: &mut Ctx<'_>, key: &str, before: &str, at: &str, made_at: &str) -> Result { cut_in(ctx, TABLE, key, before, at, made_at) } /// [`cut`] into any of the three cut tables: the key through the one normaliser's refusal, every time in the one /// shape, its state live. pub(super) fn cut_in(ctx: &mut Ctx<'_>, table: &str, key: &str, before: &str, at: &str, made_at: &str) -> Result { if let Some(why) = mail_cuts::refused_key(key) { return Err(format!("cut {key}: {why}")); } let (Some(before), Some(at), Some(made_at)) = (mail_cuts::normalise_time(before), mail_cuts::normalise_time(at), mail_cuts::normalise_time(made_at)) else { return Err(format!("cut {key}: a time not in the one shape")) }; let made = tables::create_produced_record(ctx, &json!({ "table": table, "data": { "key": key, "before": before, "at": at, "made_at": made_at, "state": "live" } }).as_object().cloned().unwrap_or_default()).map_err(|f| f.to_string())?; made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| "no id for the cut".to_string()) } /// Undo of an Archive: the row goes. pub(super) fn uncut(ctx: &mut Ctx<'_>, id: &str) -> Result<(), String> { uncut_in(ctx, TABLE, id) } /// Undo: an Archive's or a Mark read's row goes; a Delete's row is never removed by a phone (item 3), its state is /// written undone, held to the version this copy read, so an erase begun on another device wins over it or loses. pub(super) fn uncut_in(ctx: &mut Ctx<'_>, table: &str, id: &str) -> Result<(), String> { if table == BIN { return set_state(ctx, id, "undone"); } tables::delete_record(ctx, &json!({ "table": table, "id": id }).as_object().cloned().unwrap_or_default()).map(|_| ()).map_err(|f| f.to_string()) } /// A Delete row's state as this copy holds it (`live` when unwritten), or None when the row is gone. pub(super) fn state_of(ctx: &mut Ctx<'_>, id: &str) -> Result, String> { Ok(one(ctx, &format!("SELECT coalesce(state, 'live') AS state FROM {} WHERE id = ? AND deleted_at IS NULL", mail_cuts::BIN_TABLE), &[text(id.to_string())])?.and_then(|r| s(&r, "state"))) } /// Whether a Delete can no longer be undone: its erase has begun (here, or on a device whose write the object took). pub(super) fn undo_refused(ctx: &mut Ctx<'_>, id: &str) -> Result { Ok(matches!(state_of(ctx, id)?.as_deref(), Some("erasing") | Some("erased"))) } /// A Delete row's state written: the state the object last held kept as the edit's base (`_edit_base`), so a post /// the object refuses because the row moved is never laid over the newer state ([`merge_states`] settles it). fn set_state(ctx: &mut Ctx<'_>, id: &str, state: &str) -> Result<(), String> { let base = state_of(ctx, id)?.unwrap_or_else(|| "live".into()); ctx.db().exec(cotton_client::seal::EDIT_BASE_DDL).map_err(|e| e.to_string())?; ctx.db().run("INSERT OR IGNORE INTO _edit_base (tbl, row_id, col, base) VALUES (?, ?, 'state', ?)", &[text(BIN.into()), text(id.to_string()), text(base)]).map_err(|e| e.to_string())?; tables::update_produced_record(ctx, &json!({ "table": BIN, "id": id, "patch": { "state": state } }).as_object().cloned().unwrap_or_default()).map(|_| ()).map_err(|f| f.to_string()) } /// The Delete rows due for their erase at `due` (30 days before now, by `made_at`, when he tapped: never `at`): /// live ones, oldest first. pub(super) fn due(ctx: &mut Ctx<'_>, due: &str) -> Result, String> { let time = mail_cuts::TIME_FUNCTION; Ok(rows(ctx, &format!("SELECT id FROM {} WHERE kind = 'bin' AND coalesce(state, 'live') = 'live' AND {time}(made_at) <= {time}(?) ORDER BY {time}(made_at), id LIMIT 20", mail_cuts::CUTS), &[text(due.to_string())])?.iter().filter_map(|r| s(r, "id")).collect()) } /// The erase of a Delete begins: its state written erasing, held to the version read. Nothing is erased until the /// object has taken that write ([`taken`]). pub(super) fn begin_erasing(ctx: &mut Ctx<'_>, id: &str) -> Result<(), String> { set_state(ctx, id, "erasing") } /// Once nothing of a Delete is left and every erase was taken: erased, kept as the rule for what it covered. pub(super) fn mark_erased(ctx: &mut Ctx<'_>, id: &str) -> Result<(), String> { set_state(ctx, id, "erased") } /// The Delete rows being erased or erased: what they cover is erased where it is seen. pub(super) fn erasing_cuts(ctx: &mut Ctx<'_>) -> Result, String> { Ok(rows(ctx, &format!("SELECT id, state FROM {} WHERE kind = 'bin' AND state IN ('erasing', 'erased') ORDER BY id", mail_cuts::CUTS), &[])?.iter().filter_map(|r| Some((s(r, "id")?, s(r, "state")?))).collect()) } /// Whether the object has taken this copy's last write of a Delete row: none of it waits in the outbox, and no post /// of it was refused as moved (its newer state still to be settled). pub(super) fn taken(ctx: &mut Ctx<'_>, id: &str) -> Result { let pending = one(ctx, &format!("SELECT 1 AS one FROM _outbox o JOIN _writes w ON w.op_id = o.op_id WHERE w.tbl = '{}' AND w.row_id = ? LIMIT 1", mail_cuts::BIN_TABLE), &[text(id.to_string())])?.is_some(); if pending { return Ok(false); } let held = one(ctx, "SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = '_edit_base'", &[])?.is_some(); if !held { return Ok(true); } Ok(one(ctx, "SELECT 1 AS one FROM _edit_base WHERE tbl = ? AND row_id = ? AND col = 'state' AND (moved = 1 OR theirs IS NOT NULL)", &[text(BIN.into()), text(id.to_string())])?.is_none()) } /// Up to `limit` mails the Delete row `id` covers, by the shared predicate, found by the row's key in `_mail_landed` /// (an index seek: covered mail has landed by definition): `(id, thread_id)` rows. pub(super) fn bin_covered(ctx: &mut Ctx<'_>, id: &str, limit: usize) -> Result>, String> { let Some(key) = one(ctx, &format!("SELECT \"key\" FROM {} WHERE kind = 'bin' AND id = ?", mail_cuts::CUTS), &[text(id.to_string())])?.and_then(|r| s(&r, "key")) else { return Ok(Vec::new()) }; rows(ctx, &bin_covered_sql(key.starts_with('@'), limit), &[text(key), text(id.to_string()), ws(ctx)]) } /// What [`bin_covered`] asks (`?1` the row's key, `?2` its id, `?3` the workspace): a seek of `_mail_landed` by the /// key, or by the domain for a domain's row, then each mail by its id. pub(super) fn bin_covered_sql(domain: bool, limit: usize) -> String { let column = if domain { "domain" } else { "\"key\"" }; format!( // CROSS JOIN keeps this order (SQLite never reorders it): the row, its landings by key, each mail by id. "SELECT e.id, e.thread_id FROM {cuts} c CROSS JOIN {landed} l CROSS JOIN {EMAILS} e WHERE c.kind = 'bin' AND c.id = ?2 AND l.{column} = ?1 AND e.id = l.id AND e.workspace_id = ?3 AND {} LIMIT {limit}", mail_cuts::covering_where(mail_cuts::BIN_TABLE, "e."), landed = mail_cuts::LANDED, cuts = mail_cuts::CUTS, ) } /// After a pass: each Delete row whose state post the object refused as moved, and whose newer state the pull brought, /// takes the object's state (it came first: the object's version check made it the winner). Answers the rows whose /// state this copy lost: (id, what it had written, what won). pub(super) fn merge_states(ctx: &mut Ctx<'_>) -> Result, String> { let held = one(ctx, "SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = '_edit_base'", &[])?.is_some(); if !held { return Ok(Vec::new()); } let waiting = rows(ctx, "SELECT row_id, theirs FROM _edit_base WHERE tbl = ? AND col = 'state' AND theirs IS NOT NULL", &[text(BIN.into())])?; let mut lost = Vec::new(); for row in waiting { let (Some(id), Some(theirs)) = (s(&row, "row_id"), s(&row, "theirs")) else { continue }; let mine = state_of(ctx, &id)?.unwrap_or_default(); if mine != theirs { tables::update_produced_record(ctx, &json!({ "table": BIN, "id": id, "patch": { "state": theirs } }).as_object().cloned().unwrap_or_default()).map_err(|f| f.to_string())?; lost.push((id.clone(), mine, theirs.clone())); } ctx.db().run("UPDATE _edit_base SET base = ?, theirs = NULL, moved = 0 WHERE tbl = ? AND row_id = ? AND col = 'state'", &[text(theirs), text(BIN.into()), text(id)]).map_err(|e| e.to_string())?; } ctx.db() .run( &format!("DELETE FROM _edit_base WHERE tbl = ? AND col = 'state' AND theirs IS NULL AND moved = 0 AND NOT EXISTS (SELECT 1 FROM _outbox o JOIN _writes w ON w.op_id = o.op_id WHERE w.tbl = '{}' AND w.row_id = _edit_base.row_id)", mail_cuts::BIN_TABLE), &[text(BIN.into())], ) .map_err(|e| e.to_string())?; Ok(lost) } /// Rule 7, his own later act on one mail wins over a cut: the mail's id joins the `except` of EVERY cut of `table`'s /// kind that covers it (restored from the Bin: the bin cuts; marked unread: the read cuts; back to the Inbox: the /// archive cuts). Refused, in words, past [`mail_cuts::EXCEPT_MAX`]. `table` is the kit table: `email_cut` /// ([`ARCHIVE`]), [`BIN`] or [`READ`]. pub(super) fn keep_out_of(ctx: &mut Ctx<'_>, table: &str, email: &str) -> Result<(), String> { let physical = format!("cotton_{table}"); let covering = rows(ctx, &format!("SELECT c.id AS id, c.\"except\" AS except_list FROM {EMAILS} e, {} c WHERE e.workspace_id = ? AND e.id = ? AND {}", mail_cuts::CUTS, mail_cuts::covering_where(&physical, "e.")), &[ws(ctx), text(email.to_string())])?; for c in covering { let Some(id) = s(&c, "id") else { continue }; let mut except: Vec = s(&c, "except_list").and_then(|e| serde_json::from_str(&e).ok()).unwrap_or_default(); if except.iter().any(|e| e == email) { continue; } if except.len() >= mail_cuts::EXCEPT_MAX { // Undo is offered only where it can still be done: a Delete being erased cannot come back. let erasing = table == BIN && undo_refused(ctx, &id)?; return Err(if erasing { ERASING_FULL } else { EXCEPT_FULL }.to_string()); } except.push(email.to_string()); tables::update_produced_record(ctx, &json!({ "table": table, "id": id, "patch": { "except": serde_json::to_string(&except).unwrap_or_default() } }).as_object().cloned().unwrap_or_default()).map_err(|f| f.to_string())?; } Ok(()) } #[cfg(test)] mod tests { /// RULE (review of the rules, 2; PHASE 2 PHONE 2, low): every cut, Archive, Delete and Mark read, is written, read /// and matched here or in the shared predicate (cotton-rules mail/cuts.rs) and nowhere else. No other source of /// cotton-ffi, cotton-core, cotton-tools, cotton-client, cotton-store, cotton-rules or the Worker names a cut /// table, by its name or through the predicate's constants, but the few that only declare or install them: the /// store's schema, its system-table list and the 157 move's words, the kit step that installs the mirror, the first /// sync's pull list and the Worker's generated kit list. #[test] fn no_cut_is_written_or_matched_any_other_way() { let names = ["email_cut", "email_bin_cut", "email_read_cut", "_mail_cuts"]; let constants = ["cuts::BIN_TABLE", "cuts::READ_TABLE", "cuts::ARCHIVE_TABLE", "cuts::CUTS", "cuts::KINDS", "cuts::mirror"]; let allowed: [(&str, Option<&str>); 10] = [ ("cotton-rules/src/mail/cuts.rs", None), ("cotton-ffi/src/phone/chat_mail_post_cuts.rs", None), ("cotton-store/src/schema/ddl.rs", None), ("cotton-store/src/meta.rs", Some("\"_mail_cuts\",")), ("cotton-store/src/schema/move_intents.rs", Some("MigrationIntent { version: 157,")), ("cotton-store/src/schema/package_shape.rs", None), ("cotton-ffi/src/phone/first_sync.rs", Some("const MAIL: &[&str]")), ("apps/business/src/kits.ts", Some("import d")), ("cotton-rules/src/mail/public_domains.json", None), // The store's list of local places names the mirror as derivable (copy_keep's lint), nothing more. ("cotton-store/src/local_places.rs", Some("(\"_mail_cuts\", Place::Derivable")), ]; let here = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap().to_path_buf(); let mut roots: Vec = ["cotton-ffi", "cotton-core", "cotton-tools", "cotton-client", "cotton-store", "cotton-rules"].iter().map(|c| here.join(c).join("src")).collect(); roots.push(here.join("../apps/business/src")); let mut found = Vec::new(); let mut stack = roots; while let Some(path) = stack.pop() { if path.is_dir() { stack.extend(std::fs::read_dir(&path).unwrap().map(|e| e.unwrap().path())); continue; } let name = path.to_string_lossy().replace('\\', "/"); let rust = name.ends_with(".rs"); if !(rust || name.ends_with(".ts")) || name.ends_with("_tests.rs") || name.ends_with(".test.ts") { continue; } let text = std::fs::read_to_string(&path).unwrap(); // A file's own test module is a test. let text = if rust { text.split("#[cfg(test)]").next().unwrap_or_default().to_string() } else { text }; let allow = allowed.iter().find(|(file, _)| name.ends_with(file)); for (n, line) in text.lines().enumerate() { let code = line.trim_start(); if code.starts_with("//") || code.starts_with("*") || code.starts_with("/*") { continue; } let named = names.iter().any(|t| code.split(|c: char| !(c.is_alphanumeric() || c == '_')).any(|word| word == *t || word == format!("cotton_{t}"))); let through = constants.iter().any(|t| code.contains(t)); if !(named || through) { continue; } match allow { Some((_, None)) => {} Some((_, Some(start))) if code.starts_with(start) => {} _ => found.push(format!("{name}:{}: {code}", n + 1)), } } } assert!(found.is_empty(), "a cut is named outside the files that may:\n{}", found.join("\n")); } }