Cotton code
1265 lines · 54.1 KB · RustRaw
//! ONE PLACE WHERE CHANGES ARE MADE. Every write this file makes on its own//! account — the owner's tap, a job's row, a token's edit, an automation's//! follow-up — is an ACT handed to [`mint`]: an [`Actor`], the changes with//! their kind, a verb, and whether history is kept. `mint` stamps the ops with//! the FILE's author and the clock it is given, takes op ids from the caller's//! [`IdSource`], folds them through [`crate::fold::arrive`] as//! [`Arrival::Local`], refuses any rejection or stale skip, and on a replica//! queues them for the serving Mac.//!//! Why one place: today a device's write (`outbox::write_local`), the//! server's (`cotton-tools`' `Writer`, `write_here`) and three routes each//! stamp and fold on their own, with four different answers to what a stale//! skip means and forty author constants a reader branches on. Slices 2b and//! 2c move every one of them here; the guard//! `tests/no_cotton_op_literal_outside_mint_wire_stored.rs` holds the list of//! what is left.//!//! **Three hooks, each in its own file, each empty here**: `clock`//! (slice 1 — judge time and the release pass), `history` (slice 6 — one//! history rule) and `kinds` (slice 5a-ii — the five kinds of delete). Later//! slices fill the hook's file in their own seam and never edit this one.//!//! **The author.** Each database file gets one author, `device:<ulid>`, kept//! in `_meta.author_id` and announced by a `cotton_authors` fact, which is the//! first receipt in its own author's stream, at `first_stamp` with counter 0.//! [`first_author`] mints both when the device first holds the database, and//! again after a take-over (slice 12) and after a re-date (slice 1). The//! FIRST mint in a file that has no author mints the author first, in the same//! transaction: that first write IS the device first holding the database,//! and the fact lands as the first receipt of the stream, before the write.use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value as JsonValue};pub use crate::actor::{Actor, JobName};use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::fold::{self, Arrival};use crate::outbox::queue_ops;pub use crate::outbox::IdSource;use crate::protocol::hlc::next_hlc;use crate::protocol::js;use crate::canonical::{self, Receipt};use crate::protocol::types::CottonOp;use crate::receipts;use std::collections::{BTreeMap, BTreeSet};use crate::schema::ddl::SCHEMA_VERSION;#[path = "mint_clock.rs"]pub mod clock;#[path = "mint_history.rs"]pub mod history;#[path = "mint_kinds.rs"]pub mod kinds;/// The four readings a mint is given ([`clock`] says what each state does).#[derive(Debug, Clone, PartialEq, Eq)]pub struct Clock {    /// Judge time — the relay's word on what time it is, carried forward by    /// the continuous clock — or why there is none.    pub judge: JudgeTime,    /// The wall clock, ms since the epoch, as this device reads it.    pub wall: i64,    /// The continuous clock, ms since boot, which no NTP step moves.    pub cont: i64,    /// The boot session `cont` counts in — `kern.bootsessionuuid`, or on    /// iOS the id the app mints and keeps — which `_writes.mint_boot` stores. `None` when the caller has none (a    /// wall-only clock), never a made-up id.    pub boot: Option<String>,}/// What a mint knows of judge time.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum JudgeTime {    /// Judge time, ms since the epoch.    At(i64),    /// No judge time this boot: the mint is Unchecked and holds.    Unheard,    /// A writer whose handle has no judge — a server with no relay, a test    /// ([`clock::writer_clock`]).    /// CHECKED BY CONSTRUCTION: it stamps by the wall clock, never holds, and    /// is never judged poisoned, because its wall clock is not judge time.    WallOnly,}impl Clock {    /// A writer whose shell holds no judge clock yet ([`JudgeTime::WallOnly`]).    /// It records no continuous clock or boot session.    pub fn wall(now_ms: i64) -> Clock {        Clock {            judge: JudgeTime::WallOnly,            wall: now_ms,            cont: 0,            boot: None,        }    }    /// A shell's reading of all four: judge time if it has one this boot,    /// the wall clock, the continuous clock and the boot session it counts in.    pub fn judged(judge: Option<i64>, wall: i64, cont: i64, boot: String) -> Clock {        Clock {            judge: judge.map_or(JudgeTime::Unheard, JudgeTime::At),            wall,            cont,            boot: Some(boot),        }    }    /// Judge time, when this mint has it.    pub fn judge_ms(&self) -> Option<i64> {        match self.judge {            JudgeTime::At(judge) => Some(judge),            JudgeTime::Unheard | JudgeTime::WallOnly => None,        }    }}/// What a change does to its row — the receipt's own three words.pub use crate::canonical::Kind;/// One row's change inside an act.#[derive(Debug, Clone, PartialEq)]pub struct Change {    pub kind: Kind,    pub table: String,    pub row_id: String,    /// The columns named, storage-encoded. `None` for a retract only.    pub patch: Option<Map<String, JsonValue>>,    /// Which kind of delete a retract is (design 6.2): `Some` exactly when    /// the change is a retract. `mint` refuses a retract without one and a    /// create or change with one.    pub delete: Option<Delete>,}/// The five kinds of delete (design 6.2), named at the delete site and/// checked by `mint`'s kinds hook. A fact table refuses every delete, so the/// fifth kind, Fact, is not something a site asks for.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Delete {    /// The row leaves while no create is above the retract; a later create    /// makes it live again, and its history stays.    Retract,    /// The row, its receipts, its history, its search rows and its owned    /// descendants leave for good; the erase is kept in `_gone` as its    /// receipt, and a later write at the id parks `gone`. `reason` is what    /// erased it: `bin`, or the verb that destroys bytes today.    Erase { reason: String },    /// An Erase mirroring a deletion made outside Cotton by `job`;    /// `_gone.reason` is `source:<job>`.    SourceErase { job: String },    /// A revocation subject's row, retracted beside its `cotton_revocations`    /// fact (`revocation::revoke`).    Revocation,    /// An Erase that is Undo of an add ([`crate::take_back`]): minted only    /// while the add is the asker's own and nothing changed the record after    /// `through`, the stamp of the last receipt of the add's act;    /// `_gone.reason` is `taken_back`.    TakeBack { through: String },}impl Delete {    /// The `erase` a receipt of this delete carries: `Some` for an Erase or a    /// Source-erase, `None` for every other kind.    pub fn erase_reason(&self) -> Option<String> {        match self {            Delete::Erase { reason } => Some(reason.clone()),            Delete::SourceErase { job } => Some(format!("source:{job}")),            Delete::TakeBack { .. } => Some(crate::take_back::REASON.to_string()),            Delete::Retract | Delete::Revocation => None,        }    }}impl Change {    pub fn create(table: &str, row_id: &str, patch: Map<String, JsonValue>) -> Change {        Change {            kind: Kind::Create,            table: table.to_string(),            row_id: row_id.to_string(),            patch: Some(patch),            delete: None,        }    }    pub fn update(table: &str, row_id: &str, patch: Map<String, JsonValue>) -> Change {        Change {            kind: Kind::Change,            table: table.to_string(),            row_id: row_id.to_string(),            patch: Some(patch),            delete: None,        }    }    /// A Retract ([`Delete::Retract`]).    pub fn retract(table: &str, row_id: &str) -> Change {        Change::delete(table, row_id, Delete::Retract)    }    /// A delete of the kind `delete` names.    pub fn delete(table: &str, row_id: &str, delete: Delete) -> Change {        Change {            kind: Kind::Retract,            table: table.to_string(),            row_id: row_id.to_string(),            patch: None,            delete: Some(delete),        }    }    /// An Erase of the row and its owned descendants ([`Delete::Erase`]).    pub fn erase(table: &str, row_id: &str, reason: &str) -> Change {        Change::delete(table, row_id, Delete::Erase { reason: reason.to_string() })    }}/// Every collected change, in the shape `mint` takes.////// A writer collects upserts and deletes; a receipt is a create, a change or/// a retract. Each row's presence is walked through the batch: it starts as/// the file holds it, a delete makes it absent, and an upsert of an absent row/// is its CREATE and makes it present; an upsert of a present row is a change./// Decided here, against the file and the batch, because a change with no/// create above the row's retract is dormant: an upsert read as a change —/// after a delete of the same row in the same batch, say — would mint a row/// nobody sees.pub fn changes_of(db: &Driver, local: &[crate::outbox::LocalChange]) -> Vec<Change> {    let mut present: std::collections::HashMap<(String, String), bool> = std::collections::HashMap::new();    local        .iter()        .map(|change| {            let key = (change.table.clone(), change.row_id.clone());            let here = *present                .entry(key)                .or_insert_with(|| row_present(db, &change.table, &change.row_id));            let kind = match change.kind {                crate::protocol::types::OpKind::Delete => Kind::Retract,                crate::protocol::types::OpKind::Upsert if here => Kind::Change,                crate::protocol::types::OpKind::Upsert => Kind::Create,            };            present.insert(                (change.table.clone(), change.row_id.clone()),                kind != Kind::Retract,            );            Change {                kind,                table: change.table.clone(),                row_id: change.row_id.clone(),                patch: if kind == Kind::Retract { None } else { change.patch.clone() },                // The kind the site named; `mint`'s kinds hook refuses one                // on anything but a retract.                delete: change.delete.clone(),            }        })        .collect()}fn row_present(db: &Driver, table: &str, row_id: &str) -> bool {    crate::schema::package_shape::spec_on(db, table).ok().flatten().is_some_and(|spec| {        db.get(            &format!("SELECT 1 AS present FROM {} WHERE \"{}\" = ?", table, spec.pk),            &[SqlValue::Text(row_id.to_string())],        )        .ok()        .flatten()        .is_some()    })}/// Whether the act leaves history rows. Read by the `history` hook (slice 6);/// a job that touches a row every hour says `None`.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum History {    Kept,    None,}/// How this process holds the file — what decides whether a minted op is/// queued, and which actors the file may name.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Held {    /// The serving Mac: the file every peer syncs from. Nothing is queued; a    /// peer reads the write out of the tables by author and stamp.    Served,    /// A phone or a client Mac: the write is queued for the serving Mac.    Replica,    /// The carry's offline import, no server running (slice 13).    Offline,}/// What a caller hands `mint`.#[derive(Debug, Clone, PartialEq)]pub struct Act {    pub actor: Actor,    /// The verb that asked — `create_todo`, `revoke`, `import` — for history    /// and for a refusal's sentence. Never read by the fold.    pub verb: String,    pub history: History,    pub changes: Vec<Change>,}/// What `mint` did: the stamped ops, and the rows they changed.#[derive(Debug, Clone, PartialEq)]pub struct Minted {    /// The act's own ops, in order.    pub ops: Vec<CottonOp>,    pub applied_rows: Vec<(String, String)>,    /// The author this act minted first — when it was the file's first    /// write, or when `last_hlc` was poisoned and the file moved to a fresh    /// author (reason `redate`; see [`mint`]): its fact was folded and queued    /// ahead of `ops`.    pub minted_author: Option<Author>,    /// How the clock stood: Checked, Corrected (the line "This Mac's clock is    /// off by N" is the caller's to show) or Unchecked.    pub state: crate::judge::ClockState,    /// The act's receipts are held: minted Unchecked, applied here, not    /// travelling until the release pass.    pub held: bool,}struct MetaRow {    workspace_id: String,    /// The device's own id (`_meta.device_id`) — the credential an author    /// names, never the author itself.    device_id: String,    author: Option<String>,    last_hlc: Option<String>,}/// The author every write of this file is stamped with, or a refusal when/// none was minted yet.pub fn file_author(db: &Driver) -> Result<String> {    meta(db)?.author.ok_or_else(|| {        StoreError::refused(            "this file has no author yet — `mint::first_author` mints one when the device first holds the database",        )    })}fn meta(db: &Driver) -> Result<MetaRow> {    let row = db        .get("SELECT workspace_id, device_id, author_id, last_hlc FROM _meta", &[])?        .ok_or_else(|| StoreError::refused("file has no _meta row — create the workspace first"))?;    Ok(MetaRow {        workspace_id: row.text("workspace_id").unwrap_or_default().to_string(),        device_id: row.text("device_id").unwrap_or_default().to_string(),        author: row.text("author_id").filter(|a| !a.is_empty()).map(str::to_string),        last_hlc: row.text("last_hlc").map(str::to_string),    })}/// Why an author was minted — the `reason` column of its fact.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum AuthorReason {    /// The device first holds this database.    First,    /// Slice 12's take-over: a new serving Mac starts a fresh stream.    TakeOver,    /// Slice 1's release pass re-dated held receipts under a fresh author.    Redate,    /// The device signs its receipts and the file's author does not name its    /// key (keys slice KS1): a fresh author that does.    Keys,}impl AuthorReason {    pub fn as_str(self) -> &'static str {        match self {            AuthorReason::First => "first",            AuthorReason::TakeOver => "take-over",            AuthorReason::Redate => "redate",            AuthorReason::Keys => "keys",        }    }}/// An author this file minted: its id, the stamp its stream starts at, and/// the fact that announces it — the receipt a peer needs before it applies/// anything else of this author's.#[derive(Debug, Clone, PartialEq)]pub struct Author {    pub id: String,    pub first_stamp: String,    pub fact: CottonOp,}/// Mint this file's author and its fact, atomically.////// The author is `device:<ulid>`, the ulid from the caller's ids. Its first/// stamp is counter 0 at the first millisecond above everything this file has/// stamped — a new stream starts at 0 and never below the file's clock. The/// fact is minted under that author, at that stamp, as the first receipt of/// its stream; folded as [`Arrival::Local`] it is self-naming and waits for/// nothing (4.1 point 5). `device_credential_id` is the device's own id in/// `cotton_devices.device_id`; `device_name` is for a screen.////// `First` refuses a file that already has an author; `TakeOver` and `Redate`/// refuse one that has none, because they replace an author.pub fn first_author(    db: &Driver,    device_credential_id: &str,    device_name: Option<&str>,    reason: AuthorReason,    clock: &Clock,    ids: &mut dyn IdSource,    held: Held,) -> Result<Author> {    crate::device_scope::require_write(db, device_credential_id)?;    if let Some(signer) = db.signer() { crate::device_scope::require_write(db, &signer.device_key())?; }    if let Some(scope) = db.device_scope() { scope.require_write()?; }    db.transaction(|db| {        let stamping = clock::stamping(clock);        let _after_stamp = crate::spans::span("mint::fold_and_after");        let arrival = if stamping.held { Arrival::LocalHeld } else { Arrival::Local };        let author = coin_author(db, device_credential_id, device_name, reason, clock, ids, None)?;        let result = fold::arrive(db, std::slice::from_ref(&author.fact), arrival)?;        if let Some(rejection) = result.rejected.first() {            return Err(StoreError::refused(format!(                "the author fact was refused by the fold: {}",                rejection.reason            )));        }        if !result.applied.contains(&author.fact.op_id) {            return Err(StoreError::refused(                "the author fact did not apply — a self-naming fact never waits, so the fold is wrong",            ));        }        let minted_at = js::to_iso_string(clock::stamp_ms(clock))            .ok_or_else(|| StoreError::encode("timestamp out of range".to_string()))?;        db.run(            "UPDATE _meta SET last_hlc = ? WHERE last_hlc IS NULL OR last_hlc < ?",            &[                SqlValue::Text(author.first_stamp.clone()),                SqlValue::Text(author.first_stamp.clone()),            ],        )?;        if held == Held::Replica && !stamping.held {            queue_ops(db, std::slice::from_ref(&author.fact), &minted_at)?;        }        clock::record(db, std::slice::from_ref(&author.fact), clock, stamping.held)?;        if !stamping.held {            crate::cursors::advance_cursor(db, &author.id, &author.first_stamp, &minted_at)?;        }        Ok(author)    })}/// Mint the author and its fact, and set `_meta.author_id` — WITHOUT folding/// the fact. [`first_author`] folds it alone; [`mint`] folds it at the head of/// the act's own batch, because the fact names the workspace (a foreign key)/// and the file's first write may be the one that creates the workspace row./// Inside a transaction: an act that then fails rolls the author back too.////// A re-date's stream starts at judge time, or at `redate_from` when the/// caller says where: the release pass starts its author at the lowest stamp/// it re-dates to (`clock::release_held`).pub(crate) fn coin_author(    db: &Driver,    device_credential_id: &str,    device_name: Option<&str>,    reason: AuthorReason,    clock: &Clock,    ids: &mut dyn IdSource,    redate_from: Option<i64>,) -> Result<Author> {    if device_credential_id.is_empty() {        return Err(StoreError::refused(            "an author names the device credential it was minted for — none was given",        ));    }    // A handle that signs names the KEY it signs with, whatever the caller    // passed: the fact is what a verifier reads the key from (`signed`), so an    // author under any other id is one whose receipts nobody could check.    let signing_key = db.signer().map(|signer| signer.device_key());    let device_credential_id = signing_key.as_deref().unwrap_or(device_credential_id);    let current = meta(db)?;    match (reason, &current.author) {        (AuthorReason::First, Some(author)) => {            return Err(StoreError::refused(format!(                "this file already has the author {author} — a take-over or a re-date mints the next one"            )))        }        (AuthorReason::TakeOver | AuthorReason::Redate | AuthorReason::Keys, None) => {            return Err(StoreError::refused(format!(                "a {} replaces an author, and this file has none yet",                reason.as_str()            )))        }        _ => {}    }    let stamp_ms = clock::stamp_ms(clock);    let author = format!("device:{}", ids.next_op_id(stamp_ms)?);    let first_stamp = match (reason, clock.judge_ms()) {        // A RE-DATE starts its stream at judge time, whatever `last_hlc` says:        // the file is moving off a `last_hlc` it cannot trust.        (AuthorReason::Redate, Some(judge)) => next_hlc(&author, None, redate_from.unwrap_or(judge))?,        (AuthorReason::Redate, None) => {            return Err(StoreError::refused(                "a re-date starts its author at judge time, and this device has none yet",            ))        }        _ => crate::protocol::hlc::first_stamp_of(&author, current.last_hlc.as_deref(), stamp_ms)?,    };    let minted_at = js::to_iso_string(stamp_ms)        .ok_or_else(|| StoreError::encode(format!("timestamp out of range: {stamp_ms}")))?;    let mut patch = Map::new();    patch.insert("id".into(), JsonValue::String(author.clone()));    patch.insert(        "workspace_id".into(),        JsonValue::String(current.workspace_id.clone()),    );    patch.insert(        "device_id".into(),        JsonValue::String(device_credential_id.to_string()),    );    patch.insert(        "device_name".into(),        device_name.map_or(JsonValue::Null, |n| JsonValue::String(n.to_string())),    );    patch.insert("minted_at".into(), JsonValue::String(minted_at));    patch.insert(        "reason".into(),        JsonValue::String(reason.as_str().to_string()),    );    patch.insert("first_stamp".into(), JsonValue::String(first_stamp.clone()));    let fact = crate::signed::seal(        db,        &current.workspace_id,        crate::wire::from_receipt(            ids.next_op_id(stamp_ms)?,            &receipt_of(                db,                "first_author",                &Change::create(fold::AUTHORS_TABLE, &author, patch),                &first_stamp,                &author,                &Actor::device_job(JobName::named("mint-author")?).to_wire(),            )?,        )?,    )?;    // The file's author first, so every stamp from here on is this one's.    db.run(        "UPDATE _meta SET author_id = ?",        &[SqlValue::Text(author.clone())],    )?;    Ok(Author {        id: author,        first_stamp,        fact,    })}/// The receipt of one change (design 3.2, 3.7 point 1): each named column's/// value after its codec, a per-key column's keys as `column.key` fields, the/// kind, stamp, author, actor and schema version. Refuses an unknown column,/// a value its codec refuses, an integer an f64 cannot hold exactly, and a/// create that leaves out a column the table requires. On a table with/// revocation mirror columns a create's NULL mirror is dropped, because NULL/// is the default and a default never travels (3.7 point 3).pub(crate) fn receipt_of(    db: &Driver,    verb: &str,    change: &Change,    hlc: &str,    author: &str,    actor: &str,) -> Result<Receipt> {    let Some(spec) = crate::schema::package_shape::spec_on(db, &change.table)? else {        return Err(StoreError::refused(format!("`{verb}` names a table this file does not have: {}", change.table)));    };    let mut fields: BTreeMap<String, JsonValue> = BTreeMap::new();    if let Some(patch) = change.patch.as_ref().filter(|_| change.kind != Kind::Retract) {        for (column, value) in patch {            let Some(codec) = spec.columns.iter().find(|(c, _)| c == column).map(|(_, codec)| *codec) else {                return Err(StoreError::refused(format!("`{verb}` names a column {} does not have: {column}", change.table)));            };            if column == spec.pk {                if *value != JsonValue::String(change.row_id.clone()) {                    return Err(StoreError::refused(format!("`{verb}` names {column} = {value} on row {}", change.row_id)));                }                continue;            }            if change.kind == Kind::Create && value.is_null() && receipts::MIRROR_COLUMNS.contains(&column.as_str()) {                continue;            }            if receipts::is_per_key(&change.table, column) {                let JsonValue::Object(keys) = value else {                    return Err(StoreError::refused(format!("`{verb}`: {}.{column} is merged per key and takes an object", change.table)));                };                for (key, value) in keys {                    let after = canonical::canonical_value(value).map_err(|e| {                        StoreError::refused(format!("`{verb}`: {}.{column}.{key}: {e}", change.table))                    })?;                    fields.insert(format!("{column}.{key}"), after);                }                continue;            }            let after = canonical::after_codec(codec, value).map_err(|e| {                StoreError::refused(format!("`{verb}`: {}.{column}: {e}", change.table))            })?;            fields.insert(column.clone(), after);        }    }    if change.kind == Kind::Create {        for required in required_columns(db, &change.table)? {            let named = fields.get(&required).is_some_and(|v| !v.is_null())                || receipts::is_per_key(&change.table, &required);            if !named {                return Err(StoreError::refused(format!(                    "`{verb}` creates {} {} without `{required}`, which the table requires",                    change.table, change.row_id                )));            }        }    }    Ok(Receipt {        table: change.table.clone(),        row_id: change.row_id.clone(),        kind: change.kind,        stamp: hlc.to_string(),        author: author.to_string(),        actor: actor.to_string(),        schema: SCHEMA_VERSION,        fields,        restamps: None,        erase: if change.kind == Kind::Retract { change.delete.as_ref().and_then(Delete::erase_reason) } else { None },        undo: None,    })}/// The columns a create of this table must name: NOT NULL with no default,/// the primary key and the stamps aside.fn required_columns(db: &Driver, table: &str) -> Result<Vec<String>> {    db.batch_fact(&format!("required_columns {table}"), || read_required_columns(db, table))}fn read_required_columns(db: &Driver, table: &str) -> Result<Vec<String>> {    Ok(db        .all(&format!("PRAGMA table_info({table})"), &[])?        .iter()        .filter(|row| row.int("notnull") == Some(1) && row.int("pk") == Some(0) && row.get("dflt_value").is_none_or(|v| matches!(v, SqlValue::Null)))        .filter_map(|row| row.text("name").map(str::to_string))        .filter(|name| !name.starts_with('_'))        .collect())}/// What a served row is now ([`served`]).#[derive(Debug, Clone, PartialEq)]pub enum ServedRow {    /// The row's columns, each after its codec.    Live(BTreeMap<String, JsonValue>),    /// The writer deleted it: a [`Delete::Retract`], so a later create brings    /// it back.    Retracted,    /// The writer ERASED it, saying why (the object keeps the reason its    /// erase was sent with): a retract naming that `erase`, so the copy that    /// folds it ends the row for good as the device that erased it did.    Erased(String),}/// The receipt of a row a writer that keeps no receipts serves: the Worker's/// object serves rows, not receipts, and the copy that takes one folds it as/// a receipt of the object's author at the object's own stamp (`<ms>:/// <counter>:<author>`), naming `actor`. Minted here, once, by that copy, as/// `mint` mints its own: its bytes are made now and never again.////// `replaces` names the receipt of the same row at the same stamp the copy/// already holds, when this one says all of it and more (the same version/// pulled again by a copy that now keeps a column it lacked): one row keeps/// one receipt per stamp, and the fold's re-stamp rule drops that one for/// this.////// A live row is said as [`mint`] says a create: a revocation mirror it holds/// nothing in is not named (3.7 point 3) — a row the object never revoked is/// no un-revocation, and the fold's fence refuses any receipt naming a/// mirror null (27 Oct 2026: every code credential the object serves sat/// parked as one, and none reached the phone).pub fn served(op_id: String, table: &str, row_id: &str, stamp: &str, actor: &Actor, row: ServedRow, replaces: Option<&str>) -> Result<CottonOp> {    let author = fold::author_of(stamp).ok_or_else(|| StoreError::encode(format!("a served row's stamp names no author: {stamp}")))?;    let mut erase = None;    let (kind, fields) = match row {        ServedRow::Live(mut fields) => {            fields.retain(|column, value| !(value.is_null() && receipts::MIRROR_COLUMNS.contains(&column.as_str())));            (Kind::Create, fields)        }        ServedRow::Retracted => (Kind::Retract, BTreeMap::new()),        ServedRow::Erased(reason) => {            erase = Some(reason);            (Kind::Retract, BTreeMap::new())        }    };    let receipt = Receipt {        table: table.to_string(),        row_id: row_id.to_string(),        kind,        stamp: stamp.to_string(),        author: author.to_string(),        actor: actor.to_wire(),        schema: SCHEMA_VERSION,        fields,        restamps: replaces.map(str::to_string),        erase,        undo: None,    };    crate::wire::from_receipt(op_id, &receipt)}/// The receipt of a change a writer that keeps no receipts serves of a row/// this copy keeps for itself — the workspace's `owner_person_id`, which the/// object serves with the database's meta — stamped and named as [`served`]/// stamps a served row, and said as [`mint`] says a change: the columns/// `patch` names (storage-encoded, as a [`Change`]'s), with what the row/// holds past its receipts ([`with_what_the_row_holds`]). A row with no/// create kept (one written into the file before its receipts were) is/// minted as its create, so the fold never takes it, and every row under it,/// away for a bare change it cannot make live.pub fn served_change(    db: &Driver,    op_id: String,    table: &str,    row_id: &str,    stamp: &str,    actor: &Actor,    patch: Map<String, JsonValue>,) -> Result<CottonOp> {    let author = fold::author_of(stamp).ok_or_else(|| StoreError::encode(format!("a served change's stamp names no author: {stamp}")))?;    let change = Change { kind: Kind::Change, table: table.to_string(), row_id: row_id.to_string(), patch: Some(patch), delete: None };    let change = with_what_the_row_holds(db, &change)?;    let receipt = receipt_of(db, "served", &change, stamp, author, &actor.to_wire())?;    crate::wire::from_receipt(op_id, &receipt)}/// Make an act's changes in this file, atomically.////// Refuses: an empty act; a create or change with no patch; an actor this/// holder may not name ([`fold::actor_may_be_named_by`]); any rejection; any/// stale skip (a write minted a microsecond ago against rows this call just/// read cannot honestly lose, so losing means the clock is behind the file,/// and success would drop the write).pub fn mint(    db: &Driver,    act: &Act,    clock: &Clock,    ids: &mut dyn IdSource,    held: Held,) -> Result<Minted> {    mint_undo(db, act, clock, ids, held, None)}/// [`mint`] many rows as one batch ([`fold::as_one_batch`]): the act's/// receipts are the ones [`mint`] makes, row for row, with the file's shape/// read once for the batch.pub fn mint_batch(    db: &Driver,    act: &Act,    clock: &Clock,    ids: &mut dyn IdSource,    held: Held,) -> Result<Minted> {    fold::as_one_batch(db, || mint_undo(db, act, clock, ids, held, None))}/// [`mint`] an UNDO (slice 3b): `undo` is the id of the `cotton_undos` fact/// the act writes, and every other receipt of the act names it, so a device/// whose fact loses to a twin's parks the whole act/// ([`crate::fact_hooks::undo_refusal`]). `None` is a plain [`mint`].pub fn mint_undo(    db: &Driver,    act: &Act,    clock: &Clock,    ids: &mut dyn IdSource,    held: Held,    undo: Option<&str>,) -> Result<Minted> {    crate::device_scope::require_local_write(db, &act.actor)?;    if act.changes.is_empty() {        return Err(StoreError::refused(format!(            "`{}` asked for a write that changes nothing",            act.verb        )));    }    if let Err(reason) = fold::actor_may_be_named_by(held, &act.actor) {        return Err(StoreError::refused(format!("`{}`: {reason}", act.verb)));    }    for change in &act.changes {        if change.kind != Kind::Retract && change.patch.is_none() {            return Err(StoreError::refused(format!(                "`{}` names no column of {} {} — a create or a change says what it writes",                act.verb, change.table, change.row_id            )));        }    }    // Named for whoever holds the file (`crate::held::tally`): the verb and    // the actor, which is the job for a worker's write.    let who = format!("a write ({} by {})", act.verb, act.actor.to_wire());    crate::held::doing(&who);    // A JOB'S ACT AND AN ERASE ARE BOUNDED in what they ask of the file    // (`crate::held::ACT_STEPS`), and measured here, where every write is made.    let bounded = matches!(act.actor, crate::actor::Actor::Job(_))        || act.changes.iter().any(|change| change.delete.as_ref().and_then(Delete::erase_reason).is_some());    let (began, steps, facts) = (std::time::Instant::now(), db.steps(), act.changes.len());    let minted = mint_in_the_file(db, act, clock, ids, held, undo);    if bounded && minted.is_ok() {        crate::held::act_done(&who, facts, db.steps() - steps, began.elapsed());    }    minted}/// [`mint_undo`], once the act is known to be one a file can take.fn holding_now(db: &Driver, workspace: &str, author: Option<&str>, held: Held, actor: &Actor) -> Result<Held> {    if held != Held::Served || db.signer().is_none() || actor == &Actor::Takeover {        return Ok(held);    }    if crate::serving::served_elsewhere(db, workspace,        db.signer().map(|signer| signer.device_key()).as_deref())?.is_none() {        return Ok(held);    }    if let Some(author) = author {        if crate::serving::is_serving_author(db, author)? {            return Err(StoreError::refused("not_served_here: this device no longer serves the database"));        }    }    if let Err(reason) = fold::actor_may_be_named_by(Held::Replica, actor) {        return Err(StoreError::refused(format!("not_served_here: {reason}")));    }    Ok(Held::Replica)}fn mint_in_the_file(    db: &Driver,    act: &Act,    clock: &Clock,    ids: &mut dyn IdSource,    held: Held,    undo: Option<&str>,) -> Result<Minted> {    // Receipts kept for the fold ([`fold::keep_minted`]) go when this act    // ends, however it ends.    let _kept = fold::KeptReceipts;    db.transaction(|db| {        // RULE: a store write takes its stamp only after its committing        // transaction opens, so a lock wait cannot make a synced receipt sort        // before the write it describes (architect, 18 Oct 2026).        let stamping = clock::stamping(clock);        let current = meta(db)?;        let own_database = current.workspace_id.clone();        // A caller may have opened this handle while it still served. Read        // the authority inside the write transaction: a phone's edit after        // its grant must queue, and an old server worker must stop.        let held = holding_now(db, &own_database, current.author.as_deref(), held, &act.actor)?;        // AN ERASE WRITES ITS MEDIA ERASURES (slice 7): one fact per key the        // erased record and its owned descendants name, after the erase in        // this same act, read before the fold takes the rows out.        let expanded = crate::media_erasure::with_erasure_facts(db, act, &own_database, stamping.ms)?;        let act = expanded.as_ref().unwrap_or(act);        let mut ops: Vec<CottonOp> = Vec::with_capacity(act.changes.len() + 1);        let mut minted_author = None;        let (mut author, mut last_hlc) = match current.author {            Some(author) => (author, current.last_hlc),            // THE FIRST HOLDING. A file with no author is one no device has            // written into yet; the device writing now is the one that first            // holds it, so its author is minted here, and the fact is the first            // receipt of the stream — folded at the HEAD of this act's batch,            // not alone before it: the fact names the workspace, and the file's            // first write may be the one that creates the workspace row (the            // fold retries a foreign-key failure once the batch has applied).            None => {                if current.device_id.is_empty() {                    return Err(StoreError::refused(format!(                        "`{}`: this file names no device in _meta, so nobody can be its author",                        act.verb                    )));                }                let coined = coin_author(                    db,                    &current.device_id,                    None,                    AuthorReason::First,                    clock,                    ids,                    None,                )?;                ops.push(coined.fact.clone());                let first_stamp = coined.first_stamp.clone();                minted_author = Some(coined);                (                    minted_author.as_ref().map(|a| a.id.clone()).unwrap_or_default(),                    Some(first_stamp),                )            }        };        let stamp_ms = stamping.ms;        // POISONED: the next stamp would land beyond judge time + the bound.        // The file moves to a fresh author whose stream starts at judge time,        // and `last_hlc` drops to what it can trust — never minting ahead.        if !stamping.held && minted_author.is_none() {            let next = next_hlc(&author, last_hlc.as_deref(), stamp_ms)?;            if clock::poisoned(clock, &next)? {                let judge = clock.judge_ms().unwrap_or(stamp_ms);                let coined = coin_author(                    db,                    &current.device_id,                    None,                    AuthorReason::Redate,                    clock,                    ids,                    None,                )?;                let trusted = clock::last_hlc_after_redate(db, &coined.first_stamp, judge)?;                db.run("UPDATE _meta SET last_hlc = ?", &[SqlValue::Text(trusted.clone())])?;                ops.push(coined.fact.clone());                author = coined.id.clone();                last_hlc = Some(trusted);                minted_author = Some(coined);            }        }        // THE AUTHOR NAMES THE KEY THAT SIGNS. A file whose author was coined        // before this handle had a device key (or under another's) moves to a        // fresh author that names it, once; from then on every receipt this        // handle mints verifies against its own author's fact.        if minted_author.is_none() {            if let Some(key) = db.signer().map(|signer| signer.device_key()) {                if crate::fact_hooks::author_device(db, &author)?.as_deref() != Some(key.as_str()) {                    let coined = coin_author(db, &key, None, AuthorReason::Keys, clock, ids, None)?;                    ops.push(coined.fact.clone());                    author = coined.id.clone();                    last_hlc = Some(coined.first_stamp.clone());                    minted_author = Some(coined);                }            }        }        // NOTHING BUT `revocation::revoke` WRITES A MIRROR (slice 5b-i), read        // against the rows as they stand before this act.        crate::revocation::refuse_mirror_write(db, act)?;        let actor = act.actor.to_wire();        // HISTORY (slice 6): the records this act keeps history for, read as        // they stand before it; their rows are minted after it folds.        let history_span = crate::spans::span("mint::history_before");        let history_before = history::before(db, act)?;        drop(history_span);        // FOLDED FORWARD, NEVER REFUSED (architect, 11 Oct 2026): a write is        // made after the rows it writes, so it is stamped after them. This        // device's clock can be behind a row it already holds — its judge time        // lagging the serving Mac's while a copy catches up, and the fold        // adopting no stamp past judge time + the bound — and a write stamped        // below that row lost on every field: "That wasn't kept. Try again."        // for an approval the owner tapped on phone 242, nothing queued, and,        // where only some fields lost, a write that said Ok and was dropped on        // the Mac. Its stamp now starts past the newest clock any row it        // writes holds — a clock the serving Mac already took, so the Mac        // takes this one too — and it queues like any other change. The next        // mint finds `last_hlc` there; past judge time + the bound that is the        // poison move to a fresh author, so no author's stream goes backwards.        let newest_span = crate::spans::span("mint::newest_clock_of");        let newest_floor = newest_clock_of(db, &act.changes)?;        drop(newest_span);        if let Some(floor) = newest_floor {            if next_hlc(&author, last_hlc.as_deref(), stamp_ms)? <= floor {                last_hlc = Some(floor);            }        }        let mut stamp = |changes: &[Change], ops: &mut Vec<CottonOp>| -> Result<()> {            for change in changes {                let checks = crate::spans::span("mint::row_checks");                let change = &history::with_actor(change, &actor);                refuse_identity_change(db, &act.verb, change)?;                let change = &without_restated_identity(db, change)?;                if change.kind == Kind::Change {                    let named = change.patch.iter().flat_map(|patch| patch.keys());                    if let Some(reason) = fold::identity_change_refusal(&change.table, &change.row_id, named) {                        return Err(StoreError::refused(format!("`{}`: {reason}", act.verb)));                    }                    if let Some(sentence) = fold::insert_only_refusal(&change.table) {                        return Err(StoreError::refused(format!(                            "`{}`: {sentence} — {} {} is not changed",                            act.verb, change.table, change.row_id                        )));                    }                }                let change = &with_what_the_row_holds(db, change)?;                let change = &own_database_as_none(change, &own_database);                kinds::check(db, act, change)?;                drop(checks);                let _receipt = crate::spans::span("mint::receipt_and_seal");                let hlc = next_hlc(&author, last_hlc.as_deref(), stamp_ms)?;                last_hlc = Some(hlc.clone());                let of = crate::spans::span("mint::receipt_of");                let mut receipt = receipt_of(db, &act.verb, change, &hlc, &author, &actor)?;                drop(of);                if change.table != crate::fact_hooks::UNDOS_TABLE {                    receipt.undo = undo.map(str::to_string);                }                // ONE canonical encode: the stored bytes and the signature                // are the same bytes, and in a batch the fold takes this                // struct beside them instead of decoding them again.                let op = crate::signed::seal(                    db,                    &own_database,                    crate::wire::from_receipt(ids.next_op_id(stamp_ms)?, &receipt)?,                )?;                fold::keep_minted(db, &op, receipt);                ops.push(op);            }            Ok(())        };        stamp(&act.changes, &mut ops)?;        let arrival = if stamping.held { Arrival::LocalHeld } else { Arrival::Local };        let result = fold::arrive(db, &ops, arrival)?;        if let Some(rejection) = result.rejected.first() {            return Err(StoreError::refused(format!(                "`{}` was refused by the fold: {}",                act.verb, rejection.reason            )));        }        if !result.skipped_stale.is_empty() {            return Err(StoreError::refused(format!(                "`{}` was folded as stale ({} op(s)) — the write clock is behind the rows it is writing",                act.verb,                result.skipped_stale.len()            )));        }        // A CREATE UNDER A PARENT THAT IS NOT PRESENT IS REFUSED HERE (3.7        // point 8): a peer's would arrive dormant, but a write made now under        // a parent this file does not show is a mistake to say, not a row to        // hide. A change that moves a row under one is refused the same way.        // A row this same act takes out by retracting its ancestor is not.        let retracted: BTreeSet<(String, String)> = act            .changes            .iter()            .filter(|change| change.kind == Kind::Retract)            .map(|change| (change.table.clone(), change.row_id.clone()))            .collect();        for change in act.changes.iter().filter(|change| change.kind != Kind::Retract) {            if let Some(parent) = fold::held_out_by_parent(db, &change.table, &change.row_id, &retracted)? {                return Err(StoreError::refused(format!(                    "`{}` {} {} {} under {parent}, which is not present",                    act.verb,                    if change.kind == Kind::Create { "creates" } else { "writes" },                    change.table,                    change.row_id                )));            }        }        let at = js::to_iso_string(stamp_ms)            .ok_or_else(|| StoreError::encode(format!("timestamp out of range: {stamp_ms}")))?;        if let Some(before) = history_before {            let rows = history::rows(db, act, before, &ops, &own_database, &at)?;            if !rows.is_empty() {                let from = ops.len();                stamp(&rows, &mut ops)?;                let result = fold::arrive(db, &ops[from..], arrival)?;                if let Some(rejection) = result.rejected.first() {                    return Err(StoreError::refused(format!(                        "`{}`'s history was refused by the fold: {}",                        act.verb, rejection.reason                    )));                }            }        }        // The fold moved `_meta.last_hlc` forward from what applied; written        // through here as well so a restarted process continues the chain        // even when a change applied as a no-op column set.        if let Some(newest) = ops.last() {            db.run(                "UPDATE _meta SET last_hlc = ? WHERE last_hlc IS NULL OR last_hlc < ?",                &[                    SqlValue::Text(newest.hlc.clone()),                    SqlValue::Text(newest.hlc.clone()),                ],            )?;        }        if held == Held::Replica {            // A replica's write has to be handed to the serving Mac — unless            // it is HELD, which never travels until the release pass; and a            // row moving locally is the event a parked push was waiting for.            // A local observation may be this file's first write. Its new            // author fact is kept here too; browsing alone must not queue            // infrastructure on behalf of an act with nothing to send.            // The receipt stream supplies that fact when a peer needs it.            if !stamping.held && act.changes.iter().any(|change| {                crate::schema::table_specs::is_handed_over(&change.table)            }) {                queue_ops(db, &ops, &at)?;            }            crate::rejected::requeue_touched_pushes(db, &result.applied_rows, &at)?;        }        clock::record(db, &ops, clock, stamping.held)?;        // A peer's write this file refused is waiting on the row; a local        // write IS the row moving.        crate::rejected::retry_touched_rows(db, &result.applied_rows, &Default::default(), &at)?;        // A fact this file mints for itself announces its author, or the        // serving authors a serving fact makes (`fact_hooks::announced`): a        // receipt parked waiting for it is offered again, as when a peer's        // fact arrives (`exchange::fold_incoming`). Without it a re-keyed        // Mac's own serving fact left those receipts waiting, and the phone        // that sent them handed them over again every pass (syncpage5 row 3).        for announced in &result.announced {            crate::rejected::retry_waiting_for(db, announced, &at)?;        }        // THIS FILE HAS SEEN ITS OWN WRITES: without the cursor a peer would        // hand every one of them straight back on the next exchange. A held        // write never reached a peer, so there is nothing to hand back.        if let Some(newest) = ops.last().filter(|_| !stamping.held) {            crate::cursors::advance_cursor(db, &author, &newest.hlc, &at)?;        }        if minted_author.is_some() {            if !result.applied.contains(&ops[0].op_id) {                return Err(StoreError::refused(format!(                    "`{}`: the file's author fact did not apply — a self-naming fact never waits, so the fold is wrong",                    act.verb                )));            }            ops.remove(0);        }        Ok(Minted {            ops,            applied_rows: result.applied_rows,            minted_author,            state: stamping.state,            held: stamping.held,        })    })}/// The newest clock any row `changes` writes already holds here — its kept/// receipts and its retract — or `None` when none of them holds one.fn newest_clock_of(db: &Driver, changes: &[Change]) -> Result<Option<String>> {    let mut newest: Option<String> = None;    for change in changes {        let row = db.get(            "SELECT MAX(hlc) AS hlc FROM (SELECT hlc FROM _writes WHERE tbl = ?1 AND row_id = ?2 \             UNION ALL SELECT hlc FROM _tombstones WHERE tbl = ?1 AND row_id = ?2)",            &[SqlValue::Text(change.table.clone()), SqlValue::Text(change.row_id.clone())],        )?;        if let Some(hlc) = row.as_ref().and_then(|row| row.text("hlc")) {            if newest.as_deref().is_none_or(|top| hlc > top) {                newest = Some(hlc.to_string());            }        }    }    Ok(newest)}/// A change of a row the table holds past its receipts says what the row/// holds ([`fold::unreceipted`]): the columns its receipts would not write/// back join the patch (the change's own columns win), and a row with no/// create kept is minted as its create. So a write moves only what it names,/// and a row a schema move carried is never lost to the fold.fn with_what_the_row_holds(db: &Driver, change: &Change) -> Result<Change> {    let mut change = change.clone();    if change.kind != Kind::Change {        return Ok(change);    }    let Some((live, held)) = fold::unreceipted(db, &change.table, &change.row_id)? else {        return Ok(change);    };    let patch = change.patch.get_or_insert_with(Map::new);    for (column, value) in held {        patch.entry(column).or_insert(value);    }    if !live {        change.kind = Kind::Create;    }    Ok(change)}/// The columns of a database's own `cotton_workspaces` row that are fixed/// when the row is made (several databases 3.1): what the database is, the id/// its derived record ids take, and whose it is. A change to any of them would/// silently re-home every derived id or every token's reach, so there is no/// exception — not from empty, not for the owner.pub const WORKSPACE_IDENTITY_COLUMNS: [&str; 3] = ["kind", "namespace", "owner_user_id"];/// Refuse a write that changes [`WORKSPACE_IDENTITY_COLUMNS`] on a workspace/// row that already exists. Naming the value already there is not a change./// `change` less every identity column ([`fold::IDENTITY_WRITE_ONCE`]) it/// restates at the value the row already holds — a writer that stamps/// `workspace_id` onto every patch says nothing new, and a change receipt/// naming an identity column is refused on every device. A value that/// differs is left for the refusal to name.fn without_restated_identity(db: &Driver, change: &Change) -> Result<Change> {    let mut change = change.clone();    if change.kind != Kind::Change {        return Ok(change);    }    let Some((_, identity)) = fold::IDENTITY_WRITE_ONCE.iter().find(|(table, _)| *table == change.table) else {        return Ok(change);    };    let Some(patch) = change.patch.as_mut() else {        return Ok(change);    };    let named: Vec<&str> = identity.iter().copied().filter(|column| patch.contains_key(*column)).collect();    if named.is_empty() {        return Ok(change);    }    let Some(row) = db.get(        &format!("SELECT {} FROM {} WHERE id = ?", named.join(", "), change.table),        &[SqlValue::Text(change.row_id.clone())],    )?    else {        return Ok(change);    };    for column in named {        let held = row.text(column);        let restated = match patch.get(column) {            Some(JsonValue::Null) => held.is_none(),            Some(JsonValue::String(value)) => held == Some(value.as_str()),            _ => false,        };        if restated {            patch.remove(column);        }    }    Ok(change)}fn refuse_identity_change(db: &Driver, verb: &str, change: &Change) -> Result<()> {    if change.table != "cotton_workspaces" || change.kind == Kind::Retract {        return Ok(());    }    let Some(patch) = change.patch.as_ref() else {        return Ok(());    };    let Some(row) = db.get(        "SELECT kind, namespace, owner_user_id FROM cotton_workspaces WHERE id = ?",        &[SqlValue::Text(change.row_id.clone())],    )?    else {        return Ok(());    };    for column in WORKSPACE_IDENTITY_COLUMNS {        let Some(value) = patch.get(column) else { continue };        let held = row.text(column);        if value.as_str() != held || (value.is_null() != held.is_none()) {            return Err(StoreError::refused(format!(                "`{verb}` changes cotton_workspaces.{column} of {}, which never changes after the \                 database's row is made",                change.row_id            )));        }    }    Ok(())}/// A link naming this database as `to_database` is stored as one naming none,/// so the two spellings are one row with one id ([`link_id_for`]).////// [`link_id_for`]: crate::protocol::derived_id::link_id_forfn own_database_as_none(change: &Change, own_database: &str) -> Change {    let mut change = change.clone();    if change.table == "cotton_links" {        if let Some(to_database) = change.patch.as_mut().and_then(|patch| patch.get_mut("to_database")) {            if to_database.as_str() == Some(own_database) {                *to_database = JsonValue::Null;            }        }    }    change}