//! Facts in the fold, and the registry of what folding one sets off. //! //! A FACT is a row that is only ever inserted. The fold takes a fact whose id //! this file does not hold, treats a replay as nothing, and refuses every //! update and every delete of one. Two different writes to one fact id are //! settled the same way on every device: the earlier `(stamp, op id)` stands //! and the other parks `conflict` — except on [`NO_SWAP_FACT_TABLES`], where //! the held fact is never swapped, whatever the stamps. //! //! `fold.rs` names no fact table and no side effect of folding one: it asks //! this file, and each side effect is a hook here, an empty function in the //! file of the seam that fills it (as `mint`'s hooks are). Slice 5b-i fills //! the revocation hook, 5a-ii the erase hook, 6 the history-row hook, 7 the //! media-erasure hook; none of them edits `fold.rs`. 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::receipts::{self, Stored}; /// The table of author facts. A receipt in it names its own author, so it is /// the bootstrap of a stream: it never waits for itself. pub const AUTHORS_TABLE: &str = "cotton_authors"; /// The table of undo facts (slice 3b): one per undone change, its id /// [`undo_fact_id`] of the change's, so two devices undoing one change write /// one fact id and the earlier stands. pub const UNDOS_TABLE: &str = "cotton_undos"; /// History: one row per act per record (slice 6). pub const HISTORY_TABLE: &str = "cotton_changes"; /// The record of truth for revocation ([`crate::revocation`]). pub const REVOCATIONS_TABLE: &str = "cotton_revocations"; /// Batch safety stays behind the fact-hook registry just like row hooks. /// The fold can keep atomic approval replacement without knowing fact tables. pub(crate) fn before_batch(db: &Driver, ops: &[CottonOp]) -> Result> { if ops.iter().any(|op| op.table == crate::revocation::DEVICES_SUBJECT || op.table == REVOCATIONS_TABLE) { crate::revocation::approving_databases(db) } else { Ok(Vec::new()) } } pub(crate) fn after_batch(db: &Driver, approving_before: &[String]) -> Result<()> { crate::revocation::retain_approving_devices(db, approving_before) } pub(crate) fn last_approver_refusal(reason: &str) -> bool { reason == crate::revocation::LAST_FULL_DEVICE } pub(crate) fn ends_approver(op: &CottonOp) -> bool { if op.table == crate::revocation::DEVICES_SUBJECT { return op.kind == crate::protocol::types::OpKind::Delete || op.patch.as_ref().and_then(|p| p.get("revoked_at")).is_some_and(|v| !v.is_null()); } op.table == REVOCATIONS_TABLE && op.patch.as_ref().and_then(|p| p.get("subject_table")) .and_then(serde_json::Value::as_str) .is_some_and(|subject| matches!(subject, "cotton_devices" | "device_key" | "person")) } /// Subjects whose security decisions mirror a revocation fact. The fact's /// own declaration supplies them; the fold and receipt assembly ask this /// registry so they do not depend on an individual fact handler. pub const MIRROR_TABLES: &[&str] = crate::revocation::SUBJECT_TABLES; /// What folding one fact sets off. Run once, when the fact is taken. type Hook = fn(&Driver, &Receipt) -> Result<()>; /// The fact tables, each with its hook. /// /// `cotton_serving_machine` is NOT here yet: `cotton_server::databases:: /// record_serving_fact` writes it through `Writer::upsert`, and slice 12's /// act fills `start_positions` on a row that exists, so an update of it is /// still an honest write. Slice 12 adds it when its act is the only writer. const FACTS: &[(&str, Hook)] = &[ (AUTHORS_TABLE, nothing), (REVOCATIONS_TABLE, crate::revocation::fact_folded), // Slice 9b's chain reads these; nothing happens at the fold. ("cotton_vault_retired_keys", nothing), // Slice 7's media-erasure hook: a dead key enters this device's unlink // queue, when `media_unlink` allows it for this file. ("cotton_media_erasures", crate::media_erasure::fact_folded), // Every refresh rotation writes one (`crate::grant_rotations`); reuse is // read from the rows and their parked twins, not at the fold. ("cotton_grant_rotations", nothing), // Slice 3b: the inverse rides as the act's own signed receipts, each // naming the fact ([`undo_refusal`]), so nothing happens at the fold. (UNDOS_TABLE, nothing), // Slice 6: a history row is written once and only an erase takes it out; // whether it was undone is its undo fact, never an edit of the row. (HISTORY_TABLE, nothing), // Keys and sharing (KS0): membership is read from the rows // (`membership`, KS3), so nothing happens at the fold. ("cotton_admissions", nothing), ("cotton_member_person_claims", nothing), ("cotton_device_statements", nothing), ("cotton_invites", nothing), // A Mac's relay key kept by the serving Mac (v136): written once by the // judge of the row's epoch ([`relay_key_refusal`]), never changed or // deleted; readers take the lowest epoch's. (RELAY_KEYS_TABLE, nothing), ]; /// `cotton_device_relay_keys` (v136). pub const RELAY_KEYS_TABLE: &str = "cotton_device_relay_keys"; /// The keys tables, each with the words a refusal names its row by. A row of /// one is signed when it is made, so a second write to its id is never taken. const KEYS_FACTS: &[(&str, &str)] = &[ ("cotton_admissions", "an admission"), ("cotton_member_person_claims", "a member's People claim"), ("cotton_device_statements", "a device statement"), ("cotton_invites", "an invite"), ]; fn keys_fact(table: &str) -> Option<&'static str> { KEYS_FACTS .iter() .find(|(name, _)| *name == table) .map(|(_, what)| *what) } /// The fact tables where a held fact is never swapped: a different second /// write parks `conflict`, whatever the stamps. An author's fact is what every /// receipt of its stream was admitted under, so an earlier-stamped twin /// arriving later must not replace it. A keys fact carries a signature over /// what it says, so the one held is the one that was checked. pub const NO_SWAP_FACT_TABLES: &[&str] = &[ AUTHORS_TABLE, "cotton_admissions", "cotton_member_person_claims", "cotton_device_statements", "cotton_invites", RELAY_KEYS_TABLE, ]; /// The invites fact table, named here so `fold.rs` never spells it (the /// facts-in-the-fold guard: fold.rs asks this registry about facts). pub const INVITES_TABLE: &str = "cotton_invites"; /// The columns of an invite that say TO WHOM it goes and WHETHER it hands the /// database over (version 141) — set by the op that makes the invite and by /// nothing after: a patch that turned a staff invite into a handover, or /// moved a handover to another phone, would admit an owner nobody invited. /// The invite is a no-swap signed fact as well, so the row the file holds is /// the one whose signature was checked. pub const INVITE_WRITE_ONCE_COLUMNS: &[&str] = &["recipient", "hands_over"]; /// Write-once columns of fact tables, with the words a refusal uses for the /// row ("an invite's recipient is written once…"). `fold.rs` reads this list /// next to its own non-fact fences, so a fact table's fence lives with its /// facts and fold.rs names no fact table. pub const FACT_WRITE_ONCE: &[(&str, &[&str], &str)] = &[(INVITES_TABLE, INVITE_WRITE_ONCE_COLUMNS, "an invite's")]; fn nothing(_db: &Driver, _fact: &Receipt) -> Result<()> { Ok(()) } /// Every fact table's name. pub fn fact_tables() -> impl Iterator { FACTS.iter().map(|(table, _)| *table) } /// Whether `table` holds facts. pub fn is_fact_table(table: &str) -> bool { FACTS.iter().any(|(name, _)| *name == table) } /// Whether the op is folded before the rest of its batch: an author's fact, /// so the receipts beside it find their author known. pub fn folds_first(op: &CottonOp) -> bool { op.table == AUTHORS_TABLE } /// Whether `author` has announced itself to this file. pub fn author_has_fact(db: &Driver, author: &str) -> Result { Ok(author_device(db, author)?.is_some()) } /// The device credential `author`'s fact names, when this file holds the fact. pub fn author_device(db: &Driver, author: &str) -> Result> { Ok(db .get( "SELECT device_id FROM cotton_authors WHERE id = ?", &[SqlValue::Text(author.to_string())], )? .and_then(|row| row.text("device_id").map(str::to_string))) } /// Whether this file's own author (`_meta.author_id`) has its fact in the /// table — the sign that the file was born on the one write path. pub fn this_file_holds_its_authors_fact(db: &Driver) -> Result { Ok(db .get( "SELECT 1 AS held FROM cotton_authors WHERE id = (SELECT author_id FROM _meta)", &[], )? .is_some()) } /// What the fold does with one arriving receipt, asked of every receipt this /// file does not already hold. pub enum Arriving { /// Not a fact table: the fold's ordinary rules. NotAFact, /// A fact this file does not hold: taken. Take, /// An earlier write of a fact this file holds another write of: it stands, /// and each held write, listed here, is dropped and parked `conflict`. Swap(Vec), /// Refused, with the reason it parks under. Refuse(String), } /// What the hooks read ONCE for a batch, before the fold applies any of it, /// and are handed back with every receipt ([`arriving`]): what the batch's /// erases own (`crate::erase::Owned`) — asked once per erased row it is a /// read of a table per row, inside the file. pub(crate) type Batch = crate::erase::Owned; /// [`Batch`] for `ops`. pub(crate) fn read_for_batch(db: &Driver, ops: &[CottonOp]) -> Result { crate::erase::Owned::of_erases(db, ops) } /// The fact rule for `receipt`, which this file does not hold. /// /// It is also the ERASE HOOK (slice 5a-ii, `crate::erase`): a write at an /// erased id, or under an erased owning parent, is refused here with a `gone` /// reason; an erase of a row that is not a fact is applied here, before the /// fold stores its receipt as the row's tombstone. pub(crate) fn arriving(db: &Driver, op: &CottonOp, receipt: &Receipt, owned: &Batch) -> Result { if op.table == crate::revocation::DEVICES_SUBJECT && receipt.kind == Kind::Retract { return Ok(Arriving::Refuse("Devices are removed by revoking their key; the approval row remains as the revocation audit".into())); } // A write into a table is news to whatever was read of it for the batch's // erases (`erase::Owned`); an erase only takes rows out, and is not. if receipt.erase.is_none() { owned.wrote(&op.table); } if let Some(reason) = crate::erase::refusal(db, op, receipt)? { return Ok(Arriving::Refuse(reason)); } if let Some(reason) = undo_refusal(db, receipt)? { return Ok(Arriving::Refuse(reason)); } if op.table == SERVING_TABLE && receipt.erase.is_none() { if let Some(reason) = crate::serving_grant::fact_refusal(db, &receipt.fields, &receipt.author, &receipt.row_id, &receipt.stamp)? { return Ok(Arriving::Refuse(reason)); } if let Some(reason) = crate::serving_succession::refusal(db, &receipt.fields, &receipt.author)? { return Ok(Arriving::Refuse(reason)); } } if !is_fact_table(&op.table) || erases_history(&op.table, receipt.erase.is_some()) { crate::erase::apply(db, op, receipt, owned)?; return Ok(Arriving::NotAFact); } match receipt.kind { Kind::Retract => { return Ok(Arriving::Refuse(format!( "{} holds facts, and a fact is never deleted — this delete of {} is not applied", op.table, op.row_id ))) } Kind::Change => { if let Some(what) = keys_fact(&op.table) { return Ok(Arriving::Refuse(format!( "{what} is written once, when it is made — this change of {} is not applied", op.row_id ))); } return Ok(Arriving::Refuse(format!( "{} holds facts, and a fact is never updated — this change of {} is not applied", op.table, op.row_id ))) } Kind::Create => {} } if op.table == RELAY_KEYS_TABLE { if let Some(reason) = relay_key_refusal(db, receipt)? { return Ok(Arriving::Refuse(reason)); } } let held = receipts::of_row(db, &op.table, &op.row_id)?; let Some(first) = held .iter() .map(|stored| (stored.hlc.as_str(), stored.op_id.as_str())) .min() else { return Ok(Arriving::Take); }; if NO_SWAP_FACT_TABLES.contains(&op.table.as_str()) { return Ok(Arriving::Refuse(format!( "conflict: {} already holds the fact {} from another write, and a held fact of this table is never replaced", op.table, op.row_id ))); } if (op.hlc.as_str(), op.op_id.as_str()) < first { return Ok(Arriving::Swap(held)); } Ok(Arriving::Refuse(conflict_reason(&op.table, &op.row_id))) } /// Why a kept relay key is not taken: only a serving author of the epoch the /// row names may write it (architect, 12 Oct 2026). Before this file holds a /// fact of that epoch the receipt WAITS for it, and is offered again when the /// fact folds; from any other author it parks `conflict`. A pure function of /// the receipt and the serving facts, so every device answers alike in any /// order. fn relay_key_refusal(db: &Driver, receipt: &Receipt) -> Result> { let workspace_id = receipt.fields.get("workspace_id").and_then(|value| value.as_str()); let epoch = receipt.fields.get("epoch").and_then(serde_json::Value::as_i64); let (Some(workspace_id), Some(epoch)) = (workspace_id, epoch) else { return Ok(Some(format!( "conflict: a kept relay key names its database and serving epoch — this one from {} does not", receipt.author ))); }; Ok(match crate::serving::authors_of_epoch(db, workspace_id, epoch)? { None => Some(crate::rejected::waiting_for_serving_reason(&receipt.author)), Some(authors) if authors.contains(&receipt.author) => None, Some(_) => Some(format!( "conflict: a relay key is kept only by the serving Mac of epoch {epoch}, and {} is not its author", receipt.author )), }) } /// Why the later of two different writes to one fact id parks. pub fn conflict_reason(table: &str, row_id: &str) -> String { format!( "conflict: {table} holds an earlier write of the fact {row_id} — the earlier stamp stands on every device" ) } /// The table of serving facts ([`crate::serving`]) — not a fact table here /// yet (see [`FACTS`]), but taking a row of it can make an author a serving /// author ([`announced`]). const SERVING_TABLE: &str = "cotton_serving_machine"; /// The authors a row the fold just APPLIED makes known to this file: an /// author fact announces its own author; a serving fact announces the /// authors it makes serving authors ([`crate::serving::announced_by_fact`]). /// Whoever parked receipts of theirs `waiting` offers them again /// ([`crate::rejected::retry_waiting_for`]) — one trigger for both waits. pub fn announced(db: &Driver, op: &CottonOp) -> Result> { if op.table == AUTHORS_TABLE { return Ok(vec![op.row_id.clone()]); } if op.table == SERVING_TABLE { return crate::serving::announced_by_fact(db, &op.row_id); } Ok(Vec::new()) } /// A row that is not a fact was taken: what folding it sets off. Two things /// mark the serving Mac's pass due (`crate::revocation`): a `cotton_devices` /// create that the standing reader skips as a late approval, and a row of /// what an ended key holds (a live credential, an unfinished job or its /// runner) arriving after the key ended. And a row of a media-key holder /// names its keys in `_media_key_names` (`crate::media_keys`, slice 7), /// which takes each of them out of the unlink queue. pub fn row_taken(db: &Driver, receipt: &Receipt) -> Result<()> { crate::revocation::approval_taken(db, receipt)?; crate::revocation::holding_taken(db, receipt)?; let named = crate::media_keys::names_taken(db, receipt)?; crate::media_erasure::named_again(db, &named) } /// A fact was taken: run its table's hook. pub fn folded(db: &Driver, fact: &Receipt) -> Result<()> { match FACTS.iter().find(|(table, _)| *table == fact.table) { Some((_, hook)) => hook(db, fact), None => Ok(()), } } /// The id of the undo fact of the change `change_id`: derived from the change /// alone, so every device undoing it writes the same id. /// Whether this is an ERASE of a history row — the one way a history fact /// leaves (slice 6): it is taken and kept gone like any erased row. pub fn erases_history(table: &str, erase: bool) -> bool { erase && table == HISTORY_TABLE } pub fn undo_fact_id(change_id: &str) -> String { format!("undo:{change_id}") } /// Why a receipt of an UNDO act is not taken: its fact is not held here, or /// the fact held is another author's write — a twin undo of the same change /// stood first, and this act is the one that parks, whole, on every device. pub fn undo_refusal(db: &Driver, receipt: &Receipt) -> Result> { let Some(fact) = receipt.undo.as_deref() else { return Ok(None); }; let held = receipts::of_row(db, UNDOS_TABLE, fact)?; if held.iter().any(|stored| stored.author == receipt.author) { return Ok(None); } Ok(Some(if held.is_empty() { format!("conflict: this write is part of the undo {fact}, whose fact this file does not hold") } else { undo_conflict_reason(fact) })) } /// Why the receipts of an undo whose fact lost to a twin park. pub fn undo_conflict_reason(fact: &str) -> String { format!( "conflict: another device's undo of the same change stands ({fact}) — the earlier stamp stands on every device, and this undo's writes are not applied" ) } pub(crate) const UNDO_RECEIPT: &str = "json_extract(CAST(bytes AS TEXT), '$.undo') = ?"; /// The receipts this file holds of the undo act whose fact `fact` is, by the /// authors in `authors`: what a Swap of that fact drops and parks beside it. pub fn undo_act_receipts( db: &Driver, fact: &str, authors: &[String], ) -> Result)>> { let mut out = Vec::new(); use crate::receipts::pages::{Pages, Side}; for side in [Side::Writes, Side::Tombstones] { let mut pages = Pages::new(side); while let Some(rows) = pages.next(db, UNDO_RECEIPT, &[SqlValue::Text(fact.to_string())])? { for row in rows.into_iter().filter(|row| row.int("matches") == Some(1)) { let bytes = match row.get("bytes") { Some(SqlValue::Blob(bytes)) => bytes.clone(), Some(SqlValue::Text(text)) => text.as_bytes().to_vec(), _ => continue, }; let named = crate::canonical::decode(&bytes)?; if let (true, Some(op_id)) = (authors.contains(&named.author), row.text("op_id")) { out.push((op_id.to_string(), bytes)); } } } } Ok(out) }