Cotton code
213 lines · 10.2 KB · RustRaw
//! Undo of a delete restores a binned row and preserves later peer changes.mod support;use cotton_store::fold::fold_ops;use cotton_store::mint::Change;use cotton_tools::test_fixtures::{author_fact, peer_op};use serde_json::{json, Map, Value};use support::harness::Harness;use support::mcp::{call_tool, call_tool_as_owner, mint_token};const PEER: &str = "device:peer";fn harness() -> (Harness, String) {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    (h, secret)}/// A stamp one millisecond above `stamp`, written by [`PEER`].fn just_above(stamp: &str) -> String {    let ms: i64 = stamp[..13].parse().expect("a stamp starts with its millisecond");    format!("{:013}:0000:{PEER}", ms + 1)}/// RULE: Undoing a binned row restores the same row, and a field another/// device changed while it was binned keeps that later value over history's/// `before`, so Undo never overwrites a received peer change.#[test]fn undo_of_a_binned_row_keeps_a_later_peer_change() {    let (h, secret) = harness();    let created = call_tool(        &h,        &secret,        "create_record",        json!({ "table": "note", "data": { "title": "Synthetic lunch", "body": "Capture note" } }),    );    let id = created["record"]["id"].as_str().expect("the note's id").to_string();    let owner = |tool: &str, args: Value| {        let answer = call_tool_as_owner(&h, "device:phone", tool, args);        assert!(!answer.is_error, "{tool} refused: {}", answer.text);        answer.json()    };    let binned = || h.one(            "SELECT trashed_at FROM cotton_notes WHERE id = ?",            &[rusqlite::types::Value::Text(id.clone())],        )        .and_then(|row| row.get("trashed_at").and_then(Value::as_str).map(str::to_owned));    let deleted = owner("delete_record", json!({ "table": "note", "id": id }));    assert_eq!(deleted["change"]["undoable"], true, "{}", deleted["change"]);    assert!(binned().is_some(), "the delete moved the note to the bin");    // A peer can still update the binned row. Undo must restore that received    // change instead of replacing it with the old title from history.    let deleted_change = h.one("SELECT _hlc AS hlc FROM cotton_changes WHERE id = ?", &[rusqlite::types::Value::Text(deleted["change"]["id"].as_str().expect("delete change").into())]).expect("the delete receipt");    let stamp = just_above(deleted_change["hlc"].as_str().expect("its stamp"));    let mut patch = Map::new();    patch.insert("title".into(), Value::from("Synthetic dinner"));    let rename = peer_op(&Change::update("cotton_notes", &id, patch), &stamp, PEER, "peer", "peer-rename");    let folded = fold_ops(&h.db, &[author_fact(&h.workspace_id, PEER, &stamp), rename]).expect("the page folds");    assert!(folded.rejected.is_empty() && folded.waiting.is_empty(), "{folded:?}");    assert!(binned().is_some(), "a peer update does not take the row out of the bin");    let change_id = deleted["change"]["id"].as_str().expect("the delete's change");    let undone = owner("undo", json!({ "change_id": change_id }));    assert_eq!(undone["change"]["verb"], "restore");    assert_eq!(undone["record"]["id"], id.as_str(), "the same row id");    assert_eq!(undone["record"]["data"]["title"], "Synthetic dinner", "the dormant change wins over before");    assert_eq!(undone["record"]["data"]["body"], "Capture note", "a field no receipt names comes from before");    // The restore is itself a change that undoes to the bin again.    let restore_id = undone["change"]["id"].as_str().expect("the restore's change");    owner("undo", json!({ "change_id": restore_id }));    assert!(binned().is_some());}/// RULE: Every built-in delete gives the same record back on undo — each column the record showed before the delete, at the same id — because an undo that returned a thinner row would lose what the owner wrote.#[test]fn a_deleted_row_comes_back_as_it_was() {    let (h, _) = harness();    let owner = |tool: &str, args: Value| {        let answer = call_tool_as_owner(&h, "device:phone", tool, args);        assert!(!answer.is_error, "{tool} refused: {}", answer.text);        answer.json()    };    for (table, data) in [        ("note", json!({ "title": "Run a marathon", "body": "For the view" })),        ("todo", json!({ "title": "Book the physio" })),        ("person", json!({ "full_name": "Sela Porchwalker" })),    ] {        let created = owner("create_record", json!({ "table": table, "data": data }));        let id = created["record"]["id"].as_str().expect("its id").to_string();        let deleted = owner("delete_record", json!({ "table": table, "id": id }));        let undone = owner("undo", json!({ "change_id": deleted["change"]["id"] }));        assert_eq!(undone["record"]["id"], id.as_str(), "{table}");        assert_eq!(undone["record"]["data"], created["record"]["data"], "{table}");    }}/// RULE: Undoing a new note or todo removes the row the create made, because a receipt's Undo that leaves the record behind is a lie on the screen.#[test]fn undoing_a_create_removes_the_new_row() {    let (h, _) = harness();    let owner = |tool: &str, args: Value| {        let answer = call_tool_as_owner(&h, "device:phone", tool, args);        assert!(!answer.is_error, "{tool} refused: {}", answer.text);        answer.json()    };    for (table, sql, data) in [        ("note", "SELECT count(*) AS c FROM cotton_notes", json!({ "title": "Spare key under the blue pot" })),        ("todo", "SELECT count(*) AS c FROM cotton_todos", json!({ "title": "Call the plumber" })),    ] {        let created = owner("create_record", json!({ "table": table, "data": data }));        assert_eq!(h.count(sql, &[]), 1, "{table} made");        let change = created["change"]["id"].as_str().expect("the create's change").to_string();        let undone = owner("undo", json!({ "change_id": change }));        assert_eq!(h.count(sql, &[]), 0, "{table} undone: {undone}");    }}// ── a deleted event comes back by Undo ──────────────────────────────────────/// An upsert the way a device mints one, for seeding a calendar and its events.fn seeded(table: &str, row_id: &str, n: u32, patch: Value) -> Value {    json!({        "opId": format!("01K{:023}", n),        "deviceId": "device:seed",        "kind": "upsert",        "table": table,        "rowId": row_id,        "patch": patch,        "hlc": format!("1700000000{n:03}:0000:device:seed"),        "schemaVersion": cotton_store::schema::ddl::SCHEMA_VERSION,    })}/// A calendar with one event Google knows about: the event's id.fn synced_event(h: &Harness) -> String {    let calendar = support::harness::synthetic_uuid("calendar");    let event = support::harness::synthetic_uuid("synced event");    let at = "2026-10-01T09:00:00.000Z";    h.seed(&[        seeded(            "cotton_collections",            &calendar,            1,            json!({ "kind": "calendar", "name": "Personal", "is_default": true, "workspace_id": h.workspace_id, "created_at": at }),        ),        seeded(            "cotton_events",            &event,            2,            json!({                "collection_id": calendar, "title": "Kite festival", "starts_at": "2026-10-12T09:00:00.000Z",                "ends_at": "2026-10-12T11:00:00.000Z", "all_day": false, "gcal_id": "g-kite", "sync_state": "synced",                "created_at": at, "updated_at": at,            }),        ),    ]);    event}fn event_column(h: &Harness, column: &str, id: &str) -> Value {    h.one(&format!("SELECT {column} AS value FROM cotton_events WHERE id = ?"), &[rusqlite::types::Value::Text(id.to_string())])        .and_then(|row| row.get("value").cloned())        .unwrap_or(Value::Null)}/// RULE: Deleting an event that lives only here offers Undo, and Undo brings it back at the same id with every value it showed.#[test]fn undo_of_a_local_events_delete_brings_it_back() {    let (h, _) = harness();    synced_event(&h);    let owner = |tool: &str, args: Value| {        let answer = call_tool_as_owner(&h, "device:phone", tool, args);        assert!(!answer.is_error, "{tool} refused: {}", answer.text);        answer.json()    };    let created = owner(        "create_record",        json!({ "table": "event", "data": { "title": "Dentist", "starts_at": "2026-10-15T09:30:00.000Z", "location": "Harbour clinic" } }),    );    let id = created["record"]["id"].as_str().expect("the event's id").to_string();    let deleted = owner("delete_record", json!({ "table": "event", "id": id }));    assert_eq!(deleted["change"]["undoable"], true, "{}", deleted["change"]);    assert_eq!(deleted["change"]["reason"], Value::Null);    assert!(event_column(&h, "trashed_at", &id).is_string(), "a local event's delete did not bin it");    let undone = owner("undo", json!({ "change_id": deleted["change"]["id"] }));    assert_eq!(undone["change"]["verb"], "restore");    assert_eq!(undone["record"]["id"], id.as_str());    assert_eq!(undone["record"]["data"], created["record"]["data"]);}/// RULE: Deleting an event Google knows about offers Undo, and Undo takes it out of the trash with its Google identity; nothing marks it for a push, as nothing writes to Google (Days, 20 Nov 2026).#[test]fn undo_of_a_synced_events_delete_takes_it_out_of_the_trash() {    let (h, _) = harness();    let id = synced_event(&h);    let owner = |tool: &str, args: Value| {        let answer = call_tool_as_owner(&h, "device:phone", tool, args);        assert!(!answer.is_error, "{tool} refused: {}", answer.text);        answer.json()    };    let deleted = owner("delete_record", json!({ "table": "event", "id": id }));    assert_eq!(deleted["change"]["undoable"], true, "{}", deleted["change"]);    assert_ne!(event_column(&h, "trashed_at", &id), Value::Null, "a synced event's delete trashes it");    let undone = owner("undo", json!({ "change_id": deleted["change"]["id"] }));    assert_eq!(undone["record"]["id"], id.as_str(), "{undone}");    assert_eq!(undone["record"]["data"]["title"], "Kite festival");    assert_eq!(event_column(&h, "trashed_at", &id), Value::Null);    assert_eq!(event_column(&h, "sync_state", &id), "synced");    assert_eq!(event_column(&h, "gcal_id", &id), "g-kite");}