Cotton code
285 lines · 12.4 KB · RustRaw
//! The cursor map — one row per author, and the ceiling a copied file starts at.use rusqlite::types::Value as SqlValue;use super::*;use crate::changes::changes_since;use crate::test_support::{seeded_file, WORKSPACE};const DEV_A: &str = "device:aaaa";const DEV_B: &str = "device:bbbb";const NOW: &str = "2026-09-16T09:00:00.000Z";fn stamp(ms: i64, device: &str) -> String {    format!("{ms:013}:0000:{device}")}fn todo_change(id: &str) -> crate::mint::Change {    crate::mint::Change::create(        "cotton_todos",        id,        serde_json::json!({            "id": id, "title": "a todo", "status": "open", "priority": 0,            "created_at": "2026-09-01T00:00:00.000Z", "updated_at": "2026-09-01T00:00:00.000Z",            "workspace_id": WORKSPACE,        })        .as_object()        .expect("an object")        .clone(),    )}/// Fold one change at the stamp the test names, under the stamp's author.fn fold_at(db: &Driver, change: crate::mint::Change, hlc: &str) {    let author = crate::fold::author_of(hlc).expect("an author").to_string();    let op = crate::wire::op_of_change(        db,        &change,        hlc,        &author,        &crate::fixtures::fixture_actor(),        format!("op-{}-{hlc}", change.row_id),    )    .expect("a receipt");    let result = crate::fold::fold_ops(db, std::slice::from_ref(&op)).expect("folds");    assert!(result.applied.contains(&op.op_id), "{result:?}");}fn insert_todo(db: &Driver, id: &str, hlc: &str) {    fold_at(db, todo_change(id), hlc);}#[test]fn a_file_that_has_seen_nothing_holds_no_cursors() {    let db = seeded_file(DEV_A);    assert!(read_cursors(&db).expect("reads").is_empty());}#[test]fn advance_cursor_only_moves_forward() {    let db = seeded_file(DEV_A);    let early = stamp(1_700_000_000_000, DEV_B);    let late = stamp(1_700_000_005_000, DEV_B);    assert!(advance_cursor(&db, DEV_B, &early, NOW).expect("advances"));    assert_eq!(read_cursors(&db).expect("reads").get(DEV_B), Some(&early));    assert!(advance_cursor(&db, DEV_B, &late, NOW).expect("advances"));    assert_eq!(read_cursors(&db).expect("reads").get(DEV_B), Some(&late));    // A page folded out of order — a retry landing after the page that    // followed it — must not rewind the cursor and re-ask for what has already    // been folded. Backwards is a no-op, not an error.    assert!(        !advance_cursor(&db, DEV_B, &early, "2026-09-16T10:00:00.000Z").expect("does not move"),        "a backwards cursor is refused"    );    assert_eq!(read_cursors(&db).expect("reads").get(DEV_B), Some(&late));    assert!(        !advance_cursor(&db, DEV_B, &late, NOW).expect("does not move"),        "and so is the same cursor again"    );    // One row per author, never a row per peer: B's cursor is untouched by A's.    assert!(advance_cursor(&db, DEV_A, &early, NOW).expect("advances"));    let cursors = read_cursors(&db).expect("reads");    assert_eq!(cursors.get(DEV_A), Some(&early));    assert_eq!(cursors.get(DEV_B), Some(&late));}#[test]fn the_updated_at_is_the_callers_own() {    // Nothing in this crate reads the clock (spec R7).    let db = seeded_file(DEV_A);    advance_cursor(&db, DEV_B, &stamp(1_700_000_000_000, DEV_B), NOW).expect("advances");    let row = db        .get("SELECT updated_at FROM _cursors WHERE author_device_id = ?", &[            SqlValue::Text(DEV_B.to_string()),        ])        .expect("reads")        .expect("a row");    assert_eq!(row.text("updated_at"), Some(NOW));}#[test]fn cursor_ceiling_names_every_author() {    // What a whole-file copy sets: a device holding the file has seen every    // write in it, and the ceiling is read FROM the file so it cannot claim a    // write the copy did not carry.    let db = seeded_file(DEV_A);    let a_early = stamp(1_700_000_000_000, DEV_A);    let a_late = stamp(1_700_000_004_000, DEV_A);    insert_todo(&db, "todo-1", &a_early);    insert_todo(&db, "todo-2", &a_late);    // B, only ever as the author of a later change to a row A created.    let b_shadow = stamp(1_700_000_005_000, DEV_B);    fold_at(        &db,        crate::mint::Change::update(            "cotton_todos",            "todo-2",            serde_json::json!({ "notes": "B's" }).as_object().expect("an object").clone(),        ),        &b_shadow,    );    // C, only ever as a delete.    let c_delete = stamp(1_700_000_003_000, "device:cccc");    fold_at(&db, crate::mint::Change::retract("cotton_todos", "todo-1"), &c_delete);    let ceiling = cursor_ceiling(&db).expect("a ceiling");    assert_eq!(ceiling.get(DEV_A), Some(&a_late), "A's maximum, not its first");    assert_eq!(        ceiling.get(DEV_B),        Some(&b_shadow),        "an author who only ever changed somebody else's row is still an author"    );    assert_eq!(        ceiling.get("device:cccc"),        Some(&c_delete),        "and so is one that has only ever deleted something"    );    assert!(!ceiling.contains_key(""), "no write is nobody's");    // The point of it: a file set to its own ceiling asks for nothing back.    for (author, seen) in &ceiling {        advance_cursor(&db, author, seen, NOW).expect("advances");        let page = changes_since(&db, author, seen, 50).expect("a page");        assert!(page.ops.is_empty(), "{author} would re-fold {:?}", page.ops);        assert!(!page.has_more);    }}#[test]fn what_a_file_has_seen_is_what_it_holds_raised_by_what_it_folded() {    // The map a peer is told, so it knows what to hand over. `cursor_ceiling`    // is what this file HOLDS; `_cursors` is what it has FOLDED, and a write    // that lost to a newer one leaves the first and not the second. Told only    // the ceiling, a peer would hand that write over again on every pass for    // ever and the fold would discard it again every time.    let db = seeded_file(DEV_A);    let held = stamp(1_700_000_000_000, DEV_A);    insert_todo(&db, "t1", &held);    let discarded = stamp(1_700_000_009_000, DEV_B);    advance_cursor(&db, DEV_B, &discarded, NOW).expect("advances");    let seen = seen_ceiling(&db).expect("the map");    assert_eq!(seen.get(DEV_A), Some(&held), "what this file holds");    assert_eq!(        seen.get(DEV_B),        Some(&discarded),        "and what it folded and then lost — no row left, and it has still seen it"    );}#[test]fn a_folded_cursor_behind_what_this_file_holds_does_not_lower_it() {    let db = seeded_file(DEV_A);    let top = stamp(1_700_000_009_000, DEV_B);    insert_todo(&db, "t1", &top);    advance_cursor(&db, DEV_B, &stamp(1_700_000_000_000, DEV_B), NOW).expect("advances");    assert_eq!(seen_ceiling(&db).expect("the map").get(DEV_B), Some(&top));}/// The ceiling as one pass over each table says it — what [`cursor_ceiling`]/// was, kept here as the answer the index walk has to give.fn ceiling_by_a_pass(db: &Driver) -> std::collections::BTreeMap<String, String> {    let known = crate::changes::known_tables_clause(db).expect("the clause");    let mut ceiling = std::collections::BTreeMap::new();    for table in ["_writes", "_tombstones"] {        let sql = format!("SELECT author, MAX(hlc) AS top FROM {table} WHERE held = 0 AND {known} GROUP BY 1");        for row in db.all(&sql, &[]).expect("reads") {            let (author, top) = (row.text("author").unwrap_or_default().to_string(), row.text("top").unwrap_or_default().to_string());            if author.is_empty() || top.is_empty() {                continue;            }            let entry: &mut String = ceiling.entry(author).or_default();            if top > *entry {                *entry = top;            }        }    }    ceiling}/// `count` receipts of `author` straight into the write log, for rows no/// table holds — the log's size is all these are for.fn fill_the_log(db: &Driver, author: &str, from_ms: i64, count: i64) {    db.transaction(|db| {        for n in 0..count {            db.run(                "INSERT INTO _writes (tbl, row_id, hlc, author, held) VALUES ('cotton_todos', ?, ?, ?, 0)",                &[                    SqlValue::Text(format!("filler-{author}-{n}")),                    SqlValue::Text(stamp(from_ms + n, author)),                    SqlValue::Text(author.to_string()),                ],            )?;        }        Ok(())    })    .expect("fills");}/// RULE: What a file has seen of each author is read by walking the author index — a seek per author — so an exchange with nothing to fold reads the same few steps whether the write log holds two hundred receipts or twenty thousand, and it answers exactly what a pass over the log would./// 11 Oct 2026: asked as one GROUP BY over the log on every exchange, it read all 679,687 receipts of the owner's personal database (7.88 M steps, five to nine seconds inside the file) to answer sixteen rows; the walk read 1,426 steps there./// Measured on this fixture (`Driver::steps`): the whole nothing-to-fold exchange reads 2,516 steps over 210 receipts and 2,516 over 21,000.#[test]fn what_a_file_has_seen_is_read_by_author_and_never_by_a_pass_over_the_log() {    let steps_of = |receipts: i64| {        let db = seeded_file(DEV_A);        insert_todo(&db, "todo-1", &stamp(1_700_000_000_000, DEV_A));        insert_todo(&db, "todo-2", &stamp(1_700_000_001_000, DEV_B));        fold_at(&db, crate::mint::Change::retract("cotton_todos", "todo-1"), &stamp(1_700_000_002_000, "device:cccc"));        for (at, author) in [DEV_A, DEV_B, "device:dddd"].into_iter().enumerate() {            fill_the_log(&db, author, 1_700_000_100_000 + 1_000_000 * at as i64, receipts / 3);        }        // What must NOT raise a ceiling, each newer than everything its author        // has: a held receipt, and one of a table this build does not have.        db.run(            "INSERT INTO _writes (tbl, row_id, hlc, author, held) VALUES ('cotton_todos', 'held', ?, ?, 1)",            &[SqlValue::Text(stamp(1_800_000_000_000, DEV_A)), SqlValue::Text(DEV_A.to_string())],        )        .expect("a held receipt");        db.run(            "INSERT INTO _writes (tbl, row_id, hlc, author, held) VALUES ('cotton_a_later_builds', 'r', ?, ?, 0)",            &[SqlValue::Text(stamp(1_800_000_000_000, DEV_B)), SqlValue::Text(DEV_B.to_string())],        )        .expect("a later build's receipt");        db.run(            "INSERT INTO _writes (tbl, row_id, hlc, author, held) VALUES ('cotton_a_later_builds', 'r2', ?, 'device:eeee', 0)",            &[SqlValue::Text(stamp(1_800_000_000_000, "device:eeee"))],        )        .expect("an author only a later build knows");        // AN EXCHANGE WITH NOTHING TO FOLD, as the server answers one: what        // this file has seen, then the page for a peer that has seen it all.        let before = db.steps();        let seen = seen_ceiling(&db).expect("a ceiling");        let answered = crate::exchange::answer(&db, &seen, 500).expect("an answer");        let steps = db.steps() - before;        assert!(answered.ops.is_empty() && !answered.has_more, "a peer that has seen it all is handed {:?}", answered.ops.len());        assert_eq!(cursor_ceiling(&db).expect("a ceiling"), ceiling_by_a_pass(&db), "the walk and the pass disagree");        for author in [DEV_A, DEV_B, "device:cccc", "device:dddd"] {            assert!(seen.contains_key(author), "{author} is missing: {seen:?}");        }        assert!(!seen.contains_key("device:eeee"), "an author only a later build's receipt names was raised");        assert!(seen[DEV_A] < stamp(1_800_000_000_000, DEV_A), "a held receipt raised A");        assert!(seen[DEV_B] < stamp(1_800_000_000_000, DEV_B), "a later build's receipt raised B");        steps    };    let (small, large) = (steps_of(210), steps_of(21_000));    assert!(large <= small + small / 4, "an exchange with nothing to fold read {large} steps over 21,000 receipts and {small} over 210");}/// RULE: Restore's author count seeks bounded pages on an offline backup in any journal mode, retaining an empty author and every page boundary.#[test]fn offline_restore_counts_authors_in_bounded_pages() {    let db = rusqlite::Connection::open_in_memory().unwrap();    db.execute_batch(crate::schema::ddl::CURSORS_TABLE).unwrap();    db.execute_batch("INSERT INTO _cursors VALUES ('','seen','now'); WITH RECURSIVE n(x) AS (VALUES(0) UNION ALL SELECT x+1 FROM n WHERE x<129) INSERT INTO _cursors SELECT printf('%08d',x),'seen','now' FROM n").unwrap();    assert_eq!(count_cursors(&db).unwrap(), 131);}