//! Receipts: what a row is made of (design 3.1, 3.4, 3.7, 3.8).//!//! Every row keeps one receipt per write that still shows in it, as minted,//! in `_writes`; the highest retract it has seen in `_tombstones`, as its//! receipt too. A row's state is a FUNCTION of those and of its retract stamp//! T, computed here by [`assemble`] and nowhere else://!//! - receipts stamped below T belong to an earlier life and are dropped;//! - the row is live iff it holds a create stamped above T;//! - each field is the highest-stamped receipt above T that names it (or,//! for the few columns on [`crate::fold::COLUMN_POLICIES`], the one the//! policy picks among them);//! - `_born` is the smallest `(stamp, op id)` among its creates;//! - a receipt LIVES while it is current for a field or is the row's smallest//! or largest create; otherwise it is dropped — except one that loses only//! to a HELD receipt, which is kept until the held one is released or//! re-dated (3.8).//!//! Because the function reads only the row's own receipts, two devices that//! have seen the same writes hold the same `_writes` rows and the same table//! row, in any arrival order. Nothing here re-encodes a receipt: the bytes a//! writer minted are the bytes stored, and [`Stored::receipt`] is their//! decoding, used for reading only.//!//! A receipt whose row is not present is DORMANT: stored, no table row,//! nothing shown. [`dormant_fields`] is how an undo of a retract (3.5) reads//! what a dormant change would have set.pub(crate) mod pages;pubmod implied;pubmod table_pages;use std::collections::{BTreeMap, BTreeSet};use rusqlite::types::ValueasSqlValue;use serde_json::ValueasJsonValue;usecrate::canonical::{self, Kind, Receipt};usecrate::driver::Driver;usecrate::error::{Result, StoreError};usecrate::fold::{policy_for, Policy};usecrate::protocol::types::CottonOp;/// The JSON columns merged PER KEY (3.1 rule 1): a field of one is/// `column.key`, and the column's stored text is the canonical object of its/// current keys. The legacy store retains this rule until the non-additive/// retirement rise, so older peers inside the floor still merge safely.pubconst PER_KEY_COLUMNS: &[(&str, &str)] = &[("cotton_records", "data")];/// Whether `table.column` is merged per key.pubfn is_per_key(table: &str, column: &str) -> bool { PER_KEY_COLUMNS .iter() .any(|(t, c)| *t == table && *c == column)}/// The mirror columns of a revocation (design 3.7 point 3, 6.6): a receipt/// that sets one to a value outlives a retract of its row, so a retract/// followed by a create at the same id brings the row back revoked.pubconst MIRROR_COLUMNS: &[&str] = &["revoked_at", "revoked_by_device", "revoked_reason"];/// One receipt as this file holds it.#[derive(Debug, Clone, PartialEq)]pubstructStored {pub op_id: String,pub kind: Kind,pub hlc: String,pub author: String,pub actor: String,/// Kept back from every stream (3.8). Only ever true on its writer.pub held: bool,/// The canonical bytes, as minted.pub bytes: Vec<u8>,/// The bytes, decoded — for reading. Never re-encoded.pub receipt: Receipt,}implStored {fn from_row(db: &Driver, row: &crate::driver::Row) -> Result<Stored> {letSome(bytes) = implied::bytes_of(db, row)? else {returnErr(StoreError::encode(format!("_writes row {} {} {} holds no receipt bytes", row.text("tbl").unwrap_or_default(), row.text("row_id").unwrap_or_default(), row.text("hlc").unwrap_or_default() ))); };let receipt = canonical::decode(&bytes)?;Ok(Stored { op_id: row.text("op_id").unwrap_or_default().to_string(), kind: receipt.kind, hlc: receipt.stamp.clone(), author: receipt.author.clone(), actor: receipt.actor.clone(), held: row.int("held").unwrap_or(0) != 0, bytes, receipt, }) }}/// Every receipt this file holds for a row, in stamp order — present or/// dormant alike.pubfn of_row(db: &Driver, table: &str, row_id: &str) -> Result<Vec<Stored>> { db.all("SELECT * FROM _writes WHERE tbl = ? AND row_id = ? ORDER BY hlc", &[SqlValue::Text(table.to_string()),SqlValue::Text(row_id.to_string()), ], )? .iter() .map(|row| Stored::from_row(db, row)) .collect()}/// The row's retract stamp T — the highest retract this file has seen — or/// `None` when it has never been retracted.pubfn retract_stamp(db: &Driver, table: &str, row_id: &str) -> Result<Option<String>> {Ok(db .get("SELECT hlc FROM _tombstones WHERE tbl = ? AND row_id = ?", &[SqlValue::Text(table.to_string()),SqlValue::Text(row_id.to_string()), ], )? .and_then(|row| row.text("hlc").map(str::to_string)))}/// Whether this file already holds the write `op` carries — as a receipt in/// `_writes` or as its row's retract. A second arrival of it changes nothing/// (3.1 rule 9: the op id is minted once).////// THE RETRACT IS ASKED OF THE OP'S OWN ROW. `_tombstones` is keyed by the/// row and has no index on the op id, so asking it by op id alone read every/// tombstone of the file — once for every op of every fold, which on a file/// that has pruned twenty thousand rows is twenty thousand rows read per/// write (11 Oct 2026). An op id is minted once, for one row.pubfn holds_op(db: &Driver, op: &CottonOp) -> Result<bool> {Ok(db .get("SELECT 1 AS held FROM _writes WHERE op_id = ? \ UNION ALL SELECT 1 FROM _tombstones WHERE tbl = ? AND row_id = ? AND op_id = ? LIMIT 1", &[SqlValue::Text(op.op_id.clone()),SqlValue::Text(op.table.clone()),SqlValue::Text(op.row_id.clone()),SqlValue::Text(op.op_id.clone()), ], )? .is_some())}/// The names a receipt's `fields` column lists: every field the receipt/// names, as a canonical JSON array, so SQL can find the receipts of a field/// without decoding bytes.pubfn field_names(receipt: &Receipt) -> String {let names: Vec<JsonValue> = receipt .fields .keys() .map(|name| JsonValue::String(name.clone())) .collect(); canonical::canonical_json(&JsonValue::Array(names)).unwrap_or_else(|_| "[]".to_string())}/// Store a create's or a change's receipt, byte for byte.pubfn store(db: &Driver, op: &CottonOp, receipt: &Receipt, held: bool) -> Result<()> { db.transaction(|db| {// An implied receipt of the row is whole again before another joins it (implied.rs). implied::materialize_row(db, &receipt.table, &receipt.row_id)?; db.run("INSERT INTO _writes (tbl, row_id, hlc, author, op_id, kind, actor, held, bytes, fields, sig) \ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", &[SqlValue::Text(receipt.table.clone()),SqlValue::Text(receipt.row_id.clone()),SqlValue::Text(receipt.stamp.clone()),SqlValue::Text(receipt.author.clone()),SqlValue::Text(op.op_id.clone()),SqlValue::Text(receipt.kind.as_str().to_string()),SqlValue::Text(receipt.actor.clone()),SqlValue::Integer(i64::from(held)),SqlValue::Blob(op.receipt.as_bytes().to_vec()),SqlValue::Text(field_names(receipt)), sig_value(op), ], )?;for column in owner_columns(&receipt.table) {ifletSome(owner) = receipt.fields.get(column).and_then(JsonValue::as_str) { db.run("INSERT OR IGNORE INTO _writes_owners (receipt,tbl,owner) VALUES (?,?,?)", &[ op.op_id.clone().into(), receipt.table.clone().into(), owner.to_string().into(), ])?; } }Ok(()) })}/// Every field used by dormant-child and erase ownership lookups, once.pub(crate) fn owner_columns(table: &str) -> BTreeSet<&'static str> {crate::schema::table_specs::OWNING_REFS .iter() .chain(crate::erase::OWNED_BY.iter()) .filter(|(child, _, _)| *child == table) .map(|(_, column, _)| *column) .collect()}/// The normalized index bounds the candidates. The canonical field check is/// still needed: the three-column projection does not say which of a row's/// several owning fields named this id, and the same id can occur in both./// `names` compares the indexed owner: `= ?` or `IN (...)`.pub(crate) fn owners_naming_sql(table: &str, column: &str, names: &str) -> String { format!("SELECT w.row_id, o.owner AS parent FROM _writes_owners o JOIN _writes w ON w.op_id = o.receipt \ WHERE o.tbl = '{table}' AND o.owner {names} \ AND ({}) = o.owner", implied::field_sql("w", table, column))}/// Populate the new local projection during the in-place shape move without/// altering a receipt's bytes or identity. Nullable legacy receipt rows name/// no parent; only textual reference values can match a textual parent id.pub(crate) fn rebuild_owners(db: &Driver) -> Result<()> {// not a copy: receipts the row's fold no longer stands on (assemble keeps the ones it is made of), or their owners projection, made again. db.run("DELETE FROM _writes_owners", &[])?;let references: BTreeSet<(&str, &str)> = crate::schema::table_specs::OWNING_REFS .iter() .chain(crate::erase::OWNED_BY.iter()) .map(|(table, column, _)| (*table, *column)) .collect();for (table, column) in references {// The shape move needs the projection atomically before ownership// lookups resume. Each read still seeks a bounded receipt page.letmut pages = table_pages::TablePages::new(table);whileletSome(rows) = pages.next(db)? {for row in rows {letSome(op) = row.text("op_id") else { continue; };letSome(bytes) = implied::bytes_of(db, &row)?.map(SqlValue::Blob) else { continue; }; db.run(&format!("INSERT OR IGNORE INTO _writes_owners (receipt,tbl,owner) \ SELECT ?1,?2,json_extract(CAST(?3 AS TEXT), '$.fields.\"{column}\"') \ WHERE json_type(CAST(?3 AS TEXT), '$.fields.\"{column}\"') = 'text'"), &[op.to_string().into(), table.to_string().into(), bytes.clone()])?; } } }Ok(())}/// Store a retract's receipt as the row's tombstone, replacing a lower one./// A lower retract that a higher one replaces goes with its bytes (3.4)./// `held` as for [`store`]: a delete minted Unchecked is the row's tombstone/// here and travels nowhere until the release pass.pubfn store_retract(db: &Driver, op: &CottonOp, receipt: &Receipt, held: bool) -> Result<()> { implied::materialize_row(db, &receipt.table, &receipt.row_id)?; db.run("INSERT INTO _tombstones (tbl, row_id, hlc, op_id, author, actor, bytes, held, sig) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) \ ON CONFLICT(tbl, row_id) DO UPDATE SET hlc = excluded.hlc, op_id = excluded.op_id, \ author = excluded.author, actor = excluded.actor, bytes = excluded.bytes, sig = excluded.sig, \ held = excluded.held, mint_cont = NULL, mint_boot = NULL", &[SqlValue::Text(receipt.table.clone()),SqlValue::Text(receipt.row_id.clone()),SqlValue::Text(receipt.stamp.clone()),SqlValue::Text(op.op_id.clone()),SqlValue::Text(receipt.author.clone()),SqlValue::Text(receipt.actor.clone()),SqlValue::Blob(op.receipt.as_bytes().to_vec()),SqlValue::Integer(i64::from(held)), sig_value(op), ], )?;Ok(())}/// The op's signature as its `sig` column keeps it: the 64 raw bytes, or/// NULL for a receipt that carries none.pub(crate) fn sig_value(op: &CottonOp) -> SqlValue {crate::signed::sig_bytes(op).map_or(SqlValue::Null, SqlValue::Blob)}/// Whether the row's retract is HELD — minted Unchecked here, not yet/// released or re-dated.pubfn retract_held(db: &Driver, table: &str, row_id: &str) -> Result<bool> {Ok(db .get("SELECT held FROM _tombstones WHERE tbl = ? AND row_id = ?", &[SqlValue::Text(table.to_string()),SqlValue::Text(row_id.to_string()), ], )? .and_then(|row| row.int("held"))// Held is 1; a set-aside receipt (`rejected::SET_ASIDE`) is not a held one (QUEUE BAD OP 3). .is_some_and(|held| held == 1))}/// Drop every receipt of the row that [`assemble`] did not keep.pubfn keep_only(db: &Driver, table: &str, row_id: &str, keep: &BTreeSet<String>) -> Result<()> {let held: Vec<String> = db .all("SELECT op_id FROM _writes WHERE tbl = ? AND row_id = ?", &[SqlValue::Text(table.to_string()),SqlValue::Text(row_id.to_string()), ], )? .iter() .filter_map(|row| row.text("op_id").map(str::to_string)) .collect();for op_id in held {if !keep.contains(&op_id) { db.run(// not a copy: receipts the row's fold no longer stands on (assemble keeps the ones it is made of), or their owners projection, made again."DELETE FROM _writes WHERE op_id = ?", &[SqlValue::Text(op_id)], )?; } }Ok(())}/// [`keep_only`] over the op ids the row's receipts are known to be — read/// with the row in this same transaction — instead of reading them again.pubfn keep_only_of(db: &Driver, held: &[String], keep: &BTreeSet<String>) -> Result<()> {for op_id in held.iter().filter(|op_id| !keep.contains(*op_id)) {// not a copy: receipts the row's fold no longer stands on (assemble keeps the ones it is made of), or their owners projection, made again. db.run("DELETE FROM _writes WHERE op_id = ?", &[SqlValue::Text(op_id.clone())])?; }Ok(())}/// One field's current write.#[derive(Debug, Clone, PartialEq)]pubstructCurrent {pub stamp: String,pub op_id: String,pub value: JsonValue,}/// A row's state, as a function of its receipts and its retract stamp.#[derive(Debug, Clone, PartialEq, Default)]pubstructLife {/// A create above T exists.pub live: bool,/// The smallest `(stamp, op id)` among the creates above T — the stamp.pub born: Option<String>,/// The highest stamp among the kept receipts: the row's `_hlc`.pub newest: Option<String>,/// Each field named by a receipt above T, with its current write. A/// per-key field is under its `column.key` name.pub fields: BTreeMap<String, Current>,/// The op ids of the receipts that live (3.1 rule 6).pub keep: BTreeSet<String>,}/// THE FUNCTION. `receipts` are the row's, `t` its retract stamp.pubfn assemble(table: &str, receipts: &[Stored], t: Option<&str>) -> Life { assemble_under(table, receipts, t, false)}/// [`assemble`], with `t_held` saying the retract stamp is a HELD retract./// The life is the same; what changes is what is kept: a receipt that a held/// retract buries loses only to a held write, so it is kept (3.8) — the/// release pass may re-date the retract below it, and then it counts again.pubfn assemble_under(table: &str, receipts: &[Stored], t: Option<&str>, t_held: bool) -> Life {letmut life = assemble_unheld_retract(table, receipts, t);if t_held {let travelling: Vec<Stored> = receipts.iter().filter(|r| !r.held).cloned().collect(); life.keep .extend(assemble_unheld_retract(table, &travelling, None).keep); } life}fn assemble_unheld_retract(table: &str, receipts: &[Stored], t: Option<&str>) -> Life {let mirrors = has_mirror_columns(table);// What each receipt may still speak for: every field it names when it is// above T; only its non-null mirror fields when it is below T on a table// with mirrors (3.7 point 3); nothing otherwise.let speaks: Vec<(&Stored, Vec<&String>)> = receipts .iter() .map(|r| {let above = t.is_none_or(|t| r.hlc.as_str() > t);let names: Vec<&String> = if above { r.receipt.fields.keys().collect() } elseif mirrors { r.receipt .fields .iter() .filter(|(name, value)| MIRROR_COLUMNS.contains(&name.as_str()) && !value.is_null()) .map(|(name, _)| name) .collect() } else {Vec::new() }; (r, names) }) .collect();let creates: Vec<&Stored> = speaks .iter() .filter(|(r, _)| r.kind == Kind::Create && t.is_none_or(|t| r.hlc.as_str() > t)) .map(|(r, _)| *r) .collect();let live = !creates.is_empty();let smallest_create = creates .iter() .min_by(|a, b| (a.hlc.as_str(), a.op_id.as_str()).cmp(&(b.hlc.as_str(), b.op_id.as_str()))) .copied();let largest_create = creates .iter() .max_by(|a, b| (a.hlc.as_str(), a.op_id.as_str()).cmp(&(b.hlc.as_str(), b.op_id.as_str()))) .copied();let currents = |with_held: bool| -> BTreeMap<String, Current> {letmut by_field: BTreeMap<&str, Vec<&Stored>> = BTreeMap::new();for (r, names) in &speaks {if !with_held && r.held {continue; }for name in names { by_field.entry(name.as_str()).or_default().push(r); } } by_field .into_iter() .map(|(name, candidates)| {let winner = pick(table, name, &candidates); ( name.to_string(),Current { stamp: winner.hlc.clone(), op_id: winner.op_id.clone(), value: winner.receipt.fields.get(name).cloned().unwrap_or(JsonValue::Null), }, ) }) .collect() };let fields = currents(true);letmut keep: BTreeSet<String> = fields.values().map(|c| c.op_id.clone()).collect();// A receipt that loses only to a held one is kept (3.8): current once the// held receipts are set aside.if receipts.iter().any(|r| r.held) { keep.extend(currents(false).into_values().map(|c| c.op_id)); }ifletSome(c) = smallest_create { keep.insert(c.op_id.clone()); }ifletSome(c) = largest_create { keep.insert(c.op_id.clone()); }let newest = receipts .iter() .filter(|r| keep.contains(&r.op_id)) .map(|r| r.hlc.clone()) .max();Life { live, born: smallest_create.map(|c| c.hlc.clone()), newest, fields, keep, }}/// How a device row's `revoked_reason` begins when the take-over act revoked/// it for its successor (`crate::revocation`).pubconst SUPERSEDED_BY: &str = "superseded by ";/// The receipt that is current for `field` among those naming it: the highest/// stamp, unless a column policy picks by value — the smallest or largest/// non-null value, the stamp breaking a tie, and a null only when nothing/// else names the field.fn pick<'a>(table: &str, field: &str, candidates: &[&'a Stored]) -> &'a Stored {let value_of = |r: &Stored| bind(r.receipt.fields.get(field).unwrap_or(&JsonValue::Null));let newest = |rs: &[&'a Stored]| -> &'a Stored { rs.iter().max_by(|a, b| a.hlc.cmp(&b.hlc)).copied().expect("at least one candidate") };// A `superseded by …` reason wins on a device row, whatever the stamps// (slice 4, F-V9-5): a `lost` a phone wrote offline above the take-over// act must not leave the phone and the new Mac with different reasons.// `revoked_by_device` comes from the same receipt.if table == "cotton_devices" && matches!(field, "revoked_reason" | "revoked_by_device") {let superseding: Vec<&'a Stored> = candidates .iter() .copied() .filter(|r| { r.receipt .fields .get("revoked_reason") .and_then(JsonValue::as_str) .is_some_and(|reason| reason.starts_with(SUPERSEDED_BY)) }) .collect();if !superseding.is_empty() {return newest(&superseding); } }let policy = policy_for(table, field);if policy == Policy::Lww {return newest(candidates); }let non_null: Vec<&'a Stored> = candidates .iter() .copied() .filter(|r| !matches!(value_of(r), SqlValue::Null)) .collect();if non_null.is_empty() {return newest(candidates); }match policy {Policy::MinNonNull => non_null .iter() .min_by(|a, b| {crate::fold::value_order(&value_of(a), &value_of(b)).then_with(|| b.hlc.cmp(&a.hlc)) }) .copied() .expect("one non-null"), _ => non_null .iter() .max_by(|a, b| {crate::fold::value_order(&value_of(a), &value_of(b)).then_with(|| a.hlc.cmp(&b.hlc)) }) .copied() .expect("one non-null"), }}/// Whether `receipt` still speaks below its row's retract: a receipt that/// sets a mirror column to a value outlives the retract (3.7 point 3), so its/// arrival after the retract is stored and assembled, never dropped as an/// earlier life's write — or a revoke arriving after a newer retract would be/// lost on that device alone.pub(crate) fn speaks_below_retract(table: &str, receipt: &Receipt) -> bool { receipt.kind != Kind::Retract && has_mirror_columns(table) && receipt .fields .iter() .any(|(name, value)| MIRROR_COLUMNS.contains(&name.as_str()) && !value.is_null())}fn has_mirror_columns(table: &str) -> bool {crate::fact_hooks::MIRROR_TABLES.contains(&table) || crate::schema::specs::columns_of(table) .is_some_and(|columns| columns.iter().any(|(name, _)| MIRROR_COLUMNS.contains(name)))}/// A receipt's field value as SQLite binds it. The receipt holds the value/// after the codec (text, integer, real or null), so no codec runs here.pubfn bind(value: &JsonValue) -> SqlValue {match value {JsonValue::Null => SqlValue::Null,JsonValue::Bool(b) => SqlValue::Integer(i64::from(*b)),JsonValue::Number(n) => n .as_i64() .map(SqlValue::Integer) .or_else(|| n.as_f64().map(SqlValue::Real)) .unwrap_or(SqlValue::Null),JsonValue::String(s) => SqlValue::Text(s.clone()),// A per-key column's keys are assembled into one object by the fold;// a structured value anywhere else is the canonical text of itself. other => SqlValue::Text(canonical::canonical_json(other).unwrap_or_default()), }}/// The columns a life writes into its table row: every current plain field/// bound, and each per-key column as the canonical object of its current/// keys. `_hlc` and `_born` are added by the caller.pubfn row_columns(table: &str, life: &Life) -> Result<Vec<(String, SqlValue)>> {letmut columns: Vec<(String, SqlValue)> = Vec::with_capacity(life.fields.len());letmut per_key: BTreeMap<String, serde_json::Map<String, JsonValue>> = BTreeMap::new();for (name, current) in &life.fields {ifletSome((column, key)) = name.split_once('.').filter(|(column, _)| is_per_key(table, column)) { per_key .entry(column.to_string()) .or_default() .insert(key.to_string(), current.value.clone()); } else { columns.push((name.clone(), bind(¤t.value))); } }// A per-key column is always written: a live row with no key yet holds// the empty object, never the column's absence.for (owner, column) in PER_KEY_COLUMNS {if *owner == table { per_key.entry((*column).to_string()).or_default(); } }for (column, keys) in per_key {// A key set to null is a write of null (3.1 rule 2): the receipt// stays, the key leaves the stored object.let present: serde_json::Map<String, JsonValue> = keys.into_iter().filter(|(_, v)| !v.is_null()).collect();let text = canonical::canonical_json(&JsonValue::Object(present))?; columns.push((column, SqlValue::Text(text))); }Ok(columns)}/// What a dormant row's receipts above T would set: each field's current/// value, by the same function a live row is assembled with. For the undo of/// a retract (3.5), which takes these over history's `before`.pubfn dormant_fields(db: &Driver, table: &str, row_id: &str) -> Result<BTreeMap<String, JsonValue>> {let receipts = of_row(db, table, row_id)?;let t = retract_stamp(db, table, row_id)?;let life = assemble(table, &receipts, t.as_deref());Ok(life .fields .into_iter() .map(|(name, current)| (name, current.value)) .collect())}#[cfg(test)]#[path = "receipt_owners_tests.rs"]mod owner_tests;