Cotton code
382 lines · 17.8 KB · RustRaw
//! What a launch, a run of database switches and a cold relaunch leave//! waiting to send on a phone whose person wrote nothing (295 C, walker294://! Me read "1 change waiting to send" at first launch, 2 after 13 database//! switches, 6 after a cold relaunch, then 7 and 9). Every name and row is//! synthetic.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine;use serde_json::{json, Value};use crate::handle::{CottonHandle, OpenConfig, OpenMode};fn open(home: &std::path::Path) -> CottonHandle {    CottonHandle::open(OpenConfig {        mode: OpenMode::Phone {            container_path: home.to_string_lossy().to_string(),            previous_container_path: None,        },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(URL_SAFE_NO_PAD.encode([9u8; 32])),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core")}/// A paired phone that can make databases: its personal copy founded and its/// vault unlocked, as `databases.create` asks.fn a_phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let layout = cotton_client::layout::Layout::new(dir.path());    std::fs::create_dir_all(layout.client_dir()).expect("the client folder");    std::fs::write(        layout.connection_json(),        serde_json::to_vec_pretty(&json!({            "mode": "remote",            "baseUrl": "https://server.invalid",            "workspaceId": crate::fixture::WORKSPACE,            "ownerId": crate::fixture::OWNER,            "connectedAt": "2026-10-04T09:00:00.000Z",        }))        .expect("json"),    )    .expect("the connection record");    let replica = layout.replica(crate::fixture::WORKSPACE);    std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder");    drop(crate::fixture::seeded(&replica));    let handle = open(dir.path());    let public = URL_SAFE_NO_PAD.encode(cotton_core::vault::wrap::public_of(&[31u8; 32]));    let slot = handle.client().receipt_signer_slot();    let signer = slot.get().expect("a receipt signer");    handle        .client()        .with_writer(|file| {            crate::fixture::device_row(file.driver, &signer.device_key());            cotton_client::founding::personal(                file.driver,                file.workspace_id,                signer.as_ref(),                &public,                "Synthetic Owner",                "2026-10-04T00:00:00.000Z",                1_791_072_000_000,                &mut cotton_client::seams::op_ids(std::sync::Arc::new(cotton_client::seams::SystemRandom)),            )            .map_err(|error| error.to_string())        })        .expect("the personal copy is founded");    ask(&handle, "vault.publishKey", json!({"publicKey": public}));    ask(&handle, "vault.unlock", json!({"privateKey": URL_SAFE_NO_PAD.encode([31u8; 32])}));    (dir, handle)}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    crate::methods::dispatch(handle, method, &request)        .unwrap_or_else(|error| panic!("{method} {request}: {}: {}", error.code, error.message))}fn held(handle: &CottonHandle) -> Vec<String> {    handle.client().databases().expect("the list").into_iter().map(|database| database.id).collect()}/// Run `sql` on every held copy, as a sync that took everything would leave/// it, or as rows that arrived from the serving Mac would stand.fn on_every_copy(handle: &CottonHandle, sql: &[&str]) {    for id in held(handle) {        handle            .client()            .with_writer_in(&id, |file| {                for statement in sql {                    file.driver.run(statement, &[]).map_err(|error| error.to_string())?;                }                Ok(())            })            .expect("the copy takes it");    }}/// What Me's sync line counts for `database`: `read.sync_state`'s own/// `this_device.changes_waiting`, the queue plus the held writes.fn waiting(handle: &CottonHandle, database: &str) -> u64 {    let mut request = json!({});    if database != crate::fixture::WORKSPACE {        request["database"] = json!(database);    }    let answer = ask(handle, "read.sync_state", request);    answer["this_device"]["changes_waiting"]        .as_u64()        .or_else(|| answer["thisDevice"]["changesWaiting"].as_u64())        .unwrap_or_else(|| panic!("no changes_waiting: {answer}"))}/// Which tables queued or hold a change in each copy — the failure's own words.fn queued(handle: &CottonHandle) -> Vec<String> {    let mut found = Vec::new();    for id in held(handle) {        let rows = handle            .client()            .with_file_in(&id, |file| {                file.driver                    .all(                        "SELECT 'queued ' || tbl || ' ' || kind AS what FROM _outbox \                         UNION ALL SELECT 'held ' || tbl FROM _writes WHERE held = 1",                        &[],                    )                    .map_err(|error| error.to_string())            })            .expect("the copy reads");        found.extend(rows.iter().filter_map(|row| row.text("what").map(|what| format!("{id}: {what}"))));    }    found}/// What the app asks at a ready launch (`RootView`, `.ready`): the boot and/// database reads, Home and Me, then its own passes — recurring todos and the/// people's cities.fn launch(handle: &CottonHandle) {    for (method, request) in [        ("read.boot", json!({})),        ("read.databases", json!({})),        ("databases.show", json!({"databaseId": crate::fixture::WORKSPACE})),        ("read.sync_state", json!({})),        ("read.home", json!({})),        ("read.account", json!({})),        ("read.alarms", json!({})),        ("records.list", json!({"table": "note", "page": 0, "limit": 50})),        ("routes.list", json!({})),        ("definitions.catalogue", json!({})),        ("write", json!({"tool": "materialize_todo_recurrences", "args": {"timezone": "Asia/Kolkata"}})),        ("people.fillCities", json!({})),    ] {        ask(handle, method, request);    }}/// One switch on the Databases screen: the window pins the new database and/// lets the old one go, and reads it.fn switch(handle: &CottonHandle, from: &str, to: &str) {    ask(handle, "databases.show", json!({"databaseId": to}));    ask(handle, "databases.hide", json!({"databaseId": from}));    for (method, mut request) in [        ("read.home", json!({})),        // A list every database holds: the shell's themes.        ("records.list", json!({"table": "theme", "page": 0, "limit": 50})),        ("definitions.catalogue", json!({})),    ] {        if to != crate::fixture::WORKSPACE {            request["database"] = json!(to);        }        ask(handle, method, request);    }}/// RULE: A phone that launches, switches through its databases thirteen times and relaunches cold without a person's write reads zero changes waiting to send in every database it holds, and a person's real write still counts (295 C, walker294).////// WHY: Me's line is the person's own measure of what this phone owes the/// Mac. walker294 read 1, 2, 6, 7 and 9 changes waiting on a phone whose person/// wrote nothing: a launch pass re-stamped this device's own observation/// about itself, which never travels (architect, 16 Oct 2026). The count is/// the queue's, never filtered on the way to the screen, so the writes stop/// at their source.#[test]fn a_phone_that_wrote_nothing_has_no_changes_waiting() {    let (dir, handle) = a_phone();    let made = |name: &str| crate::phone::databases::made_here(&handle, &json!({"name": name, "toolkit": "blank"})).expect("a database")["databaseId"]        .as_str()        .expect("a database id")        .to_string();    let garden = made("Garden");    let allotment = made("Allotment");    // The household as the serving Mac left it: a daily todo whose occurrences    // are made, the zone claimed, a person whose city is filled — and every    // change of it already taken.    let todo = ask(&handle, "write", json!({"tool": "create_todo", "args": {"title": "Water the plants"}}));    let todo = todo["answer"]["id"].as_str().expect("a todo id").to_string();    ask(&handle, "write", json!({"tool": "make_todo_recurring", "args": {"todoId": todo, "rrule": "FREQ=DAILY", "dtstart": "2026-10-01T03:30:00.000Z", "timezone": "Asia/Kolkata"}}));    ask(&handle, "write", json!({"tool": "create_person", "args": {"fullName": "Ada Example", "timezone": "Europe/Paris"}}));    launch(&handle);    on_every_copy(&handle, &["DELETE FROM _outbox", "UPDATE _writes SET held = 0", "UPDATE _tombstones SET held = 0"]);    launch(&handle);    let order = [crate::fixture::WORKSPACE.to_string(), garden, allotment];    let mut at = order[0].clone();    for n in 1..=13 {        let to = order[n % order.len()].clone();        switch(&handle, &at, &to);        at = to;    }    drop(handle);    let handle = open(dir.path());    launch(&handle);    for database in held(&handle) {        assert_eq!(waiting(&handle, &database), 0, "{database} owes nothing: {:?}", queued(&handle));    }    // A person's own write is still a change waiting — every op of it.    let wrote = ask(&handle, "write", json!({"tool": "create_todo", "args": {"title": "Buy seeds"}}));    let ops = wrote["queued"].as_u64().expect("the write says what it queued");    assert!(ops >= 1, "{wrote}");    assert_eq!(waiting(&handle, crate::fixture::WORKSPACE), ops, "{:?}", queued(&handle));}/// A phone running the app whose manifest is `flavour`, started on its own.fn an_app(flavour: &str) -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let path = match flavour {        "cotton" => cotton_store::manifest_dir().join("../../apps/cotton/App/CottonManifest/flavour.json"),        flavour => cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours").join(flavour).join("flavour.json"),    };    let text = std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{} reads: {error}", path.display()));    let manifest: Value = serde_json::from_str(&text).expect("a manifest");    let handle = CottonHandle::open(OpenConfig {        mode: OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(manifest),    })    .expect("an open core");    ask(&handle, "workspace.startLocal", json!({"deviceName": "An invented phone"}));    (dir, handle)}fn zone_rows(handle: &CottonHandle) -> (i64, i64) {    handle        .client()        .with_file(|file| {            let count = |sql: &str| file.driver.get(sql, &[]).map_err(|error| error.to_string()).map(|row| row.and_then(|row| row.int("n")).unwrap_or(0));            Ok((count("SELECT COUNT(*) AS n FROM cotton_news_settings")?, count("SELECT (SELECT COUNT(*) FROM _outbox WHERE tbl = 'cotton_news_settings') + (SELECT COUNT(*) FROM _writes WHERE held = 1 AND tbl = 'cotton_news_settings') AS n")?))        })        .expect("the copy reads")}/// RULE (owner, 21 Nov 2026: Books, Music, Cinemas and Story said "Waiting to/// send 1 row" for ever): the launch pass claims the database's zone only in/// an app whose kit carries `news_settings`. No app's kit does, so Books,/// Music, Cinemas, Story, Notes and Days write no row of it (a claim/// their copy could never seal); Cotton, which keeps to no kit, claims it.#[test]fn only_an_app_whose_kit_carries_the_zone_claims_it() {    for flavour in ["books", "music", "cinemas", "story", "notes", "days"] {        let (_dir, handle) = an_app(flavour);        ask(&handle, "write", json!({"tool": "materialize_todo_recurrences", "args": {"timezone": "Asia/Kolkata"}}));        assert_eq!(zone_rows(&handle), (0, 0), "{flavour} claims no zone: {:?}", queued(&handle));    }    let (_dir, handle) = an_app("cotton");    ask(&handle, "write", json!({"tool": "materialize_todo_recurrences", "args": {"timezone": "Asia/Kolkata"}}));    assert_eq!(zone_rows(&handle), (1, 1), "Cotton claims the zone");}/// A recurring todo's day rolling over, on a phone whose copy a Mac serves and/// on one that holds its own database alone (coordinator's decision (b)).mod day_roll {    use std::sync::Arc;    use serde_json::{json, Map, Value};    use crate::shell::client::phone_tests::attached_on_a_clock_in;    use crate::shell::client::ClientController;    use cotton_client::seams::FixedClock;    fn args(value: Value) -> Map<String, Value> {        value.as_object().cloned().unwrap_or_default()    }    fn occurrences(client: &ClientController) -> i64 {        client            .with_file(|file| {                file.driver                    .get("SELECT COUNT(*) AS n FROM cotton_todos WHERE recurrence_id IS NOT NULL", &[])                    .map_err(|error| error.to_string())                    .map(|row| row.and_then(|row| row.int("n")).unwrap_or(0))            })            .expect("the copy reads")    }    /// A daily todo due today, made by the person and already taken by the    /// Mac: the queue empty and nothing held.    fn a_phone_with_a_daily_todo(mode: &str) -> (tempfile::TempDir, Arc<ClientController>, Arc<FixedClock>) {        let (dir, client, clock) = attached_on_a_clock_in(mode);        let todo = client.write("create_todo", &args(json!({"title": "Water the plants"}))).expect("a todo");        let todo = todo["answer"]["id"].as_str().expect("a todo id").to_string();        client            .write(                "make_todo_recurring",                &args(json!({"todoId": todo, "rrule": "FREQ=DAILY", "dtstart": "2026-09-01T03:30:00.000Z", "timezone": "Asia/Kolkata"})),            )            .expect("it repeats");        // The household's zone was claimed long ago: the claim is once-only,        // and what this asks is what a day rolling over costs.        client            .write("materialize_todo_recurrences", &args(json!({"timezone": "Asia/Kolkata"})))            .expect("the first pass claims the zone");        client            .with_writer(|file| {                for sql in ["DELETE FROM _outbox", "UPDATE _writes SET held = 0", "UPDATE _tombstones SET held = 0"] {                    file.driver.run(sql, &[]).map_err(|error| error.to_string())?;                }                Ok(())            })            .expect("synced");        (dir, client, clock)    }    /// A day later, the app relaunched: `RootView`'s launch passes.    fn a_day_later_relaunched(client: &ClientController, clock: &FixedClock) -> Value {        clock.advance(chrono::Duration::days(1));        client.detach();        let pass = client            .write("materialize_todo_recurrences", &args(json!({"timezone": "Asia/Kolkata"})))            .expect("the launch pass");        crate::phone::people_city::fill(client).expect("the cities pass");        pass["answer"].clone()    }    /// RULE: Only the writer of record mints a recurring todo's occurrence as days pass — a phone whose copy a Mac serves reads zero changes waiting after a day rolls over and it relaunches, and mints nothing; a phone holding its own database with no Mac (an offline writer) still mints the day's occurrence (coordinator's decision (b), 295 C, walker294).    ///    /// WHY: the phone's launch pass minted the day's occurrence on a copy the    /// Mac's hourly tick also mints: four changes waiting (the todo, the    /// template's mark, two history rows) on a phone whose person wrote    /// nothing. One rule (`recurrence::mints_occurrences`) decides it for the    /// tick and the pass; the serving Mac's side is held by `cotton-server`'s    /// recurrence worker tests and `cotton-tools`' `mcp_recurrence`.    #[test]    fn only_the_writer_of_record_mints_a_days_occurrence() {        let (_dir, client, clock) = a_phone_with_a_daily_todo("remote");        let before = occurrences(&client);        let pass = a_day_later_relaunched(&client, &clock);        assert_eq!(pass["mints"], json!(false), "{pass}");        assert_eq!(occurrences(&client), before, "a copy the Mac serves mints nothing");        let entry = crate::phone::reads::read_for("read.sync_state").expect("read.sync_state");        let state = crate::phone::answer_read(&client, entry, &Map::new()).expect("the sync line");        assert_eq!(state["this_device"]["changes_waiting"], json!(0), "{state}");        let (_dir, alone, clock) = a_phone_with_a_daily_todo("local");        // One live copy per repeating to-do (882e949a7): the open occurrence is        // the series' only one until it is done, so the person does today's        // first, and the next day's is the one a day later mints.        let open: Vec<String> = alone            .with_file(|file| {                file.driver                    .all("SELECT id FROM cotton_todos WHERE recurrence_id IS NOT NULL AND status = 'open'", &[])                    .map_err(|error| error.to_string())                    .map(|rows| rows.iter().filter_map(|row| row.text("id").map(str::to_string)).collect())            })            .expect("the open occurrences");        assert!(!open.is_empty(), "the first pass made today's occurrence");        for id in open {            alone.write("update_todo", &args(json!({"id": id, "status": "done"}))).expect("today's is done");        }        let before = occurrences(&alone);        let pass = a_day_later_relaunched(&alone, &clock);        assert_eq!(pass["mints"], json!(true), "{pass}");        assert!(pass["created"].as_u64().unwrap_or(0) >= 1, "{pass}");        assert!(occurrences(&alone) > before, "a device alone with its database still mints");    }}