Cotton code
566 lines · 23.3 KB · RustRaw
//! Changes are answered FROM THE RECEIPTS — one author's stream, on demand.//!//! There is no log to tail. Every write a file holds is a receipt in//! `_writes` (or, for a retract, in `_tombstones`), stamped and signed by its//! author, and "everything author A wrote after stamp H" is one index search//! (`idx_writes_author`). The answer cannot fall behind the file, because it//! IS the file: a row travels as its live receipts, byte for byte (design 3.1//! rule 7), each under the op id it was minted with.//!//! A HELD receipt (3.8) never travels: the partial index leaves it out, and so//! does this stream, the outbox and the position reported in `seen`.//!//! **A page is a whole number of receipts, and of stamps.** Each receipt is//! its own op, the cursor advances by stamp, and a stamp bigger than the page//! is sent whole (`page_cut`). A row need not travel whole any more: a change//! that reaches a peer before its create is dormant there, and shows when the//! create lands (3.7 point 6).use rusqlite::types::Value as SqlValue;use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::protocol::types::CottonOp;use crate::schema::table_specs::handed_over_specs;/// The wire name once given to the author of a row nobody stamped. No row is/// written without a receipt on the fresh line, so no stream answers under/// it; the fold still refuses to wait on it.pub const ORIGIN_AUTHOR: &str = "origin";/// One page of an author's stream.#[derive(Debug, Clone, PartialEq)]pub struct ChangesPage {    /// In stamp order.    pub ops: Vec<CottonOp>,    /// What to ask for next — the last receipt's stamp, or `None` when the    /// page is empty.    pub next_hlc: Option<String>,    /// Whether asking again from `next_hlc` would answer anything.    pub has_more: bool,    /// How many ROWS this page touched — what the exchange spends its budget    /// in. Several receipts of one row count once.    pub rows: usize,}/// The tables a reader is sent LAST (owner's ask, 11 Oct 2026): mail.////// A backfill of a mailbox is tens of thousands of receipts under the serving/// Mac's own author, the same stream as its todos and notes, so a todo written/// after the backfill used to queue behind the whole of it. Each author's/// stream is therefore read in two LANES: everything else first, these after,/// each with its own cursor ([`late_cursor_key`]), so a device is level on/// everything but mail within its first pages. The three are one lane because/// an email names its thread (a foreign key) and a participant its thread.pub const LATE_TABLES: [&str; 3] = [    "cotton_email_participants",    "cotton_email_threads",    "cotton_emails",];/// Which part of an author's stream a page reads.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Lane {    /// Every table but [`LATE_TABLES`].    First,    /// [`LATE_TABLES`] alone.    Late,}impl Lane {    fn clause(self) -> String {        let names: Vec<String> = LATE_TABLES.iter().map(|name| format!("'{name}'")).collect();        match self {            Lane::First => format!(" AND tbl NOT IN ({})", names.join(", ")),            Lane::Late => format!(" AND tbl IN ({})", names.join(", ")),        }    }}/// The cursor-map key of an author's LATE lane. `@`-prefixed: no author id/// starts with `@`, so it/// cannot collide with one, and a reader that walks AUTHORS walks the file's/// ceiling and never meets it. The author's own key is its first lane.pub fn late_cursor_key(author: &str) -> String {    format!("@late:{author}")}/// Between a stamp and the place inside it where a page stopped/// ([`inside_stamp`]): a control character no stamp, table name or row id/// carries.const INSIDE: char = '\u{1f}';/// A cursor that stops INSIDE one stamp, after the receipt of `(table,/// row_id)` — what a page answers when one act's receipts alone outgrow it/// (13 Oct 2026: one act of 1,984 receipts, 25.7 MB, went out as one page and/// the phone could not fold it inside its pass). It sorts after the stamp and/// before every later one, so a reader that only compares cursors as strings/// still orders it right; only [`is_behind`] and the stream read inside it.pub fn inside_stamp(stamp: &str, table: &str, row_id: &str) -> String {    format!("{stamp}{INSIDE}{table}{INSIDE}{row_id}")}/// A cursor as its stamp and, when it stops inside that stamp, the `(table,/// row_id)` it stopped after.pub fn split_cursor(cursor: &str) -> (&str, Option<(&str, &str)>) {    match cursor.split_once(INSIDE) {        Some((stamp, rest)) => match rest.split_once(INSIDE) {            Some((table, row)) => (stamp, Some((table, row))),            None => (cursor, None),        },        None => (cursor, None),    }}/// Is a reader at `since` behind an author whose newest receipt is `top`?/// A cursor inside `top`'s own stamp is: the rest of that act is owed.pub fn is_behind(top: &str, since: &str) -> bool {    match split_cursor(since) {        (stamp, Some(_)) => top >= stamp,        (stamp, None) => top > stamp,    }}/// One author's writes after `since_hlc`, at most `limit_rows` rows' worth.////// `author` is an author id (`device:<ulid>`). `since_hlc` is that author's/// cursor, `""` for "everything this author ever wrote".pub fn changes_since(    db: &Driver,    author: &str,    since_hlc: &str,    limit_rows: usize,) -> Result<ChangesPage> {    changes_since_in(db, author, since_hlc, limit_rows, None)}/// [`changes_since`], kept to one [`Lane`] of the stream (`None`: all of it).pub fn changes_since_in(    db: &Driver,    author: &str,    since_hlc: &str,    limit_rows: usize,    lane: Option<Lane>,) -> Result<ChangesPage> {    let take = limit_rows.max(1);    // One more than the page, so the merge knows whether there IS a next page    // without asking a second time.    let lookahead = (take + 1) as i64;    let mut entries = stamped_entries(db, author, since_hlc, None, lookahead, lane)?;    sort_entries(&mut entries);    let (entries, has_more) = match page_cut(&entries, take) {        Some(cut) => {            let has_more = entries.len() > cut;            entries.truncate(cut);            (entries, has_more)        }        None => {            // THE FIRST STAMP ALONE OUTGROWS THE PAGE: it is cut inside, in            // (table, row) order, and the cursor says where (`inside_stamp`).            // A page is bounded whatever one act wrote.            let shared = entries[0].key.clone();            let mut group = stamped_entries(db, author, since_hlc, Some(&shared), lookahead, lane)?;            sort_entries(&mut group);            // A ROW NEVER STRADDLES A PAGE: a write and a retract of one row            // in one stamp go together.            let mut cut = take.min(group.len());            while cut < group.len()                && (&group[cut].op.table, &group[cut].op.row_id) == (&group[cut - 1].op.table, &group[cut - 1].op.row_id)            {                cut += 1;            }            group.truncate(cut);            let last = group.last().expect("the stamp has receipts");            let inside = inside_stamp(&shared, &last.op.table, &last.op.row_id);            let has_more = !stamped_entries(db, author, &inside, None, 1, lane)?.is_empty();            let ops = group.into_iter().map(|entry| entry.op).collect::<Vec<_>>();            let rows = ops.len();            return Ok(ChangesPage {                ops,                next_hlc: Some(if has_more { inside } else { shared }),                has_more,                rows,            });        }    };    let next_hlc = entries.last().map(|entry| entry.key.clone());    let rows = {        let mut seen: std::collections::BTreeSet<(&str, &str)> = std::collections::BTreeSet::new();        for entry in &entries {            seen.insert((entry.op.table.as_str(), entry.op.row_id.as_str()));        }        seen.len()    };    Ok(ChangesPage {        ops: entries.into_iter().map(|entry| entry.op).collect(),        next_hlc,        has_more,        rows,    })}/// The SQL that keeps a `_writes` or `_tombstones` row to a table THIS BUILD/// HAS AND HANDS OVER: `tbl IN ('cotton_todos', …)`, every name of/// [`handed_over_specs`]. A receipt for a table this build cannot name is/// nothing this build can hand over, so the stream and the ceiling/// ([`crate::cursors::cursor_ceiling`]) read the side tables through the same/// clause. The names are compile-time constants, which is why they are/// inlined rather than bound — and so is every package table this FILE holds/// (`package_shape::held_tables`): a tool's own table is handed over like a/// compiled one, its name an identifier the definition's validation checked.pub(crate) fn known_tables_clause(db: &Driver) -> Result<String> {    let names: Vec<String> = handed_over_specs()        .map(|spec| format!("'{}'", spec.name))        .chain(            crate::schema::package_shape::held_tables(db)?                .into_iter()                .filter(|name| name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'))                .map(|name| format!("'{name}'")),        )        .collect();    Ok(format!("tbl IN ({})", names.join(", ")))}/// One receipt waiting to go out, at the cursor value it sits at.#[derive(Debug)]struct Entry {    key: String,    op: CottonOp,}/// Stamp order, then `(table, row id)` — one order for every merge of streams.fn sort_entries(entries: &mut [Entry]) {    entries.sort_by(|left, right| {        left.key            .cmp(&right.key)            .then_with(|| left.op.table.cmp(&right.op.table))            .then_with(|| left.op.row_id.cmp(&right.op.row_id))    });}/// Where the page ends: at most `take` entries, never inside a stamp — or/// `None` when the FIRST stamp alone has more entries than `take`.fn page_cut(entries: &[Entry], take: usize) -> Option<usize> {    let cut = take.min(entries.len());    if entries.len() <= cut || cut == 0 {        return Some(cut);    }    let boundary = &entries[cut].key;    let mut trimmed = cut;    while trimmed > 0 && &entries[trimmed - 1].key == boundary {        trimmed -= 1;    }    (trimmed > 0).then_some(trimmed)}/// An author's two streams: its receipts in `_writes` (never a held one) and/// its retracts in `_tombstones`. Everything after `since`, up to and/// including `until` when it is given, at most `limit` entries per place/// (`-1`: no limit, SQLite's own spelling).fn stamped_entries(    db: &Driver,    author: &str,    since: &str,    until: Option<&str>,    limit: i64,    lane: Option<Lane>,) -> Result<Vec<Entry>> {    // A cursor INSIDE a stamp: the rest of that stamp in (table, row) order —    // a small read of one act — then the stream past the stamp as usual.    let (stamp, inside) = split_cursor(since);    let mut out = Vec::new();    if let Some((table, row)) = inside {        out = read_entries(            db,            author,            "hlc = ? AND (tbl > ? OR (tbl = ? AND row_id > ?))",            vec![                SqlValue::Text(stamp.to_string()),                SqlValue::Text(table.to_string()),                SqlValue::Text(table.to_string()),                SqlValue::Text(row.to_string()),            ],            "hlc, tbl, row_id",            limit,            lane,        )?;        if until.is_some_and(|until| until <= stamp) {            return Ok(out);        }    }    let mut params = vec![SqlValue::Text(stamp.to_string())];    let after = match until {        Some(until) => {            params.push(SqlValue::Text(until.to_string()));            "hlc > ? AND hlc <= ?"        }        None => "hlc > ?",    };    // One stamp's group (`until`) is read in its page order; the open stream    // by the index alone, because a tie-break would sort every row past the    // cursor on every page.    let order = if until.is_some() { "hlc, tbl, row_id" } else { "hlc" };    out.extend(read_entries(db, author, after, params, order, limit, lane)?);    Ok(out)}/// One author's receipts in `_writes` and `_tombstones` that meet `after`,/// at most `limit` from each place (`-1`: no limit, SQLite's own spelling).fn read_entries(    db: &Driver,    author: &str,    after: &str,    after_params: Vec<SqlValue>,    order: &str,    limit: i64,    lane: Option<Lane>,) -> Result<Vec<Entry>> {    let lane = lane.map(Lane::clause).unwrap_or_default();    let mut params = vec![SqlValue::Text(author.to_string())];    params.extend(after_params);    params.push(SqlValue::Integer(limit));    let known = known_tables_clause(db)?;    let mut out = Vec::new();    for table in ["_writes", "_tombstones"] {        // Retracts carry the same author in their stamp. Their existing        // index names that expression, not the separately stored column;        // naming `author` here scanned every delete for every page.        let author_is = if table == "_tombstones" { "substr(hlc, 20)" } else { "author" };        // A held receipt — a write or a delete — never travels (3.8).        let rows = db.all(            &format!(                "SELECT op_id, hlc, bytes, sig FROM {table} WHERE {author_is} = ? AND {after} AND held = 0 AND {known}{lane} \                 ORDER BY {order} LIMIT ?"            ),            &params,        )?;        for row in &rows {            let op = crate::stored::receipt_row(row).map_err(StoreError::encode)?;            out.push(Entry {                key: row.text("hlc").unwrap_or_default().to_string(),                op,            });        }    }    Ok(out)}/// How many receipts this file holds past a reader's `cursors`, counted up to/// `cap` and no further.////// INDEX-ONLY: per author one `LIMIT`ed walk of `idx_writes_author (author,/// hlc) WHERE held = 0`, plus the author's tombstones by/// `idx_tombstones_author (substr(hlc, 20), hlc)` — the stamp's own author,/// because `_tombstones` has no index on its `author` column and a count by it/// scans the table — and no `tbl` predicate (which the index does not carry)./// It counts RECEIPTS — "changes" — not rows, and a table a reader's build/// does not know is counted too.////// INDEX-ONLY IS STILL ONE STEP PER RECEIPT: on the owner's file a fresh phone/// owes some 1.7 million, and a full count read 12.3 million steps, 6.5 s/// (12 Oct 2026 01:48Z, inside the write hold, on every page). So `cap` is/// where the walking stops: an exchange answer and the catch-up wake give/// `BEHIND_BY_CAP`; the one exact count of a catch-up (what it owed at its/// start) is taken outside the hold, on a read connection.pub fn receipts_past(    db: &Driver,    cursors: &std::collections::BTreeMap<String, String>,    cap: u64,) -> Result<u64> {    crate::held::doing("counting what a reader is behind by");    let mut total: u64 = 0;    for (author, top) in crate::cursors::seen_ceiling(db)? {        // LANE BY LANE, as [`receipts_owed`] counts (13 Oct 2026: counted        // from the LOWER lane, a phone level on everything but mail was        // re-counted for every first-lane receipt it already held and read        // 10,000 while it owed 503, so its catch-up never ended): everything        // past the HIGHER lane, index-only, and the lagging lane's own        // receipts between the two.        let (first, late) = lanes_of(cursors, &author);        let (first, late) = (split_cursor(first).0, split_cursor(late).0);        let (low, high, lagging) = if late < first {            (late, first, Lane::Late)        } else {            (first, late, Lane::First)        };        if !is_behind(&top, low) {            continue;        }        for (table, author_is) in [("_writes", "author"), ("_tombstones", "substr(hlc, 20)")] {            let left = cap.saturating_sub(total);            if left == 0 {                return Ok(cap);            }            let limit = SqlValue::Integer(i64::try_from(left).unwrap_or(i64::MAX));            let past = db.get(                &format!(                    "SELECT COUNT(*) AS n FROM (SELECT 1 FROM {table} WHERE {author_is} = ? AND hlc > ? \                     AND held = 0 LIMIT ?)"                ),                &[SqlValue::Text(author.clone()), SqlValue::Text(high.to_string()), limit],            )?;            total = total.saturating_add(count_of(past));            // The lagging lane's window reads each receipt's table, so its            // walk is bounded too: at most WINDOW_WALK receipts of the            // window, inside the hold. What lies beyond is still owed, and            // the answer says so by `has_more`.            if low < high && total < cap {                let window = db.get(                    &format!(                        "SELECT COUNT(*) AS n FROM (SELECT tbl FROM {table} WHERE {author_is} = ? AND hlc > ? \                         AND hlc <= ? AND held = 0 ORDER BY hlc LIMIT ?) WHERE 1 = 1{}",                        lagging.clause()                    ),                    &[                        SqlValue::Text(author.clone()),                        SqlValue::Text(low.to_string()),                        SqlValue::Text(high.to_string()),                        SqlValue::Integer(WINDOW_WALK),                    ],                )?;                total = total.saturating_add(count_of(window));            }        }    }    Ok(total.min(cap))}/// How many receipts of a lagging lane's window [`receipts_past`] reads inside/// the write hold, per author and place.const WINDOW_WALK: i64 = 20_000;fn count_of(row: Option<crate::driver::Row>) -> u64 {    row.and_then(|row| row.int("n")).and_then(|n| u64::try_from(n).ok()).unwrap_or(0)}/// Where a reader stands on one author, lane by lane: its first lane's/// cursor, and its mail lane's — the first lane's until the exchange wrote/// the mail lane down on its own, as the exchange itself reads it.fn lanes_of<'c>(    cursors: &'c std::collections::BTreeMap<String, String>,    author: &str,) -> (&'c str, &'c str) {    let first = cursors.get(author).map(String::as_str).unwrap_or("");    let late = cursors.get(&late_cursor_key(author)).map_or(first, String::as_str);    (first, late)}/// What a reader at `cursors` is OWED, exactly: each author's first lane/// past the first lane's cursor and its mail past the mail lane's — the/// receipts the exchange will still deal it, and no receipt it holds.////// [`receipts_past`] counts every table from the LOWER of the two lanes/// (index-only, so it can be asked inside the write hold): a reader level on/// everything but mail is counted again for every first-lane receipt it/// already holds since its mail lane's point. On 13 Oct 2026 that read the/// serving Mac's own client as owing 462,238 changes where it owed 329,154./// This count is the whole a catch-up's percent is a share of, asked once,/// outside the hold: index-only past the HIGHER of the two lanes, and only/// the window between them reads its receipts' rows, for their table.pub fn receipts_owed(    db: &Driver,    cursors: &std::collections::BTreeMap<String, String>,) -> Result<u64> {    crate::held::doing("counting what a reader owes");    let mut total: u64 = 0;    for (author, top) in crate::cursors::seen_ceiling(db)? {        let (first, late) = lanes_of(cursors, &author);        let (low, high, lagging) = if late < first {            (late, first, Lane::Late)        } else {            (first, late, Lane::First)        };        if !is_behind(&top, low) {            continue;        }        for (table, author_is) in [("_writes", "author"), ("_tombstones", "substr(hlc, 20)")] {            let past = db.get(                &format!(                    "SELECT COUNT(*) AS n FROM {table} WHERE {author_is} = ? AND hlc > ? AND held = 0"                ),                &[SqlValue::Text(author.clone()), SqlValue::Text(high.to_string())],            )?;            // The lagging lane's own receipts between the two cursors.            let window = if low < high {                db.get(                    &format!(                        "SELECT COUNT(*) AS n FROM {table} WHERE {author_is} = ? AND hlc > ? \                         AND hlc <= ? AND held = 0{}",                        lagging.clause()                    ),                    &[                        SqlValue::Text(author.clone()),                        SqlValue::Text(low.to_string()),                        SqlValue::Text(high.to_string()),                    ],                )?            } else {                None            };            for row in [past, window].into_iter().flatten() {                let n = row.int("n").unwrap_or(0);                total = total.saturating_add(u64::try_from(n).unwrap_or(0));            }        }    }    Ok(total)}/// How many receipts this file holds past a reader's `cursors`, BY TABLE —/// each lane from its own cursor, as [`receipts_owed`] counts them, so the/// counts sum to it — for the one exact count of a catch-up ("Email · 41,000/// of 58,900" on the device's own page).////// NEVER INSIDE THE WRITE HOLD. The author indexes do not carry `tbl`, so/// this reads every counted receipt's row: on the owner's file a fresh phone/// owes some 1.7 million. It is asked once per catch-up, on a read/// connection of the file, after the answer that found the device behind/// (`cotton_server::routes::sync::count_owed_at_start`); an exchange answer/// asks [`receipts_past`] with a cap instead. Each author is still a SEARCH/// of its own index, never a scan of the table (`INDEXED BY`: grouping by/// `tbl` would otherwise tempt the planner onto the primary key, a walk of/// every receipt in the file whatever the reader has seen).pub fn receipts_past_by_table(    db: &Driver,    cursors: &std::collections::BTreeMap<String, String>,) -> Result<std::collections::BTreeMap<String, u64>> {    let mut by_table = std::collections::BTreeMap::new();    for (author, top) in crate::cursors::seen_ceiling(db)? {        let (first, late) = lanes_of(cursors, &author);        for (lane, since) in [(Lane::First, first), (Lane::Late, late)] {            if !is_behind(&top, since) {                continue;            }            for statement in [WRITES_PAST, TOMBSTONES_PAST] {                let rows = db.all(                    &past_by_table(statement, lane),                    &[SqlValue::Text(author.clone()), SqlValue::Text(since.to_string())],                )?;                for row in rows {                    let (Some(table), Some(n)) = (row.text("tbl"), row.int("n")) else { continue };                    *by_table.entry(table.to_string()).or_insert(0) +=                        u64::try_from(n).unwrap_or(0);                }            }        }    }    Ok(by_table)}/// One author's receipts past a stamp, of one lane, by table/// ([`receipts_past_by_table`]).pub(crate) fn past_by_table(statement: &str, lane: Lane) -> String {    format!("{statement}{} GROUP BY tbl", lane.clause())}/// One author's receipts past a stamp ([`past_by_table`]).pub(crate) const WRITES_PAST: &str = "SELECT tbl, COUNT(*) AS n FROM _writes INDEXED BY \     idx_writes_author WHERE author = ? AND hlc > ? AND held = 0";/// And its tombstones, by the stamp's own author as `receipts_past` reads them.pub(crate) const TOMBSTONES_PAST: &str = "SELECT tbl, COUNT(*) AS n FROM _tombstones \     INDEXED BY idx_tombstones_author WHERE substr(hlc, 20) = ? AND hlc > ? AND held = 0";#[cfg(test)]#[path = "changes_tests.rs"]mod tests;