use super::*; use cotton_core::rules::sync_state::SyncState; fn answer(client: &ClientController) -> SyncState { serde_json::from_value(crate::phone::sync_state::read(client, &serde_json::Map::new()).unwrap()) .unwrap() } /// RULE: Behind is the serving copy's unapplied receipts; local unsent writes must only increase changes_waiting, and a later failure must preserve the last observed incoming backlog offline. #[test] fn sync_state_counts_only_the_serving_receipts_this_copy_has_not_applied() { let (dir, client) = phone_tests::attached(); let serving = crate::fixture::seeded(&dir.path().join("synthetic-serving.db")); let cursors = cotton_store::cursors::seen_ceiling(&serving).unwrap(); use cotton_store::mint::{self, Act, Change, Clock, Held, History}; let mut ids = cotton_store::protocol::ulid::Monotonic::new(|bytes: &mut [u8]| bytes.fill(7)); mint::mint( &serving, &Act { actor: cotton_store::fixtures::fixture_actor(), verb: "synthetic-incoming".into(), history: History::None, changes: vec![Change::create( "cotton_todos", "waiting-on-phone", json!({ "workspace_id":crate::fixture::WORKSPACE,"title":"Synthetic incoming change", "created_at":"2026-10-01T10:00:00Z","updated_at":"2026-10-01T10:00:00Z" }) .as_object() .unwrap() .clone(), )], }, &Clock::wall(client.now().timestamp_millis()), &mut ids, Held::Served, ) .unwrap(); let remaining = cotton_store::changes::receipts_owed(&serving, &cursors).unwrap(); assert!(remaining > 0); let report = cotton_client::sync::Reported { pushed: 0, pulled: 0, behind: true, remaining: Some(remaining), owed_at_start: Some(remaining), unsent: 0, handed: 0, passed: 0, }; client.say_reported(crate::fixture::WORKSPACE, Some(report), None, None); client.say_reported( "synthetic-other-database", Some(cotton_client::sync::Reported { remaining: Some(remaining + 100), ..report }), None, None, ); let before = answer(&client); client .write( "create_todo", &json!({"title":"Synthetic outgoing change"}) .as_object() .unwrap() .clone(), ) .unwrap(); client.say_reported(crate::fixture::WORKSPACE, None, None, None); let offline = answer(&client); assert!(offline.this_device.changes_waiting > before.this_device.changes_waiting); let local = offline .devices .iter() .find(|copy| Some(©.device.id) == offline.this_device.id.as_ref()) .unwrap(); assert_eq!(local.behind.changes, Some(remaining)); assert_eq!(offline.as_of, before.as_of); // The persisted observation, rather than a transport call, answers after restart. let reopened = ClientController::new( client.layout().clone(), Arc::new(EventBus::new()), None, None, ); let after_restart = answer(&reopened); let local = after_restart .devices .iter() .find(|copy| Some(©.device.id) == after_restart.this_device.id.as_ref()) .unwrap(); assert_eq!(local.behind.changes, Some(remaining)); assert_eq!(after_restart.as_of, before.as_of); }