//! The fold: given receipts, decide what the file becomes (design 3).//!//! A row is made of RECEIPTS (`crate::receipts`): one per write that still//! shows in it, as minted, and its highest retract. The fold's whole job is//! to put an arriving receipt beside the row's others, let//! [`crate::receipts::assemble`] say what the row now is, and write that one//! INSERT, UPDATE or DELETE — in a savepoint of its own, so a row that fails//! rolls back alone and the page goes on (3.1 rule 8).//!//! The rule for a field is one line: the highest-stamped receipt that names it//! wins (3.1 rules 4-5), per field, so two devices a second apart — one//! renaming a todo, the other ticking it off — keep both writes. A few columns//! settle a race by value instead ([`COLUMN_POLICIES`]): a refresh chain is//! made monotone rather than merely recent. The fences below refuse the quiet//! forgeries a policy alone would settle in silence.//!//! Row life (3.7): a retract raises the row's stamp T; receipts below T belong//! to an earlier life; the row is live iff a create is above T; a change that//! arrives before its create is DORMANT — stored, no table row — and shows//! when the create lands. The op id travels beside the bytes and is never//! re-derived; a second arrival of a write this file holds changes nothing.//!//! A table a build does not have is unknown, and rejected: the retired list is//! EMPTY on the fresh line.use std::cmp::OrderingasCmpOrdering;use std::collections::{BTreeMap, BTreeSet};use std::sync::atomic::{AtomicU64, Ordering};use rusqlite::types::ValueasSqlValue;use serde::{Deserialize, Serialize};use serde_json::{Map, ValueasJsonValue};usecrate::canonical::{self, Kind, Receipt};usecrate::driver::Driver;usecrate::error::{Result, StoreError};usecrate::protocol::types::CottonOp;usecrate::receipts;usecrate::schema::codecs::decode_value;usecrate::schema::decl::TableSpec;usecrate::schema::specs::spec_for;/// What a batch did. The field names ARE the wire names the conformance/// harness compares against the TypeScript object.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pubstructFoldResult {pub applied: Vec<String>, #[serde(rename = "skippedStale")]pub skipped_stale: Vec<String>,/// Ops naming a table a migration RETIRED/// ([`crate::migrate::Migration::retired_tables`]). Stepped over, not/// rejected: the cursor still advances and nothing lands in/// `_parked`. The ladder retires ten tables today, nine of them/// domain tables an op really can name. #[serde(rename = "skippedRetired")]pub skipped_retired: Vec<String>,pub rejected: Vec<Rejection>,/// The ROWS this batch changed — `(table, row_id)`, deduped, in the order/// they first changed.////// A merge is reported from HERE and never from a row count: one row/// arrives as several ops (a base patch and a column at its own stamp),/// counting ops over-reports, and counting rows before and against after/// reports zero for two devices that converged on the same derived id. The/// exchange tallies these per table. #[serde(rename = "appliedRows", default)]pub applied_rows: Vec<(String, String)>,/// Ops whose AUTHOR this file has no `cotton_authors` fact for yet. Not/// applied and not refused: the caller parks each one `waiting` and the/// fact's arrival ([`FoldResult::announced`]) brings it back. Absent from/// the wire when empty. Only a file that holds its own author's fact asks/// this (see [`fold_arriving`]). #[serde(default, skip_serializing_if = "Vec::is_empty")]pub waiting: Vec<Waiting>,/// The authors whose fact this batch applied — whoever parked receipts of/// theirs as waiting offers them again now. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub announced: Vec<String>,/// Lines for the owner's board, once each: today only "the sync found a/// child it did not expect" — a child the owning walk missed, made/// dormant so its parent could go (3.7 point 9). This crate has no board/// of its own; the caller carries these to one. Absent when empty. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub board: Vec<String>,/// Re-dated receipts whose `restamps` names a receipt this file holds/// from another device, or a different write (5.2 point 8): parked, not/// applied, and the receipt they name is left standing. Absent when empty. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub parked: Vec<Rejection>,}/// One op held back for its author's fact.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructWaiting { #[serde(rename = "opId")]pub op_id: String,pub author: String,}pubusecrate::fact_hooks::{author_has_fact, AUTHORS_TABLE, MIRROR_TABLES};#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructRejection { #[serde(rename = "opId")]pub op_id: String,pub reason: String,}// ---------------------------------------------------------------------------// The merge policy of one column// ---------------------------------------------------------------------------/// How one column settles a race.////// The clock answers for nearly every column, and the exceptions are the ones/// where "most recent" is the wrong question: a refresh chain must not be wound/// back by a device that had not heard of the last rotation and wrote the row a/// second later.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumPolicy {/// The newer stamp wins. Every column, unless [`COLUMN_POLICIES`] names it.Lww,/// The SMALLEST non-null value wins, and a null never overwrites anything.////// Order-independent, so it converges without consulting a stamp at all:/// whichever order the writes arrive in, the column ends at the minimum of/// the non-null values any of them carried, and once it is non-null it/// never goes back to null. No shipped column registers it since slice/// 5a-i made revocation a fact; the fold's own tests keep it exercised.MinNonNull,/// The LARGEST non-null value wins, and a null never overwrites anything.////// `MinNonNull` upside down, and order-independent for the same reason: the/// column ends at the maximum of the non-null values any write carried,/// whichever order they arrive in, and it never goes back to null.////// That is the right shape for a COUNTER that must not be wound back —/// `cotton_oauth_grants.refresh_generation`, the position of an OAuth/// refresh chain. Every Mac of a household can mint a refresh token now/// (`cotton_core::vault::tokens`), and replay detection is "is the/// generation you presented older than the one the row carries" — so a Mac/// that had not heard of the last rotation must not be able to win the/// merge by a second and reopen the window in which a token that was/// already spent is honoured. The rotation's own timestamp travels the same/// way, so the two stay paired: the write that carried the highest/// generation is the write whose timestamp is latest.MaxNonNull,}/// The columns that do NOT settle a race by the clock.////// THREE entries, all one fact: an OAuth refresh chain's position must never/// be wound BACK, because a lower generation is what replay detection reads/// as "this token was already spent", and a Mac that had not heard of the last/// rotation must not win the merge by a second. Slice 5b-i's/// `cotton_grant_rotations` facts (`crate::grant_rotations`) carry each/// rotation and the reuse read off two tokens at one generation, but they do/// not replace these: every reader of the chain's position — the writer's/// compare-and-set, the sync route's screen, [`no_digest_swap`] — reads the/// row, so a lower generation stamped later would win the row under the clock.////// `revoked_at` is NOT here any more (slice 5a-i). A revocation is a fact in/// `cotton_revocations` (`crate::revocation`), which no later write can/// out-vote because a fact is never updated; the `revoked_at` columns are its/// mirror. [`no_un_revocation`] refuses every receipt that names a/// mirror NULL, and re-admitting a key is a NEW ROW at an id of/// its own (`cotton_tools::devices::approval_row_id`), never a patch that/// clears the column.pubconst COLUMN_POLICIES: &[(&str, &str, Policy)] = &[// Version 21: see `Policy::MaxNonNull`. The timestamp travels with the// counter so the pair cannot come apart. ("cotton_oauth_grants", "refresh_generation", Policy::MaxNonNull), ("cotton_oauth_grants", "refresh_rotated_at", Policy::MaxNonNull),// Version 45. The digest of the current generation's refresh token, with// the generation zero-padded in front, so the LARGEST value is the digest// of the HIGHEST generation: it settles exactly as `refresh_generation`// does and can never be left naming a position the chain has moved past.// [`no_digest_swap`] is its fence. ("cotton_oauth_grants", "refresh_digest", Policy::MaxNonNull),];/// The one entry the tests need, so the non-LWW path is exercised by a real/// fold rather than by a unit test of its own arithmetic. It is NOT part of the/// shipped table — `cfg(test)` is this crate's own tests only, so every other/// crate, the conformance lanes included, sees [`COLUMN_POLICIES`] as it ships.#[cfg(test)]const TEST_COLUMN_POLICIES: &[(&str, &str, Policy)] = &[("cotton_todos", "snoozed_until", Policy::MinNonNull)];/// The policy of one column — LWW unless a table above names it.pubfn policy_for(table: &str, column: &str) -> Policy { #[cfg(test)]ifletSome((_, _, policy)) = TEST_COLUMN_POLICIES .iter() .find(|(owner, name, _)| *owner == table && *name == column) {return *policy; } COLUMN_POLICIES .iter() .find(|(owner, name, _)| *owner == table && *name == column) .map_or(Policy::Lww, |(_, _, policy)| *policy)}/// SQLite's own value order — the storage classes rank NULL, then numbers, then/// text, then blobs, and two values of one class compare within it.pub(crate) fn value_order(a: &SqlValue, b: &SqlValue) -> CmpOrdering {fn class(value: &SqlValue) -> u8 {match value {SqlValue::Null => 0,SqlValue::Integer(_) | SqlValue::Real(_) => 1,SqlValue::Text(_) => 2,SqlValue::Blob(_) => 3, } }match (a, b) { (SqlValue::Integer(left), SqlValue::Integer(right)) => left.cmp(right), (SqlValue::Text(left), SqlValue::Text(right)) => left.cmp(right), (SqlValue::Blob(left), SqlValue::Blob(right)) => left.cmp(right), (SqlValue::Real(left), SqlValue::Real(right)) => { left.partial_cmp(right).unwrap_or(CmpOrdering::Equal) } #[allow(clippy::cast_precision_loss)] (SqlValue::Integer(left), SqlValue::Real(right)) => (*left as f64) .partial_cmp(right) .unwrap_or(CmpOrdering::Equal), #[allow(clippy::cast_precision_loss)] (SqlValue::Real(left), SqlValue::Integer(right)) => left .partial_cmp(&(*right as f64)) .unwrap_or(CmpOrdering::Equal), (left, right) => class(left).cmp(&class(right)), }}/// Every column is quoted: a made table's columns are a person's words, and/// any of them may be an SQL keyword (`limit`, `order`, `group`).fn q(column: &str) -> String { format!("\"{column}\"")}/// The author an HLC names — everything after `<13 ms>:<4 counter>:`, which is/// a device id and carries a colon of its own, so the split is a bounded one./// The SQL half of this is `substr(_hlc, 20)`, which the author indexes use.pubfn author_of(hlc: &str) -> Option<&str> {letmut parts = hlc.splitn(3, ':'); parts.next()?; parts.next()?; parts.next().filter(|author| !author.is_empty())}/// Fold `ops` into the file, in one transaction.////// EVERY per-op failure is a per-op rejection — malformed ops (unknown table or/// column), and database-level failures: UNIQUE, CHECK, NOT NULL and FOREIGN/// KEY. Each op runs inside its own SAVEPOINT, so a violation rolls back that/// one statement and leaves every op beside it standing.////// That is the whole point, and the alternative is a WEDGE, which is unbounded./// A batch abort on the push path 500s the route, so the phone's outbox replays/// the same poisoned batch forever; on the pull path the throw rolls back the/// cursor along with the rows, so the device re-pulls the same page on every/// attempt and never sees another server write again. Weighed against that, a/// rejected op costs exactly one write — and it is never a quiet loss: the/// reason travels back on the push response, both callers park it in/// `_parked`, and the parked row keeps the RECEIPT, so a/// rejection is a record that can be rebuilt rather than a sentence about one.////// FOREIGN KEYS ARE ENFORCED IMMEDIATELY, per statement. They used to be/// deferred to COMMIT so a batch could arrive in any order — but deferral put/// the verdict somewhere this function cannot see it: every caller already runs/// inside a transaction, `transaction` is re-entrant, and a deferred check/// fires at the OUTERMOST commit, so the violation escaped after this function/// had already returned a clean result.////// A child under an OWNING parent that is not present never meets its foreign/// key at all: it is dormant — stored, reported applied, no table row — and/// the parent's arrival re-assembles it (3.7 points 7-8). The SECOND PASS/// stays for the references that are not owning: a soft column (`SOFT_REFS`)/// or a `workspace_id` naming a row later in the same batch fails on its/// foreign key and is retried once after the rest of the batch has applied./// Whatever still fails is a rejection.////// The retry is LWW-preserving but NOT order-preserving: a held op applies/// after the rest of the batch and re-reads the row's state first, so a column/// the batch has since superseded is skipped as stale rather than clobbering/// the newer write.////// **A BATCH IS APPLIED IN THE ORDER IT IS GIVEN, and that order is the page/// builder's to get right.** Both are recorded: `applied` and `skipped_stale`/// depend on it, and the conformance vectors pin them. Ordering a page by stamp/// is what `crate::changes::answer` does for the answer and what/// `crate::exchange::exchange_request` does for the request — at the two places/// a page is BUILT, never here, because everything else that reaches this/// function (`crate::outbox::write_local`, `crate::rejected::retry_rejected`)/// already hands it its writes in the order they were minted.pubfn fold_ops(db: &Driver, ops: &[CottonOp]) -> Result<FoldResult> { fold_arriving(db, ops, Arrival::Handed, None)}/// [`fold_ops`], for a batch taken from the answer of the peer this file syncs/// FROM — see [`Arrival::Pulled`] for the one thing that changes.pubfn fold_pulled(db: &Driver, ops: &[CottonOp]) -> Result<FoldResult> { fold_arriving(db, ops, Arrival::Pulled, None)}/// [`fold_pulled`], at judge time `judge_ms`: the newest applied stamp moves/// `_meta.last_hlc` no further than judge time + the bound (H1). `None` — no/// judge time on this device yet — adopts unbounded, as [`fold_pulled`] does;/// such a device's own mints are held, and the move to a fresh author once it/// has judge time takes back a `last_hlc` an answer poisoned.pubfn fold_pulled_judged(db: &Driver, ops: &[CottonOp], judge_ms: Option<i64>) -> Result<FoldResult> { fold_arriving(db, ops, Arrival::Pulled, judge_ms)}/// Where a batch came from.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumArrival {/// Written on this device, or handed over BY a device — everything a/// server folds, and everything a device writes for itself. Every fence/// holds in full.Handed,/// Taken from the ANSWER of the peer this file syncs from: a device's/// pull, a standby Mac's pass, a parked pull retried.Pulled,/// Minted HERE, by [`crate::mint`]: this file's own write, folded before/// it is queued or served. Every fence holds in full, as for a handed/// batch; what differs is what the caller does with a stale skip, which/// `mint` refuses rather than reports.Local,/// Minted HERE while Unchecked (slice 1): folded as [`Arrival::Local`],/// and its receipts are stored HELD — applied on this file, never/// travelling, until the release pass.LocalHeld,}/// Fold a batch that came from `arrival`. The one entry the three builders of/// an op share: `mint` folds as [`Arrival::Local`], the exchange as/// [`Arrival::Handed`] or [`Arrival::Pulled`].pubfn arrive(db: &Driver, ops: &[CottonOp], arrival: Arrival) -> Result<FoldResult> { fold_arriving(db, ops, arrival, None)}/// Whether a file held this way may name `actor` in a write it mints.////// The serving Mac admits tokens, credentials and grants and runs the jobs, so/// it may name them; a replica — a phone, a client Mac — names only what/// happens on it: its owner or member, its sessions, the jobs a device runs for itself,/// and an automation acting for one of those. The carry's offline import/// names `import:` and nothing else, and no serving process names `import:`./// Slice 3a asks this of a peer's receipt on arrival, once the receipt carries/// its actor; here it is asked of every local mint.pubfn actor_may_be_named_by( held: crate::mint::Held, actor: &crate::actor::Actor,) -> std::result::Result<(), String> {usecrate::actor::Actor;usecrate::mint::Held;let allowed = match (held, actor) { (Held::Offline, Actor::Import(_)) => true, (Held::Offline, _) | (_, Actor::Import(_)) => false, (Held::Served, _) => true, (Held::Replica, Actor::Owner(_) | Actor::Member(_) | Actor::Session(_) | Actor::DeviceJob(_)) => true, (Held::Replica, Actor::Automation { on_behalf_of, .. }) => {return actor_may_be_named_by(held, on_behalf_of) } (Held::Replica, _) => false, };if allowed {Ok(()) } else {Err(format!("a file held as {held:?} may not name the actor `{actor}` — its device is not the one that admits or runs it" )) }}/// Why an arriving receipt's actor is not one its author's device may name,/// or `None` when it is (or when this file cannot yet tell).////// The actor must read as one: text that names no actor is refused whole./// An `owner:<device row>` or a `member:<device row>` — directly, or as the/// principal an automation acts for — is a person at THAT device's screen, so/// its author must be an author minted for the same device: the device row's/// `device_id` and the author fact's `device_id` must agree — unless the/// author is a serving author ([`crate::serving::is_serving_author`]), which/// writes for the devices that ask its Mac. And the KIND must/// be the row's (KS11): a row naming a `person_key` is a member's device and/// never writes as the owner; a row naming none is the owner's and never/// writes as a member. Asked only when the file holds both rows; an author/// with no fact parks `waiting` before this is reached.////// An author that is no serving author YET — a serving reason, and the/// serving fact that would open its window not here/// ([`crate::serving::awaits_a_serving_fact`]) — is not refused: the receipt/// parks `waiting` for that fact ([`Foreign::Awaits`]), and the fact's/// arrival offers it again. A client author naming another device is refused/// at once, as is one whose fact is here and does not make it serving./// MAKING A MAC A RUNNER IS THE OWNER'S ORDER, AND ONLY THE SERVING MAC/// ANSWERS IT. `runner_ordered_at` is written only by the owner at one of their/// own devices' screens — never a token, a session, a connector, an automation/// or a member — because the order ends with a Mac's copy dropped./// `runner_confirmed_at` and `runner_problem` are written only by the serving/// Mac, because a Mac that could confirm itself could drop a copy nobody holds.fn runner_order_refused(db: &Driver, receipt: &Receipt) -> Result<Option<String>> {if receipt.fields.contains_key("runner_ordered_at") && !matches!(crate::actor::Actor::from_wire(&receipt.actor), Ok(crate::actor::Actor::Owner(_))) {returnOk(Some("only the owner, at their own device, orders a Mac to become a runner".into())); }if (receipt.fields.contains_key("runner_confirmed_at") || receipt.fields.contains_key("runner_problem")) && !crate::serving::is_serving_author(db, &receipt.author)? {returnOk(Some("only the serving Mac answers a runner order".into())); }Ok(None)}fn actor_foreign_to_author(db: &Driver, receipt: &Receipt) -> Result<Option<Foreign>> {let actor = matchcrate::actor::Actor::from_wire(&receipt.actor) {Ok(actor) => actor,Err(error) => returnOk(Some(Foreign::Refused(format!("the receipt's actor is not one: {error}")))), };let (device, as_member) = match actor.principal() {crate::actor::Actor::Owner(device) => (device, false),crate::actor::Actor::Member(device) => (device, true), _ => returnOk(None), };let author_device = crate::fact_hooks::author_device(db, &receipt.author)?;letSome(row) = db.get("SELECT device_id, person_key FROM cotton_devices WHERE id = ?", &[SqlValue::Text(device.as_str().to_string())], )?else {returnOk(None); };let row_device = row.text("device_id").map(str::to_string);let row_is_members = row .text("person_key") .is_some_and(|key| !key.trim().is_empty());iflet (Some(author_device), Some(row_device)) = (author_device, row_device) {// A SERVING author acts for the devices that ask the serving Mac: it// may name another device's owner or member. Only the device half is// relaxed; the kind half below holds for it too. An older epoch's// author is still parked by the old-author cut-off, asked later.if author_device != row_device && !crate::serving::is_serving_author(db, &receipt.author)? {ifcrate::serving::awaits_a_serving_fact(db, &receipt.author)? {returnOk(Some(Foreign::Awaits(crate::rejected::waiting_for_serving_reason(&receipt.author)))); }returnOk(Some(Foreign::Refused(format!("the receipt's actor `{}` is at another device than its author {}'s — an author names only its own device's owner or member", receipt.actor, receipt.author )))); } }Ok(match (as_member, row_is_members) { (false, true) => Some(Foreign::Refused(format!("the receipt's actor `{}` claims the owner, and its device is a member's — a member's device never writes as the owner", receipt.actor ))), (true, false) => Some(Foreign::Refused(format!("the receipt's actor `{}` claims a member, and its device is the owner's — only a member's device writes as a member", receipt.actor ))), _ => None, })}/// Why [`actor_foreign_to_author`] does not take a receipt's actor.enumForeign {/// Never by this author: refused.Refused(String),/// Not until a serving fact arrives: parked `waiting` under this reason.Awaits(String),}fn fold_arriving( db: &Driver, ops: &[CottonOp], arrival: Arrival, judge_ms: Option<i64>,) -> Result<FoldResult> {// In a batch ([`as_one_batch`]) each receipt read here is kept for the// fold below, which would otherwise decode the same bytes again.let _kept = KeptReceipts;if matches!(arrival, Arrival::Local | Arrival::LocalHeld) {let _span = crate::spans::span("fold::local_scope");let keep = db.batching();for op in ops {// A receipt the mint handed over beside its bytes is not decoded// again ([`keep_minted`]).let minted = DECODED.with(|decoded| { decoded.borrow().get(&op.op_id).filter(|(bytes, _)| *bytes == op.receipt).map(|(_, receipt)| receipt.actor.clone()) });let actor = match minted {Some(actor) => actor,None => {let receipt = canonical::decode(op.receipt.as_bytes())?;let actor = receipt.actor.clone();if keep { DECODED.with(|decoded| decoded.borrow_mut().insert(op.op_id.clone(), (op.receipt.clone(), receipt))); } actor } };let actor = crate::actor::Actor::from_wire(&actor).map_err(StoreError::refused)?;crate::device_scope::require_local_write(db, &actor)?; } }if arrival != Arrival::Pulled {// Refuse the whole reader stream even when its author fact is in// this batch and is itself refused, so the remaining ops never park// as unknown-author work that could later be retried.letmut reader_authors = std::collections::BTreeSet::new();for op in ops.iter().filter(|op| op.table == AUTHORS_TABLE) {ifletOk(receipt) = canonical::decode(op.receipt.as_bytes()) {ifletSome(key) = receipt.fields.get("device_id").and_then(JsonValue::as_str) {ifcrate::device_scope::scope_of(db, key)? == crate::device_scope::DeviceScope::Reader { reader_authors.insert(receipt.author); } } } }if !reader_authors.is_empty() {let (refused, allowed): (Vec<_>, Vec<_>) = ops.iter().cloned().partition(|op| reader_authors.contains(&op.device_id));letmut result = fold_arriving(db, &allowed, arrival, judge_ms)?; result.rejected.extend(refused.into_iter().map(|op| Rejection { op_id: op.op_id, reason: crate::device_scope::READER_WRITE_REFUSAL.into(), }));returnOk(result); } } db.transaction(|db| {match fold_transaction(db, ops, arrival, judge_ms) {Err(StoreError::Refused(reason))ifcrate::fact_hooks::last_approver_refusal(&reason) && matches!(arrival, Arrival::Handed | Arrival::Pulled) => {// The failed trial rolled back its facts, mirrors and clocks.// Refuse the device-ending receipts through the normal sync// verdicts, so their neighbours land and the cursor can pass.let (ending, rest): (Vec<_>, Vec<_>) = ops.iter().cloned().partition(crate::fact_hooks::ends_approver);if ending.is_empty() {returnErr(StoreError::refused(reason)); }letmut result = fold_transaction(db, &rest, arrival, judge_ms)?; result .rejected .extend(ending.into_iter().map(|op| Rejection { op_id: op.op_id, reason: reason.clone(), }));Ok(result) } result => result, } })}fn fold_transaction( db: &Driver, ops: &[CottonOp], arrival: Arrival, judge_ms: Option<i64>,) -> Result<FoldResult> {// NAMED AND COUNTED for whoever holds the file (`crate::held::tally`): a// sync batch names itself here, a local write is named by `mint`.match arrival {Arrival::Handed => crate::held::doing("a pushed batch"),Arrival::Pulled => crate::held::doing("a pulled batch"),Arrival::Local | Arrival::LocalHeld => {} }crate::held::folded(ops.len());let _span = crate::spans::span("fold"); db.transaction(|db| {// The invariant belongs to this transaction, including a pulled batch:// no caller can commit a revoke that removes its last Full approver.let approving_before = crate::fact_hooks::before_batch(db, ops)?;letmut result = FoldResult::default();// Ops that failed on nothing but a foreign key — a soft reference or a// workspace, never an owning parent (a child of one is dormant). The// row it names may be later in this same batch, so they get one more// chance once it has all applied.letmut awaiting_parent: Vec<&CottonOp> = Vec::new();// THE FILE'S KIND, read once for the batch: the link rule// (`crate::link_rule`) asks it of every write minted here (held or// not) or handed over by a device. A pulled batch is the serving Mac's// answer, which that rule already held at its own fold.let file = match arrival {Arrival::Local | Arrival::LocalHeld | Arrival::Handed => {Some(crate::link_rule::this_file(db)?) }Arrival::Pulled => None, };let file = file.as_ref();// WHAT THE HOOKS READ ONCE FOR THE BATCH, and never once per op// (`fact_hooks::Batch`).let owned = crate::fact_hooks::read_for_batch(db, ops)?;// THE DEFINITIONS THIS BATCH WRITES, as the file holds them before// it: what the step after the fold compares, to step only the tables// whose storage changed (`package_shape::after_definitions`).let written: BTreeSet<String> = ops.iter().filter(|op| op.table == DEFINITIONS_TABLE).map(|op| op.row_id.clone()).collect();let definitions_before: BTreeMap<String, Option<String>> = if written.is_empty() { BTreeMap::new() } else {let held: BTreeMap<String, String> =crate::schema::package_shape::definition_texts(db, Some(&written))?.into_iter().collect(); written.iter().map(|id| (id.clone(), held.get(id).cloned())).collect() };// Reader admission is a batch gate. Files with no readers need no// per-receipt device lookup; a batch changing admissions checks again// as it folds, including a reader admitted earlier in this batch.let reader_checks = arrival != Arrival::Pulled && ( ops.iter().any(|op| op.table == "cotton_devices") || db.get("SELECT 1 AS reader FROM cotton_devices WHERE scope = 'reader' LIMIT 1", &[])?.is_some() );// AUTHOR FACTS FIRST. A fact names its own author and is the bootstrap// of that author's stream, so it never waits for itself (4.1 point 5),// and the receipts beside it in the same batch find their author known.let (facts, rest): (Vec<&CottonOp>, Vec<&CottonOp>) = ops.iter().partition(|op| crate::fact_hooks::folds_first(op));for op in &facts { apply(db, op, arrival, file, &owned, reader_checks, &mut result, Some(&mut awaiting_parent))?; }// A RECEIPT WHOSE AUTHOR HAS NO FACT YET PARKS WAITING; it is never// refused (a refusal lets the cursor pass it for good). Asked only by// a file that holds its own author's fact: a file whose author was// never minted is still on the old write paths, where no author has a// fact, and parking every peer's write would stop its sync. The gate// leaves when slice 2c makes `mint` the only writer and every file is// born with its author (`mint::first_author`).let armed = crate::fact_hooks::this_file_holds_its_authors_fact(db)?;letmut known: BTreeSet<String> = BTreeSet::new();for op in rest {if armed && !op.device_id.is_empty() && op.device_id != crate::changes::ORIGIN_AUTHOR && !known.contains(&op.device_id) {if author_has_fact(db, &op.device_id)? { known.insert(op.device_id.clone()); } else { result.waiting.push(Waiting { op_id: op.op_id.clone(), author: op.device_id.clone(), });continue; } } apply(db, op, arrival, file, &owned, reader_checks, &mut result, Some(&mut awaiting_parent))?; }// Second and last attempt. `apply` re-reads the row's current state, so// an op this batch has since superseded is skipped as stale rather than// clobbering the newer write.for op in std::mem::take(&mut awaiting_parent) { apply(db, op, arrival, file, &owned, reader_checks, &mut result, None)?; }// The rows were pushed as they changed, a row once per op; deduped// here once, in the order they first changed, rather than by a scan// of every row before each push (O(n²) over a 3,744-row birth). dedupe_rows(&mut result.applied_rows);let applied: std::collections::HashSet<&str> = result.applied.iter().map(String::as_str).collect();// Announced once APPLIED — a fact whose workspace row came later in// this same batch applies on the retry above, and counts just the same.// An author fact announces its author; a serving fact the authors it// makes serving authors (`fact_hooks::announced`).for op in ops {if !applied.contains(op.op_id.as_str()) {continue; }for author incrate::fact_hooks::announced(db, op)? {if !result.announced.contains(&author) { result.announced.push(author); } } }// Only APPLIED ops move this device's clock. A rejected op may carry a// wild future stamp, and adopting it would push every later local write// ahead of real time — so the newest stamp is taken after both passes,// from what actually landed, never from what was merely offered.letmut newest: Option<&str> = None;for op in ops {if !applied.contains(op.op_id.as_str()) {continue; }if newest.is_none_or(|current| op.hlc.as_str() > current) { newest = Some(&op.hlc); } }// THE ADOPTION BOUND (H1): at judge time J, no further than J + the// bound — an applied receipt stamped further ahead is stored, but its// stamp does not carry every later local write ahead with it.let bounded = match (newest, judge_ms) { (Some(newest), Some(judge)) => Some(bounded_adoption(newest, judge)?), (newest, _) => newest.map(str::to_string), };ifletSome(newest) = bounded.as_deref() {// Never backwards: a batch of old ops must not rewind this device's// clock. db.run("UPDATE _meta SET last_hlc = ? WHERE last_hlc IS NULL OR last_hlc < ?", &[SqlValue::Text(newest.to_string()),SqlValue::Text(newest.to_string()), ], )?; }// A DEFINITION ARRIVED OR CHANGED: the file steps to at least every// package it declares before anything else reads it, and the// receipts that waited for that shape fold now. A shape the step// refuses (a changed column) changes nothing and goes to the board.ifletSome(definition) = ops.iter().rev().find(|op| { op.table == DEFINITIONS_TABLE && result.applied_rows.iter().any(|(t, r)| *t == op.table && *r == op.row_id) }) {let applied: BTreeMap<String, Option<String>> = definitions_before .into_iter() .filter(|(id, _)| result.applied_rows.iter().any(|(t, r)| *t == DEFINITIONS_TABLE && r == id)) .collect();let (_, refused) = crate::schema::package_shape::after_definitions(db, &Moving::at(&definition.hlc).at, &applied)?;for (id, why) in refused { result.board.push(format!("The tool table {id} could not take its new shape: {why}")); } }let _after = crate::spans::span("fold::after_batch");crate::fact_hooks::after_batch(db, &approving_before)?;crate::derived::after_fold(db, &result.applied_rows);Ok(result) })}/// `min(newest, J + the bound)` as a stamp: `newest` itself when it is at or/// below the bound, else counter 0 at the bound's millisecond under the same/// author.fn bounded_adoption(newest: &str, judge_ms: i64) -> Result<String> {let parts = crate::protocol::hlc::hlc_parts(newest)?;let bound = judge_ms + crate::mint::clock::FUTURE_BOUND_MS;if parts.ms <= bound {returnOk(newest.to_string()); }crate::protocol::hlc::bound_at(&parts.device_id, bound)}/// Park a receipt `newer-shape`, as a pull whichever way it arrived: it/// names a package table or column this file does not hold yet, and folds/// once this file has stepped to that package's revision.fn wait_for_shape(db: &Driver, op: &CottonOp, result: &mutFoldResult, reason: String) -> Result<()> {crate::rejected::park(db, op, crate::rejected::Direction::Pull, crate::rejected::Class::NewerShape, &reason, &Moving::at(&op.hlc).at)?; result.parked.push(Rejection { op_id: op.op_id.clone(), reason });Ok(())}/// ONE BATCH OF ROWS (copy-installer-fold, 8 Nov 2026): `body` — a mint of/// many rows, a fold of their receipts — reads the file's shape once rather/// than once a row: the package specs' stamp, a table's required columns and/// declared defaults, whether a table is a reservation's, whether this/// device may write ([`Driver::in_batch`]). A fact is read again after any/// write to the table it comes from, any schema change and any rollback, so/// every row is minted and folded exactly as a row-by-row write would be:/// the same receipts, the same refusals, a byte-identical file.pubfn as_one_batch<T>(db: &Driver, body: implFnOnce() -> T) -> T {if ROW_BY_ROW.with(std::cell::Cell::get) {return body(); } db.in_batch(body)}thread_local! {static ROW_BY_ROW: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };}/// Run `body` with [`as_one_batch`] folding row by row on this thread: how a/// test proves a batch makes the file a row-by-row write makes.#[doc(hidden)]pubfn row_by_row_for_tests<T>(body: implFnOnce() -> T) -> T {let before = ROW_BY_ROW.with(|cell| cell.replace(true));let out = body(); ROW_BY_ROW.with(|cell| cell.set(before)); out}thread_local! {/// The receipts a batch's fold already decoded, by op id, beside the/// bytes they were decoded from ([`fold_arriving`]).static DECODED: std::cell::RefCell<BTreeMap<String, (String, Receipt)>> = const { std::cell::RefCell::new(BTreeMap::new()) };}/// In a batch ([`as_one_batch`]), keep the receipt `mint` just encoded into/// `op` beside its bytes, so the fold applies the struct and never decodes/// the bytes it was made from. Outside a batch, nothing is kept.pub(crate) fn keep_minted(db: &Driver, op: &CottonOp, receipt: Receipt) {if db.batching() && canonical::reads_back_as_itself(&receipt) { DECODED.with(|decoded| decoded.borrow_mut().insert(op.op_id.clone(), (op.receipt.clone(), receipt))); }}/// Empties [`DECODED`] when a fold ends, however it ends — and when a mint/// that kept its receipts ([`keep_minted`]) ends before its fold.pub(crate) structKeptReceipts;implDropforKeptReceipts {fn drop(&mutself) { DECODED.with(|decoded| decoded.borrow_mut().clear()); }}/// The table whose rows declare the package tables a file holds.const DEFINITIONS_TABLE: &str = "cotton_table_definitions";/// One op, inside its own savepoint.////// `awaiting_parent` `Some` means this is the first pass: an FK-only failure is/// held for the retry instead of rejected. `None` means this is the retry, and/// an FK failure is final.fn apply<'a>( db: &Driver, op: &'a CottonOp, arrival: Arrival, file: Option<&crate::link_rule::ThisFile>, owned: &crate::fact_hooks::Batch, reader_checks: bool, result: &mutFoldResult, awaiting_parent: Option<&mutVec<&'a CottonOp>>,) -> Result<()> {let reject = |result: &mutFoldResult, reason: String| { result.rejected.push(Rejection { op_id: op.op_id.clone(), reason, }); };// A package table is known by THIS file's definitions and the columns// the file holds (`package_shape::spec_on`), not by the build.let spec_span = crate::spans::span("fold::apply spec_on");let spec = crate::schema::package_shape::spec_on(db, &op.table)?; drop(spec_span);let gates = crate::spans::span("fold::apply decode+gates");letSome(spec) = spec else {// A table a migration RETIRED is stepped over rather than rejected.// The list is empty on the fresh line; the branch stays because the// declaration does.ifcrate::migrate::is_retired_table(&op.table) {if !result.skipped_retired.contains(&op.op_id) { result.skipped_retired.push(op.op_id.clone()); }returnOk(()); }// A package table whose definition this file has not taken yet: the// receipt waits for it, off the owner's board, and folds after the// step that makes the table (`package_shape::after_definitions`).ifcrate::schema::package_shape::may_arrive(&op.table) && crate::rejected::keeps_newer_shape(db)? {return wait_for_shape(db, op, result, crate::schema::package_shape::waits_for_shape(&op.table, None)); } reject(result, format!("unknown table: {}", op.table));returnOk(()); };let package = spec_for(&op.table).is_none();// THE RECEIPT IS THE WRITE. The op's other fields are its reading; a// receipt that is not canonical, or that disagrees with the op beside it,// is refused whole — nothing here rebuilds one.let kept = DECODED.with(|decoded| { decoded.borrow_mut().remove(&op.op_id).filter(|(bytes, _)| *bytes == op.receipt).map(|(_, receipt)| receipt) });let receipt = match kept.map_or_else(|| canonical::decode(op.receipt.as_bytes()), Ok) {Ok(receipt) => receipt,Err(error) => { reject(result, format!("the receipt is not readable: {error}"));returnOk(()); } };if receipt.table != op.table || receipt.row_id != op.row_id || receipt.stamp != op.hlc || receipt.author != op.device_id || receipt.actor != op.actor { reject( result,"the op beside the receipt names a different write than the receipt does".to_string(), );returnOk(()); }if receipt.author.is_empty() || author_of(&receipt.stamp) != Some(receipt.author.as_str()) { reject(result, "the receipt's stamp does not end in its author".to_string());returnOk(()); }// A local or pushed movement needs a serving author, including retracts. A pull is the// authenticated server's judged state; its serving fact may arrive on a later page.// Guard: cotton-tools/tests/mcp_automations.rs, reservation_claim_cancel_and_offline_edit_fence.if arrival != Arrival::Pulled {// Local mints are trusted server actions; signer and device scope were// checked before the fold, even before a first serving epoch.ifletSome(reason) = crate::server_actions::refusal(db, &op.table, &receipt.author)? { reject(result, reason);returnOk(()); } }if reader_checks {ifletSome(reason) = crate::device_scope::receipt_refusal(db, &receipt)? { reject(result, reason);returnOk(()); } }// A PEER'S receipt names an actor its author's device may name. `mint`// asks this of every local write before it stamps one// ([`actor_may_be_named_by`]); here it is asked of what arrives.if !matches!(arrival, Arrival::Local | Arrival::LocalHeld) {match actor_foreign_to_author(db, &receipt)? {None => {}Some(Foreign::Refused(reason)) => { reject(result, reason);returnOk(()); }// Parked `pull` whichever way it arrived, as a receipt held for// its author's fact is (`exchange::fold_incoming`): a write this// file has not taken, retried by a fold, never re-pushed.Some(Foreign::Awaits(reason)) => {crate::rejected::park(db, op, crate::rejected::Direction::Pull, crate::rejected::Class::Waiting, &reason, &Moving::at(&op.hlc).at)?; result.parked.push(Rejection { op_id: op.op_id.clone(), reason, });returnOk(()); } } }if op.table == "cotton_devices" && (receipt.fields.contains_key("scope") || receipt.fields.contains_key("takes_placements")) {let stored = db.get("SELECT * FROM cotton_devices WHERE id = ?", &[SqlValue::Text(op.row_id.clone())])?;let scope = receipt.fields.get("scope").cloned().unwrap_or_else(|| JsonValue::from(stored.as_ref().and_then(|row| row.text("scope")).unwrap_or("full")));let takes = receipt.fields.get("takes_placements").cloned().unwrap_or_else(|| JsonValue::from(stored.as_ref().and_then(|row| row.int("takes_placements")).unwrap_or(0)));ifletErr(reason) = crate::device_scope::DeviceScope::written_pair(&scope, &takes) { reject(result, reason.to_string()); returnOk(()); } }if op.table == "cotton_devices" {ifletSome(reason) = runner_order_refused(db, &receipt)? { reject(result, reason);returnOk(()); } }// The fields, bound: every name is a column of the table or a key of a// per-key column, with a value the receipt could only hold after the// codec. The primary key is the row's address, not a field: a create may// name it, equal to the row id, and nothing gates it.letmut encoded: Vec<(String, SqlValue)> = Vec::with_capacity(receipt.fields.len());for (name, value) in &receipt.fields {if op.table == "cotton_devices" && name == "scope" {ifletErr(reason) = crate::device_scope::DeviceScope::written(value) { reject(result, reason.to_string());returnOk(()); } }let column = name.split_once('.').map_or(name.as_str(), |(column, _)| column);let is_key = name.contains('.') && receipts::is_per_key(&op.table, column);if !spec.columns.iter().any(|(c, _)| *c == column) || (name.contains('.') && !is_key) {// A column a newer revision of the package brings: the receipt// waits for this file to take that revision.// So is a column a person added to a shipped table (`own_<key>`)// on a device whose copy has not taken that definition yet.let added = name.starts_with(crate::schema::package_shape::OWN_PREFIX);if (package || added) && !name.contains('.') && crate::rejected::keeps_newer_shape(db)? {return wait_for_shape(db, op, result, crate::schema::package_shape::waits_for_shape(&op.table, Some(name))); } reject(result, format!("unknown column: {}.{name}", op.table));returnOk(()); }if column == spec.pk && *value != JsonValue::String(op.row_id.clone()) { reject(result, format!("the receipt names {} as its key and {} as its row", value, op.row_id));returnOk(()); }if !is_key && matches!(value, JsonValue::Object(_) | JsonValue::Array(_)) { reject(result, format!("{}.{name} is not a value after its codec", op.table));returnOk(()); }if !is_key && column != spec.pk { encoded.push((name.clone(), receipts::bind(value))); } }// The fences, asked before the row is touched: each refuses a write the// policies would otherwise settle in silence.let fenced = receipt.kind != Kind::Retract;if fenced {ifletSome(reason) = no_un_revocation(op, receipt.kind, &encoded) { reject(result, reason);returnOk(()); }ifletSome(reason) = no_digest_swap(db, op, Some(&encoded))? { reject(result, reason);returnOk(()); }ifletSome(reason) = no_grant_rewrite(db, op, Some(&encoded))? { reject(result, reason);returnOk(()); }if receipt.kind == Kind::Change {ifletSome(reason) = identity_change_refusal(&op.table, &op.row_id, receipt.fields.keys()) { reject(result, reason);returnOk(()); }ifletSome(sentence) = insert_only_refusal(&op.table) { reject( result, format!("{sentence}: this change of {} {} is not applied", op.table, op.row_id), );returnOk(()); } }// THE FILE'S IDENTITY AND THE LINK RULE (design 5.3), for a write// minted here or handed over by a device: a workspace row's kind,// namespace and owner never change, and a record in a shared database// never points into the personal one.ifletSome(file) = file {let refusal = matchcrate::link_rule::no_identity_change(db, op, Some(&encoded))? {Some(reason) => Some(reason),None => crate::link_rule::check_on(db, file, op, Some(&encoded))?, };ifletSome(reason) = refusal { reject(result, reason);returnOk(()); } } }// WHO MAY HOLD THE RECORD (`crate::audience`), for a write minted here or// handed over by a device — a delete as much as a change: another// person's device never writes an only-you record, and only the owner// sets or releases an audience.if file.is_some() {let patch = (receipt.kind != Kind::Retract).then_some(encoded.as_slice());ifletSome(reason) = crate::audience::refusal(db, op, patch)? { reject(result, reason);returnOk(()); } }// A write this file already holds, arriving again, is the same write: a// replay must change nothing (3.1 rule 9) — except settle a row its// receipts say is present and its table does not hold: a child parked// `conflict` on re-assembly (3.7 point 9), which is how its retry heals. drop(gates);let holds = crate::spans::span("fold::apply holds+facts");if receipts::holds_op(db, op)? {if receipt.kind != Kind::Retract && !in_table(db, &op.table, spec.pk, &op.row_id)? {letmut moving = Moving::at(&op.hlc);match nested(db, |db| {let life = life_of(db, &op.table, &op.row_id)?; settle(db, &op.table, &op.row_id, spec, &life, &mut moving)?; in_table(db, &op.table, spec.pk, &op.row_id) }) {Ok(true) => { result.applied.push(op.op_id.clone());let row = (op.table.clone(), op.row_id.clone()); push_row(&mut result.applied_rows, row); moving.report(result);returnOk(()); }Ok(false) => {}Err(error) if is_constraint_failure(&error) => { reject(result, reassembly_reason(&error));returnOk(()); }Err(error) => returnErr(error), } }if !result.skipped_stale.contains(&op.op_id) { result.skipped_stale.push(op.op_id.clone()); }returnOk(()); }// A receipt another of its author's re-stamped at this same stamp, saying// all of it and more (`restamp_verdict`), is that write already: stale.if receipt.restamps.is_none() && said_at_its_stamp(db, op, &receipt)? {if !result.skipped_stale.contains(&op.op_id) { result.skipped_stale.push(op.op_id.clone()); }returnOk(()); }// THE OLD-AUTHOR CUT-OFF (slice 12): a peer's receipt by an author of a// Mac that stopped serving, stamped after the epoch that ended it began,// is parked `conflict` — never applied, never dropped. Below the cut-off// it is judged like any receipt. An author fact is not a write: it folds// as before, so the receipts of its stream meet this same rule.if !matches!(arrival, Arrival::Local | Arrival::LocalHeld) && !crate::fact_hooks::folds_first(op) {ifletSome(reason) = crate::serving::past_the_cut_off(db, &receipt.author, &receipt.stamp)? {crate::rejected::park(db, op, direction_of(arrival), crate::rejected::Class::Conflict, &reason, &Moving::at(&op.hlc).at)?; result.parked.push(Rejection { op_id: op.op_id.clone(), reason, });returnOk(()); } }// The row's own savepoint (3.1 rule 8): a constraint the row cannot// satisfy rolls back this receipt's storage and the row's change together,// and leaves every other row of the page standing. It is opened before a// re-stamp drops the receipt it replaces, so the two go or stay together.//// The prefix is deliberately NOT the driver's own (`cotton_tx_`): these// savepoints are issued through `exec`, outside the depth counter, and a// shared name would make a nested `transaction`'s `ROLLBACK TO` unwind to// the wrong place.let mark = format!("sp_{}", next_savepoint()); db.exec(&format!("SAVEPOINT {mark}"))?;// A RE-STAMP REPLACES ONLY ITS OWN DEVICE'S IDENTICAL RECEIPT (5.2 point// 8). A re-dated receipt names the one it replaces; that one goes only// when both authors' facts name the same device credential and the two// are the same write. Otherwise any writer could delete another's receipt// by naming it, so the re-stamp parks and nothing is dropped. A named// receipt this file never held is nothing to drop: the re-stamp applies.letmut restamped: Option<String> = None;ifletSome(old) = receipt.restamps.as_deref() {match restamp_verdict(db, &receipt, old)? {Restamp::NothingHere => {}Restamp::Replaces => { drop_receipt(db, old)?; restamped = Some(old.to_string()); }Restamp::Refused(reason) => {let _ = db.exec(&format!("ROLLBACK TO {mark}"));let _ = db.exec(&format!("RELEASE {mark}"));crate::rejected::park(db, op, direction_of(arrival), crate::rejected::Class::Conflict, &reason, &Moving::at(&op.hlc).at)?; result.parked.push(Rejection { op_id: op.op_id.clone(), reason, });returnOk(()); } } }// A FACT IS ONLY EVER INSERTED (`crate::fact_hooks`): an update or a// delete of one is refused, and of two different writes to one fact id// the earlier `(stamp, op id)` stands on every device — the other parks.let is_fact = matchcrate::fact_hooks::arriving(db, op, &receipt, owned)? {crate::fact_hooks::Arriving::NotAFact => false,crate::fact_hooks::Arriving::Take => true,crate::fact_hooks::Arriving::Swap(held) => {// AN UNDO'S FACT SWAPPED (slice 3b): the losing twin's act goes// with it — each receipt naming the fact by the losing authors is// dropped and parked, and its row says what is left.if op.table == crate::fact_hooks::UNDOS_TABLE {let losers: Vec<String> = held.iter().map(|stored| stored.author.clone()).collect();let reason = crate::fact_hooks::undo_conflict_reason(&op.row_id);for (op_id, bytes) incrate::fact_hooks::undo_act_receipts(db, &op.row_id, &losers)? { drop_receipt(db, &op_id)?;let lost = crate::wire::from_bytes(op_id.clone(), &bytes).map_err(StoreError::encode)?;crate::rejected::park(db, &lost, direction_of(arrival), crate::rejected::Class::Conflict, &reason, &Moving::at(&op.hlc).at)?;ifletSome(lost_spec) = spec_for(&lost.table) { resettle(db, &lost, lost_spec, result)?; } result.parked.push(Rejection { op_id, reason: reason.clone() }); } }for stored in held { drop_receipt(db, &stored.op_id)?;let lost = crate::wire::from_bytes(stored.op_id.clone(), &stored.bytes) .map_err(StoreError::encode)?;let reason = crate::fact_hooks::conflict_reason(&op.table, &op.row_id);crate::rejected::park(db, &lost, direction_of(arrival), crate::rejected::Class::Conflict, &reason, &Moving::at(&op.hlc).at)?; result.parked.push(Rejection { op_id: stored.op_id, reason, }); }true }crate::fact_hooks::Arriving::Refuse(reason) => {let _ = db.exec(&format!("ROLLBACK TO {mark}"));let _ = db.exec(&format!("RELEASE {mark}"));// This file's own write is refused to its writer; a peer's parks.if matches!(arrival, Arrival::Local | Arrival::LocalHeld) { reject(result, reason);returnOk(()); }// A fact that waits for the serving fact of its epoch (a kept// relay key, `fact_hooks::relay_key_refusal`) parks `waiting`, and// that fact's arrival offers it again; every other refusal of a// fact is a conflict.// Filed `pull` whichever way it came, as every waiting receipt is// (`exchange::fold_incoming`): a write that exists on the other// side and this file has not taken — the side a retry reads.let (class, direction) = if reason.starts_with(crate::rejected::WAITING_FOR_SERVING) { (crate::rejected::Class::Waiting, crate::rejected::Direction::Pull) } else { (crate::rejected::Class::Conflict, direction_of(arrival)) };crate::rejected::park(db, op, direction, class, &reason, &Moving::at(&op.hlc).at)?; result.parked.push(Rejection { op_id: op.op_id.clone(), reason, });returnOk(()); } };let t = receipts::retract_stamp(db, &op.table, &op.row_id)?;// Below the row's retract: an earlier life's write, dropped on arrival// (3.7 point 2) — except a receipt that sets a mirror, which outlives the// retract (point 3) and so must be stored whenever it arrives. A retract// at or below the one held is replaced by it.let stale = match receipt.kind {Kind::Retract => t.as_deref().is_some_and(|t| t >= op.hlc.as_str()), _ => { t.as_deref().is_some_and(|t| t > op.hlc.as_str()) && !receipts::speaks_below_retract(&op.table, &receipt) } };if stale {// The receipt it replaced is gone all the same: the row is what is// left says.if restamped.is_some() {ifletErr(error) = resettle(db, op, spec, result) {let _ = db.exec(&format!("ROLLBACK TO {mark}"));let _ = db.exec(&format!("RELEASE {mark}"));if !is_constraint_failure(&error) {returnErr(error); } reject(result, sqlite_message(&error));returnOk(()); } } db.exec(&format!("RELEASE {mark}"))?;if !result.skipped_stale.contains(&op.op_id) { result.skipped_stale.push(op.op_id.clone()); }returnOk(()); } drop(holds);let _move = crate::spans::span("fold::apply move_row");letmut moving = Moving::at(&op.hlc);let held = arrival == Arrival::LocalHeld;match move_row(db, op, &receipt, spec, t.as_deref(), held, &mut moving) {Ok(Moved::Changed) => { db.exec(&format!("RELEASE {mark}"))?;if is_fact {crate::fact_hooks::folded(db, &receipt)?; } else {crate::fact_hooks::row_taken(db, &receipt)?; } result.applied.push(op.op_id.clone());let row = (op.table.clone(), op.row_id.clone()); push_row(&mut result.applied_rows, row); moving.report(result);Ok(()) }Ok(Moved::Lost) => {// The receipt lost on every field it names: not stored (3.1 rule// 6), and the savepoint takes back the attempt — but not the drop// of the receipt it re-stamps, which is made again.let _ = db.exec(&format!("ROLLBACK TO {mark}"));ifletSome(old) = restamped.as_deref() {let resettled = drop_receipt(db, old).and_then(|()| resettle(db, op, spec, result));ifletErr(error) = resettled {let _ = db.exec(&format!("ROLLBACK TO {mark}"));let _ = db.exec(&format!("RELEASE {mark}"));if !is_constraint_failure(&error) {returnErr(error); } reject(result, sqlite_message(&error));returnOk(()); } }let _ = db.exec(&format!("RELEASE {mark}"));if !result.skipped_stale.contains(&op.op_id) { result.skipped_stale.push(op.op_id.clone()); }Ok(()) }Err(error) => {let _ = db.exec(&format!("ROLLBACK TO {mark}"));let _ = db.exec(&format!("RELEASE {mark}"));if !is_constraint_failure(&error) {returnErr(error); }ifletSome(held) = awaiting_parent {if is_foreign_key_failure(&error) { held.push(op);returnOk(()); } } reject(result, sqlite_message(&error));Ok(()) } }}/// The side a parked write is kept for: a pulled answer's, or a push's.fn direction_of(arrival: Arrival) -> crate::rejected::Direction {if arrival == Arrival::Pulled {crate::rejected::Direction::Pull } else {crate::rejected::Direction::Push }}/// What a re-stamp may do to the receipt it names.enumRestamp {/// This file does not hold it: nothing to drop.NothingHere,/// Its own device's identical receipt: dropped, the re-stamp stands for it.Replaces,/// Another device's receipt, or another write: parked, nothing dropped.Refused(String),}/// What `receipt`'s `restamps` may do to `old`, the op id it names./// Whether `wider` says every field and value `narrower` says, at one stamp/// of one row: each field it names, with the same value — or with a value/// where `narrower` named null in a column that cannot hold null, which was/// never a value of the row.fn says_all_of(db: &Driver, wider: &Receipt, narrower: &Receipt) -> Result<bool> {let cannot_hold_null = not_null_columns(db, &wider.table)?;Ok(narrower.fields.iter().all(|(name, value)| match wider.fields.get(name) {Some(said) if said == value => true,Some(said) => value.is_null() && !said.is_null() && cannot_hold_null.iter().any(|column| column == name),None => false, }))}/// Whether this file holds another receipt of the same author at this/// receipt's own stamp that says all of it ([`says_all_of`]): the one that/// re-stamped it there. Arriving again — a park of it offered once more — it/// is stale, never a second receipt at that stamp.fn said_at_its_stamp(db: &Driver, op: &CottonOp, receipt: &Receipt) -> Result<bool> {letSome(row) = db.get("SELECT * FROM _writes WHERE tbl = ? AND row_id = ? AND hlc = ? AND op_id <> ?", &[SqlValue::Text(op.table.clone()),SqlValue::Text(op.row_id.clone()),SqlValue::Text(receipt.stamp.clone()),SqlValue::Text(op.op_id.clone()), ], )?else {returnOk(false); };let held = match receipts::implied::bytes_of(db, &row)? {Some(bytes) => canonical::decode(&bytes)?,None => returnOk(false), };Ok(held.author == receipt.author && held.kind == receipt.kind && held.actor == receipt.actor && says_all_of(db, &held, receipt)?)}/// The columns of `table` that cannot hold null, its key aside.fn not_null_columns(db: &Driver, table: &str) -> Result<Vec<String>> {Ok(db .all("SELECT name FROM pragma_table_info(?) WHERE \"notnull\" = 1 AND pk = 0", &[SqlValue::Text(table.to_string())])? .iter() .filter_map(|row| row.text("name").map(str::to_string)) .collect())}fn restamp_verdict(db: &Driver, receipt: &Receipt, old: &str) -> Result<Restamp> {let key = [SqlValue::Text(old.to_string())];letSome(row) = (match db.get("SELECT * FROM _writes WHERE op_id = ?", &key)? {Some(row) => Some(row),None => db.get("SELECT * FROM _tombstones WHERE op_id = ?", &key)?, }) else {returnOk(Restamp::NothingHere); };letSome(bytes) = receipts::implied::bytes_of(db, &row)? else {returnErr(StoreError::encode(format!("the receipt {old} is stored with no bytes"))); };let named = canonical::decode(&bytes)?;let device_of = |author: &str| crate::fact_hooks::author_device(db, author);let same_device = match (device_of(&named.author)?, device_of(&receipt.author)?) { (Some(named), Some(restamping)) => named == restamping, _ => false, };if !same_device {returnOk(Restamp::Refused(format!("this re-dated write names {old}, which {} wrote — a re-date replaces only its own device's receipt, so nothing was dropped", named.author ))); }// At its own stamp a receipt may say MORE than the one it replaces —// every field and value of it, and fields it could not say: a copy that// pulled a row again once it kept a column the object fills// (`mint::served`). Nothing the replaced receipt said goes with it: a// null it named in a column that cannot hold null was never a value of// the row (no row could be assembled from it), so the receipt that names// that column's value there says it all — a copy minting the object's// nothing as the column's default, where an earlier build named null.let says_it_all = if named.stamp == receipt.stamp { says_all_of(db, receipt, &named)? } else { named.fields == receipt.fields };let same_write = named.table == receipt.table && named.row_id == receipt.row_id && named.kind == receipt.kind && named.actor == receipt.actor && says_it_all;if !same_write {returnOk(Restamp::Refused(format!("this re-dated write names {old} but is not the same write — a re-date keeps the table, row, kind, actor, fields and values, so nothing was dropped" ))); }Ok(Restamp::Replaces)}/// Take a receipt out of this file: its row in `_writes` or its tombstone,/// and its queued push, which must not travel once it is replaced.fn drop_receipt(db: &Driver, op_id: &str) -> Result<()> {for table in ["_writes", "_tombstones", "_outbox"] { db.run( &format!("DELETE FROM {table} WHERE op_id = ?"), &[SqlValue::Text(op_id.to_string())], )?; }Ok(())}/// Make `op`'s row say what its receipts say now, after a re-stamp dropped/// one of them and itself did not land.fn resettle(db: &Driver, op: &CottonOp, spec: &TableSpec, result: &mutFoldResult) -> Result<()> {letmut moving = Moving::at(&op.hlc);let life = life_of(db, &op.table, &op.row_id)?; receipts::keep_only(db, &op.table, &op.row_id, &life.keep)?; settle(db, &op.table, &op.row_id, spec, &life, &mut moving)?;let row = (op.table.clone(), op.row_id.clone()); push_row(&mut result.applied_rows, row); moving.report(result);Ok(())}/// Note a row the batch changed. A row is pushed again only when it is not/// the last one pushed; [`dedupe_rows`] takes the rest out once the batch's/// passes end.fn push_row(rows: &mutVec<(String, String)>, row: (String, String)) {if rows.last() != Some(&row) { rows.push(row); }}/// Keep each row once, where it first changed.fn dedupe_rows(rows: &mutVec<(String, String)>) {letmut seen = std::collections::HashSet::with_capacity(rows.len()); rows.retain(|row| seen.insert(row.clone()));}/// What putting one receipt beside its row's others did.enumMoved {/// Stored, and the row (or its dormant state) changed.Changed,/// Current for nothing: not stored.Lost,}/// Put the receipt beside the row's others, assemble the row and settle it.fn move_row( db: &Driver, op: &CottonOp, receipt: &Receipt, spec: &TableSpec, t: Option<&str>, held: bool, moving: &mutMoving,) -> Result<Moved> {let read = crate::spans::span("fold::move_row of_row");letmut others = receipts::of_row(db, &op.table, &op.row_id)?;letmut t_held = receipts::retract_held(db, &op.table, &op.row_id)?; drop(read);// Every receipt `_writes` holds for the row once this one is stored:// what `keep_only` drops from.letmut held_ids: Vec<String> = others.iter().map(|stored| stored.op_id.clone()).collect();let storing = crate::spans::span("fold::move_row store");let t_after: Option<String> = match receipt.kind {Kind::Retract => { receipts::store_retract(db, op, receipt, held)?; t_held = held;Some(receipt.stamp.clone()) }Kind::Create | Kind::Change => { receipts::store(db, op, receipt, held)?; held_ids.push(op.op_id.clone()); others.push(receipts::Stored { op_id: op.op_id.clone(), kind: receipt.kind, hlc: receipt.stamp.clone(), author: receipt.author.clone(), actor: receipt.actor.clone(), held, bytes: op.receipt.as_bytes().to_vec(), receipt: receipt.clone(), }); others.sort_by(|a, b| a.hlc.cmp(&b.hlc)); t.map(str::to_string) } }; drop(storing);let assembling = crate::spans::span("fold::move_row assemble");let life = receipts::assemble_under(&op.table, &others, t_after.as_deref(), t_held); drop(assembling);if receipt.kind != Kind::Retract && !life.keep.contains(&op.op_id) {returnOk(Moved::Lost); }let keeping = crate::spans::span("fold::move_row keep_only"); receipts::keep_only_of(db, &held_ids, &life.keep)?; drop(keeping);let settling = crate::spans::span("fold::move_row settle"); settle(db, &op.table, &op.row_id, spec, &life, moving)?; drop(settling);// The object's receipt, its row's only one, is kept as its identity while the row says it (receipts/implied.rs).if receipt.author == receipts::implied::OBJECT_AUTHOR && !held { receipts::implied::imply(db, &op.op_id)?; }Ok(Moved::Changed)}// ---------------------------------------------------------------------------// Presence under owning parents (design 3.7 points 7-9)// ---------------------------------------------------------------------------//// A row is PRESENT — holds its table row — only while it is live by its own// receipts AND every owning parent it names is present. The fold moves// presence itself, in its own SQL, and never leaves it to SQLite's// `ON DELETE CASCADE`: a row that stops being present first takes its present// owning children out of their tables (recursively, their receipts KEPT, so// they are dormant), then itself; a row that becomes present re-assembles// every owning child that is live by its own receipts. Each child's move is a// savepoint of its own inside the row's. Nothing is minted for a child: its// receipts say everything, and they are the same on every device, which is// why a parent's retract and a child's create converge in either order./// What one row's move did besides the row: the board lines it owes, and the/// instant a park it makes is dated (the arriving receipt's stamp, so a/// replay dates it the same).pub(crate) structMoving { at: String, board: Vec<String>,}implMoving {fn at(hlc: &str) -> Moving {let at = hlc .get(..13) .and_then(|ms| ms.parse::<i64>().ok()) .and_then(crate::protocol::js::to_iso_string) .unwrap_or_else(|| hlc.to_string());Moving { at, board: Vec::new(), } }/// Hand the board lines of a move that held to the batch's result, once/// each. There is no board in this crate: the result carries them to the/// caller, and each is also said on stderr.fn report(self, result: &mutFoldResult) {for line inself.board {if !result.board.contains(&line) { eprintln!("cotton: {line}"); result.board.push(line); } } }}/// `(column, parent table)` for each owning reference of `table`.fn owning_parents(table: &str) -> implIterator<Item = (&'static str, &'static str)> + '_ {crate::schema::table_specs::OWNING_REFS .iter() .filter(move |(child, _, _)| *child == table) .map(|(_, column, parent)| (*column, *parent))}/// `(child table, column)` for each owning reference to `table`.fn owning_children(table: &str) -> implIterator<Item = (&'static str, &'static str)> + '_ {crate::schema::table_specs::OWNING_REFS .iter() .filter(move |(_, _, parent)| *parent == table) .map(|(child, column, _)| (*child, *column))}/// Whether `table` holds the row — which, for a replicated table, is whether/// the row is present.fn in_table(db: &Driver, table: &str, pk: &str, row_id: &str) -> Result<bool> {Ok(db .get( &format!("SELECT 1 AS here FROM {table} WHERE {} = ?", q(pk)), &[SqlValue::Text(row_id.to_string())], )? .is_some())}/// A row's life from the receipts this file holds for it.fn life_of(db: &Driver, table: &str, row_id: &str) -> Result<receipts::Life> {let held = receipts::of_row(db, table, row_id)?;let t = receipts::retract_stamp(db, table, row_id)?;let t_held = receipts::retract_held(db, table, row_id)?;Ok(receipts::assemble_under(table, &held, t.as_deref(), t_held))}/// Make one row's table row say what its stored receipts say now, in a/// savepoint of its own — for a caller that changed the receipts themselves/// (a snapshot copy setting its held receipts aside), never for an arrival.pub(crate) fn reassemble_row(db: &Driver, table: &str, row_id: &str) -> Result<()> {letSome(spec) = spec_for(table) else {returnOk(()); };let life = life_of(db, table, row_id)?;letmut moving = Moving::at(life.newest.as_deref().unwrap_or_default()); nested(db, |db| settle(db, table, row_id, spec, &life, &mut moving))}/// A shape move from `from` has just ended the owning references the rises/// above it release (`move_intents::RELEASES`): every row such a reference/// held out of its table — live by its own receipts, its parent never here —/// is settled now, each in a savepoint of its own, and becomes present. A row/// that breaks a constraint on the way in stays out and is parked `conflict`,/// as a re-assembly's is. The released table's receipt-owner projection, which/// only an owning reference reads, goes with its last such reference./// Answers how many rows came in.pub(crate) fn settle_released(db: &Driver, from: u32) -> Result<usize> {letmut settled = 0;for (table, _column) incrate::schema::move_intents::released_above(from) {letSome(spec) = spec_for(table) else {continue; };if receipts::owner_columns(table).is_empty() {// not a copy: the owners projection of a table, made again from the receipts. db.run("DELETE FROM _writes_owners WHERE tbl = ?", &[SqlValue::Text(table.to_string())])?; }let held_out: Vec<String> = 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.{} = w.row_id) ORDER BY w.row_id", q(spec.pk) ), &[SqlValue::Text(table.to_string())], )? .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect();for id in held_out {let life = life_of(db, table, &id)?;if !life.live {continue; }letmut moving = Moving::at(life.newest.as_deref().unwrap_or_default());match nested(db, |db| settle(db, table, &id, spec, &life, &mut moving)) {Ok(()) => settled += usize::from(in_table(db, table, spec.pk, &id)?),Err(error) if is_constraint_failure(&error) => { park_conflict(db, table, &id, &reassembly_reason(&error), &moving.at)?; }Err(error) => returnErr(error), } } }Ok(settled)}/// What a row present in its table holds that its receipts would not write/// back — `None` when the row is not here (or its table is not one the fold/// writes from receipts). `Some((live, columns))`: `live` is false when no/// create of the row is kept, and then `columns` is the whole row; otherwise/// `columns` are the ones whose table value differs from what the receipts/// (or, where none names it, the column's default) say.////// THE FOLD WRITES A ROW FROM ITS RECEIPTS, so a row a schema move carried/// with no receipt (v90's person handles, 139's money rows) or rewrote past/// its receipts is lost at its next write: a bare change of a row with no/// create is not live and the row is taken out; one with stale receipts is/// rewritten to what they said. On the owner's Personal (21 Oct 2026) a/// merge's handle repoint deleted both handles, and a counterparty repoint/// put a transaction back to its pre-139 status and the CHECK refused it./// `mint` asks this before every change and says the row's own values in it./// Mirror and identity columns are never carried: nothing but a revocation/// writes the one, and a change may not name the other.pub(crate) fn unreceipted( db: &Driver, table: &str, row_id: &str,) -> Result<Option<(bool, Map<String, JsonValue>)>> {letSome(spec) = spec_for(table) else {returnOk(None); };letSome(row) = db.get( &format!("SELECT * FROM {table} WHERE {} = ?", q(spec.pk)), &[SqlValue::Text(row_id.to_string())], )?else {returnOk(None); };if row.get("_born").is_none() {returnOk(None); }letSome(decoded) = read_row(db, table, row_id)? else {returnOk(None); };let life = life_of(db, table, row_id)?;if !life.live {let whole = decoded .into_iter() .filter(|(column, value)| { column != spec.pk && !value.is_null() && !receipts::MIRROR_COLUMNS.contains(&column.as_str()) }) .collect();returnOk(Some((false, whole))); }let written: std::collections::BTreeMap<String, SqlValue> = receipts::row_columns(table, &life)?.into_iter().collect();let defaults = unnamed_defaults(db, table, spec, &written.clone().into_iter().collect::<Vec<_>>())?;letmut differ = Map::new();for (column, _) in spec.columns {if *column == spec.pk || receipts::MIRROR_COLUMNS.contains(column) || identity_change_refusal(table, row_id, [&(*column).to_string()]).is_some() {continue; }let held = row.get(column).cloned().unwrap_or(SqlValue::Null);let says = match written.get(*column) {Some(value) => value.clone(),None => match defaults.iter().find(|(name, _)| name == column) {Some((_, default)) => db .get(&format!("SELECT {default} AS v"), &[])? .and_then(|row| row.get("v").cloned()) .unwrap_or(SqlValue::Null),None => SqlValue::Null, }, };if held != says { differ.insert( (*column).to_string(), decoded.get(*column).cloned().unwrap_or(JsonValue::Null), ); } }Ok(Some((true, differ)))}/// The first owning parent `fields` names that is not present, as/// `(parent table, parent id)`. A null owning column names no parent.fn absent_parent( db: &Driver, table: &str, fields: &std::collections::BTreeMap<String, receipts::Current>,) -> Result<Option<(&'static str, String)>> {for (column, parent) in owning_parents(table) {letSome(JsonValue::String(id)) = fields.get(column).map(|current| ¤t.value) else {continue; };let pk = spec_for(parent).map_or("id", |spec| spec.pk);if !in_table(db, parent, pk, id)? {returnOk(Some((parent, id.clone()))); } }Ok(None)}/// Why a write `mint` just folded left its row out of its table while the/// row is live by its receipts — the owning ancestor that is not present —/// or `None` when the row is present, not live, or held out only by an/// ancestor this same act retracts. `mint` refuses a create (or a change)/// under a parent that is not present; a peer's arrives dormant instead.pub(crate) fn held_out_by_parent( db: &Driver, table: &str, row_id: &str, retracted: &BTreeSet<(String, String)>,) -> Result<Option<String>> {letSome(spec) = spec_for(table) else {returnOk(None); };if in_table(db, table, spec.pk, row_id)? {returnOk(None); }letmut life = life_of(db, table, row_id)?;if !life.live {returnOk(None); }letmut at = table.to_string();// Owning chains are a few links deep; the bound only stops a cycle.for _ in0..64 {letSome((parent, id)) = absent_parent(db, &at, &life.fields)? else {returnOk(None); };if retracted.contains(&(parent.to_string(), id.clone())) {returnOk(None); }let parent_life = life_of(db, parent, &id)?;if !parent_life.live {returnOk(Some(format!("{parent} {id}"))); } at = parent.to_string(); life = parent_life; }Ok(Some(format!("an owning chain above {table} {row_id}")))}/// Run `body` in a savepoint of its own: released when it holds, rolled back/// (and released) when it fails, so the failure takes back only its own work.fn nested<T>(db: &Driver, body: implFnOnce(&Driver) -> Result<T>) -> Result<T> {let mark = format!("sp_{}", next_savepoint()); db.exec(&format!("SAVEPOINT {mark}"))?;match body(db) {Ok(value) => { db.exec(&format!("RELEASE {mark}"))?;Ok(value) }Err(error) => {let _ = db.exec(&format!("ROLLBACK TO {mark}"));let _ = db.exec(&format!("RELEASE {mark}"));Err(error) } }}/// Make the table row say what `life` says, under the presence rule: written/// (INSERT or UPDATE) when the row is live and every owning parent present,/// removed — children first — otherwise. A row that has just become present/// re-assembles its owning children.fn settle( db: &Driver, table: &str, row_id: &str, spec: &TableSpec, life: &receipts::Life, moving: &mutMoving,) -> Result<()> {let here = in_table(db, table, spec.pk, row_id)?;let present = life.live && absent_parent(db, table, &life.fields)?.is_none();if !present {if here { remove(db, table, row_id, spec, moving)?; }returnOk(()); }letmut columns = receipts::row_columns(table, life)?;// A kept receipt may name a column the table no longer has: a migration// that folds a column away (cotton_people.emails and .phones into// cotton_person_handles at v90) keeps the receipts that wrote it. The row// is what its receipts say about the columns it HAS; the rest is history. columns.retain(|(column, _)| column != spec.pk && spec.columns.iter().any(|(c, _)| c == column)); columns.push(("_hlc".to_string(),SqlValue::Text(life.newest.clone().unwrap_or_default()), )); columns.push(("_born".to_string(), life.born.clone().map_or(SqlValue::Null, SqlValue::Text), ));if here {// THE ROW IS A FUNCTION OF THE RECEIPTS IT KEEPS. An UPDATE writes// every column, not only the ones a kept receipt names: a column no// kept receipt names goes back to its default, exactly as the INSERT// below would leave it. Otherwise a receipt that stopped counting — a// change below a retract, dropped by `keep_only` — leaves its value in// the row on the device that held the row through the retract, while// a device that re-created the row from the same receipts shows the// default.letmut assignments = columns .iter() .map(|(column, _)| format!("{} = ?", q(column))) .collect::<Vec<_>>(); assignments.extend( unnamed_defaults(db, table, spec, &columns)? .into_iter() .map(|(column, default)| format!("{} = {default}", q(&column))), );let assignments = assignments.join(", ");letmut params: Vec<SqlValue> = columns.into_iter().map(|(_, value)| value).collect(); params.push(SqlValue::Text(row_id.to_string())); db.run( &format!("UPDATE {table} SET {assignments} WHERE {} = ?", q(spec.pk)), ¶ms, )?;returnOk(()); } columns.push((spec.pk.to_string(), SqlValue::Text(row_id.to_string())));let names = columns .iter() .map(|(column, _)| q(column)) .collect::<Vec<_>>() .join(", ");let holders = vec!["?"; columns.len()].join(", ");let params: Vec<SqlValue> = columns.into_iter().map(|(_, value)| value).collect(); db.run( &format!("INSERT INTO {table} ({names}) VALUES ({holders})"), ¶ms, )?; reassemble_children(db, table, row_id, moving)}/// Every column of `table`'s spec that `named` does not write, with the SQL/// of the value an INSERT that left it out would give it: the column's/// declared default as the file's own schema spells it, or `NULL` when it/// declares none. The primary key is the row's address, never reset.fn unnamed_defaults( db: &Driver, table: &str, spec: &TableSpec, named: &[(String, SqlValue)],) -> Result<Vec<(String, String)>> {let declared = db.batch_fact(&format!("declared_defaults {table}"), || { db.all("SELECT name, dflt_value FROM pragma_table_info(?)", &[SqlValue::Text(table.to_string())]) })?;Ok(spec .columns .iter() .map(|(column, _)| *column) .filter(|column| *column != spec.pk && !named.iter().any(|(n, _)| n == column)) .filter_map(|column| {let row = declared.iter().find(|row| row.text("name") == Some(column))?;let default = row.text("dflt_value").unwrap_or("NULL");Some((column.to_string(), format!("({default})"))) }) .collect())}/// Take a row out of its table, its present owning children first, each in a/// savepoint of its own. Receipts are not touched: every row taken out here/// is dormant, and comes back when its parent does.////// The walk is [`OWNING_REFS`](crate::schema::table_specs::OWNING_REFS). A/// child it missed trips the parent's DELETE on a foreign key (once the/// schema's cascades are gone); then the remaining children are read off the/// live schema, made dormant the same way, the DELETE is tried once more, and/// the board is told. If it still fails, the row's move fails with "fold/// could not remove", and the row's receipts are refused — never the page.fn remove( db: &Driver, table: &str, row_id: &str, spec: &TableSpec, moving: &mutMoving,) -> Result<()> {for (child, column) in owning_children(table) {letSome(child_spec) = spec_for(child) else {continue; };let held = db.all( &format!("SELECT {pk} AS id FROM {child} WHERE {column} = ?", pk = q(child_spec.pk) ), &[SqlValue::Text(row_id.to_string())], )?;for id in held.iter().filter_map(|row| row.text("id").map(str::to_string)) {if child == table && id == row_id {continue; } nested(db, |db| remove(db, child, &id, child_spec, moving))?; } }// A receipt is implied only while its row is here: whole again before the row goes (receipts/implied.rs). receipts::implied::materialize_row(db, table, row_id)?;let delete = format!("DELETE FROM {table} WHERE {} = ?", q(spec.pk));let key = [SqlValue::Text(row_id.to_string())];match db.run(&delete, &key) {Ok(_) => Ok(()),Err(error) if is_foreign_key_failure(&error) => {let missed = missed_children(db, table, row_id)?;if missed.is_empty() {returnErr(could_not_remove(table, row_id, &error)); }for (child, column, child_spec, ids) in missed {for id in ids { nested(db, |db| remove(db, child, &id, child_spec, moving))?; }let line = format!("The sync found a child it did not expect: {child}.{column} under {table}");if !moving.board.contains(&line) { moving.board.push(line); } } db.run(&delete, &key) .map(|_| ()) .map_err(|error| could_not_remove(table, row_id, &error)) }Err(error) => Err(error), }}/// [`remove`] for every row `temp._keep_cut` lists, set-based: the rows,/// and the present rows that hang off them — their owning children/// ([`OWNING_REFS`](crate::schema::table_specs::OWNING_REFS)) and the/// children the live schema's foreign keys name, as [`missed_children`]/// reads them — leave their tables, one DELETE a table. Receipts are not/// touched. The caller has deferred the foreign keys to its commit: a child/// left behind (a server-only one) refuses the whole transaction there.pub(crate) fn remove_listed(db: &Driver) -> Result<()> { db.exec("CREATE TEMP TABLE IF NOT EXISTS _keep_out (tbl TEXT NOT NULL, row_id TEXT NOT NULL, \ PRIMARY KEY (tbl, row_id)) WITHOUT ROWID", )?; db.run("DELETE FROM temp._keep_out", &[])?; db.run("INSERT INTO temp._keep_out (tbl, row_id) SELECT tbl, row_id FROM temp._keep_cut", &[])?;let edges = child_edges(db)?;loop {letmut added = 0;for (child, column, parent) in &edges {letSome(spec) = spec_for(child) else { continue }; added += db.run( &format!("INSERT OR IGNORE INTO temp._keep_out (tbl, row_id) SELECT ?1, {pk} FROM {child} \ WHERE {column} IN (SELECT row_id FROM temp._keep_out WHERE tbl = ?2)", pk = q(spec.pk), column = q(column), ), &[SqlValue::Text((*child).to_string()), SqlValue::Text(parent.clone())], )?; }if added == 0 {break; } }let tables: Vec<String> = db .all("SELECT DISTINCT tbl FROM temp._keep_out", &[])? .iter() .filter_map(|row| row.text("tbl").map(str::to_string)) .collect();for table in tables {letSome(spec) = spec_for(&table) else { continue };if !db.table_exists(spec.name)? {continue; } receipts::implied::materialize_rows(db, &table, "SELECT row_id FROM temp._keep_out WHERE tbl = ?2", &[SqlValue::Text(table.clone())])?; db.run( &format!("DELETE FROM {name} WHERE {pk} IN (SELECT row_id FROM temp._keep_out WHERE tbl = ?)", name = spec.name, pk = q(spec.pk) ), &[SqlValue::Text(table.clone())], )?; } db.run("DELETE FROM temp._keep_out", &[])?;Ok(())}/// Every `(child, column, parent)` a row's removal takes children by: the/// owning references, and the live schema's foreign keys that are neither/// soft nor from a server-only table ([`missed_children`]'s reading).fn child_edges(db: &Driver) -> Result<Vec<(&'static str, String, String)>> {letmut edges: Vec<(&'static str, String, String)> = crate::schema::table_specs::OWNING_REFS .iter() .map(|(child, column, parent)| (*child, (*column).to_string(), (*parent).to_string())) .collect();let keys = db.all("SELECT m.name AS child, f.\"from\" AS col, f.\"table\" AS parent, f.\"to\" AS target \ FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f WHERE m.type = 'table'", &[], )?;for key in &keys {let (Some(child), Some(column), Some(parent)) = (key.text("child"), key.text("col"), key.text("parent")) else {continue; };letSome(child_spec) = spec_for(child) else { continue };let soft = crate::schema::table_specs::SOFT_REFS .iter() .any(|(c, col, p)| *c == child && *col == column && *p == parent);let parent_pk = spec_for(parent).map_or("id", |spec| spec.pk);let by_key = key.text("target").is_none_or(|to| to.is_empty() || to == parent_pk);if soft || !by_key || crate::schema::table_specs::is_server_only(child) || !child_spec.columns.iter().any(|(c, _)| *c == column) || edges.iter().any(|(c, col, p)| *c == child_spec.name && col == column && p == parent) {continue; } edges.push((child_spec.name, column.to_string(), parent.to_string())); }letmut held = Vec::with_capacity(edges.len());for edge in edges {if db.table_exists(edge.0)? { held.push(edge); } }Ok(held)}/// The refusal of a row whose table row the fold could not take out.fn could_not_remove(table: &str, row_id: &str, error: &StoreError) -> StoreError {StoreError::refused(format!("fold could not remove {table} {row_id}: {}", sqlite_message(error) ))}/// The children of `table`'s row `row_id` the walk did not know: read off the/// live schema (`pragma_foreign_key_list`), every replicated table whose/// foreign key to `table` is neither an owning reference the walk already/// took nor a soft one (a soft reference only points: its row stands), with/// the rows that still name `row_id`.#[allow(clippy::type_complexity)]fn missed_children( db: &Driver, table: &str, row_id: &str,) -> Result<Vec<(&'static str, String, &'staticTableSpec, Vec<String>)>> {let keys = db.all("SELECT m.name AS child, f.\"from\" AS col, f.\"to\" AS target \ FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f \ WHERE m.type = 'table' AND f.\"table\" = ? ORDER BY m.name, f.\"from\"", &[SqlValue::Text(table.to_string())], )?;letmut missed = Vec::new();for key in &keys {let (Some(child), Some(column)) = (key.text("child"), key.text("col")) else {continue; };let soft = crate::schema::table_specs::SOFT_REFS .iter() .any(|(c, col, p)| *c == child && *col == column && *p == table);letSome(child_spec) = spec_for(child) else {continue; };let parent_pk = spec_for(table).map_or("id", |spec| spec.pk);let by_key = key.text("target").is_none_or(|to| to.is_empty() || to == parent_pk);// A server-only child holds no receipts: taking its row out would// lose it, so it is left for the DELETE to refuse.if soft || !by_key || crate::schema::table_specs::is_server_only(child) || !child_spec.columns.iter().any(|(c, _)| *c == column) {continue; }let ids: Vec<String> = db .all( &format!("SELECT {pk} AS id FROM {child} WHERE {col} = ?", pk = q(child_spec.pk), col = q(column) ), &[SqlValue::Text(row_id.to_string())], )? .iter() .filter_map(|row| row.text("id").map(str::to_string)) .filter(|id| !(child_spec.name == table && id == row_id)) .collect();if !ids.is_empty() { missed.push((child_spec.name, column.to_string(), child_spec, ids)); } }Ok(missed)}/// A row has just become present: put back every owning child that is live/// by its own receipts and names it, each in a savepoint of its own. A child/// whose re-assembly breaks a constraint — a UNIQUE value another row took/// while it was dormant — is rolled back alone, stays dormant, and is parked/// `conflict`; the parent's move holds./// Find dormant candidates through the normalized per-receipt owner index./// The canonical field check distinguishes simultaneous owning columns; the/// caller still sorts, deduplicates and checks the assembled current field.pub(crate) fn dormant_children_sql(child: &str, column: &str, pk: &str) -> String { format!("SELECT row_id AS id FROM ({}) w WHERE NOT EXISTS (SELECT 1 FROM {child} c WHERE c.{} = w.row_id)", receipts::owners_naming_sql(child,column,"= ?"), q(pk))}fn reassemble_children(db: &Driver, table: &str, row_id: &str, moving: &mutMoving) -> Result<()> {for (child, column) in owning_children(table) {letSome(child_spec) = spec_for(child) else {continue; };let candidates: Vec<String> = db .all( &dormant_children_sql(child, column, child_spec.pk), &[SqlValue::Text(row_id.to_string())], )? .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect::<std::collections::BTreeSet<_>>() .into_iter() .collect();for id in candidates {if child == table && id == row_id {continue; }let life = life_of(db, child, &id)?;let names_this = life .fields .get(column) .is_some_and(|current| current.value == JsonValue::String(row_id.to_string()));if !life.live || !names_this {continue; }match nested(db, |db| settle(db, child, &id, child_spec, &life, moving)) {Ok(()) => {}Err(error) if is_constraint_failure(&error) => { park_conflict(db, child, &id, &reassembly_reason(&error), &moving.at)?; }Err(error) => returnErr(error), } } }Ok(())}/// Why a row could not be re-assembled — the park's reason, the same whether/// the parent's return or a retry of the park asked.fn reassembly_reason(error: &StoreError) -> String {if is_unique_failure(error) {"unique clash on re-assembly".to_string() } else { format!("{} on re-assembly", sqlite_message(error)) }}/// Park a dormant row's receipts `conflict`: every receipt it holds, as it/// was minted, so the row's next arrival or a retry of the park re-assembles/// it once the clash is gone.fn park_conflict(db: &Driver, table: &str, row_id: &str, reason: &str, at: &str) -> Result<()> {for stored in receipts::of_row(db, table, row_id)? {let op = crate::wire::from_bytes(stored.op_id.clone(), &stored.bytes) .map_err(StoreError::encode)?;crate::rejected::park(db, &op, crate::rejected::Direction::Pull, crate::rejected::Class::Conflict, reason, at)?; }Ok(())}/// FENCE 3 — a revocation's mirror is never cleared by a receipt.////// The threat version 9 introduces: a revoked device keeps its copy of the file/// and its outbox, and its last act could be replayed into the household by the/// merge. The record of truth is the revocation FACT (`crate::revocation`),/// which no write can update or delete; this fence guards its mirror. The/// chokepoint refuses a revoked device before its body is read/// (`cotton_server::auth::verify_owner`), and a revoke rotates the workspace/// master key.////// **What it refuses** (slice 4, note 6.6): on the declared mirror tables/// ([`MIRROR_TABLES`]), a receipt, create or change, that names any mirror column/// ([`receipts::MIRROR_COLUMNS`]) as NULL — whatever its stamp and whatever/// the row holds on this device. A pure function of the receipt, so every/// device refuses the same receipts in any arrival order: a clear that arrives/// BEFORE the revoke is refused as surely as one after it, and the fresh/// fold's last-writer-wins never lets one late receipt clear a revoke while the/// fact stands. A `create` is refused alike: an id is derived to converge, so/// a create is the first write of its row only where it was minted, and/// elsewhere its NULL would win per field over a revoke stamped below it (a/// premint). No honest receipt names a mirror NULL: a revocation is ended by/// a new row at an id of its own, never by a patch, and `mint` drops a/// create's NULL mirror (3.7 point 3), which/// `honest_device_grant_and_token_creates_sync_between_two_files_at_every_slice_boundary`/// holds.////// **It does not ask who the author is, and it cannot.** An op's `device_id` is/// an AUTHOR id (`device:<ulid>`, minted by the file's own replica) and a device/// row's `device_id` is a CREDENTIAL id (base64url of an Ed25519 public key)./// The two are deliberately separate — `cotton_client::replica::resolve_device_id`/// says why: conflating them would put a credential in every op's `device_id`/// column. So "the row this op is about IS its author" is a question the store/// cannot answer, and a column a device filled in about itself would answer it/// with whatever the device chose to say. The identity-shaped form of this/// fence lives at the chokepoint, which does hold the key that signed.////// `None` is "nothing to say"; `Some(reason)` is the rejection.fn no_un_revocation(op: &CottonOp, kind: Kind, encoded: &[(String, SqlValue)]) -> Option<String> {if !MIRROR_TABLES.contains(&op.table.as_str()) || kind == Kind::Retract {returnNone; }// A receipt that does not NAME a mirror as NULL says nothing about it.let (cleared, _) = encoded.iter().find(|(column, value)| { receipts::MIRROR_COLUMNS.contains(&column.as_str()) && matches!(value, SqlValue::Null) })?;Some(format!("a revoked row is not un-revoked by a patch: {} {} — a receipt naming {cleared} as NULL is \ refused whatever the row holds", op.table, op.row_id ))}/// THE DIGEST FENCE — an OAuth grant's refresh digest moves only WITH its chain.////// `cotton_oauth_grants.refresh_digest` (version 45) is what lets a Mac admit a/// `ctr_` signed under a key version the household has rotated past: the grant/// live, the generation current, and the SHA-256 of the presented token equal/// to the digest the row carries. So the digest is an authentication input/// that arrives over sync, and whoever can write it chooses which token/// outlives the next rotation. A device that was trusted and is about to be/// revoked holds the old key; the rule that bounds what it can do is that a/// digest can only land by MOVING THE CHAIN — and a moved chain is visible:/// the real client's next refresh presents the generation the attacker moved/// past, which is reuse, and reuse revokes the grant (`cotton_core::rules::/// oauth_grants`). What this refuses is every quiet way in:////// - **a digest that is cleared** — a null never lands on a grant that has a/// digest (the policy would drop it in silence; this says so). A null on a/// grant with none says nothing and is let through: it is how a consent/// without a digest travels;/// - **a digest that is not one** — `<ten digits>:<64 lowercase hex>:<the/// device id of the Mac that wrote it>`;/// - **a digest without its rotation** — the patch must set/// `refresh_generation` to the very generation the digest names;/// - **a swap** — a different digest at the generation the row's digest/// already names, the writer included: two Macs that minted the SAME/// successor each name themselves, and the first to land here keeps it, so/// no push can re-attribute a standing digest to another device;/// - **a plant** — a digest added to an existing grant at or below the/// generation the row already stands at.////// A digest at a LOWER generation than the row's is not refused: that is an/// honest rotation arriving late over sync, and `MaxNonNull` lets it lose./// The same op arriving twice is not refused either.////// `None` is "nothing to say"; `Some(reason)` is the rejection. No reason ever/// quotes a digest.fn no_digest_swap( db: &Driver, op: &CottonOp, encoded: Option<&[(String, SqlValue)]>,) -> Result<Option<String>> {if op.table != "cotton_oauth_grants" {returnOk(None); }letSome(columns) = encoded else {returnOk(None); };letSome((_, incoming)) = columns.iter().find(|(column, _)| column == "refresh_digest")else {returnOk(None); };let refuse = |why: &str| {Ok(Some(format!("an OAuth grant's refresh digest moves only with its chain: cotton_oauth_grants {} — \ {why}", op.row_id ))) };letSqlValue::Text(incoming) = incoming else {// A NULL CLEARS NOTHING THAT IS NOT THERE. The exchange hands a row// over as a base op carrying every column (`crate::changes`), so a// consent with no digest — minted before the rung, or for a client// that takes no refresh token — travels as `refresh_digest: null`,// and refusing that would refuse the consent itself on every peer.let standing = db .get("SELECT refresh_digest FROM cotton_oauth_grants WHERE id = ?", &[SqlValue::Text(op.row_id.clone())], )? .and_then(|row| row.text("refresh_digest").map(str::to_string));returnmatch standing {Some(_) => refuse("a digest is never cleared"),None => Ok(None), }; };letSome(generation) = digest_generation(incoming) else {return refuse("the value is not a generation, a SHA-256 digest and the device that wrote it", ); };let moved_to = columns.iter().find_map(|(column, value)| match value {SqlValue::Integer(value) if column == "refresh_generation" => Some(*value), _ => None, });if moved_to != Some(i64::from(generation)) {return refuse("the patch does not move the chain to the generation the digest names"); }letSome(existing) = db.get("SELECT refresh_digest, refresh_generation FROM cotton_oauth_grants WHERE id = ?", &[SqlValue::Text(op.row_id.clone())], )?else {// A grant born with its digest.returnOk(None); };match existing.text("refresh_digest") {Some(standing) if standing == incoming.as_str() => Ok(None),Some(standing) => match digest_generation(standing) {Some(at) if generation == at => { refuse("a different digest at the generation the row's digest already names") } _ => Ok(None), },None => {let stands_at = existing.int("refresh_generation").unwrap_or(0);if i64::from(generation) <= stands_at { refuse("a digest is added to an existing grant only by a rotation past where it stands") } else {Ok(None) } } }}/// The generation a stored refresh digest names, if it is well formed:/// exactly ten ASCII digits, a colon, 64 lowercase hex characters, a colon,/// and the device id of the Mac that wrote it — 1 to 128 characters of/// `[A-Za-z0-9_.:-]`. The same grammar as/// `cotton_core::vault::tokens::refresh_digest_writer`; this crate does not/// depend on that one, so it is spelled twice and each side has its test.fn digest_generation(value: &str) -> Option<u32> {let body = value.get(..75)?;let (generation, digest) = body.split_once(':')?;if generation.len() != 10 || !generation.bytes().all(|byte| byte.is_ascii_digit()) {returnNone; }if digest.len() != 64 || !digest .bytes() .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) {returnNone; }let writer = value.get(75..)?.strip_prefix(':')?;if writer.is_empty() || writer.len() > 128 || !writer .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':')) {returnNone; } generation.parse().ok()}/// The columns of a code credential's grant that say WHICH token it is and/// WHOSE it is and the authority it carries — set by its creation alone./// In particular, clearing read_only must never turn an observer into a writer.pubconst GRANT_WRITE_ONCE_COLUMNS: &[&str] = &["token_digest", "device_id", "minted_by", "scope", "read_only"];/// The columns of an OAuth consent that say WHO may act on it — the Mac that/// minted it (version 45), and the client that may spend its tokens. Set by/// the op that creates the row and by nothing after, for/// [`GRANT_WRITE_ONCE_COLUMNS`]' reason: the sync route takes a consent's/// writes from its minter (`cotton_server::sync::oauth_grant_rows`) and a/// revocation reaches what a device minted, so a patch that moved the minter/// would move a grant out of reach of the revocation that should end it.pubconst OAUTH_GRANT_WRITE_ONCE_COLUMNS: &[&str] = &["minted_by", "client_id"];/// An invite's write-once columns live with the invites fact (`fact_hooks`);/// re-exported so a test of the fence reads them from here.pubusecrate::fact_hooks::INVITE_WRITE_ONCE_COLUMNS;/// Which tables carry write-once columns, and which columns.const WRITE_ONCE: &[(&str, &[&str])] = &[ ("cotton_code_credentials", GRANT_WRITE_ONCE_COLUMNS), ("cotton_oauth_grants", OAUTH_GRANT_WRITE_ONCE_COLUMNS),];/// The tables whose WHOLE row is written once, when it is made — each with/// the sentence a refusal says. A change receipt naming one of their rows is/// refused: by the fold, from a peer or from this file's own writer, and by/// `mint` before it stamps one ([`insert_only_refusal`]). A create and a/// retract are not changes.////// `cotton_person_keys` (version 56): the person key's id is its public/// half's fingerprint, so a changed public half would be another key under/// this one's name, and a changed sealed half one nobody can check was made/// by the person.pubconst INSERT_ONLY: &[(&str, &str)] = &[("cotton_person_keys","a person key is written once, when it is made",)];/// The IDENTITY columns of a device row, an MCP token row and a database's/// own row — written only/// by the op that creates the row (`birth_patch` in `cotton_tools::devices`,/// the token mint in `cotton_tools::mcp::tokens`), never by a change (slice/// 4, V11-1 (b)). A `token_hash` change would make a live token authenticate/// a secret somebody chose; a `relay_identity_key` or `device_id` change/// would put another key on the roster under a row the owner approved.pubconst IDENTITY_WRITE_ONCE: &[(&str, &[&str])] = &[ ("cotton_mcp_tokens", &["token_hash", "scopes", "expires_at", "owner_user_id", "workspace_id", "created_at"], ), ("cotton_devices", &["device_id","workspace_id","relay_identity_key","approved_at","approved_by_device","scope","created_at", ], ),// WHICH RELAY A HOUSEHOLD IS REACHED THROUGH (version 103) is fixed when// its database is made. These two columns say where every Mac of the// household dials and under whose domain it orders its certificate, so a// change of them is a household moved to somebody else's front door — and// a change is one receipt from any device that may write the row. There// is no exception, not from empty: a database made without them is on// Cotton's relay for good, which is what keeps the owner's own name where// it is whoever writes. A deliberate move of a live household to another// domain, if ever wanted, is a new signed receipt kind the store learns// then, with every joined device re-admitted — not a loosening of// write-once. ("cotton_workspaces", &["relay_domain", "relay_tunnel_host"]),];/// Why a CHANGE receipt of `table` `row_id` naming `fields` is refused: it/// names an identity column of [`IDENTITY_WRITE_ONCE`]. A pure function of/// the receipt — whatever its stamp and whatever the row's state here — so/// every device refuses the same receipts, in any order; an arrival parks it/// `conflict`. `None` for every other change.pubfn identity_change_refusal<'a>( table: &str, row_id: &str, fields: implIntoIterator<Item = &'a String>,) -> Option<String> {let (_, identity) = IDENTITY_WRITE_ONCE.iter().find(|(name, _)| *name == table)?;let named: Vec<&str> = fields .into_iter() .map(|field| field.split_once('.').map_or(field.as_str(), |(column, _)| column)) .filter(|column| identity.contains(column)) .collect();let first = named.first()?;Some(format!("{table}.{first} is written once, with its row: this change of {table} {row_id} names it" ))}/// Why a change of a row of `table` is refused, when `table` is/// [`INSERT_ONLY`]; `None` for every other table.pubfn insert_only_refusal(table: &str) -> Option<&'static str> { INSERT_ONLY .iter() .find(|(name, _)| *name == table) .map(|(_, sentence)| *sentence)}/// A grant's write-once columns are set by the op that creates its row and by/// nothing after — a fence beside [`no_un_revocation`], guarded by/// `tests/fresh_line_fences.rs` (code credentials) and/// `tests/oauth_grant_in_the_file.rs` (OAuth consents).////// Why it matters for a code credential (version 44): after a workspace key/// rotation, a `ctg_` signed under the old key is admitted only when its grant/// row is live AND the row's digest is the SHA-256 of the presented token/// (`cotton_server::code::credentials`). Every device that held the old key can/// sign a token naming any row it reads — so the digest is the whole of the/// fence, and a patch that swapped it would turn "a device that WAS trusted"/// into one whose forged token outlives its own revocation on somebody else's/// live row. `device_id` and `minted_by` are who a revocation reaches and who/// the sync route accepts the row from (`cotton_server::sync::credential_rows`),/// so a patch that moved either would move a grant out of reach of the/// revocation that should end it. The honest mint writes all three once, in/// the same op as the row, and a replay of that op carries the same values,/// which passes.////// For an OAuth consent (version 45) the same holds of `minted_by`, and of/// `client_id`, which decides who may spend the consent's tokens. (Its refresh/// digest moves with its chain, so it is not write-once: [`no_digest_swap`] is/// that column's fence.)////// NOT applied to `cotton_repo_jobs.token_digest`: a re-queued job is handed/// out again with a new `run` token, so its digest is legitimately rewritten —/// and a `run` token dies with its job and within a day whatever is written/// here.////// The fence is "SET ONLY BY THE OP THAT CREATES THE ROW", not "set once": a/// row that exists without a value (written before its rung) is refused a/// patch that adds one, because that would be the forgery by the back door.fn no_grant_rewrite( db: &Driver, op: &CottonOp, encoded: Option<&[(String, SqlValue)]>,) -> Result<Option<String>> {// A fact table's fence lives with its facts (`fact_hooks::FACT_WRITE_ONCE`),// so this file names no fact table.let fence = WRITE_ONCE .iter() .map(|(table, once)| (*table, *once, None)) .chain(crate::fact_hooks::FACT_WRITE_ONCE .iter() .map(|(table, once, what)| (*table, *once, Some(*what))), ) .find(|(table, _, _)| *table == op.table.as_str());letSome((table, once, fact_words)) = fence else {returnOk(None); };letSome(columns) = encoded else {returnOk(None); };// A patch that NAMES none of the columns says nothing about them.let named: Vec<&(String, SqlValue)> = columns .iter() .filter(|(column, _)| once.contains(&column.as_str())) .collect();if named.is_empty() {returnOk(None); }// The row as this file holds it. No row: this op is the mint, and the// mint is the one write that sets the columns.letSome(row) = db.get(// A file on the other side of an additive rise may not hold every// grant column this binary knows. Read its actual row; a column the// op names is still checked below, including absent/null values. &format!("SELECT * FROM {table} WHERE id = ?"), &[SqlValue::Text(op.row_id.clone())], )?else {returnOk(None); };for (column, incoming) in named {let unchanged = row.columns().iter().any(|(name, held)| name == column && held == incoming);if unchanged {continue; }// INCLUDING a row that has none. A grant minted before its rung// carries no digest and no minter, and its token is refused after a// rotation for exactly that reason; a value patched onto it later// would be one somebody chose, not the one that was minted.let what = fact_words.unwrap_or(match table {"cotton_oauth_grants" => "an OAuth grant's", _ => "a code credential's", });returnOk(Some(format!("{what} {column} is written once, with its row: {table} {} exists and this patch \ changes it", op.row_id ))); }Ok(None)}/// A savepoint name unique within this connection's stack.////// Names nest, and a released name may be reused — but reusing one that is/// still open would make `ROLLBACK TO` unwind to the wrong place. A monotonic/// counter is enough: a row's savepoint and the nested ones of its children/// each take a fresh number, so no two live savepoints can share one.static SAVEPOINT_SEQ: AtomicU64 = AtomicU64::new(0);fn next_savepoint() -> u64 { SAVEPOINT_SEQ.fetch_add(1, Ordering::Relaxed) + 1}/// The message SQLite itself produced — `sqlite3_errmsg`, which is what/// rusqlite's error carries — so a UNIQUE or a CHECK failure is reported in/// SQLite's own words. Anything that is not a SQLite failure falls back to its/// own message.fn sqlite_message(error: &StoreError) -> String {match error {StoreError::Sqlite(inner) => inner.to_string(), other => other.to_string(), }}/// SQLite's constraint failures, which we turn into rejections.////// The primary error CODE first — the fact, rather than a reading of the/// sentence — with TypeScript's own regex over the message as the floor, so a/// failure that reaches us through some other shape is still classified the/// way the other half classifies it.fn is_constraint_failure(error: &StoreError) -> bool {ifletStoreError::Sqlite(rusqlite::Error::SqliteFailure(code, _)) = error {if code.code == rusqlite::ErrorCode::ConstraintViolation {returntrue; } }let message = error.to_string().to_ascii_lowercase(); message.contains("constraint failed") || message.contains("sqlite_constraint")}/// A foreign-key failure specifically — the one constraint whose verdict can/// change later in the same batch, once the parent op lands.fn is_foreign_key_failure(error: &StoreError) -> bool {/// `SQLITE_CONSTRAINT_FOREIGNKEY` = `SQLITE_CONSTRAINT | (3<<8)`.const FOREIGN_KEY: i32 = 787;ifletStoreError::Sqlite(rusqlite::Error::SqliteFailure(code, _)) = error {if code.extended_code == FOREIGN_KEY {returntrue; } }let message = error.to_string().to_ascii_lowercase(); message.contains("foreign key constraint failed") || message.contains("sqlite_constraint_foreignkey")}/// A UNIQUE (or primary key) failure specifically.fn is_unique_failure(error: &StoreError) -> bool {/// `SQLITE_CONSTRAINT_UNIQUE` and `SQLITE_CONSTRAINT_PRIMARYKEY`.const UNIQUE: i32 = 2067;const PRIMARY_KEY: i32 = 1555;ifletStoreError::Sqlite(rusqlite::Error::SqliteFailure(code, _)) = error {if matches!(code.extended_code, UNIQUE | PRIMARY_KEY) {returntrue; } } error.to_string().to_ascii_lowercase().contains("unique constraint failed")}/// Read one row back as domain values, or `None` if it is not there.////// The spec's column ORDER, not the file's: `Object.entries(spec.columns)` is/// what TypeScript walks, and the object it builds is compared key by key.pubfn read_row(db: &Driver, table: &str, row_id: &str) -> Result<Option<Map<String, JsonValue>>> {letSome(spec) = spec_for(table) else {returnOk(None); };letSome(row) = db.get( &format!("SELECT * FROM {table} WHERE {} = ?", q(spec.pk)), &[SqlValue::Text(row_id.to_string())], )?else {returnOk(None); };letmut out = Map::new();for (column, codec) in spec.columns {ifletSome(value) = row.get(column) { out.insert((*column).to_string(), decode_value(*codec, value)?); } }Ok(Some(out))}#[cfg(test)]#[path = "fold_tests.rs"]mod tests;