Cotton code
255 lines · 13.8 KB · RustRaw
use super::*;use crate::shell::client::phone_tests::attached;/// RULE: Waiting since names the serving Mac's last contact event, never the read, last sync, or first failed attempt; a missing event stays unknown.#[test]fn waiting_since_is_the_serving_macs_last_heard_event() {    let mut answer = serde_json::from_str::<Vec<SyncState>>(        include_str!("sync_state_tests/answers.json")).unwrap().remove(2);    answer.this_device.synced_at = Some("2026-10-15T21:59:00Z".into());    for read_at in ["2026-10-16T00:00:00Z", "2026-10-16T01:00:00Z"] {        answer.read_at = read_at.into();        let rows = copy_rows(&answer, &Value::Null, None);        let own = rows.iter().find(|row| row["data"]["role"] == "this_device").unwrap();        assert_eq!(own["data"]["waiting_since"], "2026-10-15T22:00:00Z");        assert!(own["data"].get("synced_at").is_none());    }    answer.devices.iter_mut().find(|copy| copy.device.serving).unwrap().last_heard_at = None;    let rows = copy_rows(&answer, &Value::Null, None);    let own = rows.iter().find(|row| row["data"]["role"] == "this_device").unwrap();    assert!(own["data"].get("waiting_since").is_none());    assert_eq!(own["data"]["ambient"], "waiting_for_mac");}/// RULE: A paused local loop or an old display line is not a failed contact; a recently synced phone with a reachable Mac never reports waiting.#[test]fn a_paused_phone_does_not_turn_a_reachable_mac_into_waiting() {    let mut answer = serde_json::from_str::<Vec<SyncState>>(        include_str!("sync_state_tests/answers.json")).unwrap().remove(2);    answer.this_device.synced_at = Some(answer.read_at.clone());    let mac = answer.devices.iter_mut().find(|copy| copy.device.serving).unwrap();    mac.reachable = Some(true);    mac.last_heard_at = Some(answer.read_at.clone());    mac.unreachable_since = None;    answer.devices.iter_mut().find(|copy| !copy.device.serving).unwrap().behind.changes = Some(0);    for waiting in [0, 3] {        answer.this_device.changes_waiting = waiting;        let rows = copy_rows(&answer, &Value::from("an old display line"), None);        let own = rows.iter().find(|row| row["data"]["role"] == "this_device").unwrap();        assert!(own["data"].get("waiting_since").is_none(), "{own}");        if waiting == 0 {            assert_eq!(own["data"]["ambient"], "up_to_date");            assert_eq!(own["data"]["synced_at"], answer.read_at);        } else {            assert_eq!(own["data"]["changes_waiting"], waiting);        }    }}/// RULE: Contact proves the Mac heard, not a level replica: it is said with its age, and unknown contact and sync evidence must not become a waiting stamp or an up-to-date claim.#[test]fn contact_without_a_level_exchange_is_heard_and_unknown_stays_unknown() {    let mut answer = serde_json::from_str::<Vec<SyncState>>(        include_str!("sync_state_tests/answers.json")).unwrap().remove(2);    answer.this_device.changes_waiting = 0;    let mac = answer.devices.iter_mut().find(|copy| copy.device.serving).unwrap();    mac.reachable = Some(true);    mac.unreachable_since = None;    let rows = copy_rows(&answer, &Value::Null, None);    let own = rows.iter().find(|row| row["data"]["role"] == "this_device").unwrap();    assert_eq!(own["data"]["mac_heard_at"], "2026-10-15T22:00:00Z");    assert!(own["data"].get("ambient").is_none());    assert!(own["data"].get("synced_at").is_none());    answer.devices.iter_mut().find(|copy| copy.device.serving).unwrap().reachable = None;    let rows = copy_rows(&answer, &Value::Null, None);    let own = rows.iter().find(|row| row["data"]["role"] == "this_device").unwrap();    assert_eq!(own["data"]["ambient"], "waiting_for_mac", "nothing observed is the Mac not heard yet");    assert!(own["data"].get("waiting_since").is_none());    assert!(own["data"].get("synced_at").is_none());}/// RULE: A recent serving Mac report makes the local copy reachable; expired reports and recent non-serving Macs cannot, so a failed media fetch never misstates which Mac is away (the owner's build 290 walk).#[test]fn serving_reachability_uses_recent_contact_from_the_serving_mac() {    use cotton_client::seams::Clock;    let (dir, client, clock) = crate::shell::client::phone_tests::attached_on_a_clock();    let now = clock.now();    // Reopen with the persisted observations of a previous run: it last    // answered an hour ago and a pass failed five minutes ago. A newer Mac    // report must supersede that failure, including after a phone relaunch.    let mut line = cotton_client::sync::line::HomeLine::default();    line.answered(Default::default(), (now - chrono::Duration::hours(1)).timestamp_millis());    line.unanswered(None, (now - chrono::Duration::minutes(5)).timestamp_millis());    cotton_client::sync::line::store(&client.layout().home_lines_json(),        &[(crate::fixture::WORKSPACE.to_string(), line)].into_iter().collect());    drop(client);    let client = ClientController::new(        cotton_client::layout::Layout::new(dir.path()),        std::sync::Arc::new(crate::events::EventBus::new()),        Some("UTC".into()), None,    ).with_seams(clock.clone(), std::sync::Arc::new(cotton_client::seams::SeededRandom::default()));    client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.into()));    client.with_writer(|file| {        for id in ["synthetic-standby-a", "synthetic-serving", "synthetic-standby-b"] {            file.driver.run(                "INSERT INTO cotton_devices (id,workspace_id,device_id,name,platform,approved_at,approved_by_device,created_at,updated_at) \                 VALUES (?,?,?,'Synthetic Mac','mac','2026-09-01','self','2026-09-01','2026-09-01')",                &[Sql::Text(id.into()), Sql::Text(file.workspace_id.into()), Sql::Text(id.into())],            ).map_err(|e| e.to_string())?;        }        file.driver.run(            "INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since) \             VALUES ('synthetic-serving-fact',?,1,'synthetic-serving','synthetic-author','2026-09-01')",            &[Sql::Text(file.workspace_id.into())],        ).map_err(|e| e.to_string())?;        Ok(())    }).unwrap();    // Device reports may be ten minutes apart; use the same twenty-minute    // report window as Devices, including its boundary. This phone's own    // recent row and the other Macs must never stand in for the serving Mac.    for (serving_age, standby_age, reported_age, reachable) in [        (60, 3600, None, true),        (1260, 3600, None, false),        (1260, 0, None, false),        (1260, 0, Some(30), true),        // Inside the window but older than the pass that failed five minutes        // ago: not heard now (architect's offline-truth ruling, 17 Oct 2026).        (1200, 0, None, false),        (1201, 0, None, false),        (240, 0, None, true),    ] {        let stamp = |seconds| cotton_client::seams::iso(now - chrono::Duration::seconds(seconds));        let serving_stamp = stamp(serving_age);        let report = reported_age.map(|age| serde_json::to_string(            &cotton_core::device::reported_state::ReportedState {                last_exchange_at: Some(stamp(age)), ..Default::default()            }).unwrap());        client.with_writer(|file| {            file.driver.run("UPDATE cotton_devices SET sampled_at=?,reported_state=NULL WHERE platform='mac'",                &[Sql::Text(stamp(standby_age))]).map_err(|e| e.to_string())?;            file.driver.run("UPDATE cotton_devices SET sampled_at=?,reported_state=? WHERE device_id='synthetic-serving'",                &[Sql::Text(serving_stamp.clone()), report.clone().map(Sql::Text).unwrap_or(Sql::Null)])                .map_err(|e| e.to_string())?;            Ok(())        }).unwrap();        let answer: SyncState = serde_json::from_value(read(&client, &Map::new()).unwrap()).unwrap();        let serving = answer.devices.iter().find(|copy| copy.device.serving).unwrap();        assert_eq!(serving.device.id, "synthetic-serving");        assert_eq!(serving.reachable, Some(reachable), "serving age {serving_age}, standby age {standby_age}, reported age {reported_age:?}");        assert_eq!(serving.last_heard_at, Some(reported_age.map(stamp).unwrap_or(serving_stamp)));        if reachable { assert_eq!(serving.unreachable_since, None); }        assert_eq!(serving_away(&client), !reachable);        let trouble = super::super::media::NotFetched { reason: "synthetic fetch failure".into(), status: Some(0), waiting: None };        let refusal = super::super::media::not_fetched("synthetic-key", &trouble, serving_away(&client));        assert_eq!(refusal.code, if reachable { "unreachable_server" } else { "mac_away" });        assert_eq!(answer.this_device.id.as_deref(), Some(crate::fixture::SELF_DEVICE_ID));    }}/// RULE: A database's sync page reads its own copy offline; unavailable peer telemetry stays unknown so lack of contact cannot become an idle, reachable, or level claim.#[test]fn answers_from_the_local_copy_without_a_transport() {    let (_dir, client) = attached(); // No transport or runtime is installed.    let entry = super::super::reads::read_for("read.sync_state").expect("the read is dispatched");    let value = super::super::answer_read(&client, entry, &Map::new()).expect("offline answer");    let answer: SyncState = serde_json::from_value(value).expect("typed columns");    assert_eq!(answer.database, crate::fixture::WORKSPACE);    assert_eq!(answer.as_of, None);    assert_eq!(        answer            .devices            .iter()            .find(|copy| Some(&copy.device.id) == answer.this_device.id.as_ref())            .unwrap()            .behind            .changes,        None    );    assert!(answer        .this_device        .storage_bytes        .is_some_and(|bytes| bytes > 0));    assert!(answer        .devices        .iter()        .all(|copy| copy.behind.oldest_age_seconds.is_none()));}/// RULE: Sync activity is a closed typed value; definitions choose its words, and a sentence cannot be accepted as a new machine state.#[test]fn activity_is_typed_and_the_three_contract_examples_decode() {    let examples: Vec<SyncState> =        serde_json::from_str(include_str!("sync_state_tests/answers.json")).unwrap();    for example in examples {        let encoded = serde_json::to_value(&example).unwrap();        assert_eq!(            serde_json::from_value::<SyncState>(encoded).unwrap(),            example        );    }    assert!(        serde_json::from_value::<DoingNow>(Value::from("Waiting for your Mac to answer")).is_err()    );}#[test]fn refuses_an_unknown_database_instead_of_reading_the_personal_copy() {    let (_dir, client) = attached();    let args = serde_json::json!({"database":"not-held"})        .as_object()        .unwrap()        .clone();    assert!(read(&client, &args).is_err());}/// RULE: A last successful exchange is historical evidence, not a second/// current state. Me draws both slip slots, so a waiting copy must not also/// publish a synced caption (290 showed waiting beside synced just now).#[test]fn a_waiting_copy_never_publishes_a_synced_caption() {    let mut answer: SyncState = serde_json::from_str::<Vec<SyncState>>(        include_str!("sync_state_tests/answers.json")).unwrap().remove(2);    answer.this_device.synced_at = Some(answer.read_at.clone());    answer.devices.iter_mut().find(|copy| !copy.device.serving).unwrap().behind.changes = Some(0);    for away in [false, true] {        answer.devices.iter_mut().find(|copy| copy.device.serving).unwrap().reachable = Some(!away);        for waiting in [0, 7] {            answer.this_device.changes_waiting = waiting;            let rows = copy_rows(&answer, &Value::Null, None);            let data = rows[0]["data"].as_object().unwrap();            let current = !away && waiting == 0;            assert_eq!(data.contains_key("synced_at"), current, "{data:?}");            assert_eq!(data.get("bytes_wanted"), Some(&Value::from(0)));        }    }}/// RULE: A catch-up still under way is never "Up to date", whatever its last page counted: the cap and Me read one copy, so Me never says level while the cap over the same copy says syncing (walker 291, Personal "syncing · 4 %" beside "Up to date · synced just now").#[test]fn a_catch_up_under_way_is_never_up_to_date() {    use cotton_client::seams::Clock;    let (dir, client, clock) = crate::shell::client::phone_tests::attached_on_a_clock();    let now = clock.now().timestamp_millis();    let mut line = cotton_client::sync::line::HomeLine::default();    line.answered(Default::default(), now - 60_000);    // The pass ended with more to ask for, though its last page said none waits.    line.answered(cotton_client::sync::line::Answered { behind: true, remaining: Some(0), owed_at_start: Some(40_000), ..Default::default() }, now);    assert!(line.facts().catching_up);    cotton_client::sync::line::store(&client.layout().home_lines_json(),        &[(crate::fixture::WORKSPACE.to_string(), line)].into_iter().collect());    drop(client);    let client = ClientController::new(        cotton_client::layout::Layout::new(dir.path()),        std::sync::Arc::new(crate::events::EventBus::new()),        Some("UTC".into()), None,    ).with_seams(clock.clone(), std::sync::Arc::new(cotton_client::seams::SeededRandom::default()));    client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.into()));    let answer: SyncState = serde_json::from_value(read(&client, &Map::new()).unwrap()).unwrap();    let own = answer.devices.iter().find(|copy| Some(copy.device.id.as_str()) == answer.this_device.id.as_deref()).unwrap();    assert_eq!(own.behind.changes, None, "a catch-up under way is not level");    let rows = copies(&client, &json!({})).unwrap();    let mine = rows.iter().find(|row| row["data"]["role"] == "this_device").unwrap();    assert_ne!(mine["data"]["ambient"], "up_to_date", "{mine}");}