//! A PASS STOPPED AT ANY POINT LOSES NOTHING, and the next one continues from//! the folded point — what makes a day of thirty-second background slices add//! up to a backfill (owner, 11 Oct 2026: a 34,000-row mail backfill reached//! the phone only while it was open).//!//! The Mac here holds a backlog and pages it out by the cursor it is asked//! from, exactly as the real one does; the device is a real file. The tests//! stop a pass after every page in turn, lose an answer the Mac had already//! acted on, and run out of time with a request in the air.use std::collections::BTreeMap;use std::sync::{Arc, Mutex};use std::time::Duration;use cotton_store::protocol::types::{CottonOp, ExchangeRequest, ExchangeResponse, ExchangeSectionsRequest,ExchangeSectionsResponse, SectionAnswer,};usesuper::*;usecrate::connection::held::HeldNotes;usecrate::test_support::{accepted, open_replica_for, queue_one_change_for, temp_layout};const NOW: &str = "2026-10-11T10:00:00.000Z";const A: &str = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";/// The other device, whose writes are the backlog.const AUTHOR: &str = "device:b";/// Rows the Mac answers per page.const PAGE: usize = 3;/// A Mac with a backlog of another device's todos.structMac { backlog: Vec<CottonOp>,/// Every request it was sent, in order. calls: Vec<ExchangeRequest>,/// How often each of the device's writes was handed to it, by op id. took: BTreeMap<String, usize>,/// The device's box, which this Mac closes to stand for time running out. time_box: TimeBox,/// The time is gone once this many pages have been answered. close_after: Option<usize>,/// The answer to this call (1-based) never arrives — AFTER the Mac has/// taken what the call handed it. lose: Option<usize>,/// …and the time runs out while that call is in the air. close_on_loss: bool,}implMac {fn with_backlog(rows: usize, time_box: &TimeBox) -> Mac {let backlog = (1..=rows) .map(|n| {letmut patch = serde_json::Map::new(); patch.insert("workspace_id".to_string(), A.into()); patch.insert("title".to_string(), format!("backlog {n}").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!("01J0000000000000000000{n:04}"),"cotton_todos", &format!("t{n:04}"), patch, &format!("17000000{n:05}:0000:{AUTHOR}"), AUTHOR, ) }) .collect();Mac { backlog, calls: Vec::new(), took: BTreeMap::new(), time_box: time_box.clone(), close_after: None, lose: None, close_on_loss: false, } }/// The HLC of the backlog's `n`th row, 1-based.fn hlc(&self, n: usize) -> &str { &self.backlog[n - 1].hlc }fn answer(&mutself, section: &ExchangeRequest) -> ExchangeResponse {let from = section.cursors.get(AUTHOR).cloned().unwrap_or_default();let waiting: Vec<&CottonOp> = self.backlog.iter().filter(|op| op.hlc > from).collect();letmut answer = accepted(section, waiting.len() > PAGE); answer.schema_version = Some(cotton_store::schema::ddl::SCHEMA_VERSION); answer.ops = waiting.into_iter().take(PAGE).cloned().collect(); answer.cursors = section.cursors.clone();ifletSome(last) = answer.ops.last() { answer.cursors.insert(AUTHOR.to_string(), last.hlc.clone()); } answer.seen.insert("origin".to_string(), format!("origin:cotton_workspaces:{A}"), ); answer }}implcrate::transport::RefusalAwareforMac {fn last_refusal(&self) -> Option<crate::transport::ServerRefusal> {None }}impl cotton_store::exchange::SyncTransportforMac {fn exchange(&mutself, request: &ExchangeRequest) -> Result<ExchangeResponse, String> { panic!("one call per page — {} was asked alone", request.workspace_id); }fn exchange_many( &mutself, request: &ExchangeSectionsRequest, ) -> Result<ExchangeSectionsResponse, String> {let [section] = request.sections.as_slice() else { panic!("one database is held, one section is asked"); };self.calls.push(section.clone());let call = self.calls.len();// THE MAC TAKES WHAT IT WAS HANDED before anything can go wrong on// the way back — which is the order the real one works in.for op in §ion.ops { *self.took.entry(op.op_id.clone()).or_default() += 1; }ifself.lose == Some(call) {ifself.close_on_loss {self.time_box.close_in(Duration::ZERO); }returnErr("the answer never arrived".to_string()); }let answer = self.answer(section);ifself.close_after == Some(call) {self.time_box.close_in(Duration::ZERO); }Ok(ExchangeSectionsResponse { sections: vec![SectionAnswer::Answered(answer)], }) }}/// A phone holding one database, and the opens a pass asked for.structPhone { _dir: tempfile::TempDir, file: Arc<Mutex<crate::Replica>>, notes: HeldNotes, opens: Mutex<usize>, time_box: TimeBox,}implPhone {fn new() -> Phone {let (dir, layout) = temp_layout();let file = Arc::new(Mutex::new(open_replica_for(&layout, dir.path(), A)));let notes = HeldNotes::beside(&dir.path().join("connection.json"));Phone { _dir: dir, file, notes, opens: Mutex::new(0), time_box: TimeBox::open(), } }/// One pass inside the phone's box. Answers the call's outcome and how/// many times the file was opened for it.fn pass(&self, mac: &mutMac) -> (Result<CycleReport, CycleFailure>, usize) { *self.opens.lock().expect("the count") = 0;let opener = |_: &str| -> Result<Arc<dynLendsFile>, String> { *self.opens.lock().expect("the count") += 1;let file: Arc<dynLendsFile> = self.file.clone();Ok(file) };let outcome = run_cycle_many_within( &[A.to_string()], &opener, &self.notes, &|_| false, mac, NOW, &self.time_box, ) .and_then(|mut passes| passes.pop().expect("one database, one pass").outcome); (outcome, *self.opens.lock().expect("the count")) }fn queue(&self, title: &str) { queue_one_change_for(&self.file.lock().expect("the file"), A, title);self.notes.note_write(A).expect("noted"); }fn pending(&self) -> i64 { cotton_store::outbox::pending_count(&self.file.lock().expect("the file").driver) .expect("a count") }/// Which of the backlog's rows the file holds, as their numbers.fn holds(&self, mac: &Mac) -> Vec<usize> {let file = self.file.lock().expect("the file"); (1..=mac.backlog.len()) .filter(|n| { file.driver .get("SELECT id FROM cotton_todos WHERE id = ?", &[rusqlite::types::Value::Text(format!("t{n:04}"))], ) .expect("reads") .is_some() }) .collect() }/// The backlog's rows in the file, counted — one row each, or the fold/// landed something twice.fn backlog_rows(&self) -> i64 {let file = self.file.lock().expect("the file");let row = file .driver .get("SELECT COUNT(*) AS n FROM cotton_todos WHERE title LIKE 'backlog %'", &[]) .expect("reads") .expect("a count");match row.get("n") {Some(rusqlite::types::Value::Integer(n)) => *n, other => panic!("a count, not {other:?}"), } }}/// RULE: A sync pass stopped after any page has kept every page before it, and the next pass continues from the folded point — no row is lost and no row is fetched twice.#[test]fn a_pass_stopped_after_any_page_loses_nothing_and_the_next_continues_from_the_folded_point() {const PAGES: usize = 6;for stop_after in1..PAGES {let phone = Phone::new();letmut mac = Mac::with_backlog(PAGES * PAGE, &phone.time_box); mac.close_after = Some(stop_after);let (stopped, _) = phone.pass(&mut mac);let stopped = stopped.expect("a stopped pass is a pass, not a failure");let landed = stop_after * PAGE; assert_eq!( mac.calls.len(), stop_after,"no page was started once the time was gone (stopped after {stop_after})" ); assert!(stopped.behind, "a pass the time ran out on says there is more"); assert_eq!(stopped.pulled, landed, "it reports the pages it folded"); assert_eq!( phone.holds(&mac), (1..=landed).collect::<Vec<_>>(),"every page before the stop is in the file, and nothing after it" );// THE NEXT SLICE, whenever iOS grants it. phone.time_box.lift(); mac.close_after = None;let (resumed, opens) = phone.pass(&mut mac);let resumed = resumed.expect("the next pass"); assert_eq!(opens, 1, "a stopped pass's note never speaks for the file: it is opened"); assert_eq!( mac.calls[stop_after].cursors.get(AUTHOR).map(String::as_str),Some(mac.hlc(landed)),"the next pass asks from the last row the stopped one folded" ); assert!(!resumed.behind, "and it reaches the end"); assert_eq!(resumed.pulled, PAGES * PAGE - landed, "having fetched only the rest"); assert_eq!(phone.holds(&mac), (1..=PAGES * PAGE).collect::<Vec<_>>()); assert_eq!(phone.backlog_rows(), (PAGES * PAGE) as i64, "each row once"); }}/// RULE: When the time runs out with a request in the air, the pass ends without failing: the pages already folded are reported, it says there is more, and the next pass fetches the lost page again from the folded point.#[test]fn the_time_running_out_on_a_request_in_the_air_ends_the_pass_and_fails_nothing() {let phone = Phone::new();letmut mac = Mac::with_backlog(4 * PAGE, &phone.time_box); mac.lose = Some(2); mac.close_on_loss = true;let (stopped, _) = phone.pass(&mut mac);let stopped = stopped.expect("the first page landed, so the pass is not a failure"); assert_eq!(mac.calls.len(), 2); assert!(stopped.behind); assert_eq!(stopped.pulled, PAGE, "the page before the lost one is reported"); assert_eq!(phone.holds(&mac), (1..=PAGE).collect::<Vec<_>>()); phone.time_box.lift(); mac.lose = None;let (resumed, _) = phone.pass(&mut mac); assert!(!resumed.expect("the next pass").behind); assert_eq!( mac.calls[2].cursors.get(AUTHOR).map(String::as_str),Some(mac.hlc(PAGE)),"the lost page is asked for again, from the folded point" ); assert_eq!(phone.backlog_rows(), (4 * PAGE) as i64, "each row once");}/// RULE: A sync pass that folded no page and whose request failed is reported as a failure, time box or none — never as a pass that synced.#[test]fn a_pass_that_landed_nothing_and_failed_is_still_a_failure() {let phone = Phone::new();letmut mac = Mac::with_backlog(PAGE, &phone.time_box); mac.lose = Some(1); mac.close_on_loss = true;let (outcome, _) = phone.pass(&mut mac); assert!( matches!(outcome, Err(CycleFailure::Transient { .. })),"nothing landed and the call failed: {outcome:?}" ); assert!(phone.holds(&mac).is_empty());}/// RULE: When a page's answer is lost after the Mac took the writes it was handed, the phone keeps every one of them queued and hands the same writes over again under the same ids, so the Mac can know them for the ones it holds.#[test]fn an_answer_lost_after_the_mac_took_the_writes_keeps_them_queued_and_resends_the_same_ones() {let phone = Phone::new();letmut mac = Mac::with_backlog(0, &phone.time_box); phone.queue("written on the phone");let queued = phone.pending(); assert!(queued > 0); mac.lose = Some(1);let (lost, _) = phone.pass(&mut mac); assert!(lost.is_err(), "the call failed"); assert_eq!(phone.pending(), queued, "nothing left the queue on a lost answer"); assert_eq!(mac.took.len() as i64, queued, "though the Mac had taken every write"); mac.lose = None;let (settled, _) = phone.pass(&mut mac); settled.expect("the next pass"); assert_eq!(phone.pending(), 0, "the queue settles on the answer that arrives");let ids = |call: usize| -> Vec<&str> { mac.calls[call].ops.iter().map(|op| op.op_id.as_str()).collect() }; assert_eq!(ids(0), ids(1), "the same writes, under the same ids"); assert!( mac.took.values().all(|times| *times == 2),"each was offered twice and is one write: {:?}", mac.took );}/// RULE: A sync pass with no time left asks the Mac nothing and opens no file; it says there is more, so the next slice asks.#[test]fn a_pass_with_no_time_left_asks_nothing_and_opens_no_file() {let phone = Phone::new();letmut mac = Mac::with_backlog(PAGE, &phone.time_box); phone.queue("written on the phone");let queued = phone.pending(); phone.time_box.close_in(Duration::ZERO);let (outcome, opens) = phone.pass(&mut mac);let report = outcome.expect("not a failure: nothing was tried"); assert!(mac.calls.is_empty(), "no request without room for its answer"); assert_eq!(opens, 0); assert!(report.behind); assert_eq!((report.pulled, report.pushed), (0, 0)); assert_eq!(phone.pending(), queued);}