Cotton code
766 lines · 34.0 KB · RustRaw
//! An author's stream, read back out of the receipts.//!//! The file is built through the fold, from receipts made the way `mint`//! makes them (`wire::op_of_change`), because a receipt IS the write: there is//! no honest way to put a row in `_writes` that the fold would not have put//! there. The two receipts for a table this build never had are the one//! exception, stored through `receipts::store`/`store_retract` directly —//! the fold would refuse them, which is the point of that case.use std::collections::BTreeMap;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value as JsonValue};use super::*;use crate::canonical::{Kind, Receipt};use crate::fixtures::fixture_actor;use crate::fold::fold_ops;use crate::mint::Change;use crate::protocol::types::OpKind;use crate::schema::ddl::SCHEMA_VERSION;use crate::test_support::{seeded_file, WORKSPACE};const DEV_A: &str = "device:aaaa";const DEV_B: &str = "device:bbbb";fn stamp(ms: i64, device: &str) -> String {    format!("{ms:013}:0000:{device}")}fn obj(value: JsonValue) -> Map<String, JsonValue> {    value.as_object().expect("an object").clone()}/// The receipt of one change, at the stamp the test names, under the stamp's/// own author.fn op_at(db: &Driver, change: Change, hlc: &str) -> CottonOp {    let author = crate::fold::author_of(hlc).expect("a stamp names its author").to_string();    let op_id = format!("op-{}-{}-{hlc}", change_row(&change), author);    crate::wire::op_of_change(db, &change, hlc, &author, &fixture_actor(), op_id).expect("a receipt")}fn change_row(change: &Change) -> String {    change.row_id.clone()}fn todo_fields(id: &str, title: &str) -> Map<String, JsonValue> {    obj(json!({        "id": id,        "title": title,        "status": "open",        "priority": 0,        "created_at": "2026-09-01T00:00:00.000Z",        "updated_at": "2026-09-01T00:00:00.000Z",        "workspace_id": WORKSPACE,    }))}fn create_op(db: &Driver, id: &str, title: &str, hlc: &str) -> CottonOp {    op_at(db, Change::create("cotton_todos", id, todo_fields(id, title)), hlc)}fn change_op(db: &Driver, id: &str, patch: JsonValue, hlc: &str) -> CottonOp {    op_at(db, Change::update("cotton_todos", id, obj(patch)), hlc)}fn retract_op(db: &Driver, id: &str, hlc: &str) -> CottonOp {    op_at(db, Change::retract("cotton_todos", id), hlc)}/// Fold these ops, every one of them applied.fn fold_all(db: &Driver, ops: &[CottonOp]) {    let result = fold_ops(db, ops).expect("the fold");    assert!(result.rejected.is_empty(), "{:?}", result.rejected);    for op in ops {        assert!(result.applied.contains(&op.op_id), "{} did not apply: {result:?}", op.op_id);    }}/// A todo created at one stamp.fn insert_todo(db: &Driver, id: &str, title: &str, hlc: &str) {    fold_all(db, &[create_op(db, id, title, hlc)]);}fn rows_of(page: &ChangesPage) -> Vec<(String, String)> {    let mut out: Vec<(String, String)> = Vec::new();    for op in &page.ops {        let key = (op.table.clone(), op.row_id.clone());        if !out.contains(&key) {            out.push(key);        }    }    out}#[test]fn an_offline_authors_old_writes_are_found_by_its_own_cursor() {    // The whole point of the author index: a device that has been away for a    // month is caught up from ITS cursor, however much everyone else wrote    // after it. Nothing was pruned, because there is no log to prune.    let db = seeded_file(DEV_B);    let old = stamp(1_700_000_000_000, DEV_A);    let older = stamp(1_600_000_000_000, DEV_A);    insert_todo(&db, "todo-old", "from a month ago", &older);    insert_todo(&db, "todo-new", "from yesterday", &old);    for index in 0..5 {        let mine = stamp(1_800_000_000_000 + index, DEV_B);        insert_todo(&db, &format!("todo-b-{index}"), "mine", &mine);    }    let page = changes_since(&db, DEV_A, "", 50).expect("A's stream");    assert_eq!(        rows_of(&page),        vec![            ("cotton_todos".to_string(), "todo-old".to_string()),            ("cotton_todos".to_string(), "todo-new".to_string()),        ],        "A's own two writes, oldest first, and none of B's"    );    assert_eq!(page.next_hlc.as_deref(), Some(old.as_str()));    assert!(!page.has_more);    // From the cursor it would have held after the first of them.    let caught_up = changes_since(&db, DEV_A, &older, 50).expect("A's stream");    assert_eq!(        rows_of(&caught_up),        vec![("cotton_todos".to_string(), "todo-new".to_string())]    );    assert!(changes_since(&db, DEV_A, &old, 50)        .expect("A's stream")        .ops        .is_empty());}#[test]fn every_author_of_a_row_streams_its_own_receipt_of_it() {    // A row is its receipts, and each travels in its author's stream, byte for    // byte: B's create in B's, A's later rename in A's — never a re-stamped    // reading of the row under somebody else's name.    let db = seeded_file(DEV_A);    let mine = stamp(1_700_000_000_000, DEV_B);    let theirs = stamp(1_700_000_001_000, DEV_A);    let create = create_op(&db, "todo-1", "B wrote it", &mine);    let rename = change_op(&db, "todo-1", json!({ "title": "A renamed it" }), &theirs);    fold_all(&db, &[create.clone(), rename.clone()]);    let page = changes_since(&db, DEV_B, "", 50).expect("B's stream");    assert_eq!(page.ops, vec![create], "B's create, exactly as it was minted");    assert_eq!(page.next_hlc.as_deref(), Some(mine.as_str()));    let theirs_page = changes_since(&db, DEV_A, "", 50).expect("A's stream");    assert_eq!(theirs_page.ops, vec![rename.clone()]);    let patch = rename.patch.as_ref().expect("a change carries fields");    assert_eq!(patch.keys().collect::<Vec<_>>(), vec!["title"], "only what A wrote");}#[test]fn a_tombstone_appears_in_its_authors_stream() {    let db = seeded_file(DEV_A);    let born = stamp(1_700_000_001_000, DEV_B);    let deleted_at = stamp(1_700_000_002_000, DEV_A);    fold_all(        &db,        &[create_op(&db, "todo-gone", "short-lived", &born), retract_op(&db, "todo-gone", &deleted_at)],    );    let page = changes_since(&db, DEV_A, "", 50).expect("A's stream");    assert_eq!(page.ops.len(), 1, "{:?}", page.ops);    assert_eq!(page.ops[0].kind, OpKind::Delete);    assert_eq!(page.ops[0].row_id, "todo-gone");    assert_eq!(page.ops[0].hlc, deleted_at);    assert!(page.ops[0].patch.is_none(), "a delete carries no patch");    assert_eq!(page.next_hlc.as_deref(), Some(deleted_at.as_str()));    // And not in anybody else's.    assert!(changes_since(&db, DEV_B, "", 50)        .expect("B's stream")        .ops        .iter()        .all(|op| op.kind != OpKind::Delete));}/// A receipt for a table this build does not declare, stored as the fold/// would store a known one.fn store_unknown(db: &Driver, table: &str, row_id: &str, kind: Kind, hlc: &str) {    let receipt = Receipt {        table: table.to_string(),        row_id: row_id.to_string(),        kind,        stamp: hlc.to_string(),        author: DEV_A.to_string(),        actor: fixture_actor().to_wire(),        schema: SCHEMA_VERSION,        restamps: None,        erase: None,        undo: None,        fields: match kind {            Kind::Retract => BTreeMap::new(),            _ => BTreeMap::from([("name".to_string(), json!("a pin"))]),        },    };    let op = crate::wire::from_receipt(format!("op-{table}-{row_id}"), &receipt).expect("an op");    match kind {        Kind::Retract => crate::receipts::store_retract(db, &op, &receipt, false).expect("stored"),        _ => crate::receipts::store(db, &op, &receipt, false).expect("stored"),    }}#[test]fn a_receipt_for_a_table_this_build_never_had_is_not_served() {    // The file has carried tombstones for the TypeScript era's tables since    // before the flip — `cotton_record_tags`, `cotton_pins` — and no Rust build    // has ever declared them. Served, each one reaches a phone as `unknown    // table`, refused and parked; on 2026-09-16 a re-pulling phone parked two    // hundred. A table this build cannot name is nothing it can hand over.    let db = seeded_file(DEV_A);    let born = stamp(1_700_000_000_000, DEV_B);    let gone = stamp(1_700_000_001_000, DEV_A);    let never = stamp(1_700_000_002_000, DEV_A);    let unknown_write = stamp(1_700_000_003_000, DEV_A);    fold_all(&db, &[create_op(&db, "todo-gone", "x", &born), retract_op(&db, "todo-gone", &gone)]);    store_unknown(&db, "cotton_record_tags", "tag-1", Kind::Retract, &never);    store_unknown(&db, "cotton_pins", "pin-1", Kind::Retract, &never);    store_unknown(&db, "cotton_pins", "pin-2", Kind::Create, &unknown_write);    let page = changes_since(&db, DEV_A, "", 50).expect("A's stream");    let tables: Vec<&str> = page.ops.iter().map(|op| op.table.as_str()).collect();    assert_eq!(        tables,        vec!["cotton_todos"],        "only the real table's delete is served: {tables:?}"    );    // And the page's resume point is the served row's, never one of the    // unserved ones — a cursor past `never` would be a cursor past nothing.    assert_eq!(page.next_hlc.as_deref(), Some(gone.as_str()));    assert!(!page.has_more);    // The ceiling reads the side tables through the same clause: A's top is    // the todo's delete, not the unknown tables' later stamps — or A would be    // "behind" on every pass and answered an empty page for ever.    let ceiling = crate::cursors::cursor_ceiling(&db).expect("the ceiling");    assert_eq!(ceiling.get(DEV_A).map(String::as_str), Some(gone.as_str()));}#[test]fn one_row_two_stamps_emits_two_ops() {    // One receipt, one op: a row created at one stamp and renamed at another    // is two ops, the create carrying what it named and the change only its    // own column.    let db = seeded_file(DEV_A);    let base = stamp(1_700_000_000_000, DEV_A);    let later = stamp(1_700_000_005_000, DEV_A);    fold_all(        &db,        &[            create_op(&db, "todo-1", "first title", &base),            change_op(&db, "todo-1", json!({ "title": "renamed later" }), &later),        ],    );    let page = changes_since(&db, DEV_A, "", 50).expect("A's stream");    assert_eq!(page.ops.len(), 2);    assert_eq!(page.ops[0].hlc, base, "the create comes first");    assert_eq!(page.ops[1].hlc, later);    let first = page.ops[0].patch.as_ref().expect("a patch");    assert_eq!(first.get("status"), Some(&json!("open")));    let second = page.ops[1].patch.as_ref().expect("a patch");    assert_eq!(second.keys().collect::<Vec<_>>(), vec!["title"]);    assert_eq!(second.get("title"), Some(&json!("renamed later")));    assert_eq!(page.rows, 1, "two receipts of one row count once");    assert_eq!(page.next_hlc.as_deref(), Some(later.as_str()));}/// RULE: One act's receipts are cut INSIDE their stamp when they outgrow a page — the cursor says where in the stamp the page stopped — and the next page resumes there: every row of the act arrives exactly once, none is lost and none is sent twice, so no act outgrows a page (13 Oct 2026: one act of 1,984 receipts went out as one 25.7 MB page the phone could not fold).#[test]fn a_stamp_shared_by_more_rows_than_the_page_is_cut_inside_and_resumed() {    // One write can stamp several rows with ONE stamp — a tool call filing ten    // links, a toolkit's thousand definitions.    let db = seeded_file(DEV_A);    let shared = stamp(1_700_000_000_000, DEV_A);    for index in 0..10 {        insert_todo(&db, &format!("todo-{index}"), "one write", &shared);    }    let after = stamp(1_700_000_001_000, DEV_A);    insert_todo(&db, "todo-after", "the next write", &after);    let first = changes_since(&db, DEV_A, "", 3).expect("A's stream");    assert_eq!(first.rows, 3, "a page of three rows carries three");    assert!(first.has_more);    let inside = first.next_hlc.clone().expect("a cursor");    assert!(inside.as_str() > shared.as_str() && inside.as_str() < after.as_str(), "it sorts inside the stamp");    assert!(is_behind(&shared, &inside), "the rest of the act is still owed");    let mut rows = rows_of(&first);    let mut cursor = inside;    for _ in 0..10 {        let page = changes_since(&db, DEV_A, &cursor, 3).expect("A's stream");        rows.extend(rows_of(&page));        let Some(next) = page.next_hlc.clone() else { break };        cursor = next;        if !page.has_more {            break;        }    }    let mut expected: Vec<(String, String)> =        (0..10).map(|index| ("cotton_todos".to_string(), format!("todo-{index}"))).collect();    expected.push(("cotton_todos".to_string(), "todo-after".to_string()));    assert_eq!(rows, expected, "every row once, in order");    assert_eq!(cursor, after, "and the cursor ends on the last stamp");}#[test]fn the_page_is_ordered_and_bounded() {    let db = seeded_file(DEV_A);    for index in 0..7 {        let hlc = stamp(1_700_000_000_000 + index, DEV_A);        insert_todo(&db, &format!("todo-{index}"), "one of many", &hlc);    }    // B's row, A's delete of it: one entry of A's from `_tombstones`.    fold_all(        &db,        &[            create_op(&db, "todo-gone", "B's", &stamp(1_600_000_000_000, DEV_B)),            retract_op(&db, "todo-gone", &stamp(1_700_000_000_003, DEV_A)),        ],    );    let mut cursor = String::new();    let mut seen: Vec<String> = Vec::new();    loop {        let page = changes_since(&db, DEV_A, &cursor, 3).expect("A's stream");        assert!(rows_of(&page).len() <= 3, "the page is bounded in rows");        let stamps: Vec<String> = page.ops.iter().map(|op| op.hlc.clone()).collect();        let mut sorted = stamps.clone();        sorted.sort();        assert_eq!(stamps, sorted, "a page is in stamp order");        for hlc in stamps {            assert!(hlc.as_str() > cursor.as_str(), "{hlc} is not after {cursor}");            seen.push(hlc);        }        if !page.has_more {            break;        }        cursor = page.next_hlc.expect("a page with more has a cursor");    }    assert_eq!(seen.len(), 8, "seven rows and one delete: {seen:?}");    let mut sorted = seen.clone();    sorted.sort();    assert_eq!(seen, sorted, "the pages together are still in order");}#[test]fn a_re_emitted_page_carries_the_same_op_ids() {    // A page re-sent after a dropped response has to fold to nothing on the way    // in, and every idempotency key on that path is the op id.    let db = seeded_file(DEV_A);    let hlc = stamp(1_700_000_000_000, DEV_A);    let op = create_op(&db, "todo-1", "once", &hlc);    fold_all(&db, std::slice::from_ref(&op));    let first = changes_since(&db, DEV_A, "", 50).expect("A's stream");    let again = changes_since(&db, DEV_A, "", 50).expect("A's stream");    assert_eq!(first, again);    assert_eq!(first.ops, vec![op], "the minted op id and bytes, unchanged");    assert_eq!(first.ops[0].schema_version, SCHEMA_VERSION);}#[test]fn the_query_plan_uses_the_author_index() {    // The guard under the whole design: without the index every exchange scans    // every receipt the file holds.    let db = seeded_file(DEV_A);    insert_todo(&db, "todo-1", "indexed", &stamp(1_700_000_000_000, DEV_A));    let plan = db        .all(            &format!(                "EXPLAIN QUERY PLAN SELECT op_id, hlc, bytes FROM _writes \                 WHERE author = ? AND hlc > ? AND held = 0 AND {} ORDER BY hlc LIMIT ?",                known_tables_clause(&db).expect("the clause")            ),            &[                SqlValue::Text(DEV_A.to_string()),                SqlValue::Text(String::new()),                SqlValue::Integer(10),            ],        )        .expect("a plan");    let detail: String = plan        .iter()        .filter_map(|row| row.text("detail"))        .collect::<Vec<_>>()        .join(" | ");    assert!(        detail.contains("idx_writes_author"),        "the author index is not being used: {detail}"    );    assert!(        detail.contains("SEARCH"),        "the author index is being scanned rather than searched: {detail}"    );}#[test]fn rebuilt_row_carries_no_field_under_a_stamp_that_did_not_write_it() {    // A row is sent as the receipts that made it, never re-read from the row    // as it stands now. A's create named the first title and B later wrote    // another, so A's create still carries A's title, B's change only its    // own, and A's later note carries the note alone.    let db = seeded_file(DEV_A);    let born = stamp(1_700_000_000_000, DEV_A);    let retitled = stamp(1_700_000_001_000, DEV_B);    let noted = stamp(1_700_000_002_000, DEV_A);    fold_all(        &db,        &[            create_op(&db, "todo-1", "A's title", &born),            change_op(&db, "todo-1", json!({ "title": "B's title" }), &retitled),            change_op(&db, "todo-1", json!({ "notes": "A's note" }), &noted),        ],    );    let row = crate::fold::read_row(&db, "cotton_todos", "todo-1").expect("a row").expect("live");    assert_eq!(row.get("title"), Some(&json!("B's title")), "the row shows B's title");    assert_eq!(row.get("notes"), Some(&json!("A's note")));    let mut sent: BTreeMap<String, Map<String, JsonValue>> = BTreeMap::new();    for author in [DEV_A, DEV_B] {        for op in changes_since(&db, author, "", 50).expect("a stream").ops {            sent.insert(op.hlc.clone(), op.patch.clone().expect("a patch"));        }    }    assert_eq!(sent.len(), 3, "one op per receipt: {sent:?}");    assert_eq!(sent[&born].get("title"), Some(&json!("A's title")), "the create keeps the title it wrote");    assert!(!sent[&born].contains_key("notes"), "the create never wrote the note");    assert_eq!(sent[&retitled], obj(json!({ "title": "B's title" })), "B's change carries only B's title");    assert_eq!(sent[&noted], obj(json!({ "notes": "A's note" })), "A's note carries only the note");}#[test]fn the_streams_rebuild_the_same_tables_in_an_empty_file() {    // The round trip. A real fold builds one file from two devices' writes; the    // streams take it apart author by author; a second fold puts it back    // together somewhere that has never seen any of it.    let source = seeded_file(DEV_A);    let born = stamp(1_700_000_000_000, DEV_A);    let edited = stamp(1_700_000_001_000, DEV_B);    let dropped = stamp(1_700_000_002_000, DEV_B);    fold_all(        &source,        &[            create_op(&source, "todo-1", "written by A", &born),            create_op(&source, "todo-2", "also A's", &born),            // B edits a column of A's row.            change_op(&source, "todo-1", json!({ "notes": "B's note" }), &edited),            retract_op(&source, "todo-2", &dropped),        ],    );    // Every author the file knows about, drained page by page.    let ceiling = crate::cursors::cursor_ceiling(&source).expect("a ceiling");    assert!(ceiling.contains_key(DEV_A) && ceiling.contains_key(DEV_B), "{ceiling:?}");    let mut ops: Vec<CottonOp> = Vec::new();    for author in ceiling.keys() {        let mut cursor = String::new();        loop {            let page = changes_since(&source, author, &cursor, 2).expect("a page");            ops.extend(page.ops);            if !page.has_more {                break;            }            cursor = page.next_hlc.expect("a page with more has a cursor");        }    }    ops.sort_by(|left, right| left.hlc.cmp(&right.hlc));    let target = seeded_file("device:cccc");    let result = fold_ops(&target, &ops).expect("the target file folds");    assert!(result.rejected.is_empty(), "{:?}", result.rejected);    assert_eq!(        table_state(&source, "cotton_todos"),        table_state(&target, "cotton_todos"),        "the rebuilt table is the same table, clocks included"    );    assert_eq!(        side_state(&source, "_tombstones"),        side_state(&target, "_tombstones"),        "and the delete travelled too"    );    assert_eq!(        side_state(&source, "_writes"),        side_state(&target, "_writes"),        "and so did every receipt, byte for byte"    );    assert_eq!(        crate::fold::read_row(&target, "cotton_todos", "todo-1")            .expect("a row")            .expect("todo-1 is live")            .get("notes"),        Some(&json!("B's note")),        "B's column survived the trip as B's"    );}fn table_state(db: &Driver, table: &str) -> Vec<Vec<(String, SqlValue)>> {    db.all(&format!("SELECT * FROM {table} ORDER BY id"), &[])        .expect("the table reads")        .into_iter()        .map(|row| row.columns().to_vec())        .collect()}fn side_state(db: &Driver, table: &str) -> Vec<Vec<(String, SqlValue)>> {    db.all(&format!("SELECT * FROM {table} ORDER BY tbl, row_id, hlc"), &[])        .expect("the side table reads")        .into_iter()        .map(|row| row.columns().to_vec())        .collect()}/// RULE: "Behind by" counts the receipts past a reader's cursors and stops at the cap its caller gives — an exchange answer and the catch-up wake's recount both count inside the write hold and give one, and only the once-per-catch-up count of what was owed, outside the hold, gives none and is told the whole.#[test]fn what_a_reader_is_behind_by_is_counted_past_its_cursors_and_capped() {    let db = seeded_file(DEV_A);    for i in 0..5 {        insert_todo(&db, &format!("a{i}"), "a", &stamp(1_000 + i, DEV_A));    }    for i in 0..3 {        insert_todo(&db, &format!("b{i}"), "b", &stamp(2_000 + i, DEV_B));    }    let nothing = BTreeMap::new();    let all = receipts_past(&db, &nothing, 10_000).expect("count");    assert!(all >= 8, "{all}");    // Level with A, two of B's three behind.    let mut at = crate::cursors::seen_ceiling(&db).expect("ceiling");    let level = receipts_past(&db, &at, 10_000).expect("count");    assert_eq!(level, 0);    let a_author = crate::fold::author_of(&stamp(1_000, DEV_A)).expect("author").to_string();    let b_author = crate::fold::author_of(&stamp(2_000, DEV_B)).expect("author").to_string();    at.insert(b_author, stamp(2_000, DEV_B));    assert_eq!(receipts_past(&db, &at, 10_000).expect("count"), 2);    // A cap is where the walk stops; with none, the count is the whole.    at.remove(&a_author);    assert_eq!(receipts_past(&db, &at, 4).expect("count"), 4);    let whole = receipts_past(&db, &at, u64::MAX).expect("count");    assert!(whole >= 7, "A's five and two of B's at least: {whole}");    assert_eq!(whole, receipts_past(&db, &at, 10_000).expect("count"));}/// The owner's file's shape: one author with 2.9 million receipts (a third of/// them mail) and 100,000 tombstones, five authors with three hundred each./// Answers the file and how many receipts its seed already held.fn skewed_three_million() -> (Driver, u64) {    let db = seeded_file(DEV_A);    let seeded = receipts_past(&db, &BTreeMap::new(), u64::MAX).expect("count");    db.exec(&format!(        "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2900000) \         INSERT INTO _writes (tbl, row_id, hlc, author, held) \         SELECT CASE WHEN i % 3 = 0 THEN 'cotton_emails' ELSE 'cotton_todos' END, 'big-' || i, \         printf('%013d:0000:{BIG}', 1000 + i), '{BIG}', 0 FROM n"    ))    .expect("the big author's receipts");    for small in 0..5 {        let device = format!("device:small{small}");        db.exec(&format!(            "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 300) \             INSERT INTO _writes (tbl, row_id, hlc, author, held) \             SELECT 'cotton_todos', '{device}-' || i, printf('%013d:0000:{device}', 1000 + i), '{device}', 0 FROM n"        ))        .expect("a small author's receipts");    }    db.exec(&format!(        "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100000) \         INSERT INTO _tombstones (tbl, row_id, hlc, op_id, author, actor, bytes, held) \         SELECT 'cotton_todos', 'gone-' || i, printf('%013d:0001:{BIG}', 1000 + i), 'tomb-' || i, '{BIG}', 'a', x'00', 0 FROM n"    ))    .expect("the big author's tombstones");    (db, seeded)}/// The author who wrote nearly all of [`skewed_three_million`].const BIG: &str = "device:big0";/// RULE: The behind-by count inside an exchange write hold caps its indexed work per counted receipt; even an index-only count would otherwise walk a skewed household's entire receipt history on every page.#[test]fn the_capped_behind_by_count_is_cheap_on_a_skewed_three_million_receipt_file() {    const CAP: u64 = 10_000;    let (db, seeded) = skewed_three_million();    // Both statements are searches of an author index, never a scan.    for (table, author_is, index) in [        ("_writes", "author", "COVERING INDEX idx_writes_author"),        ("_tombstones", "substr(hlc, 20)", "idx_tombstones_author"),    ] {        let plan: Vec<String> = db            .all(                &format!(                    "EXPLAIN QUERY PLAN SELECT COUNT(*) AS n FROM (SELECT 1 FROM {table} WHERE \                     {author_is} = ? AND hlc > ? AND held = 0 LIMIT ?)"                ),                &[                    SqlValue::Text(BIG.to_string()),                    SqlValue::Text(String::new()),                    SqlValue::Integer(10),                ],            )            .expect("a plan")            .iter()            .filter_map(|row| row.text("detail").map(str::to_string))            .collect();        assert!(            plan.iter().any(|detail| detail.contains("SEARCH") && detail.contains(index)),            "{table}: {plan:?}"        );        assert!(!plan.iter().any(|detail| detail.starts_with("SCAN") && detail.contains(table)), "{table}: {plan:?}");    }    // A fresh phone: it has seen nothing.    let nothing = BTreeMap::new();    let before = db.steps();    let capped = receipts_past(&db, &nothing, CAP).expect("count");    let steps = db.steps() - before;    assert_eq!(capped, CAP);    assert!(steps < CAP * 10, "the capped count read {steps} steps");    // The whole is still there to be counted once, outside the hold.    let whole = receipts_past(&db, &nothing, u64::MAX).expect("count");    assert_eq!(whole, seeded + 2_900_000 + 5 * 300 + 100_000);}/// RULE: A catch-up's whole BY TABLE is the one count that reads receipts' rows, so it is never asked inside the write hold — the exchange answer asks the capped, index-only count — and, asked once outside it on the owner's file's shape, each author is still a SEARCH of its own index (never a scan of the table), the counts sum to the exact whole, and a reader part-way through owes only what is past its cursor (coordinator, 12 Oct 2026 02:45Z, on the architect's 02:17Z ruling).#[test]fn the_whole_by_table_is_counted_by_author_index_and_sums_to_the_whole() {    let (db, seeded) = skewed_three_million();    for (statement, table, index) in [        (WRITES_PAST, "_writes", "idx_writes_author"),        (TOMBSTONES_PAST, "_tombstones", "idx_tombstones_author"),    ]    .into_iter()    .flat_map(|each| [(each, Lane::First), (each, Lane::Late)])    .map(|((statement, table, index), lane)| (past_by_table(statement, lane), table, index))    {        let plan: Vec<String> = db            .all(                &format!("EXPLAIN QUERY PLAN {statement}"),                &[SqlValue::Text(BIG.to_string()), SqlValue::Text(String::new())],            )            .expect("a plan")            .iter()            .filter_map(|row| row.text("detail").map(str::to_string))            .collect();        assert!(            plan.iter().any(|detail| detail.contains("SEARCH") && detail.contains(index)),            "{table}: {plan:?}"        );        assert!(!plan.iter().any(|detail| detail.starts_with("SCAN") && detail.contains(table)), "{table}: {plan:?}");    }    // A fresh phone owes everything, and the tables sum to the exact whole.    let nothing = BTreeMap::new();    let whole = receipts_past(&db, &nothing, u64::MAX).expect("count");    assert_eq!(whole, seeded + 2_900_000 + 5 * 300 + 100_000);    let before = db.steps();    let by_table = receipts_past_by_table(&db, &nothing).expect("by table");    let steps = db.steps() - before;    assert_eq!(by_table.values().sum::<u64>(), whole, "{by_table:?}");    // A third of the big author's receipts are mail (every i divisible by 3).    assert_eq!(by_table.get("cotton_emails"), Some(&966_666));    assert!(by_table.get("cotton_todos").is_some_and(|todos| *todos > 2_000_000), "{by_table:?}");    // One walk of what is owed and no more: a step or two per receipt for the    // index and its row, plus the grouping.    assert!(steps < whole * 40, "the by-table count read {steps} steps for {whole} receipts");    // A reader 2.8 million receipts into the big author owes its last    // hundred thousand, and only those are walked.    let mut part_way = receipts_cursors(&db);    part_way.insert(BIG.to_string(), format!("{:013}:0000:{BIG}", 1000 + 2_800_000));    let before = db.steps();    let rest = receipts_past_by_table(&db, &part_way).expect("by table");    let steps = db.steps() - before;    let owed = receipts_owed(&db, &part_way).expect("count");    assert_eq!(rest.values().sum::<u64>(), owed, "{rest:?}");    assert_eq!(rest.get("cotton_emails"), Some(&33_333), "{rest:?}");    assert!(owed <= 200_000, "{owed}");    assert!(steps < 200_000 * 40, "a reader nearly level walked {steps} steps");}/// Where a reader level with every author stands.fn receipts_cursors(db: &Driver) -> BTreeMap<String, String> {    crate::cursors::seen_ceiling(db).expect("the ceiling").into_iter().collect()}/// RULE: An exchange's tombstone page searches the stamp-author index before paging; one phone must not scan every other author's deletes while holding the served file.#[test]fn a_tombstone_page_searches_its_author_on_a_skewed_file() {    let db = seeded_file(DEV_A);    db.exec("WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i<300000)        INSERT INTO _tombstones (tbl,row_id,hlc,op_id,author,actor,bytes,held)        SELECT 'cotton_emails','synthetic:gone:'||i,printf('%013d:0000:device:bulk',1000+i),            'synthetic:delete:'||i,'device:bulk','job:synthetic',x'00',0 FROM n").unwrap();    for (i, author) in [(1, DEV_B), (2, DEV_B), (3, DEV_A)] {        let id = format!("synthetic:small:{i}");        let op = retract_op(&db, &id, &stamp(900000+i,author));        let receipt = crate::canonical::decode(op.receipt.as_bytes()).unwrap();        crate::receipts::store_retract(&db,&op,&receipt,false).unwrap();    }    let params = [SqlValue::Text(DEV_B.into()),SqlValue::Text(String::new()),SqlValue::Integer(10)];    let before = crate::held::Asked::so_far(&db);    let former = db.all("SELECT op_id,hlc,bytes,sig FROM _tombstones WHERE author=? AND hlc>? AND held=0 AND tbl IN ('cotton_todos','cotton_emails') ORDER BY hlc LIMIT ?",&params).unwrap();    let old = crate::held::Asked::since(&db,&before);    assert_eq!(former.len(),2);    println!("former tombstone page: {} steps, {:?} inside SQLite",old.steps,old.inside);    let before = crate::held::Asked::so_far(&db);    let _held = crate::held::holding("synthetic exchange file");    let began = std::time::Instant::now();    let page = stamped_entries(&db,DEV_B,"",None,10,Some(Lane::First)).unwrap();    let asked = crate::held::Asked::since(&db,&before);    let line = crate::held::slow_hold_line("synthetic",began.elapsed(),std::time::Duration::ZERO,        &crate::held::Work::default(),&asked,std::panic::Location::caller()).unwrap();    println!("{line}");    assert_eq!(page.len(),2);    assert!(asked.steps<5000,"the page must search its author rather than walk unrelated deletes: {line}");    let next = stamped_entries(&db,DEV_B,&page[0].key,None,10,Some(Lane::First)).unwrap();    assert_eq!(next.len(),1,"paging still keeps the strict stamp boundary");    assert_eq!(next[0].op.op_id,page[1].op.op_id);}/// RULE: What a reader is owed — and what an answer says it is behind by — is each lane from its own cursor — the first lane past the author's cursor, mail past `@late:<author>` — so a reader level on everything but mail is never counted again for first-lane receipts it holds, and the count by table sums to that whole (13 Oct 2026: the serving Mac's own client read as owing 462,238 changes where it owed 329,154, and a phone's catch-up began "owing" more email threads than the table holds).#[test]fn what_a_reader_owes_is_each_lane_from_its_own_cursor() {    let db = seeded_file(DEV_A);    let author = "device:lanes0";    // Ninety receipts, every third one mail.    db.exec(&format!(        "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 90) \         INSERT INTO _writes (tbl, row_id, hlc, author, held) \         SELECT CASE WHEN i % 3 = 0 THEN 'cotton_emails' ELSE 'cotton_todos' END, 'lane-' || i, \         printf('%013d:0000:{author}', 1000 + i), '{author}', 0 FROM n"    ))    .expect("receipts");    let stamp = |i: u64| format!("{:013}:0000:{author}", 1000 + i);    let mut cursors = receipts_cursors(&db);    // Level on the first lane at its end; mail behind from receipt 30.    cursors.insert(author.to_string(), stamp(90));    cursors.insert(late_cursor_key(author), stamp(30));    let owed = receipts_owed(&db, &cursors).expect("owed");    assert_eq!(owed, 20, "the mail of receipts 31..=90 and nothing it holds");    assert_eq!(receipts_past(&db, &cursors, u64::MAX).expect("behind by"), owed, "behind by is the same honest count");    let by_table = receipts_past_by_table(&db, &cursors).expect("by table");    assert_eq!(by_table, BTreeMap::from([("cotton_emails".to_string(), 20)]));    // The mail lane AHEAD of the first: first-lane receipts 31..=60 and the    // mail past 60 are owed.    cursors.insert(author.to_string(), stamp(30));    cursors.insert(late_cursor_key(author), stamp(60));    assert_eq!(receipts_owed(&db, &cursors).expect("owed"), 40 + 10);    assert_eq!(receipts_past(&db, &cursors, u64::MAX).expect("behind by"), 50);    let by_table = receipts_past_by_table(&db, &cursors).expect("by table");    assert_eq!(by_table.values().sum::<u64>(), 50, "{by_table:?}");    // No mail lane written down yet: both lanes stand at the author's cursor.    cursors.remove(&late_cursor_key(author));    assert_eq!(receipts_owed(&db, &cursors).expect("owed"), 60);    assert_eq!(receipts_owed(&db, &cursors).expect("owed"), receipts_past(&db, &cursors, u64::MAX).expect("all"));}