//! The pass half of `apps/cotton/__tests__/client/sync.test.ts`, over ONE verb.use std::collections::BTreeMap;use cotton_store::protocol::types::{CottonOp, ExchangeRequest, ExchangeResponse, PushRejection,};usesuper::*;usecrate::test_support::{ accepted, open_test_replica, queue_one_change, queue_one_change_for, Call, FakeTransport, WORKSPACE,};usecrate::transport::ServerRefusal;const NOW: &str = "2026-09-08T10:00:00.000Z";/// One op a peer is handing us, of a real table with a real workspace.fn theirs(row_id: &str, hlc: &str) -> CottonOp {letmut patch = serde_json::Map::new(); patch.insert("workspace_id".to_string(), WORKSPACE.into()); patch.insert("title".to_string(), "From the other side".into()); patch.insert("status".to_string(), "open".into()); patch.insert("created_at".to_string(), NOW.into()); patch.insert("updated_at".to_string(), NOW.into());crate::test_support::peer_create( &format!("01J00000000000000000{row_id:0>6}"),"cotton_todos", row_id, patch, hlc,"device:b", )}fn page(ops: Vec<CottonOp>, has_more: bool) -> ExchangeResponse {let cursors = ops .last() .map(|op| BTreeMap::from([(op.device_id.clone(), op.hlc.clone())])) .unwrap_or_default();letmut seen = cursors.clone(); seen.insert("origin".to_string(), format!("origin:cotton_workspaces:{WORKSPACE}"));ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WORKSPACE.to_string(), schema_version: Some(cotton_store::schema::ddl::SCHEMA_VERSION), ops, cursors, has_more, applied_rows: BTreeMap::new(), rejected: Vec::new(), seen, serving_epoch: None, server_time: None, restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }}#[test]fn one_call_carries_the_queue_up_and_the_news_down() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let transport = FakeTransport::default();let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.pushed, 2); // the author's fact, then the change assert_eq!( transport.calls(), vec![Call::Exchange { ops: 2 }],"ONE round trip where a push and a pull used to be two" );}#[test]fn it_exchanges_in_batches_of_one_thousand_the_peers_own_ceiling() {// The number itself is the assertion: a peer refuses more than 1,000// (`MAX_OPS_PER_EXCHANGE`), and a phone's old default of 200 would make a// 32k import five times as many round trips for no benefit. assert_eq!(cotton_store::exchange::EXCHANGE_OPS_BATCH, 1_000);}#[test]fn a_page_is_counted_in_rows_and_the_number_is_the_declaration() { assert_eq!(cotton_store::protocol::types::EXCHANGE_PAGE_ROWS, 500); assert_eq!(EXCHANGE_PAGES, 10);}#[test]fn push_only_is_one_exchange_an_import_calls_it_three_thousand_times() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let transport = FakeTransport::default();let pushed = push_only(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a push"); assert_eq!(pushed, 2); // the author's fact, then the change assert_eq!(transport.calls(), vec![Call::Exchange { ops: 2 }]);}#[test]fn a_failed_exchange_leaves_the_ops_queued_so_it_is_not_a_failed_import() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let transport = FakeTransport::default(); transport.refuse(ServerRefusal::offline("offline"));let failure = push_only(&replica.driver, &mut &transport, WORKSPACE, NOW).expect_err("a refusal"); assert!(matches!(failure, CycleFailure::Transient { .. })); assert_eq!(failure.message(), "offline"); assert_eq!( cotton_store::outbox::pending_count(&replica.driver).expect("a count"),2, // the author's fact and the change"the ops stay queued by construction" );}#[test]fn a_terminal_device_refusal_is_told_apart_by_its_code_and_carries_the_sentence() {let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default(); transport.refuse(ServerRefusal::new("server 403: this device is not approved", 403) .with_code("device_not_approved"), );let failure = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect_err("a refusal");match failure {CycleFailure::TerminalDevice { code, sentence, .. } => { assert_eq!(code, "device_not_approved"); assert!( sentence.contains("approve it from a device that already is"),"{sentence}" ); } other => panic!("expected a terminal refusal, got {other:?}"), }}#[test]fn a_route_that_is_gone_is_transient_so_the_outbox_survives_the_release_order() {// The whole safety of removing push and pull: a build one release behind// gets a 404, reads it as a bad afternoon, and keeps every queued write.// Delay, never data.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let transport = FakeTransport::default(); transport.refuse(ServerRefusal::new("server 404: no such route", 404));let failure = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect_err("a refusal"); assert!(!failure.is_terminal()); assert_eq!( cotton_store::outbox::pending_count(&replica.driver).expect("a count"),2// the author's fact and the change );}#[test]fn a_rate_limit_carries_the_servers_own_retry_after_rather_than_stopping_anything() {let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default(); transport.refuse(ServerRefusal::new("server 429: slow down", 429) .with_code("rate_limited") .retry_after(90), );let failure = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect_err("a refusal"); assert!(!failure.is_terminal()); assert!(failure.answered(), "a typed rate limit is an answer, not silence"); assert_eq!(failure.retry_after_seconds(), Some(90));}#[test]fn a_pass_that_hit_its_page_cap_reports_behind_rather_than_pretending_to_be_current() {let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default(); *transport.has_more.lock().expect("the flag") = true;let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass");// The fake answers `hasMore` once, so the pass takes a second exchange and// then settles — `behind` is false, and the SECOND call is the evidence the// cap is honoured rather than a single answer being read as the whole tail. assert!(!report.behind); assert_eq!( transport.calls(), vec![Call::Exchange { ops: 0 }, Call::Exchange { ops: 0 }] );}#[test]fn the_pending_count_of_a_closed_file_is_an_absence_not_a_failure() {let (_dir, _layout, replica) = open_test_replica(); assert_eq!(current_pending(&replica.driver), Some(0)); queue_one_change(&replica, "a synthetic todo");// The file's first write queues its author's fact ahead of the change. assert_eq!(current_pending(&replica.driver), Some(2));}/// RULE: Unsent counts the writes held for the Mac's time as well as the outbox, and says how many of them are held — a device holding a write never reports 0 unsent.////// 13 Oct 2026: the phone said unsent 0 while it held the owner's two/// approvals, because the count read the outbox alone.#[test]fn unsent_counts_the_writes_held_for_the_macs_time() {let (_dir, _layout, replica) = open_test_replica();crate::test_support::hold_one_change(&replica, "a synthetic todo");let held = current_held(&replica.driver).expect("counts"); assert!(held > 0, "the write is held"); assert_eq!(current_pending(&replica.driver), Some(held), "and unsent says so");}// ── the report (design ADDENDUM B7) ─────────────────────────────────────────#[test]fn a_report_accumulates_across_pages() {let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default(); transport.script([ page( vec![theirs("t1", "1700000000001:0000:device:b")],true, ), page( vec![theirs("t2", "1700000000002:0000:device:b")],false, ), ]);let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.report.received.get("cotton_todos"), Some(&2)); assert_eq!(report.pulled, 2, "the sum of both pages, not the last one"); assert_eq!(transport.calls().len(), 2);}/// RULE: What a pass says still waits is the serving Mac's LATEST answer, never a sum or a maximum over pages — each page's count is of what was left after it, and the Sync line counts down from it.#[test]fn what_remains_is_the_macs_latest_answer_not_a_sum_over_pages() {let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default();letmut first = page(vec![theirs("t1", "1700000000001:0000:device:b")], true); first.behind_by = Some(900); first.wake_refusal = Some("the vault holds no Apple push key".to_string());letmut last = page(vec![theirs("t2", "1700000000002:0000:device:b")], true); last.behind_by = Some(899); transport.script([first, last, page(Vec::new(), false)]);let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.remaining, None, "the last answer did not count, so nothing is said"); assert_eq!(report.wake_refusal, None, "nor did it carry a refusal");let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default();letmut first = page(vec![theirs("t1", "1700000000001:0000:device:b")], true); first.behind_by = Some(900);letmut last = page(vec![theirs("t2", "1700000000002:0000:device:b")], false); last.behind_by = Some(0); last.wake_refusal = Some("the vault holds no Apple push key".to_string()); transport.script([first, last]);let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.remaining, Some(0), "level after the last page"); assert_eq!(report.wake_refusal.as_deref(), Some("the vault holds no Apple push key"));}/// RULE: A pass reports the two halves of a catch-up's whole as they are said — what the serving Mac counted the device owed when the catch-up began, from whichever answer carried it, and the rows still in this device's outbox when the pass ended — so the line's percent is measured against a start nobody guessed.#[test]fn a_pass_reports_what_was_owed_at_the_start_and_what_is_still_unsent() {let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default();// The Mac's count of the start is not ready for the first answer (it is// counted outside the hold, after it) and is on the second.letmut first = page(vec![theirs("t1", "1700000000001:0000:device:b")], true); first.behind_by = Some(10_000);letmut second = page(vec![theirs("t2", "1700000000002:0000:device:b")], true); second.behind_by = Some(10_000); second.owed_at_start = Some(58_900); second.owed_by_table = Some(BTreeMap::from([("cotton_emails".to_string(), 58_900)]));// An answer that says nothing of it does not take it back.letmut third = page(Vec::new(), false); third.behind_by = Some(9_000); transport.script([first, second, third]);let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.owed_at_start, Some(58_900)); assert_eq!( report.owed_by_table,Some(BTreeMap::from([("cotton_emails".to_string(), 58_900)])),"and the same whole by table" ); assert_eq!(report.remaining, Some(9_000)); assert_eq!(report.unsent, 0, "nothing was waiting to go");// What is unsent is the outbox as the pass left it, whatever it holds.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "one");let transport = FakeTransport::default(); transport.script([page(Vec::new(), false)]);let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!( i64::try_from(report.unsent).ok(), current_pending(&replica.driver),"the outbox, counted after the pass" );}#[test]fn sent_comes_from_the_peers_answer_not_our_count() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "one"); queue_one_change(&replica, "two");let transport = FakeTransport::default();// THREE ops went up (the author's fact first, then two todos) and the// peer says ONE TODO ROW landed — a derived id both devices minted, or one// row arriving as two ops. The report says one. transport.script([ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WORKSPACE.to_string(), schema_version: Some(cotton_store::schema::ddl::SCHEMA_VERSION), ops: Vec::new(), cursors: BTreeMap::new(), has_more: false, applied_rows: BTreeMap::from([("cotton_todos".to_string(), 1)]), rejected: Vec::new(), seen: cotton_store::cursors::cursor_ceiling(&replica.driver).expect("the peer saw the batch"), serving_epoch: None, server_time: None, restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }]);let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.report.sent.get("cotton_todos"), Some(&1)); assert_eq!(report.pushed, 1, "the PEER's answer, never our op count"); assert_eq!(transport.calls(), vec![Call::Exchange { ops: 3 }]);}#[test]fn a_rejected_op_is_absent_from_applied() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "doomed");let queued: Vec<String> = replica .driver .all("SELECT op_id FROM _outbox", &[]) .expect("reads") .into_iter() .filter_map(|row| row.text("op_id").map(str::to_string)) .collect();let transport = FakeTransport::default(); transport.script([ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WORKSPACE.to_string(), schema_version: Some(cotton_store::schema::ddl::SCHEMA_VERSION), ops: Vec::new(), cursors: BTreeMap::new(), has_more: false,// NOT `{"cotton_todos": 0}` — absent. A rejected op did not move a row,// and a zero would be a table in the report that nothing happened to. applied_rows: BTreeMap::new(), rejected: vec![PushRejection::final_reason( &queued[0],"CHECK constraint failed", )], seen: cotton_store::cursors::cursor_ceiling(&replica.driver).expect("the peer saw the batch"), serving_epoch: None, server_time: None, restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }]);let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert!(report.report.sent.is_empty()); assert_eq!(report.pushed, 0);let parked = cotton_store::rejected::list_parked(&replica.driver, 10).expect("the list"); assert_eq!(parked.len(), 1, "and it is not lost in silence");}#[test]fn the_data_events_tables_are_the_reports_keys() {// `CycleReport::tables` is what the FFI turns into the `data` event a// screen repaints on, and it is the report's own keys rather than a second// piece of bookkeeping that could disagree with it.let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default(); transport.script([page( vec![theirs("t1", "1700000000001:0000:device:b")],false, )]);let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.tables, vec!["cotton_todos".to_string()]); assert_eq!( report.tables, report.report.received.keys().cloned().collect::<Vec<_>>() );}#[test]fn a_pass_that_moved_nothing_names_no_table_at_all() {let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default();let report = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert!(report.tables.is_empty());}// ── The file is nobody's while the server is asked ─────────────────────────/// A transport that, on every round trip, checks whether the replica's mutex/// is free — which is the whole point of `run_cycle_paged`: a screen's read/// takes that mutex, and a pass that held it across the network made every/// read wait for the server.structLockWatching<'a> { inner: &'a FakeTransport, replica: &'a std::sync::Mutex<crate::Replica>,/// One entry per round trip: was the file free while the server was asked? free: std::sync::Mutex<Vec<bool>>,}implcrate::transport::RefusalAwareforLockWatching<'_> {fn last_refusal(&self) -> Option<ServerRefusal> { (&self.inner).last_refusal() }}impl cotton_store::exchange::SyncTransportforLockWatching<'_> {fn exchange(&mutself, request: &ExchangeRequest) -> Result<ExchangeResponse, String> {let free = self.replica.try_lock().is_ok();self.free.lock().expect("the log").push(free); (&mut &*self.inner).exchange(request) }}#[test]fn the_paged_cycle_holds_the_file_for_no_round_trip_at_all() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let replica = std::sync::Mutex::new(replica);let fake = FakeTransport::default();// Two pages, so the cursors are re-read between them. *fake.has_more.lock().expect("the flag") = true;letmut transport = LockWatching { inner: &fake, replica: &replica, free: std::sync::Mutex::new(Vec::new()), };let report = run_cycle_paged(&replica, &mut transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.pushed, 2); // the author's fact, then the change assert_eq!( fake.calls(), vec![Call::Exchange { ops: 2 }, Call::Exchange { ops: 0 }] );let free = transport.free.lock().expect("the log").clone(); assert_eq!( free, vec![true, true],"the file is free during EVERY round trip now — the push half no longer holds it" );}#[test]fn the_paged_cycle_reports_what_the_whole_cycle_reports() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let transport = FakeTransport::default();let whole = run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass");let (_dir2, _layout2, replica2) = open_test_replica(); queue_one_change(&replica2, "a synthetic todo");let replica2 = std::sync::Mutex::new(replica2);let transport2 = FakeTransport::default();let paged = run_cycle_paged(&replica2, &mut &transport2, WORKSPACE, NOW).expect("a pass"); assert_eq!(paged, whole); assert_eq!(transport2.calls(), transport.calls());}#[test]fn the_default_answer_tallies_a_row_once_however_many_ops_named_it() {let request = ExchangeRequest { takes_copy: false, parks_waiting: false, workspace_id: WORKSPACE.to_string(), cursors: BTreeMap::new(), ops: vec![ theirs("t1", "1700000000001:0000:device:b"), theirs("t1", "1700000000002:0000:device:b"), theirs("t2", "1700000000003:0000:device:b"), ], limit: None, schema_version: Some(cotton_store::schema::ddl::SCHEMA_VERSION), schema_floor: None, handed_over_epoch: None, handing_over_to: None, serving_author: None, }; assert_eq!( accepted(&request, false).applied_rows.get("cotton_todos"),Some(&2) );}#[test]fn a_pass_hands_over_what_the_peer_has_not_seen_even_with_an_empty_queue() {// THE ORDINARY CYCLE DOES THIS — there is no join-shaped second path. The// queue is emptied first, which is what a device that already synced its// rows to some other Mac looks like: the life is here, the outbox is not.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo"); replica .driver .run("DELETE FROM _outbox", &[]) .expect("the queue empties");let transport = FakeTransport::default();// The peer's first answer says where it is: nowhere at all. transport.script([ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WORKSPACE.to_string(), schema_version: Some(cotton_store::schema::ddl::SCHEMA_VERSION), ops: Vec::new(), cursors: BTreeMap::new(), has_more: false, applied_rows: BTreeMap::new(), rejected: Vec::new(), seen: BTreeMap::new(), serving_epoch: None, server_time: None, restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }]); run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass");let calls = transport.calls(); assert_eq!(calls.len(), 2, "the pass asked, learnt, then handed over"); assert_eq!( calls[0],Call::Exchange { ops: 0 },"nothing is queued, so the first call carries nothing" );letCall::Exchange { ops } = calls[1]; assert!( ops > 0,"the second call handed over the rows the peer had not seen" );}#[test]fn a_drain_hands_over_the_queue_and_never_goes_looking_for_more() {// `push_only` is what an import calls after every batch — 3,421 times for// this Mac's messages. Reading this file's ceiling each time to see what// the server has not seen is a `GROUP BY` per replicated table, and the// minute's cycle does it once per pass anyway.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo"); replica .driver .run("DELETE FROM _outbox", &[]) .expect("the queue empties");let transport = FakeTransport::default(); transport.script([ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WORKSPACE.to_string(), schema_version: Some(cotton_store::schema::ddl::SCHEMA_VERSION), ops: Vec::new(), cursors: BTreeMap::new(), has_more: false, applied_rows: BTreeMap::new(), rejected: Vec::new(), seen: BTreeMap::new(), serving_epoch: None, server_time: None, restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }]); push_only(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a drain"); assert_eq!( transport.calls(), vec![Call::Exchange { ops: 0 }],"a drain went looking for a catch-up" );}// ─────────────────────────────────────────────────────────────────────────────// THE DRAIN: every pass offers the oldest parked writes to the fold again// ─────────────────────────────────────────────────────────────────────────────const SESSION: &str = "88880000-0000-4000-8000-000000000002";const PROMPT: &str = "88880000-0000-4000-8000-000000000003";/// A peer's prompt, whole — and refused while its session is missing, which is/// the shape of 826 of the parks one standby Mac was carrying.fn their_prompt() -> CottonOp {letmut patch = serde_json::Map::new(); patch.insert("id".to_string(), PROMPT.into()); patch.insert("workspace_id".to_string(), WORKSPACE.into()); patch.insert("session_id".to_string(), SESSION.into()); patch.insert("seq".to_string(), 1.into()); patch.insert("ts".to_string(), NOW.into()); patch.insert("role".to_string(), "user".into()); patch.insert("text".to_string(), "does the drain run on its own".into()); patch.insert("created_at".to_string(), NOW.into()); patch.insert("updated_at".to_string(), NOW.into());crate::test_support::peer_create("01J0000000000000000PROMPT","cotton_prompts", PROMPT, patch,"1790000000000:0000:device:b","device:b", )}/// The session the prompt is owned by — present before the prompt lands.fn session_arrives(db: &cotton_store::driver::Driver) { db.run("INSERT INTO cotton_sessions \ (id, workspace_id, tool, last_active_at, created_at, updated_at) \ VALUES (?,?,?,?,?,?)", &[ rusqlite::types::Value::Text(SESSION.to_string()), rusqlite::types::Value::Text(WORKSPACE.to_string()), rusqlite::types::Value::Text("claude-code".to_string()), rusqlite::types::Value::Text(NOW.to_string()), rusqlite::types::Value::Text(NOW.to_string()), rusqlite::types::Value::Text(NOW.to_string()), ], ) .expect("the session lands"); cotton_tools::test_fixtures::reconcile(&db, "cotton_sessions");}fn parked_pulls(db: &cotton_store::driver::Driver) -> usize { cotton_store::rejected::list_parked(db, 100) .expect("the parked list") .iter() .filter(|row| row.direction == "pull") .count()}#[test]fn a_pass_drains_parked_writes_whose_cause_no_page_will_ever_name() {let (_dir, _layout, replica) = open_test_replica();let transport = FakeTransport::default();// This file's first write mints its own author's fact, and from then on a// peer's write from an author it holds no fact for waits rather than lands. queue_one_change_for(&replica, WORKSPACE, "this file has an author"); session_arrives(&replica.driver);// The prompt arrives before its author's fact and is parked — kept whole,// and out of reach of any page-scoped retry from here on. transport.script([page(vec![their_prompt()], false)]); run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(parked_pulls(&replica.driver), 1); author_arrives(&replica.driver);// A pass that brings NOTHING. The sweep still runs, and that is the whole// difference between a replica that converges on its own and one that// waits for somebody to press something. run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a second pass"); assert_eq!(parked_pulls(&replica.driver), 0);let text = replica .driver .get("SELECT text FROM cotton_prompts WHERE id = ?", &[rusqlite::types::Value::Text(PROMPT.to_string())], ) .expect("reads") .and_then(|row| row.text("text").map(str::to_string)); assert_eq!(text.as_deref(), Some("does the drain run on its own"));}/// The prompt's author's fact, arriving by a road this pass knows nothing/// about — folded straight in, so nothing retries what waited on it: no page/// will ever name the prompt again, and only the cycle's own sweep reaches it.fn author_arrives(db: &cotton_store::driver::Driver) {let fact = cotton_tools::test_fixtures::author_fact( WORKSPACE,"device:b","1789999999999:0000:device:b", );let folded = cotton_store::fold::fold_ops(db, std::slice::from_ref(&fact)).expect("the fact folds"); assert!(folded.applied.contains(&fact.op_id), "{folded:?}");}#[test]fn the_drain_is_bounded_so_a_file_full_of_parks_costs_a_pass_the_same_every_time() {// A rate, not a limit: the cost of a pass on a file carrying twenty// thousand parked writes is the same as on one carrying five hundred. assert_eq!(cotton_store::rejected::PARK_SWEEP_OPS, 500);}// ── The push-only pass, with the paged cycle's discipline ─────────────────//// Until 2026-09-24 every write on the phone ran `push_only` from inside the// replica's mutex, and every `read.*` shares that mutex: a todo ticked while// the Mac was slow to answer queued every screen behind a 60 s request. The// push is the loop's now, and the loop's push-only pass holds the file for a// batch and a fold, never for the round trip./// What `_outbox` recorded about one op's last attempt.fn attempt_recorded(replica: &crate::Replica) -> (i64, Option<String>) {let row = replica .driver .get("SELECT attempts, last_error FROM _outbox LIMIT 1", &[]) .expect("a read") .expect("the queued op"); ( row.int("attempts").unwrap_or(-1), row.text("last_error").map(str::to_string), )}#[test]fn the_push_only_pass_holds_the_file_for_no_round_trip_at_all() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let replica = std::sync::Mutex::new(replica);let fake = FakeTransport::default();letmut transport = LockWatching { inner: &fake, replica: &replica, free: std::sync::Mutex::new(Vec::new()), };let pushed = push_only_paged(&replica, &mut transport, WORKSPACE, NOW).expect("a push"); assert_eq!(pushed, 2); // the author's fact, then the change assert_eq!(fake.calls(), vec![Call::Exchange { ops: 2 }]);let free = transport.free.lock().expect("the log").clone(); assert_eq!( free, vec![true],"the file is FREE while the server is asked — a screen's read does not wait for the push" );let replica = replica.lock().expect("the replica"); assert_eq!( cotton_store::outbox::pending_count(&replica.driver).expect("a count"),0,"and the answer was folded once the file was taken back" );}#[test]fn the_push_only_pass_answers_what_push_only_answers() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let transport = FakeTransport::default();let whole = push_only(&replica.driver, &mut &transport, WORKSPACE, NOW).expect("a push");let (_dir2, _layout2, replica2) = open_test_replica(); queue_one_change(&replica2, "a synthetic todo");let replica2 = std::sync::Mutex::new(replica2);let transport2 = FakeTransport::default();let paged = push_only_paged(&replica2, &mut &transport2, WORKSPACE, NOW).expect("a push"); assert_eq!(paged, whole); assert_eq!(transport2.calls(), transport.calls());}#[test]fn a_push_only_pass_that_failed_in_the_air_keeps_the_op_and_records_the_attempt() {// The same three things `exchange_once` does on a transport failure, for a// caller that let go of the file to ask: the op stays, the attempt is// written on it, and the failure is classified off the transport's refusal.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let replica = std::sync::Mutex::new(replica);let transport = FakeTransport::default(); transport.refuse(ServerRefusal::offline("offline"));let failure = push_only_paged(&replica, &mut &transport, WORKSPACE, NOW).expect_err("a refusal"); assert!(matches!(failure, CycleFailure::Transient { .. })); assert_eq!(failure.message(), "offline");let replica = replica.lock().expect("the replica"); assert_eq!( cotton_store::outbox::pending_count(&replica.driver).expect("a count"),2, // the author's fact and the change"the op stays queued by construction" ); assert_eq!( attempt_recorded(&replica), (1, Some("offline".to_string())),"and the attempt is on the row for a person to read" );}#[test]fn an_answer_from_another_file_is_refused_and_nothing_in_it_is_taken() {// A device holding several databases asks about one of them; a page that// came out of a different file must not be folded into this one, and the// writes this device handed over stay queued for the file they belong to.const OTHER: &str = "66666666-6666-4666-8666-666666666666";let elsewhere = || {letmut answer = page(vec![theirs("t1", "1700000000001:0000:device:b")], false); answer.workspace_id = OTHER.to_string(); answer };let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let replica = std::sync::Mutex::new(replica);let transport = FakeTransport::default(); transport.script([elsewhere()]);let failure = run_cycle_paged(&replica, &mut &transport, WORKSPACE, NOW).expect_err("a refusal"); assert!(matches!(failure, CycleFailure::Transient { .. })); assert!(failure.message().contains(OTHER), "{}", failure.message()); transport.script([elsewhere()]);let failure = push_only_paged(&replica, &mut &transport, WORKSPACE, NOW).expect_err("a refusal"); assert!(failure.message().contains(OTHER), "{}", failure.message());let replica = replica.lock().expect("the replica"); transport.script([elsewhere()]); run_cycle(&replica.driver, &mut &transport, WORKSPACE, NOW).expect_err("a refusal"); assert_eq!( cotton_store::outbox::pending_count(&replica.driver).expect("a count"),2,"the author's fact and the change stay queued" );let folded = replica .driver .get("SELECT id FROM cotton_todos WHERE id = 't1'", &[]) .expect("reads"); assert!(folded.is_none(), "the other file's row was not taken");}#[test]fn a_paged_cycle_that_failed_in_the_air_records_the_attempt_too() {// The paged full cycle used to classify the failure and record nothing —// the one place the bookkeeping had drifted from `exchange_once`.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let replica = std::sync::Mutex::new(replica);let transport = FakeTransport::default(); transport.refuse(ServerRefusal::offline("offline")); run_cycle_paged(&replica, &mut &transport, WORKSPACE, NOW).expect_err("a refusal");let replica = replica.lock().expect("the replica"); assert_eq!(attempt_recorded(&replica), (1, Some("offline".to_string())));}// ── Any lender: the file is lent per step, never per pass ───────────────────/// A lender that says, at every moment, whether the file is out.structWatched { replica: std::sync::Mutex<crate::Replica>, out: std::sync::atomic::AtomicBool, lends: std::sync::atomic::AtomicUsize,}implLendsFileforWatched {fn lend(&self, work: &mutdynFnMut(&Driver)) {use std::sync::atomic::Ordering;self.lends.fetch_add(1, Ordering::SeqCst);self.out.store(true, Ordering::SeqCst);self.replica.lend(work);self.out.store(false, Ordering::SeqCst); }}structOutWatching<'a> { inner: &'a FakeTransport, file: &'a Watched, out_while_asked: Vec<bool>,}implcrate::transport::RefusalAwareforOutWatching<'_> {fn last_refusal(&self) -> Option<ServerRefusal> { (&self.inner).last_refusal() }}impl cotton_store::exchange::SyncTransportforOutWatching<'_> {fn exchange(&mutself, request: &ExchangeRequest) -> Result<ExchangeResponse, String> {self.out_while_asked .push(self.file.out.load(std::sync::atomic::Ordering::SeqCst)); (&mut &*self.inner).exchange(request) }}/// RULE: `run_cycle_lent` asks for the file once for each page's batch, once for each fold and once for the drain — and never while the peer is asked.////// The Mac's peer pass runs this over the file its own server serves.#[test]fn the_lent_cycle_never_has_the_file_out_while_the_peer_is_asked() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let file = Watched { replica: std::sync::Mutex::new(replica), out: std::sync::atomic::AtomicBool::new(false), lends: std::sync::atomic::AtomicUsize::new(0), };let fake = FakeTransport::default(); *fake.has_more.lock().expect("the flag") = true;letmut transport = OutWatching { inner: &fake, file: &file, out_while_asked: Vec::new(), };let report = run_cycle_lent(&file, &mut transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.pushed, 2); // the author's fact, then the change assert_eq!(transport.out_while_asked, vec![false, false]);// Two pages × (batch + fold) + the drain. assert_eq!(file.lends.load(std::sync::atomic::Ordering::SeqCst), 5);}/// RULE: An answer from the owner's Dev copy naming another night stops the loop with the copy_replaced code — never a transient retry, which would ask the same file the same question for ever — whatever the transport last heard.#[test]fn another_night_of_the_owners_copy_stops_the_loop_as_copy_replaced() {let transport = FakeTransport::default(); transport.refuse(ServerRefusal::new("server 503: busy", 503));let failure = classify(SyncError::CopyReplaced { night: "author-tonight".to_string(), }, &&transport, ); assert!(failure.is_terminal(), "{failure:?}");match failure {CycleFailure::TerminalDevice { code, .. } => assert_eq!(code, COPY_REPLACED), other => panic!("expected the copy_replaced stop, got {other:?}"), }}/// RULE: An exchanging device already has a readable file and never asks for another whole copy; even a copy offer and a large backlog must preserve its file and continue paging.#[test]fn a_readable_copy_never_asks_for_another_copy_and_pages_on() {let (_dir, _layout, replica) = open_test_replica();let replica = std::sync::Mutex::new(replica);let transport = FakeTransport::default(); *transport.takes_copies.lock().expect("the flag") = true;letmut offered = page(vec![theirs("t1", "1700000000001:0000:device:b")], true); offered.behind_by = Some(10_000); offered.owed_at_start = Some(100_000); offered.copy = Some(cotton_store::protocol::types::CopyOffer { bytes: 400_000_000 }); transport.script([offered, page(vec![theirs("t2", "1700000000002:0000:device:b")], false)]);let report = run_cycle_paged(&replica, &mut &transport, WORKSPACE, NOW).expect("a pass"); assert_eq!(report.copy, None); assert_eq!(transport.calls().len(), 2, "both pages were asked"); assert!( transport.said_takes_copy.lock().expect("the log").iter().all(|said| !said),"never said takesCopy" );}/// RULE: A pass whose write meets a file locked by another writer stops with the named "copy is busy" failure, never as the Mac not answering — the 304 phone's line said "Mac not heard" for hours while its own index rebuild held the lock (20 Oct 2026).#[test]fn a_locked_file_is_the_copy_being_busy_not_the_mac_silent() {let locked = cotton_store::StoreError::Sqlite(rusqlite::Error::SqliteFailure( rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_BUSY),Some("database is locked".to_string()), )); assert!(copy_busy(&locked)); assert!(!copy_busy(&cotton_store::StoreError::Refused("anything else".to_string()))); assert!(!CycleFailure::Transient { message: COPY_BUSY.to_string(), retry_after_seconds: Some(5) }.answered());}