Cotton code
212 lines · 8.1 KB · RustRaw
//! A page of synced rows is put in order where it is BUILT, never in the fold.//!//! A row that two devices have touched travels as several ops — the oldest one//! carries the whole row and can CREATE it on a file that has never seen it,//! and the later ones name only the columns they moved. The authors are walked//! in NAME order, so the device whose name sorts first gets its ops into the//! page first, whatever it wrote and whenever. That is the wrong order whenever//! the earlier name holds the later write: the receiving file meets an//! amendment for a row it has never heard of, inserts the two or three columns//! the patch names, and is refused by the first NOT NULL it meets. The write is//! parked, and the row is simply missing on that device until something retries//! it.//!//! So every place that BUILDS a page sorts it by stamp — `exchange::answer`//! (the responder's half, which this file is about), `Handover::take` and//! `exchange_request` (the caller's, held by//! `exchange_tests::a_page_is_handed_over_in_write_order_whatever_the_op_ids_say`).//! (Since receipts, a change that arrives before its create is held dormant//! rather than refused — `receipts_row_life` — so the order is no longer what//! stands between a row and its rejection; it is still what lets a file that//! has never seen the row take the page whole and at once.)//!//! Every row is synthetic and every value invented//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).use std::collections::BTreeMap;use cotton_store::actor::{Actor, JobName};use cotton_store::exchange::answer;use cotton_store::fold::fold_ops;use cotton_store::migrate::migrate_store;use cotton_store::mint::Change;use cotton_store::wire::op_of_change;use cotton_store::Driver;use rusqlite::types::Value;use serde_json::json;const WORKSPACE: &str = "22222222-2222-4222-8222-222222222222";const NOW: &str = "2026-09-20T09:00:00.000Z";const TODO: &str = "todo-fragmented-1";/// The device that AMENDED the row. Its name sorts FIRST, and its write is the/// LATER one — which is the whole shape of the failure.const AMENDER: &str = "device:aaaa";/// The device that CREATED the row. Its name sorts last and its write is the/// oldest, so name order and write order disagree.const CREATOR: &str = "device:zzzz";const BASE_MS: i64 = 1_790_000_000_000;const LATER_MS: i64 = 1_790_000_005_000;fn text(value: &str) -> Value {    Value::Text(value.to_string())}/// A stamp, spelled the way every reader of one expects: thirteen digits of/// milliseconds, a four-digit counter, then the author. The author is read back/// off character twenty, which is why the two fixed widths are not cosmetic.fn stamp(ms: i64, device: &str) -> String {    format!("{ms:013}:0000:{device}")}/// A real file at the current schema, with the workspace row every other row's/// foreign key points at.////// The workspace row is written straight in and therefore carries no receipt:/// it travels in nobody's stream.fn file() -> Driver {    let db = Driver::open_in_memory().expect("opens");    migrate_store(&db).expect("migrates");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",        &[            text(WORKSPACE),            text("A workspace"),            text("owner-1"),            text(NOW),        ],    )    .expect("the workspace row");    db}/// One todo whose fields sit at two stamps in two authors' streams: created by/// `CREATOR` at the base stamp, its title rewritten by `AMENDER` later. Each/// write is a receipt, folded in the order it was made — a stream IS its/// receipts, so there is no other honest way to put one in a file.fn fragmented_todo(db: &Driver) {    let actor = Actor::device_job(JobName::named("test").expect("a job name"));    let row = |value: serde_json::Value| value.as_object().cloned().expect("an object");    let create = op_of_change(        db,        &Change::create(            "cotton_todos",            TODO,            row(json!({                "id": TODO,                "workspace_id": WORKSPACE,                "title": "the first title",                "status": "open",                "priority": 0,                "created_at": NOW,                "updated_at": NOW,            })),        ),        &stamp(BASE_MS, CREATOR),        CREATOR,        &actor,        "op-create".to_string(),    )    .expect("the creation");    let amend = op_of_change(        db,        &Change::update("cotton_todos", TODO, row(json!({ "title": "the amended title" }))),        &stamp(LATER_MS, AMENDER),        AMENDER,        &actor,        "op-amend".to_string(),    )    .expect("the amendment");    let result = fold_ops(db, &[create, amend]).expect("folds");    assert_eq!(result.applied.len(), 2, "{result:?}");}/// RULE: A page of synced rows is put in order by the code that builds it, so the write that creates a row always travels ahead of the writes that changed it.////// WHY: the authors of a page are walked by name, so the device whose name/// sorts first has its writes read first. When that device holds the LATER/// write, an unsorted page reaches the other side as a change to a row it has/// never seen, which it cannot store — the write is set aside and the row is/// missing there until something tries again.#[test]fn an_answer_puts_the_creation_of_a_row_ahead_of_the_change_to_it() {    let db = file();    fragmented_todo(&db);    // An empty `seen` map is a peer that has seen nothing, so every author is    // behind and all of them share the page.    let answered = answer(&db, &BTreeMap::new(), 50).expect("an answer");    let stamps: Vec<&str> = answered.ops.iter().map(|op| op.hlc.as_str()).collect();    let mut ordered = stamps.clone();    ordered.sort_unstable();    assert_eq!(        stamps, ordered,        "the page is not in stamp order — it is built out of one stream per author, walked by \         NAME, so the sort at the end of `answer` is the only thing putting it in the order the \         writes happened"    );    let todo_ops: Vec<_> = answered        .ops        .iter()        .filter(|op| op.table == "cotton_todos")        .collect();    assert_eq!(todo_ops.len(), 2, "one row at two stamps is two ops");    let creation = todo_ops[0]        .patch        .as_ref()        .expect("an upsert carries a patch");    assert_eq!(        todo_ops[0].device_id, CREATOR,        "the creator's write is the older one and comes first"    );    assert!(        creation.contains_key("workspace_id") && creation.contains_key("created_at"),        "the first op has to be able to CREATE the row on a file that has never seen it, so it \         carries every column: {creation:?}"    );    let change = todo_ops[1]        .patch        .as_ref()        .expect("an upsert carries a patch");    assert_eq!(todo_ops[1].device_id, AMENDER);    assert_eq!(        change.keys().collect::<Vec<_>>(),        vec!["title"],        "the later write names only the column it moved"    );}/// RULE: A file that has never seen a row can store a whole page of changes to it in the order the page arrives.////// WHY: this is the same claim from the receiving end — the order is not a/// tidiness preference, it is the difference between a row arriving and a row/// being set aside as unstorable.#[test]fn a_file_that_has_never_seen_the_row_takes_the_whole_page_as_it_comes() {    let db = file();    fragmented_todo(&db);    let answered = answer(&db, &BTreeMap::new(), 50).expect("an answer");    let peer = file();    let result = fold_ops(&peer, &answered.ops).expect("the peer folds the page");    assert!(        result.rejected.is_empty(),        "a page in the order it was built has to land whole: {:?}",        result.rejected    );    let landed = peer        .get(            "SELECT title, status FROM cotton_todos WHERE id = ?",            &[text(TODO)],        )        .expect("a read")        .expect("the row is there");    assert_eq!(landed.text("title"), Some("the amended title"));    assert_eq!(landed.text("status"), Some("open"));}