//! The exchange, driven against a REAL peer file rather than a scripted one. //! //! The half that used to be `outbox.test.ts`'s drain/pull suite. It is a real //! file on the other side on purpose: the whole claim of one symmetric verb is //! that the two ends run the same code, and a hand-written fake answering //! whatever the assertion wanted would prove nothing about that. use super::*; use serde_json::json; use crate::outbox::{pending_count, IdSource, LocalChange}; use crate::protocol::types::{OpKind, REJECTION_AUTHOR_WAITING, REJECTION_HAND_OVER, REJECTION_SERVER_BEHIND}; use crate::protocol::ulid::Monotonic; use crate::test_support::{seeded_file, WORKSPACE as WS}; const NOW: &str = "2026-08-22T10:30:00.000Z"; const NOW_MS: i64 = 1_787_394_600_000; fn seeded(device_id: &str) -> Driver { seeded_file(device_id) } fn todo(id: &str, title: &str) -> LocalChange { LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: "cotton_todos".to_string(), row_id: id.to_string(), patch: Some( json!({ "id": id, "workspace_id": WS, "title": title, "status": "open", "created_at": NOW, "updated_at": NOW, }) .as_object() .expect("an object") .clone(), ), } } /// One local write on `db`, queued in its outbox like any other. /// fn write(db: &Driver, device_id: &str, changes: &[LocalChange]) -> Vec { // A process-wide counter rather than a hash of the change: `_outbox.op_id` // is UNIQUE and every stamp in these tests is at the same frozen // millisecond, so the ONLY thing that can tell two ids apart is this. // // THE WHOLE COUNTER, as the random half's leading base-32 digits. It used // to seed an LCG and keep each output's low byte — but `Monotonic` keeps // only `byte % 32`, and an LCG's low five bits depend only on the seed's // low five bits, so the ids repeated every 32 writes PROCESS-WIDE. Tests // running in parallel spend the counter between one test's writes, so a // test could mint an id its own peer already held, and the peer skipped // it as a write it had (`handover_after_restore_includes_parked_receipts` // failed about one run in four: r1 was minted with p1's id). Thirteen // digits hold all 64 bits; the last three stay zero for `Monotonic` to // increment within one multi-change write. Production ids are drawn from // the OS and never met this. static TICK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); let tick = TICK.fetch_add(1, std::sync::atomic::Ordering::SeqCst); let mut ids = Monotonic::new(move |digits: &mut [u8]| { digits.fill(0); for (place, digit) in digits.iter_mut().take(13).rev().enumerate() { *digit = ((tick >> (5 * place)) & 31) as u8; } }); write_as(db, device_id, NOW_MS, changes, &mut ids) } /// A write under a CHOSEN author, the way a device's write used to land before /// `mint` became the one write path: stamped in `author`'s stream, folded, /// queued and seen by this file's own cursor, in one transaction. /// /// `mint` stamps every op with the FILE's author, minted lazily as /// `device:` with its `cotton_authors` fact — and a file that holds its /// own author's fact parks every peer receipt whose author has none. These /// cases are about the EXCHANGE between authors named in the test (`device:a`, /// `device:b`, `device:laptop`), not about how a write is minted, so they /// build the ops themselves and fold them as a handed batch. fn write_as( db: &Driver, author: &str, ms: i64, changes: &[LocalChange], ids: &mut dyn IdSource, ) -> Vec { db.transaction(|db| { let mut last = db .get("SELECT last_hlc FROM _meta", &[])? .and_then(|row| row.text("last_hlc").map(str::to_string)); let mut ops = Vec::with_capacity(changes.len()); for change in crate::mint::changes_of(db, changes) { let hlc = crate::protocol::hlc::next_hlc(author, last.as_deref(), ms)?; last = Some(hlc.clone()); ops.push(crate::wire::op_of_change( db, &change, &hlc, author, &crate::fixtures::fixture_actor(), ids.next_op_id(ms)?, )?); } let folded = crate::fold::arrive(db, &ops, crate::fold::Arrival::Handed)?; assert!(folded.rejected.is_empty(), "a local write the fold refused: {:?}", folded.rejected); let at = crate::protocol::js::to_iso_string(ms).expect("an instant"); crate::outbox::queue_ops(db, &ops, &at)?; crate::rejected::requeue_touched_pushes(db, &folded.applied_rows, &at)?; crate::rejected::retry_touched_rows(db, &folded.applied_rows, &Default::default(), &at)?; if let Some(newest) = ops.last() { crate::cursors::advance_cursor(db, author, &newest.hlc, &at)?; } Ok(ops) }) .expect("a local write") } /// A peer's write, as `device:b` minted it at `NOW_MS`. fn peer_op(db: &Driver, change: crate::mint::Change, op_id: &str) -> CottonOp { crate::wire::op_of_change( db, &change, "1787394600000:0000:device:b", "device:b", &crate::fixtures::fixture_actor(), op_id.to_string(), ) .expect("a receipt") } fn title(db: &Driver, id: &str) -> Option { db.get( "SELECT title FROM cotton_todos WHERE id = ?", &[SqlValue::Text(id.to_string())], ) .expect("reads") .and_then(|row| row.text("title").map(str::to_string)) } // ───────────────────────────────────────────────────────────────────────────── // A peer that IS a file. `answer` + `fold_incoming` is the whole server. // ───────────────────────────────────────────────────────────────────────────── struct Peer { db: Driver, /// Every request this peer was handed, for the assertions about paging. seen: Vec, /// Set to refuse every op with this reason. refuse: Option<(String, Option)>, /// The word a refusal carries beside its sentence, when it carries one. code: Option, /// Set to fail the round trip outright. offline: bool, /// The serving epoch this peer answers in, and its restore point — and /// with one, it folds only what was handed over to it, as the route does. epoch: Option<(i64, Option>)>, /// Ops this peer refuses outright, by id, whatever else it takes. refuse_ids: BTreeSet, /// Ops this peer holds (`server_behind`), by id, whatever else it takes. hold_ids: BTreeSet, /// Ops this peer parks `waiting` for their author's fact, by id — kept in /// `waiting` until [`Peer::fact_arrives`] folds them, as the route's file /// does once the fact lands. wait_ids: BTreeSet, waiting: Vec, /// What one answer may carry ([`PageBudget`]), as the route sets it. budget: PageBudget, } impl Peer { fn new(device_id: &str) -> Peer { Peer { db: seeded(device_id), seen: Vec::new(), refuse: None, code: None, offline: false, epoch: None, refuse_ids: BTreeSet::new(), hold_ids: BTreeSet::new(), wait_ids: BTreeSet::new(), waiting: Vec::new(), budget: PageBudget::PAGE, } } /// The author's fact arrives: what waited on it folds. fn fact_arrives(&mut self) { self.wait_ids.clear(); fold_incoming(&self.db, &std::mem::take(&mut self.waiting)).expect("folds what waited"); } } impl SyncTransport for Peer { fn exchange( &mut self, request: &ExchangeRequest, ) -> std::result::Result { self.seen.push(request.clone()); if self.offline { return Err("offline".to_string()); } if let Some((reason, retryable)) = &self.refuse { return Ok(ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: request.workspace_id.clone(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops: Vec::new(), cursors: BTreeMap::new(), has_more: false, applied_rows: BTreeMap::new(), rejected: request .ops .iter() .map(|op| PushRejection { op_id: op.op_id.clone(), reason: reason.clone(), retryable: *retryable, code: self.code.clone(), server_time: None, }) .collect(), 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, }); } // THE ROUTE'S EPOCH GATE (slice 12): nothing is folded from a // request that names this peer's epoch in neither mark. let (serving_epoch, restored) = match &self.epoch { Some((epoch, restored)) => (Some(*epoch), restored.clone()), None => (None, None), }; if let Some(epoch) = serving_epoch.filter(|epoch| { request.handed_over_epoch != Some(*epoch) && request.handing_over_to != Some(*epoch) }) { return Ok(ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: request.workspace_id.clone(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops: Vec::new(), cursors: request.cursors.clone(), has_more: true, applied_rows: BTreeMap::new(), rejected: request .ops .iter() .map(|op| PushRejection::held(op.op_id.clone(), "hand over first", REJECTION_HAND_OVER)) .collect(), seen: crate::cursors::seen_ceiling(&self.db).map_err(|error| error.to_string())?, serving_epoch: Some(epoch), server_time: None, restored, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }); } // THE SAME TWO FUNCTIONS THE ROUTE CALLS, in the route's order: the // fold first, so a caller that wrote and asked in one breath is never // told about a state its own write already moved past. let already = handled(&request.ops); let (kept, singled): (Vec, Vec) = request .ops .iter() .cloned() .partition(|op| { !self.refuse_ids.contains(&op.op_id) && !self.hold_ids.contains(&op.op_id) && !self.wait_ids.contains(&op.op_id) }); let mut folded = fold_incoming(&self.db, &kept).map_err(|error| error.to_string())?; for op in singled { if self.wait_ids.contains(&op.op_id) { folded.waiting.push(PushRejection::held( op.op_id.clone(), "waiting: author fact for device:a", REJECTION_AUTHOR_WAITING, )); if !self.waiting.iter().any(|kept| kept.op_id == op.op_id) { self.waiting.push(op); } continue; } folded.rejected.push(if self.hold_ids.contains(&op.op_id) { PushRejection::held(op.op_id, "this Mac is behind", REJECTION_SERVER_BEHIND) } else { PushRejection { op_id: op.op_id, reason: "the new Mac refuses it".to_string(), retryable: None, code: None, server_time: None, } }); } // The route's answer of what it parked waiting, to a caller that asked. if request.parks_waiting { folded.rejected.extend(folded.waiting.clone()); } let limit = request.limit.unwrap_or(EXCHANGE_PAGE_ROWS) as usize; let answered = answer_within(&self.db, &request.cursors, limit, &already, self.budget) .map_err(|error| error.to_string())?; Ok(ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: request.workspace_id.clone(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops: answered.ops, cursors: answered.cursors, has_more: answered.has_more, applied_rows: folded.applied_rows, rejected: folded.rejected, seen: answered.seen, serving_epoch, server_time: None, restored, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: Some(answered.passed), wake_refusal: None, }) } } /// Exchange until neither side has more, at most ten times. fn settle(db: &Driver, peer: &mut Peer) -> ExchangeReport { let mut report = ExchangeReport::default(); // ONE handover for the whole pass, exactly as `cotton_client::sync::cycle` // holds one: it is the pass that must not hand a row over twice. let mut handover = Handover::default(); for _ in 0..10 { let page = exchange_once(db, peer, WS, None, NOW, &mut handover).expect("an exchange"); report.absorb(&page.report); if !page.has_more { break; } } report } // ───────────────────────────────────────────────────────────────────────────── // The queue goes up, the peer's writes come down // ───────────────────────────────────────────────────────────────────────────── #[test] fn one_call_hands_over_what_we_wrote_and_brings_back_what_we_had_not_seen() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); write(&db, "device:a", &[todo("t1", "Ours")]); write(&peer.db, "device:b", &[todo("t2", "Theirs")]); let report = settle(&db, &mut peer); assert_eq!(title(&db, "t2").as_deref(), Some("Theirs")); assert_eq!(title(&peer.db, "t1").as_deref(), Some("Ours")); assert_eq!(report.received.get("cotton_todos"), Some(&1)); assert_eq!(report.sent.get("cotton_todos"), Some(&1)); assert_eq!(pending_count(&db).expect("counts"), 0, "the queue is drained"); } /// RULE: A Reader only pulls. A copied file may hold receipts the server is /// behind on, and may still carry a stale outbox; neither is ever handed back, /// while its cursor still asks the server for the next page (walker296 next pass). #[test] fn a_reader_request_never_hands_copied_or_queued_receipts_back() { let db = seeded("device:reader"); let queued = write(&db, "device:reader", &[todo("queued", "A stale queue")]); let historical = write_as( &db, "device:server", NOW_MS + 1, &[todo("copied", "A copied receipt")], &mut Monotonic::new(|digits| digits.fill(1)), ); for op in &historical { db.run( "DELETE FROM _outbox WHERE op_id = ?", &[rusqlite::types::Value::Text(op.op_id.clone())], ) .expect("a snapshot keeps historical receipts out of its outbox"); } let pending = pending_count(&db).expect("the stale queue counts"); assert!(pending >= queued.len() as i64, "the reader starts with an untouched queue"); db.set_device_scope(crate::device_scope::DeviceScope::Reader); let mut handover = Handover::default(); let first = exchange_request(&db, WS, None, &mut handover).expect("the reader's pull"); assert!(first.request.ops.is_empty(), "a reader never sends its queue"); assert!(first.queued.is_empty()); assert!(first.request.cursors.contains_key("device:server"), "the copied receipt still advances the pull cursor"); assert_eq!(pending_count(&db).expect("the stale queue remains"), pending); let response: ExchangeResponse = serde_json::from_value(json!({ "workspaceId": WS, "ops": [], "cursors": first.request.cursors.clone(), "hasMore": true, "schemaVersion": crate::schema::ddl::SCHEMA_VERSION, "appliedRows": {}, "rejected": [], "seen": {}, })) .expect("a server that is behind the copied author"); fold_answer(&db, &first, &response, NOW, &mut handover).expect("the empty pull folds"); let next = exchange_request(&db, WS, None, &mut handover).expect("the next reader pull"); assert!(next.request.ops.is_empty(), "the later page cannot hand copied receipts back"); assert!(next.request.cursors.contains_key("device:server"), "the next page remains a normal pull"); assert_eq!(pending_count(&db).expect("the queue was not drained"), pending); } #[test] fn a_queue_with_nothing_in_it_still_asks_for_news() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); write(&peer.db, "device:b", &[todo("t2", "Theirs")]); settle(&db, &mut peer); assert_eq!(title(&db, "t2").as_deref(), Some("Theirs")); assert!(peer.seen[0].ops.is_empty()); } #[test] fn the_peer_never_hands_back_the_writes_this_device_just_sent() { // A local write moves THIS device's own cursor, so the ceiling the peer // computes for us is already covered. Without that, every write a device // made would come straight back on the same call that delivered it. let db = seeded("device:a"); let mut peer = Peer::new("device:server"); write(&db, "device:a", &[todo("t1", "Ours")]); settle(&db, &mut peer); let mine: Vec<&ExchangeRequest> = peer.seen.iter().collect(); assert!( mine[0].cursors.contains_key("device:a"), "the request declares our own author: {:?}", mine[0].cursors ); // The very first answer carried nothing back. assert!(read_cursors(&db).expect("cursors").contains_key("device:a")); } #[test] fn folding_the_same_answer_twice_changes_nothing() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); write(&peer.db, "device:b", &[todo("t2", "Theirs")]); let first = exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect("an exchange"); assert_eq!(first.report.received.get("cotton_todos"), Some(&1)); // The same page again, cursor and all — a retry after a dropped response. let response = ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WS.to_string(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops: peer .seen .last() .map(|_| Vec::new()) .unwrap_or_default(), cursors: BTreeMap::new(), has_more: false, applied_rows: BTreeMap::new(), rejected: Vec::new(), seen: Default::default(), 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 again = fold_answer( &db, &Handed::nothing(WS), &response, NOW, &mut Handover::default(), ) .expect("a second fold"); assert!(again.report.received.is_empty()); assert_eq!(title(&db, "t2").as_deref(), Some("Theirs")); } #[test] fn two_devices_converge_after_interleaved_offline_edits() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); let other = seeded("device:b"); write(&db, "device:a", &[todo("t1", "A's todo")]); write(&other, "device:b", &[todo("t2", "B's todo")]); // B goes through the same peer. let mut through = Peer { db: peer.db, seen: Vec::new(), refuse: None, code: None, offline: false, epoch: None, refuse_ids: BTreeSet::new(), hold_ids: BTreeSet::new(), wait_ids: BTreeSet::new(), waiting: Vec::new(), budget: PageBudget::PAGE, }; settle(&other, &mut through); peer = through; settle(&db, &mut peer); settle(&other, &mut peer); for file in [&db, &other, &peer.db] { assert_eq!(title(file, "t1").as_deref(), Some("A's todo")); assert_eq!(title(file, "t2").as_deref(), Some("B's todo")); } } // ───────────────────────────────────────────────────────────────────────────── // Paging // ───────────────────────────────────────────────────────────────────────────── #[test] fn a_page_is_a_whole_number_of_rows_and_the_size_is_the_declaration() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); for n in 0..5 { write(&peer.db, "device:b", &[todo(&format!("t{n}"), "Theirs")]); } let answered = answer(&peer.db, &BTreeMap::new(), 2).expect("a page"); let rows: std::collections::BTreeSet<&str> = answered.ops.iter().map(|op| op.row_id.as_str()).collect(); assert_eq!(rows.len(), 2, "two ROWS, whole: {:?}", rows); assert!(answered.has_more); // And the whole stream still arrives, one page at a time. let report = settle(&db, &mut peer); assert_eq!(report.received.get("cotton_todos"), Some(&5)); } #[test] fn the_cursor_a_page_answers_is_the_pages_own_resume_point_never_the_ceiling() { // A ceiling handed back beside `hasMore: true` would skip every write // between this page and it — silently, for ever. let peer = seeded("device:server"); for n in 0..5 { write(&peer, "device:b", &[todo(&format!("t{n}"), "Theirs")]); } let ceiling = cursor_ceiling(&peer).expect("a ceiling"); let page = answer(&peer, &BTreeMap::new(), 2).expect("a page"); assert!(page.has_more); assert!( page.cursors.get("device:b") < ceiling.get("device:b"), "{:?} must be under {:?}", page.cursors, ceiling ); } #[test] fn an_answer_deals_its_page_across_every_author_the_caller_is_behind_on() { // A page that went to the first author by name until it was drained // starved the rest: a phone pulling from empty cursors spent a day on the // Mac's archive while six transcribed meetings waited under an author // three hundred thousand rows down the list. let peer = seeded("device:server"); let archive: Vec = (0..30) .map(|n| todo(&format!("a{n:03}"), "Archive")) .collect(); write(&peer, "device:archive", &archive); write( &peer, "device:small", &[todo("s1", "Recent"), todo("s2", "Recent"), todo("s3", "Recent")], ); let page = answer(&peer, &BTreeMap::new(), 10).expect("a page"); let small: std::collections::BTreeSet<&str> = page .ops .iter() .filter(|op| op.device_id == "device:small") .map(|op| op.row_id.as_str()) .collect(); assert_eq!(small.len(), 3, "the small stream lands whole on the first page: {small:?}"); let rows: std::collections::BTreeSet<&str> = page.ops.iter().map(|op| op.row_id.as_str()).collect(); assert_eq!(rows.len(), 10, "the room the small stream left goes to the big one"); assert!(page.has_more); assert!(page.cursors.contains_key("device:archive")); assert!(page.cursors.contains_key("device:small")); // And paging on from those cursors still delivers every row exactly once. let mut cursors = page.cursors.clone(); let todos = |ops: &[CottonOp]| -> Vec { ops.iter() .filter(|op| op.table == "cotton_todos") .map(|op| op.row_id.clone()) .collect() }; let mut seen: Vec = todos(&page.ops); for _ in 0..10 { let next = answer(&peer, &cursors, 10).expect("a page"); seen.extend(todos(&next.ops)); cursors.extend(next.cursors); if !next.has_more { break; } } let unique: std::collections::BTreeSet<&String> = seen.iter().collect(); assert_eq!(unique.len(), 33, "every row arrived"); assert_eq!(seen.len(), 33, "no row arrived twice"); } #[test] fn an_author_the_caller_is_already_level_with_is_not_asked_about() { let peer = seeded("device:server"); write(&peer, "device:b", &[todo("t1", "Theirs")]); let ceiling = cursor_ceiling(&peer).expect("a ceiling"); let page = answer(&peer, &ceiling, 500).expect("a page"); assert!(page.ops.is_empty()); assert!(!page.has_more); assert!(page.cursors.is_empty()); } // ───────────────────────────────────────────────────────────────────────────── // Rejections // ───────────────────────────────────────────────────────────────────────────── #[test] fn a_final_rejection_is_parked_with_its_patch_and_the_outbox_row_goes() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); peer.refuse = Some(("CHECK constraint failed".to_string(), None)); write(&db, "device:a", &[todo("t1", "Doomed")]); exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect("an exchange"); assert_eq!(pending_count(&db).expect("counts"), 0); let parked = crate::rejected::list_parked(&db, 10).expect("the parked list"); assert_eq!(parked.len(), 1); assert_eq!(parked[0].reason, "CHECK constraint failed"); assert_eq!(parked[0].class, "conflict", "a constraint that will not change by itself"); let patch = parked[0].patch.as_ref().map(|patch| serde_json::Value::Object(patch.clone()).to_string()); assert!( patch.as_deref().is_some_and(|patch| patch.contains("Doomed")), "{patch:?}" ); } #[test] fn a_retryable_rejection_keeps_the_write_queued_and_parks_nothing() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); peer.refuse = Some(( "server schema is older than this client".to_string(), Some(true), )); write(&db, "device:a", &[todo("t1", "Waiting")]); let exchanged = exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect("an exchange"); assert_eq!(pending_count(&db).expect("counts"), 1); assert!(crate::rejected::list_parked(&db, 10) .expect("the parked list") .is_empty()); assert!(exchanged.report.sent.is_empty()); // A hold with no word is counted under the empty key — a peer one build // behind the field still holds, and the count still says so. assert_eq!(exchanged.held.get(""), Some(&1)); assert!(!exchanged.has_more, "a held queue is not a queue to drain again now"); } #[test] fn a_hold_is_counted_under_the_word_the_peer_gave_it() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); peer.refuse = Some(( "server schema is older than this client".to_string(), Some(true), )); peer.code = Some(REJECTION_SERVER_BEHIND.to_string()); write(&db, "device:a", &[todo("t1", "Waiting"), todo("t2", "Also waiting")]); let exchanged = exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect("an exchange"); assert_eq!(exchanged.held.get(REJECTION_SERVER_BEHIND), Some(&2)); assert_eq!(exchanged.held.get(""), None); assert_eq!(pending_count(&db).expect("counts"), 2); } #[test] fn an_op_the_peer_did_not_reach_stays_queued_untouched_and_the_drain_goes_on() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); peer.refuse = Some(("not reached this exchange".to_string(), Some(true))); peer.code = Some(crate::protocol::types::REJECTION_DEFERRED.to_string()); write(&db, "device:a", &[todo("t1", "Next pass")]); let exchanged = exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect("an exchange"); assert_eq!(pending_count(&db).expect("counts"), 1, "still queued"); assert!(exchanged.held.is_empty(), "not a hold: {:?}", exchanged.held); assert!(exchanged.has_more, "the drain asks again now"); assert!(crate::rejected::list_parked(&db, 10).expect("the parked list").is_empty()); let row = db.get("SELECT attempts, last_error FROM _outbox", &[]).expect("reads").expect("a row"); assert_eq!((row.int("attempts"), row.text("last_error")), (Some(0), None), "no attempt counted"); // The next exchange reaches it, and it goes. peer.refuse = None; peer.code = None; exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect("an exchange"); assert_eq!(pending_count(&db).expect("counts"), 0); } #[test] fn a_clean_exchange_holds_nothing() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); write(&db, "device:a", &[todo("t1", "Landing")]); let exchanged = exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect("an exchange"); assert!(exchanged.held.is_empty()); assert_eq!(pending_count(&db).expect("counts"), 0); } #[test] fn a_rejection_naming_an_op_this_device_never_sent_is_ignored() { let db = seeded("device:a"); let response = ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WS.to_string(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops: Vec::new(), cursors: BTreeMap::new(), has_more: false, applied_rows: BTreeMap::new(), rejected: vec![PushRejection::final_reason("never-sent", "UNIQUE")], seen: Default::default(), 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, }; fold_answer( &db, &Handed::nothing(WS), &response, NOW, &mut Handover::default(), ) .expect("a fold"); assert!(crate::rejected::list_parked(&db, 10) .expect("the parked list") .is_empty()); } #[test] fn a_transport_failure_leaves_every_op_queued() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); peer.offline = true; write(&db, "device:a", &[todo("t1", "Queued")]); let failure = exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect_err("a refusal"); assert_eq!(failure.to_string(), "offline"); assert_eq!(pending_count(&db).expect("counts"), 1); let attempts: Option = db .get("SELECT attempts FROM _outbox", &[]) .expect("reads") .and_then(|row| row.int("attempts")); assert_eq!(attempts, Some(1)); } #[test] fn an_op_the_fold_refuses_on_the_way_in_is_parked_and_the_cursor_still_moves() { let db = seeded("device:a"); let mut bad = todo("t1", "Orphan"); // A todo whose workspace does not exist — a foreign key nothing can fix. if let Some(patch) = bad.patch.as_mut() { patch.insert("workspace_id".to_string(), json!("no-such-workspace")); } let op = peer_op( &db, crate::mint::Change::create("cotton_todos", "t1", bad.patch.clone().expect("a patch")), "01J0000000000000000000000Z", ); let response = ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WS.to_string(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops: vec![op], cursors: BTreeMap::from([( "device:b".to_string(), "1787394600000:0000:device:b".to_string(), )]), has_more: false, applied_rows: BTreeMap::new(), rejected: Vec::new(), seen: Default::default(), 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, }; fold_answer( &db, &Handed::nothing(WS), &response, NOW, &mut Handover::default(), ) .expect("a fold"); assert_eq!( crate::rejected::list_parked(&db, 10) .expect("the parked list") .len(), 1 ); assert_eq!( read_cursors(&db).expect("cursors").get("device:b").cloned(), Some("1787394600000:0000:device:b".to_string()), "the cursor moves past it, or this page arrives for ever" ); } // ───────────────────────────────────────────────────────────────────────────── // The report // ───────────────────────────────────────────────────────────────────────────── #[test] fn the_report_counts_rows_and_sums_across_pages() { let mut report = ExchangeReport::default(); report.absorb(&ExchangeReport { received: BTreeMap::from([("cotton_todos".to_string(), 2)]), sent: BTreeMap::from([("cotton_notes".to_string(), 1)]), passed: BTreeMap::from([("cotton_todos".to_string(), 4)]), handed: 2, }); report.absorb(&ExchangeReport { received: BTreeMap::from([ ("cotton_todos".to_string(), 3), ("cotton_notes".to_string(), 1), ]), sent: BTreeMap::new(), passed: BTreeMap::from([("cotton_todos".to_string(), 3), ("cotton_stories".to_string(), 7)]), handed: 1, }); assert_eq!(report.passed.get("cotton_todos"), Some(&7)); assert_eq!(report.total_passed(), 14, "receipts, summed across pages like the rows"); assert_eq!(report.handed, 3); assert_eq!(report.received.get("cotton_todos"), Some(&5)); assert_eq!(report.received.get("cotton_notes"), Some(&1)); assert_eq!(report.total_received(), 6); assert_eq!(report.total_sent(), 1); assert_eq!(report.tables(), vec!["cotton_notes", "cotton_todos"]); } // RULE: A share of "what was owed" is counted in CHANGES (receipts), the unit the serving Mac counts what it owes in: the report says how many receipts the peer's answers moved this file past and how many of its own outbox it handed over, beside the rows — one row is several receipts, so rows taken in stop short of the whole (sync programme lane A, 12 Oct 2026). #[test] fn the_report_counts_changes_passed_and_handed_beside_rows() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); // Two receipts, ONE row, on each side. write(&db, "device:a", &[todo("t1", "First")]); write(&db, "device:a", &[todo("t1", "Second")]); write(&peer.db, "device:b", &[todo("t2", "First")]); write(&peer.db, "device:b", &[todo("t2", "Second")]); let report = settle(&db, &mut peer); assert_eq!(report.received.get("cotton_todos"), Some(&1), "one row came"); assert_eq!(report.passed.get("cotton_todos"), Some(&2), "in two changes"); assert_eq!(report.total_sent(), 1, "one row went"); assert_eq!(report.handed, 2, "in two changes"); } // RULE: What an answer says it moved the caller past is every receipt its page was dealt, counted before anything is left out of the page — the caller's own writes echoed back here — and a caller of a peer that does not say counts the receipts the page carried. #[test] fn an_answer_counts_what_it_passed_before_anything_is_left_out() { let here = seeded("device:server"); let ops = { let there = seeded("device:a"); write(&there, "device:a", &[todo("t1", "Ours")]) }; let already = handled(&ops); fold_incoming(&here, &ops).expect("the fold"); let seen = BTreeMap::new(); let plain = answer(&here, &seen, 500).expect("an answer"); let excluded = answer_excluding(&here, &seen, 500, &already).expect("an answer"); assert!(excluded.ops.len() < plain.ops.len(), "the echo was left out"); assert_eq!(excluded.passed, plain.passed, "and counted as passed all the same"); assert_eq!(plain.passed.values().sum::(), plain.ops.len() as u64); // A peer that says, and one that does not. let mut peer = Peer::new("device:server"); write(&peer.db, "device:b", &[todo("t2", "First")]); write(&peer.db, "device:b", &[todo("t2", "Second")]); let db = seeded("device:a"); exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect("an exchange"); let mut request = peer.seen[0].clone(); request.ops.clear(); request.cursors.clear(); let mut response = peer.exchange(&request).expect("an answer"); assert_eq!(passed(&response).get("cotton_todos"), Some(&2)); response.passed = Some(BTreeMap::from([("cotton_todos".to_string(), 9)])); assert_eq!(passed(&response).get("cotton_todos"), Some(&9), "the peer's own count wins"); response.passed = None; assert_eq!(passed(&response).values().sum::(), response.ops.len(), "a silent peer: what the page carried"); } #[test] fn sent_is_the_peers_answer_and_never_our_own_count() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); // Two ops, ONE row: a base patch and a column at its own stamp is the // ordinary shape, and counting the ops would say two. write(&db, "device:a", &[todo("t1", "First")]); write(&db, "device:a", &[todo("t1", "Second")]); assert_eq!(pending_count(&db).expect("counts"), 2); let exchanged = exchange_once(&db, &mut peer, WS, None, NOW, &mut Handover::default()).expect("an exchange"); assert_eq!( exchanged.report.sent.get("cotton_todos"), Some(&1), "one ROW moved, whatever the op count was" ); } #[test] fn a_rejected_op_is_absent_from_the_applied_map() { let db = seeded("device:server"); let good = peer_op( &db, crate::mint::Change::create("cotton_todos", "t1", todo("t1", "Fine").patch.expect("a patch")), "01J000000000000000000000AA", ); // A table this build never had: no `mint` would make it, so the receipt // is written out by hand, as a peer on a newer build would send it. let bad = crate::wire::from_receipt( "01J000000000000000000000BB".to_string(), &crate::canonical::Receipt { table: "no_such_table".to_string(), row_id: "t1".to_string(), kind: crate::canonical::Kind::Create, stamp: "1787394600000:0000:device:b".to_string(), author: "device:b".to_string(), actor: crate::fixtures::fixture_actor().to_wire(), schema: SCHEMA_VERSION, restamps: None, erase: None, undo: None, fields: std::collections::BTreeMap::from([("title".to_string(), json!("Fine"))]), }, ) .expect("an op"); let folded = fold_incoming(&db, &[good, bad]).expect("a fold"); assert_eq!(folded.applied_rows.get("cotton_todos"), Some(&1)); assert_eq!(folded.applied_rows.len(), 1); assert_eq!(folded.rejected.len(), 1); } #[test] fn a_row_created_then_edited_reaches_a_file_that_has_never_seen_it() { // THE ORDINARY SHAPE, and the one that would be silently lost: a row is // created and then one column of it is changed, so the row's columns sit at // two stamps — and a fresh file has to end up with the whole row. let db = seeded("device:a"); let mut peer = Peer::new("device:server"); write(&peer.db, "device:b", &[todo("t1", "the original")]); let mut patch = serde_json::Map::new(); patch.insert("status".to_string(), serde_json::json!("done")); patch.insert("updated_at".to_string(), serde_json::json!(NOW)); write( &peer.db, "device:b", &[LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: "cotton_todos".to_string(), row_id: "t1".to_string(), patch: Some(patch), }], ); settle(&db, &mut peer); assert_eq!(title(&db, "t1").as_deref(), Some("the original")); let status = db .get("SELECT status FROM cotton_todos WHERE id = 't1'", &[]) .expect("reads") .and_then(|row| row.text("status").map(str::to_string)); assert_eq!(status.as_deref(), Some("done")); assert!( crate::rejected::list_parked(&db, 10) .expect("the parked list") .is_empty(), "nothing was parked on the way in" ); } // ───────────────────────────────────────────────────────────────────────────── // The handover: what the peer has not seen, queue or no queue // ───────────────────────────────────────────────────────────────────────────── /// Empty the outbox the way another peer's drain would have. /// /// This is the whole shape of the bug the handover closes: the rows are still /// here, the queue that used to carry them is not. fn already_synced_elsewhere(db: &Driver) { db.run("DELETE FROM _outbox", &[]).expect("the queue empties"); assert_eq!(pending_count(db).expect("a count"), 0); } /// Every op this peer was ever handed, in order. fn handed_to(peer: &Peer) -> Vec { peer.seen .iter() .flat_map(|request| request.ops.clone()) .collect() } #[test] fn a_device_whose_outbox_is_empty_still_hands_over_what_the_peer_has_not_seen() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); write(&db, "device:a", &[todo("t1", "Ours"), todo("t2", "Also ours")]); // The rows went to some OTHER peer already: this device has the life and // an empty queue. Before the handover it would have said nothing at all. already_synced_elsewhere(&db); let report = settle(&db, &mut peer); assert_eq!(title(&peer.db, "t1").as_deref(), Some("Ours")); assert_eq!(title(&peer.db, "t2").as_deref(), Some("Also ours")); assert_eq!( report.sent.get("cotton_todos"), Some(&2), "the peer's own answer counts both rows: {:?}", report.sent ); } #[test] fn a_third_authors_rows_reach_the_peer_too() { // The joiner is not the author. A device that has been syncing with a // laptop holds that laptop's writes, and on a join they are exactly as // owed to the new peer as its own. let db = seeded("device:a"); let mut peer = Peer::new("device:server"); write(&db, "device:laptop", &[todo("t-laptop", "From the laptop")]); already_synced_elsewhere(&db); settle(&db, &mut peer); assert_eq!( title(&peer.db, "t-laptop").as_deref(), Some("From the laptop") ); let author = peer .db .get( "SELECT substr(_hlc, 20) AS author FROM cotton_todos WHERE id = 't-laptop'", &[], ) .expect("reads") .and_then(|row| row.text("author").map(str::to_string)); assert_eq!( author.as_deref(), Some("device:laptop"), "the row keeps its own author across the handover" ); } #[test] fn a_catch_up_pages_and_hands_no_row_over_twice() { // More rows than one handover page, so the pass has to walk the author's // stream — and the cursor it walks by is the pass's own, advanced as pages // are BUILT rather than re-derived from an answer that has not come back // yet. let db = seeded("device:a"); let mut peer = Peer::new("device:server"); let many: Vec = (0..(HANDOVER_PAGE_ROWS + 37)) .map(|n| todo(&format!("t{n:04}"), &format!("Row {n}"))) .collect(); write(&db, "device:a", &many); already_synced_elsewhere(&db); let report = settle(&db, &mut peer); assert_eq!( count_rows(&peer.db, "cotton_todos"), many.len() as i64, "every row crossed" ); assert_eq!( report.sent.get("cotton_todos"), Some(&many.len()), "the peer applied each row exactly once: {:?}", report.sent ); let handed = handed_to(&peer); let unique: std::collections::BTreeSet<&str> = handed.iter().map(|op| op.op_id.as_str()).collect(); assert_eq!( unique.len(), handed.len(), "a row was handed over twice in one pass" ); assert!(peer.seen.len() > 1, "the catch-up really did page"); } #[test] fn a_hand_over_deals_its_page_across_every_author_too() { // The same starvation in the other direction: a device joining a fresh // Mac with a big archive under one author and a laptop's few rows under // another must not make the laptop's rows wait for the archive. let db = seeded("device:a"); let mut peer = Peer::new("device:server"); let many: Vec = (0..(HANDOVER_PAGE_ROWS + 50)) .map(|n| todo(&format!("a{n:04}"), "Archive")) .collect(); write(&db, "device:a", &many); write(&db, "device:laptop", &[todo("t-laptop", "From the laptop")]); already_synced_elsewhere(&db); // The first call learns where the peer stands; the second hands over. let mut handover = Handover::default(); exchange_once(&db, &mut peer, WS, None, NOW, &mut handover).expect("an exchange"); let handed = exchange_request(&db, WS, None, &mut handover).expect("a request"); assert!( handed.request.ops.iter().any(|op| op.row_id == "t-laptop"), "the laptop's row is on the first page of the hand-over" ); assert!( handed.request.ops.len() <= HANDOVER_PAGE_ROWS, "and the page is still a page: {}", handed.request.ops.len() ); } #[test] fn a_device_behind_on_nothing_sends_nothing_extra() { // The ordinary minute. A pass that went looking for what the peer had not // seen and found nothing must cost one string comparison per author and // put NO ops on the wire — a catch-up that chatters every minute is a // catch-up nobody can leave running. let db = seeded("device:a"); let mut peer = Peer::new("device:server"); write(&db, "device:a", &[todo("t1", "Ours")]); settle(&db, &mut peer); peer.seen.clear(); let report = settle(&db, &mut peer); assert!( handed_to(&peer).is_empty(), "the second pass put ops on the wire: {:?}", handed_to(&peer) ); assert_eq!(report.total_sent(), 0); assert_eq!(report.total_received(), 0); } #[test] fn the_answer_does_not_hand_back_what_the_caller_just_handed_over() { // The responder folds first and answers second, so a row that has just // arrived is in this file at a stamp above the caller's own cursor — and // without this it would go straight back to the device that wrote it. On a // join that is a whole life, twice. let here = seeded("device:server"); let ops = { let there = seeded("device:a"); write(&there, "device:a", &[todo("t1", "Ours")]) }; let already = handled(&ops); fold_incoming(&here, &ops).expect("the fold"); // A caller whose cursor map has never heard of `device:a` — which is what // a device handing its own writes over looks like. let seen = BTreeMap::new(); let plain = answer(&here, &seen, 500).expect("an answer"); assert!( plain.ops.iter().any(|op| op.row_id == "t1"), "without the exclusion the row comes back" ); let excluded = answer_excluding(&here, &seen, 500, &already).expect("an answer"); assert!( !excluded.ops.iter().any(|op| op.row_id == "t1"), "the row the caller just sent came back anyway" ); // And the cursor still moves past it, which is honest: the caller has that // row — it sent it. assert_eq!(excluded.cursors, plain.cursors); } #[test] fn a_newer_write_of_a_row_the_caller_sent_still_comes_back() { // The exclusion is on the WHOLE triple and never on `(table, row)`: this // file may hold a NEWER write of the same row than the one that just // arrived, and dropping that would lose it. let here = seeded("device:server"); let there = seeded("device:a"); let stale = write(&there, "device:a", &[todo("t1", "The old title")]); // The responder's own row, written after — same row, later stamp. fold_incoming(&here, &stale).expect("the first fold"); let newer = vec![crate::wire::op_of_change( &here, &crate::mint::Change::update( "cotton_todos", "t1", json!({ "title": "The new title" }).as_object().cloned().expect("an object"), ), "1787394700000:0000:device:server", "device:server", &crate::fixtures::fixture_actor(), "01J0000000000000000000NEWR".to_string(), ) .expect("a receipt")]; fold_incoming(&here, &newer).expect("the second fold"); let answered = answer_excluding(&here, &BTreeMap::new(), 500, &handled(&stale)) .expect("an answer"); assert!( answered .ops .iter() .any(|op| op.row_id == "t1" && op.hlc == "1787394700000:0000:device:server"), "the peer's newer write of the same row was dropped: {:?}", answered.ops ); } #[test] fn the_answer_says_how_far_this_file_has_seen_each_author() { // The half that makes the handover possible at all: a caller cannot know // what to send until the peer says where it is. let here = seeded("device:server"); let there = seeded("device:a"); let ops = write(&there, "device:a", &[todo("t1", "Ours")]); fold_incoming(&here, &ops).expect("the fold"); let answered = answer(&here, &BTreeMap::new(), 500).expect("an answer"); assert_eq!( answered.seen.get("device:a").map(String::as_str), Some(ops[0].hlc.as_str()), "the responder's position on the author it just folded: {:?}", answered.seen ); } fn count_rows(db: &Driver, table: &str) -> i64 { db.get(&format!("SELECT COUNT(*) AS n FROM {table}"), &[]) .expect("a count") .and_then(|row| row.int("n")) .unwrap_or(-1) } // ── a page is handed over in write order ──────────────────────────────────── // // Half of the 2026-09-22 loss (Cotton note "Repo landmines — why the build's rules exist"). A page is // ordered where it is BUILT: the fold applies a batch in the order it is given // and records `applied` / `skipped_stale` from it, so `answer` sorts the // response and this sorts the request. Until version 25 nothing did: `_outbox` // was read by `op_id`, which carries no order at all (this crate mints no op // ids — spec R7 — and the Mac's source is a random UUID), and the catch-up half // was appended after it. /// One queued op, its receipt made directly so a case can choose its id and /// its stamp independently — which is the whole point. A patch naming `id` is /// the row's create; any other is a change. fn queue(db: &Driver, op_id: &str, hlc_ms: i64, patch: serde_json::Value) { let patch = patch.as_object().cloned().expect("an object"); let change = if patch.contains_key("id") { crate::mint::Change::create("cotton_sessions", "s1", patch) } else { crate::mint::Change::update("cotton_sessions", "s1", patch) }; let op = crate::wire::op_of_change( db, &change, &format!("{hlc_ms:013}:0000:device:a"), "device:a", &crate::fixtures::fixture_actor(), op_id.to_string(), ) .expect("a receipt"); crate::outbox::queue_ops(db, std::slice::from_ref(&op), NOW).expect("a queued op"); } #[test] fn a_page_is_handed_over_in_write_order_whatever_the_op_ids_say() { let db = seeded("device:a"); // The amendment's id sorts FIRST and its stamp is LAST — a random UUID has // every chance of doing exactly this. queue( &db, "aaaa-the-amendment", 1_790_000_037_472, json!({ "external_id": "19d6eb6a-0000-4000-8000-000000000001", "machine": "mac-c", "state": "running", }), ); queue( &db, "zzzz-the-creation", 1_790_000_000_000, json!({ "id": "s1", "workspace_id": WS, "tool": "claude-code", "state": "queued", "last_active_at": NOW, "created_at": NOW, "updated_at": NOW, }), ); let mut handover = Handover::default(); let handed = exchange_request(&db, WS, None, &mut handover).expect("a request"); let ids: Vec<&str> = handed .request .ops .iter() .map(|op| op.op_id.as_str()) .collect(); assert_eq!(ids, vec!["zzzz-the-creation", "aaaa-the-amendment"]); // The sort runs over the WHOLE `ops` vector, after the catch-up half has // been appended — two sorted halves are still one unsorted page, and the // queued half is the one whose stamps can sit either side of the other's. // // AND THE PEER CAN TAKE IT. Backwards, the amendment is an INSERT of three // columns and the first NOT NULL refuses it — the write is parked and the // row is missing there. let peer = seeded("device:server"); let result = crate::fold::fold_ops(&peer, &handed.request.ops).expect("the peer folds"); assert!( result.rejected.is_empty(), "nothing is refused: {:?}", result.rejected ); let landed = peer .get( "SELECT external_id, state FROM cotton_sessions WHERE id = 's1'", &[], ) .expect("a read") .expect("the row"); assert_eq!( landed.text("external_id"), Some("19d6eb6a-0000-4000-8000-000000000001") ); assert_eq!(landed.text("state"), Some("running")); } // ───────────────────────────────────────────────────────────────────────────── // THE GUARD: a whole file of fragmented rows, and nothing left parked // ───────────────────────────────────────────────────────────────────────────── /// One local write at an explicit millisecond. /// /// `write` freezes every stamp at the same millisecond, which is right for a /// case about two writes racing and wrong for a case that needs FORTY-EIGHT of /// them: the ids are seeded from a counter and a ULID's random half is sixteen /// base-32 digits, so two calls far enough apart in the counter can render the /// same id and `_outbox.op_id` is a primary key. A distinct millisecond gives /// each write its own timestamp half, and it is also what makes the amendment /// of a row strictly newer than its creation. fn write_at(db: &Driver, device_id: &str, ms: i64, changes: &[LocalChange]) -> Vec { let mut seed = ms as u64; let mut ids = Monotonic::new(move |bytes: &mut [u8]| { for byte in bytes.iter_mut() { *byte = (seed & 0xff) as u8; seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); } }); write_as(db, device_id, ms, changes, &mut ids) } /// How many pull writes this file could not fold. fn parked_pulls(db: &Driver) -> Vec { crate::rejected::list_parked(db, 1_000) .expect("the parked list") .into_iter() .filter(|row| row.direction == "pull") .collect() } #[test] fn a_file_of_fragmented_rows_reaches_a_fresh_replica_with_nothing_parked() { // The regression guard for the whole of this. Every row here is // FRAGMENTED — created by one device and amended by another, so its // columns sit at two stamps in two different authors' streams — and the // page is ONE ROW WIDE, which is the harshest order a peer can serve: a // row's ops can only ever arrive across pages, and the two authors are // dealt round by round. A file that ends this with anything parked is a // file where a person's rows are missing and nobody is going to ask again. let db = seeded("device:replica"); let mut peer = Peer::new("device:server"); for n in 0..24i64 { let id = format!("t{n:02}"); write_at(&peer.db, "device:b", NOW_MS + n * 2, &[todo(&id, "the original")]); let mut patch = serde_json::Map::new(); patch.insert("status".to_string(), json!("done")); patch.insert("updated_at".to_string(), json!(NOW)); write_at( &peer.db, "device:c", NOW_MS + n * 2 + 1, &[LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: "cotton_todos".to_string(), row_id: id.clone(), patch: Some(patch), }], ); } let mut handover = Handover::default(); for _ in 0..500 { let page = exchange_once(&db, &mut peer, WS, Some(1), NOW, &mut handover) .expect("an exchange"); if !page.has_more { break; } } assert_eq!( parked_pulls(&db), Vec::new(), "every fragmented row folded whole" ); let rows = db .get( "SELECT COUNT(*) AS n FROM cotton_todos WHERE title = 'the original' \ AND status = 'done'", &[], ) .expect("reads") .and_then(|row| row.int("n")); assert_eq!(rows, Some(24), "and it is the whole row, not the creation"); } // RULE: a client refuses an older serving epoch without applying rows, moving cursors or settling its outbox against a file nobody reads. // The outbox stays ready for the Mac that serves now. #[test] fn client_refuses_an_answer_from_an_older_serving_epoch() { let db = seeded("device:a"); db.run( "INSERT INTO cotton_serving_machine \ (id, workspace_id, epoch, device_credential_id, author_id, since) \ VALUES ('s-2', ?, 2, 'device:new-mac', 'author-new', '2026-10-03T00:00:00.000Z')", &[rusqlite::types::Value::Text(WS.to_string())], ) .expect("the fact this device has heard of"); write(&db, "device:a", &[todo("t1", "Mine")]); let peer = seeded("device:old-mac"); let theirs = write(&peer, "device:b", &[todo("t2", "The old Mac's")]); let mut handover = Handover::default(); let handed = exchange_request(&db, WS, None, &mut handover).expect("a request"); let before = read_cursors(&db).expect("cursors"); let answer = |serving_epoch| ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WS.to_string(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops: theirs.clone(), cursors: crate::cursors::cursor_ceiling(&peer).expect("the old Mac's ceiling"), has_more: false, applied_rows: BTreeMap::from([("cotton_todos".to_string(), 1)]), rejected: Vec::new(), seen: Default::default(), serving_epoch, server_time: None, restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }; for old in [Some(1), None] { let refused = fold_answer(&db, &handed, &answer(old), NOW, &mut handover) .expect_err("an older term's answer is refused"); assert!( refused.to_string().starts_with("an old Mac is answering"), "{refused}" ); assert_eq!(title(&db, "t2"), None, "nothing of the answer is applied"); assert_eq!(pending_count(&db).expect("counts"), 1, "the outbox is kept"); assert_eq!(read_cursors(&db).expect("cursors"), before, "no cursor moved"); } fold_answer(&db, &handed, &answer(Some(2)), NOW, &mut handover) .expect("the serving term's own answer folds"); assert_eq!(title(&db, "t2").as_deref(), Some("The old Mac's")); assert_eq!(pending_count(&db).expect("counts"), 0); } /// RULE: a replica records the newest serving epoch an answer names, never lowers it, and refuses a later answer below it before that epoch's fact has arrived. /// /// The first answer from a Mac that took over names its epoch before the fact /// naming that Mac reaches this file. Without the heard epoch, the old Mac /// answering next would be taken, and the replica would settle its outbox /// against a file nobody reads; `owes_hand_over` reads the same number. #[test] fn a_replica_remembers_the_newest_epoch_an_answer_named() { let db = seeded("device:a"); let heard = |db: &Driver| { db.get("SELECT heard_serving_epoch FROM _meta", &[]) .expect("a read") .and_then(|row| row.int("heard_serving_epoch")) }; assert_eq!(heard(&db), None, "a fresh file has heard of no epoch"); let peer = seeded("device:old-mac"); let theirs = write(&peer, "device:b", &[todo("t2", "The old Mac's")]); let answer = |serving_epoch, ops: Vec| ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WS.to_string(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops, cursors: crate::cursors::cursor_ceiling(&peer).expect("the peer's ceiling"), has_more: false, applied_rows: BTreeMap::new(), rejected: Vec::new(), seen: Default::default(), serving_epoch, 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 mut handover = Handover::default(); // The new Mac's first answer: epoch 3, no fact, nothing to fold. let handed = exchange_request(&db, WS, None, &mut handover).expect("a request"); fold_answer(&db, &handed, &answer(Some(3), Vec::new()), NOW, &mut handover) .expect("a newer term's answer folds"); assert_eq!(heard(&db), Some(3)); assert_eq!( crate::serving::serving_fact(&db, WS).expect("a read"), None, "the fact has not arrived; only the answer named the epoch" ); // The old Mac answers next, below the heard epoch or naming none. write(&db, "device:a", &[todo("t1", "Mine")]); let handed = exchange_request(&db, WS, None, &mut handover).expect("a request"); let before = read_cursors(&db).expect("cursors"); for old in [Some(2), None] { let refused = fold_answer(&db, &handed, &answer(old, theirs.clone()), NOW, &mut handover) .expect_err("an answer below the heard epoch is refused"); assert!( matches!(refused, SyncError::OldServing { held: 3, answered } if answered == old), "{refused}" ); assert_eq!(title(&db, "t2"), None, "nothing of the answer is applied"); assert_eq!(pending_count(&db).expect("counts"), 1, "the outbox is kept"); assert_eq!(read_cursors(&db).expect("cursors"), before, "no cursor moved"); assert_eq!(heard(&db), Some(3), "a refused answer never lowers it"); } // A newer one raises it; the same epoch again leaves it. fold_answer(&db, &handed, &answer(Some(4), Vec::new()), NOW, &mut handover) .expect("a newer term's answer folds"); assert_eq!(heard(&db), Some(4)); fold_answer(&db, &handed, &answer(Some(4), Vec::new()), NOW, &mut handover) .expect("the same term's answer folds"); assert_eq!(heard(&db), Some(4)); } // ───────────────────────────────────────────────────────────────────────────── // The hand-over to a Mac that took over (slice 12) // ───────────────────────────────────────────────────────────────────────────── /// A phone P that handed over to epoch 1, and the Mac serving epoch 2 from a /// backup: P's author `device:p` wrote p1..p6; the backup held p1, p2 (the /// restore point), and P's outage writes p5, p6 reached the new Mac first, so /// its `seen` for `device:p` is p6 while p3, p4 exist only on P. Author /// `device:q` (q1, q2) is absent from `restored` — paired after the restore /// point — and the new Mac holds only q2. P's outbox is one write at /// reconnect, p7. struct TakenOver { phone: Driver, mac: Peer, p: Vec, q: Vec, } fn taken_over() -> TakenOver { let phone = seeded("device:a"); let p: Vec = (1..=6) .flat_map(|n| write(&phone, "device:p", &[todo(&format!("p{n}"), &format!("P's write {n}"))])) .collect(); let q: Vec = (1..=2) .flat_map(|n| write(&phone, "device:q", &[todo(&format!("q{n}"), &format!("Q's write {n}"))])) .collect(); phone.run("DELETE FROM _outbox", &[]).expect("the old pushes landed long ago"); phone.run("UPDATE _meta SET handed_over_epoch = 1", &[]).expect("handed over to epoch 1"); write(&phone, "device:p", &[todo("p7", "P's write at reconnect")]); let mut mac = Peer::new("device:new-mac"); let held: Vec = [&p[0], &p[1], &p[4], &p[5], &q[1]].into_iter().cloned().collect(); fold_incoming(&mac.db, &held).expect("the new Mac's file"); mac.epoch = Some((2, Some(BTreeMap::from([("device:p".to_string(), p[1].hlc.clone())])))); TakenOver { phone, mac, p, q } } fn handed_over_mark(db: &Driver) -> Option { handed_over_epoch(db).expect("a read") } // RULE: a hand-over to a new epoch starts each author at min(restored, seen), never at seen — what the old Mac applied and its backup lacked reaches the new Mac from the device that holds it. #[test] fn handover_after_take_over_starts_from_the_restore_point_not_seen() { let TakenOver { phone, mut mac, p, .. } = taken_over(); assert!(mac.db.get("SELECT 1 FROM cotton_todos WHERE id = 'p3'", &[]).expect("a read").is_none()); settle(&phone, &mut mac); for n in 1..=7 { assert!(title(&mac.db, &format!("p{n}")).is_some(), "the new Mac lacks p{n}"); } let handed: Vec = handed_to(&mac).into_iter().map(|op| op.op_id).collect(); assert!(handed.contains(&p[2].op_id) && handed.contains(&p[3].op_id), "p3, p4 were handed over"); assert!(!handed.contains(&p[0].op_id), "nothing at or below the restore point goes again"); } /// RULE: When a phone's outbox reaches the new Mac before any hand-over page, raising its seen to the newest write, the hand-over still sends everything above the restore point the new Mac lacks, and the outbox replay folds as a no-op. #[test] fn outbox_first_pass_after_take_over_still_hands_over_the_unbacked_middle() { let phone = seeded("device:a"); // p1..p10 reached the old Mac; its backup held p1..p3. let p: Vec = (1..=10) .flat_map(|n| write(&phone, "device:p", &[todo(&format!("p{n}"), &format!("P's write {n}"))])) .collect(); phone.run("DELETE FROM _outbox", &[]).expect("the old pushes landed long ago"); phone.run("UPDATE _meta SET handed_over_epoch = 1", &[]).expect("handed over to epoch 1"); // The outage writes p11, p12, still queued. let outbox: Vec = (11..=12) .flat_map(|n| write(&phone, "device:p", &[todo(&format!("p{n}"), &format!("P's write {n}"))])) .collect(); let mut mac = Peer::new("device:new-mac"); fold_incoming(&mac.db, &p[..3]).expect("the restored file"); // The outbox reached the new Mac first (its answer lost, so still queued). fold_incoming(&mac.db, &outbox).expect("the outbox landed first"); mac.epoch = Some((2, Some(BTreeMap::from([("device:p".to_string(), p[2].hlc.clone())])))); assert_eq!( crate::cursors::cursor_ceiling(&mac.db).expect("a ceiling").get("device:p"), Some(&outbox[1].hlc), "the new Mac's seen for P is p12, or the test proves nothing" ); assert_eq!(pending_count(&phone).expect("counts"), 2); settle(&phone, &mut mac); for n in 4..=10 { assert_eq!( title(&mac.db, &format!("p{n}")).as_deref(), Some(format!("P's write {n}").as_str()), "the new Mac lacks p{n}" ); } let handed: Vec = handed_to(&mac).into_iter().map(|op| op.op_id).collect(); for op in &p[3..] { assert!(handed.contains(&op.op_id), "{} was not handed over", op.row_id); } assert_eq!(pending_count(&phone).expect("counts"), 0, "the replayed outbox drained"); assert_eq!(handed_over_mark(&phone), Some(2), "the pass completed"); } // RULE: an author absent from `restored` is handed over from nothing, never from `seen` — a receipt below `seen` that the new Mac lacks is still sent. #[test] fn author_absent_from_restored_is_handed_over_from_nothing() { let TakenOver { phone, mut mac, q, .. } = taken_over(); settle(&phone, &mut mac); assert_eq!(title(&mac.db, "q1").as_deref(), Some("Q's write 1"), "q1, below seen, arrived"); let handed: Vec = handed_to(&mac).into_iter().map(|op| op.op_id).collect(); assert!(handed.contains(&q[0].op_id)); } // RULE: a hand-over pass's first request folds nothing; its later requests carry handingOverTo and are folded; the outbox waits for the hand-over; handedOverEpoch is written only when the pass completes. #[test] fn hand_over_pass_requests_are_folded_by_the_new_epoch() { let TakenOver { phone, mut mac, .. } = taken_over(); let mut handover = Handover::default(); let first = exchange_once(&phone, &mut mac, WS, None, NOW, &mut handover).expect("the first call"); let asked = mac.seen[0].clone(); assert_eq!((asked.handed_over_epoch, asked.handing_over_to), (Some(1), None)); assert_eq!(title(&mac.db, "p7"), None, "the first request folds nothing"); assert_eq!(pending_count(&phone).expect("counts"), 1, "and its outbox stays queued"); assert_eq!(handover.handing_over_to(), Some(2), "the answer started a pass to epoch 2"); assert_eq!(handed_over_mark(&phone), Some(1)); assert!(first.has_more); let second = exchange_once(&phone, &mut mac, WS, None, NOW, &mut handover).expect("the second call"); let asked = mac.seen[1].clone(); assert_eq!(asked.handing_over_to, Some(2), "a later request carries the pass's target"); assert_eq!(title(&mac.db, "p3").as_deref(), Some("P's write 3"), "the pass's requests are folded"); assert_eq!(pending_count(&phone).expect("counts"), 1, "the outbox waited for the hand-over"); assert_eq!(handed_over_mark(&phone), Some(1), "not written before the pass completes"); assert!(second.has_more); for _ in 0..5 { if !exchange_once(&phone, &mut mac, WS, None, NOW, &mut handover) .expect("the pass") .has_more { break; } } assert_eq!(pending_count(&phone).expect("counts"), 0, "the outbox drained after the hand-over"); assert_eq!(title(&mac.db, "p7").as_deref(), Some("P's write at reconnect")); assert_eq!(handed_over_mark(&phone), Some(2), "the completed pass wrote its mark"); } fn parked_ids(db: &Driver, direction: &str) -> Vec { db.all("SELECT op_id FROM _parked WHERE direction = ?", &[SqlValue::Text(direction.to_string())]) .expect("reads") .iter() .map(|row| row.text("op_id").unwrap_or_default().to_string()) .collect() } // RULE: a hand-over pass carries every parked pull above its author's start position — a receipt the old Mac served and the phone could not fold may exist nowhere else — and leaves the park standing here. #[test] fn handover_after_restore_includes_parked_receipts() { let TakenOver { phone, mut mac, p, .. } = taken_over(); // Two receipts the old Mac served that the phone parked: one by author // `device:r`, absent from `restored`, and one by `device:p` at or below // the restore point, which the new Mac holds. let elsewhere = seeded("device:elsewhere"); let r = write(&elsewhere, "device:r", &[todo("r1", "R's write")]); crate::rejected::park(&phone, &r[0], Direction::Pull, Class::Conflict, "a refusal", NOW).expect("parks"); crate::rejected::park(&phone, &p[1], Direction::Pull, Class::Conflict, "a refusal", NOW).expect("parks"); settle(&phone, &mut mac); assert_eq!(title(&mac.db, "r1").as_deref(), Some("R's write"), "the parked pull reached the new Mac"); let handed: Vec = handed_to(&mac).into_iter().map(|op| op.op_id).collect(); assert_eq!(handed.iter().filter(|id| **id == r[0].op_id).count(), 1, "once"); assert!(!handed.contains(&p[1].op_id), "a park at or below the restore point does not go"); assert!(parked_ids(&phone, "pull").contains(&r[0].op_id), "it is still missing here"); assert_eq!(handed_over_mark(&phone), Some(2), "the pass completed"); } // RULE: a hand-over pass re-offers each parked push once, at its stamp, even below its author's start position — the old Mac refused it, the new one judges it afresh — and a re-offer the new Mac takes ends its park. #[test] fn phone_push_parks_are_resent_after_restore() { let TakenOver { phone, mut mac, p, .. } = taken_over(); // `device:s` wrote s1, which the old Mac refused, then s2, which the // backup holds: the restore point names s2, above s1. let s1 = write(&phone, "device:s", &[todo("s1", "S's refused write")]); let s2 = write(&phone, "device:s", &[todo("s2", "S's later write")]); phone.run("DELETE FROM _outbox WHERE op_id IN (?, ?)", &[SqlValue::Text(s1[0].op_id.clone()), SqlValue::Text(s2[0].op_id.clone())]).expect("the pushes were answered"); crate::rejected::park(&phone, &s1[0], Direction::Push, Class::Conflict, "the old Mac refused it", NOW).expect("parks"); fold_incoming(&mac.db, &s2).expect("the backup held s2"); mac.epoch = Some(( 2, Some(BTreeMap::from([ ("device:p".to_string(), p[1].hlc.clone()), ("device:s".to_string(), s2[0].hlc.clone()), ])), )); settle(&phone, &mut mac); assert_eq!(title(&mac.db, "s1").as_deref(), Some("S's refused write"), "the new Mac took the re-offer"); let handed: Vec = handed_to(&mac).into_iter().map(|op| op.op_id).collect(); assert_eq!(handed.iter().filter(|id| **id == s1[0].op_id).count(), 1, "re-offered once"); assert!(parked_ids(&phone, "push").is_empty(), "the delivered park ended"); assert_eq!(handed_over_mark(&phone), Some(2), "the pass completed"); } fn handover_offers(db: &Driver, op_id: &str) -> (Option, i64) { let row = db .get("SELECT handover_epoch, handover_offers FROM _parked WHERE op_id = ?", &[SqlValue::Text(op_id.to_string())]) .expect("reads") .expect("still parked"); (row.int("handover_epoch"), row.int("handover_offers").unwrap_or(-1)) } /// One cycle of a pass that never completes: a fresh `Handover`, as every /// cycle builds, run until the exchange says nothing more would move. fn one_cycle(phone: &Driver, mac: &mut Peer) { let mut handover = Handover::default(); for _ in 0..10 { if !exchange_once(phone, mac, WS, None, NOW, &mut handover).expect("an exchange").has_more { break; } } } // RULE: a hand-over pass that never completes offers a refused park to one serving epoch at most HANDOVER_OFFER_CEILING times; it stays parked, a newer epoch offers it again, and one the peer takes ends. #[test] fn a_refused_park_is_offered_to_an_epoch_a_bounded_number_of_times_and_again_to_a_new_one() { let TakenOver { phone, mut mac, p, .. } = taken_over(); // `phone_push_parks_are_resent_after_restore`'s shape: s1 refused by the // old Mac, s2 held by the backup, so s1 travels only as a park. let s1 = write(&phone, "device:s", &[todo("s1", "S's refused write")]); let s2 = write(&phone, "device:s", &[todo("s2", "S's later write")]); phone.run("DELETE FROM _outbox WHERE op_id IN (?, ?)", &[SqlValue::Text(s1[0].op_id.clone()), SqlValue::Text(s2[0].op_id.clone())]).expect("answered"); crate::rejected::park(&phone, &s1[0], Direction::Push, Class::Conflict, "the old Mac refused it", NOW).expect("parks"); fold_incoming(&mac.db, &s2).expect("the backup held s2"); let restored = BTreeMap::from([ ("device:p".to_string(), p[1].hlc.clone()), ("device:s".to_string(), s2[0].hlc.clone()), ]); mac.epoch = Some((2, Some(restored.clone()))); // The new Mac refuses the park, and HOLDS the phone's queued write p7 — // so the pass never completes and every cycle starts it again. mac.refuse_ids.insert(s1[0].op_id.clone()); let p7 = phone .get("SELECT op_id FROM _outbox", &[]) .expect("reads") .and_then(|row| row.text("op_id").map(str::to_string)) .expect("p7 is queued"); mac.hold_ids.insert(p7); let offers = |mac: &Peer| handed_to(mac).iter().filter(|op| op.op_id == s1[0].op_id).count(); for _ in 0..(crate::rejected::HANDOVER_OFFER_CEILING + 3) { one_cycle(&phone, &mut mac); } assert_eq!(handed_over_mark(&phone), Some(1), "the pass never completed"); assert_eq!(offers(&mac) as i64, crate::rejected::HANDOVER_OFFER_CEILING, "offered to epoch 2 exactly the ceiling"); assert_eq!(handover_offers(&phone, &s1[0].op_id), (Some(2), crate::rejected::HANDOVER_OFFER_CEILING)); assert!(parked_ids(&phone, "push").contains(&s1[0].op_id), "refused, it stays parked"); // A NEW epoch asks afresh: offered again, counted from one. mac.epoch = Some((3, Some(restored))); one_cycle(&phone, &mut mac); assert_eq!(offers(&mac) as i64, crate::rejected::HANDOVER_OFFER_CEILING + 1, "epoch 3 was offered it"); assert_eq!(handover_offers(&phone, &s1[0].op_id), (Some(3), 1)); // And when the new Mac takes it, the park ends. mac.refuse_ids.clear(); one_cycle(&phone, &mut mac); assert_eq!(title(&mac.db, "s1").as_deref(), Some("S's refused write")); assert!(!parked_ids(&phone, "push").contains(&s1[0].op_id), "the taken park ended"); } // RULE: a write the peer refused as final travels only as a park — a hand-over pass that starts its author below it offers it to one epoch at most HANDOVER_OFFER_CEILING times in all, stream and park together; a new epoch offers it again. #[test] fn a_refused_write_below_the_start_position_is_offered_to_an_epoch_a_bounded_number_of_times() { let TakenOver { phone, mut mac, p, .. } = taken_over(); // `device:s` is absent from `restored`, so the pass starts it from // nothing — below s1, which the old Mac refused, and s2, which it took. let s1 = write(&phone, "device:s", &[todo("s1", "S's refused write")]); let s2 = write(&phone, "device:s", &[todo("s2", "S's later write")]); phone.run("DELETE FROM _outbox WHERE op_id IN (?, ?)", &[SqlValue::Text(s1[0].op_id.clone()), SqlValue::Text(s2[0].op_id.clone())]).expect("answered"); crate::rejected::park(&phone, &s1[0], Direction::Push, Class::Conflict, "the old Mac refused it", NOW).expect("parks"); let restored = BTreeMap::from([("device:p".to_string(), p[1].hlc.clone())]); mac.epoch = Some((2, Some(restored.clone()))); // The new Mac refuses s1 too, and HOLDS the queued p7: the pass never // completes and every cycle starts `device:s` from nothing again. mac.refuse_ids.insert(s1[0].op_id.clone()); let p7 = phone .get("SELECT op_id FROM _outbox", &[]) .expect("reads") .and_then(|row| row.text("op_id").map(str::to_string)) .expect("p7 is queued"); mac.hold_ids.insert(p7.clone()); let offers = |mac: &Peer, op_id: &str| handed_to(mac).iter().filter(|op| op.op_id == op_id).count() as i64; let to_epoch = |mac: &Peer, epoch: i64, op_id: &str| { mac.seen .iter() .filter(|request| request.handing_over_to == Some(epoch) && request.ops.iter().any(|op| op.op_id == op_id)) .count() as i64 }; for _ in 0..(crate::rejected::HANDOVER_OFFER_CEILING + 3) { let before = to_epoch(&mac, 2, &p7); one_cycle(&phone, &mut mac); // A HELD write is not a refusal: p7 is offered to epoch 2 every cycle. assert!(to_epoch(&mac, 2, &p7) > before, "the held write is retried every cycle"); } assert_eq!(handed_over_mark(&phone), Some(1), "the pass never completed"); assert_eq!(title(&mac.db, "s2").as_deref(), Some("S's later write"), "the stream carried the rest of the author"); assert_eq!(offers(&mac, &s1[0].op_id), crate::rejected::HANDOVER_OFFER_CEILING, "offered to epoch 2 exactly the ceiling, stream and park together"); assert_eq!(handover_offers(&phone, &s1[0].op_id), (Some(2), crate::rejected::HANDOVER_OFFER_CEILING)); assert!(parked_ids(&phone, "push").contains(&s1[0].op_id), "refused, it stays parked"); assert_eq!(pending_count(&phone).expect("counts"), 1, "the held write stays queued"); // A NEW epoch asks afresh: offered again, counted from one. mac.epoch = Some((3, Some(restored))); one_cycle(&phone, &mut mac); assert_eq!(offers(&mac, &s1[0].op_id), crate::rejected::HANDOVER_OFFER_CEILING + 1, "epoch 3 was offered it"); assert_eq!(handover_offers(&phone, &s1[0].op_id), (Some(3), 1)); assert!(parked_ids(&phone, "push").contains(&s1[0].op_id), "still parked"); } /// A receipt this file HOLDS in `_writes` and has also parked as a PULL — /// what `fold::park_conflict` leaves when a dormant row's re-assembly clashes: /// `device:s`'s s1, absent from `restored`, so the pass starts it from nothing /// and both the stream and the park list could carry it. The new Mac HOLDS /// the queued p7, so the pass never completes. Answers s1 and p7's op ids. fn stored_pull_park(phone: &Driver, mac: &mut Peer, p: &[CottonOp]) -> (String, String, BTreeMap) { let s1 = write(phone, "device:s", &[todo("s1", "S's dormant write")]); phone.run("DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(s1[0].op_id.clone())]).expect("answered"); crate::rejected::park(phone, &s1[0], Direction::Pull, Class::Conflict, "unique clash on re-assembly", NOW).expect("parks"); let restored = BTreeMap::from([("device:p".to_string(), p[1].hlc.clone())]); mac.epoch = Some((2, Some(restored.clone()))); let p7 = phone .get("SELECT op_id FROM _outbox", &[]) .expect("reads") .and_then(|row| row.text("op_id").map(str::to_string)) .expect("p7 is queued"); mac.hold_ids.insert(p7.clone()); (s1[0].op_id.clone(), p7, restored) } /// How many requests to `epoch` carried `op_id`, and how many times in all. fn sent_to_epoch(mac: &Peer, epoch: i64, op_id: &str) -> (i64, i64) { let mut requests = 0; let mut copies = 0; for request in mac.seen.iter().filter(|request| request.handing_over_to == Some(epoch)) { let n = request.ops.iter().filter(|op| op.op_id == op_id).count() as i64; copies += n; requests += i64::from(n > 0); } (requests, copies) } // RULE: a stored receipt this file parked as a pull travels only as a park — a never-completing hand-over offers it to one epoch at most HANDOVER_OFFER_CEILING times, stream and park together, refused or taken; a new epoch offers it again. #[test] fn a_stored_pull_park_is_offered_to_an_epoch_a_bounded_number_of_times() { for refused in [true, false] { let TakenOver { phone, mut mac, p, .. } = taken_over(); let (s1, p7, restored) = stored_pull_park(&phone, &mut mac, &p); if refused { mac.refuse_ids.insert(s1.clone()); } for _ in 0..(crate::rejected::HANDOVER_OFFER_CEILING + 3) { let before = sent_to_epoch(&mac, 2, &p7).0; one_cycle(&phone, &mut mac); assert!(sent_to_epoch(&mac, 2, &p7).0 > before, "the held write is retried every cycle"); } assert_eq!(handed_over_mark(&phone), Some(1), "the pass never completed"); let (requests, copies) = sent_to_epoch(&mac, 2, &s1); assert_eq!(copies, requests, "never twice in one request (refused: {refused})"); assert_eq!(copies, crate::rejected::HANDOVER_OFFER_CEILING, "offered to epoch 2 exactly the ceiling (refused: {refused})"); assert_eq!(handover_offers(&phone, &s1), (Some(2), crate::rejected::HANDOVER_OFFER_CEILING)); assert!(parked_ids(&phone, "pull").contains(&s1), "nothing dropped: still parked here"); assert_eq!(title(&mac.db, "s1").is_some(), !refused, "the new Mac holds it only when it took it"); mac.epoch = Some((3, Some(restored))); one_cycle(&phone, &mut mac); assert_eq!(sent_to_epoch(&mac, 3, &s1).1, 1, "a new epoch is offered it again, once a cycle"); assert_eq!(handover_offers(&phone, &s1), (Some(3), 1)); } } // RULE: an ordinary pass never re-sends a push the peer refused as final — it is parked once, and only the bounded requeue offers it again; the author's stream leaves it out though the peer's `seen` is below it. #[test] fn an_ordinary_pass_never_resends_a_finally_refused_push() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); let t1 = write(&db, "device:a", &[todo("t1", "Doomed")]); peer.refuse_ids.insert(t1[0].op_id.clone()); for _ in 0..6 { one_cycle(&db, &mut peer); } let offers = handed_to(&peer).iter().filter(|op| op.op_id == t1[0].op_id).count(); assert_eq!(offers, 1, "sent once, from the outbox, and never again from the stream"); assert_eq!(parked_ids(&db, "push"), vec![t1[0].op_id.clone()], "parked once, still parked"); assert_eq!(pending_count(&db).expect("counts"), 0); } /// RULE: A write the Mac parked `waiting` for its author's fact is told to the phone that asked, parked there push-side and never offered again on every pass — the queue drains past it — and the park ends once the Mac's `seen` passes it, because the phone re-sent every such receipt on every pass, uncapped: 95 KB a pass for no row (16 Oct 2026). #[test] fn a_write_the_mac_parked_waiting_is_offered_once_and_ends_when_the_mac_holds_it() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); let t1 = write(&db, "device:a", &[todo("t1", "Waiting on a fact")]); peer.wait_ids.insert(t1[0].op_id.clone()); for _ in 0..3 { one_cycle(&db, &mut peer); } let offers = handed_to(&peer).iter().filter(|op| op.op_id == t1[0].op_id).count(); assert_eq!(offers, 1, "told once, and never sent again"); assert_eq!(pending_count(&db).expect("counts"), 0, "the queue drained past it"); assert_eq!(parked_ids(&db, "push"), vec![t1[0].op_id.clone()], "parked here, push-side"); peer.fact_arrives(); one_cycle(&db, &mut peer); assert_eq!(title(&peer.db, "t1").as_deref(), Some("Waiting on a fact")); assert!(parked_ids(&db, "push").is_empty(), "the Mac holds it, so the park ends"); } /// RULE: A write the Mac parked `newer-shape` — the device's build is ahead of the Mac's — is told to the device that parks, parked there push-side and never handed over again, and the park ends once the Mac has moved and folded it; the Mac's `seen` never names a parked receipt, so a device not told handed the same page over on every pass: 980 facts a minute from one Mac client, each folded and parked again (20 Oct 2026). #[test] fn a_write_the_mac_parked_newer_shape_is_handed_over_once() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); let here = crate::meta::file_schema_version(&peer.db).expect("stamp"); assert!(crate::rejected::keeps_newer_shape(&peer.db).expect("reads"), "this build's file parks newer-shape"); // The Mac is one build behind this device. peer.db.exec(&format!("PRAGMA user_version = {}", here - 1)).expect("stamps"); let t1 = write(&db, "device:a", &[todo("t1", "From a newer build")]); already_synced_elsewhere(&db); for _ in 0..5 { one_cycle(&db, &mut peer); } let offers = handed_to(&peer).iter().filter(|op| op.op_id == t1[0].op_id).count(); assert_eq!(offers, 1, "handed over once, never again on every pass"); assert_eq!(parked_ids(&db, "push"), vec![t1[0].op_id.clone()], "parked here, push-side"); assert_eq!(title(&peer.db, "t1"), None, "the Mac has not folded it yet"); // The Mac moves to this device's shape and folds what it parked. peer.db.exec(&format!("PRAGMA user_version = {here}")).expect("stamps"); crate::rejected::refold_newer_shape(&peer.db, NOW).expect("refolds"); one_cycle(&db, &mut peer); assert_eq!(title(&peer.db, "t1").as_deref(), Some("From a newer build")); assert!(parked_ids(&db, "push").is_empty(), "the Mac holds it, so the park ends"); } // RULE: a catch-up write the peer HELD (retryable) is never parked and goes again on the next pass — only a final refusal stops the stream offering it. #[test] fn a_held_catch_up_write_is_offered_again_on_every_pass() { let db = seeded("device:a"); let mut peer = Peer::new("device:server"); let t1 = write(&db, "device:a", &[todo("t1", "Waiting")]); already_synced_elsewhere(&db); peer.hold_ids.insert(t1[0].op_id.clone()); for _ in 0..3 { one_cycle(&db, &mut peer); } let offers = handed_to(&peer).iter().filter(|op| op.op_id == t1[0].op_id).count(); assert_eq!(offers, 3, "offered on each pass"); assert!(parked_ids(&db, "push").is_empty(), "a hold is never parked"); peer.hold_ids.clear(); one_cycle(&db, &mut peer); assert_eq!(title(&peer.db, "t1").as_deref(), Some("Waiting"), "and lands once the peer can take it"); } /// RULE: A replica of another night of the owner's Dev copy names its night on every request (the author of its latest serving fact), and an answer naming another night is refused before anything — no row applied, no cursor moved, the outbox kept — whatever epoch it names; an answer naming the replica's own night folds as any other. #[test] fn a_replica_of_another_night_of_the_owners_copy_is_refused_before_anything() { let db = seeded("device:a"); db.run( "INSERT INTO cotton_serving_machine \ (id, workspace_id, epoch, device_credential_id, author_id, since) \ VALUES ('s-3', ?, 3, 'device:dev-mac', 'author-last-night', '2026-10-03T00:00:00.000Z')", &[rusqlite::types::Value::Text(WS.to_string())], ) .expect("last night's fact"); write(&db, "device:a", &[todo("t1", "Made in Dev yesterday")]); let peer = seeded("device:dev-mac"); let theirs = write(&peer, "device:b", &[todo("t2", "Tonight's")]); let mut handover = Handover::default(); let handed = exchange_request(&db, WS, None, &mut handover).expect("a request"); assert_eq!( handed.request.serving_author.as_deref(), Some("author-last-night"), "the request names the replica's night" ); let before = read_cursors(&db).expect("cursors"); let answer = |copy_night: Option<&str>, serving_epoch| ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WS.to_string(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops: theirs.clone(), cursors: crate::cursors::cursor_ceiling(&peer).expect("the peer's ceiling"), has_more: false, applied_rows: BTreeMap::new(), rejected: Vec::new(), seen: Default::default(), serving_epoch, server_time: None, restored: None, copy_night: copy_night.map(str::to_string), behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }; for epoch in [None, Some(2), Some(3), Some(9)] { let refused = fold_answer(&db, &handed, &answer(Some("author-tonight"), epoch), NOW, &mut handover) .expect_err("another night is refused"); assert!( matches!(&refused, SyncError::CopyReplaced { night } if night == "author-tonight"), "{refused}" ); assert_eq!(title(&db, "t2"), None, "nothing of the answer is applied"); assert_eq!(read_cursors(&db).expect("cursors"), before, "no cursor moved"); assert_eq!(pending_count(&db).expect("counts"), 1, "the outbox is kept"); } fold_answer(&db, &handed, &answer(Some("author-last-night"), Some(3)), NOW, &mut handover) .expect("its own night folds"); assert_eq!(title(&db, "t2").as_deref(), Some("Tonight's")); } fn mail_thread(id: &str) -> LocalChange { LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: "cotton_email_threads".to_string(), row_id: id.to_string(), patch: Some( json!({ "id": id, "workspace_id": WS, "external_key": format!("gmail:{id}"), "created_at": NOW, "updated_at": NOW, }) .as_object() .expect("an object") .clone(), ), } } /// Page from `cursors` until the peer says it is level; every page in order. fn pages_from(peer: &Driver, mut cursors: BTreeMap, size: usize) -> Vec { let mut pages = Vec::new(); for _ in 0..100 { let page = answer(peer, &cursors, size).expect("a page"); cursors.extend(page.cursors.clone()); let more = page.has_more; pages.push(page); if !more { break; } } pages } /// RULE: A todo written after a mail backfill reaches a behind device before the backfill's mail: each author's stream is read in two lanes, everything but mail first, so a device is level on all but mail within its first pages. #[test] fn a_todo_written_after_a_backfill_lands_before_the_backfills_mail() { let peer = seeded("device:server"); let backfill: Vec = (0..40).map(|n| mail_thread(&format!("m{n:03}"))).collect(); write(&peer, "device:mac", &backfill); write(&peer, "device:mac", &[todo("t-after", "Written after the backfill")]); let pages = pages_from(&peer, BTreeMap::new(), 10); let first = &pages[0]; assert!( first.ops.iter().any(|op| op.row_id == "t-after"), "the todo is on the first page: {:?}", first.ops.iter().map(|op| (&op.table, &op.row_id)).collect::>() ); // No mail is sent while anything else is still owed. let todo_page = pages.iter().position(|page| page.ops.iter().any(|op| op.row_id == "t-after")); let first_mail = pages .iter() .position(|page| page.ops.iter().any(|op| op.table == "cotton_email_threads")); assert!(todo_page <= first_mail, "{todo_page:?} {first_mail:?}"); // And every thread still arrives, exactly once. let threads: Vec<&str> = pages .iter() .flat_map(|page| page.ops.iter()) .filter(|op| op.table == "cotton_email_threads") .map(|op| op.row_id.as_str()) .collect(); let unique: std::collections::BTreeSet<&&str> = threads.iter().collect(); assert_eq!(unique.len(), 40, "every thread arrived"); assert_eq!(threads.len(), 40, "no thread arrived twice"); assert!(!pages.last().expect("a page").has_more); } /// RULE: A device that has never been told of the mail lane resumes it where its author cursor stood, so turning the lanes on re-sends none of the mail it already holds. #[test] fn a_reader_from_before_the_lanes_is_not_sent_its_mail_again() { let peer = seeded("device:server"); let backfill: Vec = (0..20).map(|n| mail_thread(&format!("m{n:03}"))).collect(); write(&peer, "device:mac", &backfill); // Where an older build stood: past every thread, by its one author cursor. let stood = cursor_ceiling(&peer).expect("a ceiling"); write(&peer, "device:mac", &[todo("t-new", "New")]); write(&peer, "device:mac", &[mail_thread("m-new")]); let pages = pages_from(&peer, stood, 50); let mail: Vec<&str> = pages .iter() .flat_map(|page| page.ops.iter()) .filter(|op| op.table == "cotton_email_threads") .map(|op| op.row_id.as_str()) .collect(); assert_eq!(mail, ["m-new"], "only the new thread"); assert!(pages.iter().flat_map(|page| page.ops.iter()).any(|op| op.row_id == "t-new")); } /// `n` receipts by one far author, straight into `_writes` — the count reads /// receipts, never rows, so no row has to exist behind them. fn far_receipts(db: &Driver, n: u64) { db.exec(&format!( "WITH RECURSIVE k(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM k WHERE i < {n}) \ INSERT INTO _writes (tbl, row_id, hlc, author) \ SELECT 'cotton_todos', 'far-' || i, printf('1700000%06d:0000:device:far', i), 'device:far' FROM k" )) .expect("the receipts"); } /// RULE (sync programme lane C, 12 Oct 2026): the serving Mac offers the WHOLE FILE only to a caller that said it takes a copy and has more coming, and only when more than COPY_FASTER_PAST changes are still owed after the answer — one past the line, never at it. Its "about" is the served file's size. #[test] fn the_whole_file_is_offered_only_past_the_line_and_only_to_a_caller_that_takes_one() { use crate::protocol::types::{CopyOffer, COPY_FASTER_PAST}; // Level with everything the seed wrote; owing only the far author's. let owing_far = |db: &Driver| { let mut at = crate::cursors::seen_ceiling(db).expect("ceiling"); at.remove("device:far"); at }; let at_the_line = seeded("device:a"); far_receipts(&at_the_line, COPY_FASTER_PAST); let nowhere = owing_far(&at_the_line); assert_eq!( copy_offer(&at_the_line, true, true, &nowhere, 9).expect("asked"), None, "at the line the pages are as fast" ); let past = seeded("device:a"); far_receipts(&past, COPY_FASTER_PAST + 1); let nowhere = owing_far(&past); assert_eq!( copy_offer(&past, true, true, &nowhere, 400_000_000).expect("asked"), Some(CopyOffer { bytes: 400_000_000 }) ); assert_eq!( copy_offer(&past, false, true, &nowhere, 9).expect("asked"), None, "a caller that did not say takesCopy — cellular, a Mac — pages" ); assert_eq!( copy_offer(&past, true, false, &nowhere, 9).expect("asked"), None, "nothing more coming is nothing to copy" ); // Level with the far author: nothing owed, nothing offered. let level = crate::cursors::seen_ceiling(&past).expect("ceiling"); assert_eq!(copy_offer(&past, true, true, &level, 9).expect("asked"), None); } /// RULE: Two builds exchange iff the NEWER side's floor is at or below the OLDER side's stamp — a reader below the file is served from the file's floor_of up, a reader above it only when it says its own floor, that floor reaches the file, and the file parks what it cannot hold yet as newer-shape; anything else would fold a receipt across a rise that rebuilt a table (schema programme, 12 Oct 2026). #[test] fn the_newer_sides_floor_must_reach_the_older_sides_stamp() { let file = crate::schema::ddl::SCHEMA_VERSION; let floor = crate::schema::move_intents::floor_of(file); assert_eq!(admission(file, file, None, false), Admission::Serve); assert_eq!(admission(file, floor, None, false), Admission::Serve); if floor > 0 { assert_eq!(admission(file, floor - 1, None, true), Admission::ReaderBehind); } // A reader ahead: its own floor decides, and only a file that parks. assert_eq!(admission(file, file + 1, Some(file), true), Admission::Serve); assert_eq!(admission(file, file + 1, Some(file), false), Admission::FileBehind); assert_eq!(admission(file, file + 1, None, true), Admission::FileBehind); assert_eq!(admission(file, file + 1, Some(file + 1), true), Admission::FileBehind); } /// RULE: A page is bounded in BYTES as well as rows — it never carries more than `PAGE_BYTES` (a turn that would overrun is taken smaller, and a row that does not fit waits), says `has_more`, and the pages that follow carry every remaining row exactly once — because five hundred whole rows of a wide table were tens of megabytes that a phone behind the relay could not read inside its request's ceiling (13 Oct 2026). #[test] fn a_page_stops_at_its_byte_budget_and_the_rest_follows() { let peer = seeded("device:server"); let wide = "x".repeat(200 * 1024); for n in 0..40 { write(&peer, "device:b", &[todo(&format!("w{n:02}"), &wide)]); } let mut seen = BTreeMap::new(); let mut ids = std::collections::BTreeSet::new(); let mut pages = 0; loop { let page = answer(&peer, &seen, 500).expect("a page"); let bytes: usize = page.ops.iter().map(|op| serde_json::to_vec(op).unwrap().len()).sum(); assert!(bytes <= PAGE_BYTES, "page {pages} carried {bytes} bytes"); for op in &page.ops { if op.table == "cotton_todos" { assert!(ids.insert(op.row_id.clone()), "{} came twice", op.row_id); } } seen.extend(page.cursors.clone()); pages += 1; if !page.has_more { break; } assert!(bytes + 420 * 1024 > PAGE_BYTES, "a page cut short of its budget says it is the last"); } assert_eq!(ids.len(), 40, "every wide row arrived"); assert!(pages >= 2, "eight megabytes took more than one page"); } /// RULE: The exchange never hands a phone a table that is not on a phone — no server-only table (`SERVER_ONLY_TABLES`) and nothing the phone snapshot strips (`snapshot::NOT_ON_A_PHONE`) is ever dealt into a page, so a phone's catch-up is never spent on rows no screen there reads; the snapshot and the stream keep one rule (architect, 13 Oct 2026). #[test] fn a_page_never_carries_a_table_that_is_not_on_a_phone() { let peer = seeded("device:server"); let audit = LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: "cotton_mcp_audit".to_string(), row_id: "audit-1".to_string(), patch: Some( json!({ "id": "audit-1", "token_id": "token-1", "workspace_id": WS, "tool": "list_todos", "args_summary": "{}", "ok": true, "created_at": NOW, }) .as_object() .expect("an object") .clone(), ), }; write(&peer, "device:server", &[audit, todo("kept", "A todo")]); let receipts = peer .get("SELECT COUNT(*) AS n FROM _writes WHERE tbl = 'cotton_mcp_audit'", &[]) .expect("a count") .and_then(|row| row.int("n")); assert_eq!(receipts, Some(1), "the audit row has a receipt to leave out"); let page = answer(&peer, &BTreeMap::new(), 500).expect("a page"); assert!(page.ops.iter().any(|op| op.row_id == "kept"), "the todo travels"); for op in &page.ops { assert!( !crate::schema::table_specs::SERVER_ONLY_TABLES.iter().any(|(name, _)| *name == op.table) && !crate::snapshot::NOT_ON_A_PHONE.iter().any(|(name, _)| *name == op.table), "{} travelled", op.table ); } } /// The bytes a batch of ops carries on the wire. fn wire(ops: &[CottonOp]) -> usize { ops.iter().map(|op| serde_json::to_vec(op).expect("an op").len()).sum() } /// One ACT of `n` wide rows — one stamp, about 200 KB a row. fn wide_act(db: &Driver, device: &str, n: usize) { let wide = "x".repeat(200 * 1024); let changes: Vec = (0..n).map(|i| todo(&format!("w{i:02}"), &wide)).collect(); write(db, device, &changes); } /// RULE: The page ceiling holds on EVERY path a page is built by — an answer of any database (catch-up, first pull), one act of many wide rows, the device's queue, and its hand-over: none carries more than `PAGE_BYTES` and about a row, each says there is more, and what follows carries the rest (architect, 13 Oct 2026: a bound that applies to one path is no bound; one act of 1,984 receipts went out as one 25.7 MB page). #[test] fn every_entry_point_stops_at_the_page_ceiling_with_wide_rows() { let ceiling = PAGE_BYTES + 2 * 420 * 1024; // An answer, of one act forty wide rows long. let peer = seeded("device:server"); wide_act(&peer, "device:b", 40); let mut seen = BTreeMap::new(); let mut rows = std::collections::BTreeSet::new(); for pass in 0.. { let page = answer(&peer, &seen, 500).expect("a page"); assert!(wire(&page.ops) <= ceiling, "answer page {pass}: {} bytes", wire(&page.ops)); rows.extend(page.ops.iter().filter(|op| op.table == "cotton_todos").map(|op| op.row_id.clone())); seen.extend(page.cursors.clone()); if !page.has_more { break; } assert!(pass < 20, "the act never ended"); } assert_eq!(rows.len(), 40, "every row of the act arrived"); // The device's queue: forty wide writes waiting to go. let device = seeded("device:a"); wide_act(&device, "device:a", 40); let handed = exchange_request(&device, WS, None, &mut Handover::default()).expect("a request"); assert!(wire(&handed.request.ops) <= ceiling, "queue page: {} bytes", wire(&handed.request.ops)); assert!(handed.queued.len() < 40, "the rest of the queue waits"); // The hand-over: the same writes, queued no longer, to a peer that has seen nothing. device.run("DELETE FROM _outbox", &[]).expect("the queue went"); let mut handover = Handover::default(); let mut server = Peer::new("device:server"); exchange_once(&device, &mut server, WS, None, NOW, &mut handover).expect("an exchange"); let handed = exchange_request(&device, WS, None, &mut handover).expect("a request"); assert!(!handed.request.ops.is_empty(), "the hand-over carries the writes"); assert!(wire(&handed.request.ops) <= ceiling, "hand-over page: {} bytes", wire(&handed.request.ops)); } /// RULE: Pages are dealt in ONE place — `exchange::deal` is the only caller of the stream read (`changes_since` / `changes_since_in`) outside `changes` itself, in every crate — so the page ceiling cannot be skipped by a second dealer (architect, 13 Oct 2026). #[test] fn no_second_dealer_reads_the_stream() { let crates = crate::manifest_dir().parent().expect("the crates folder").to_path_buf(); let mut callers = Vec::new(); let mut stack = vec![crates.to_path_buf()]; while let Some(dir) = stack.pop() { for entry in std::fs::read_dir(&dir).expect("a folder") { let path = entry.expect("an entry").path(); let name = path.file_name().and_then(|name| name.to_str()).unwrap_or(""); if path.is_dir() { if !["target", "tests", "node_modules"].contains(&name) { stack.push(path); } continue; } if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name == "tests.rs" { continue; } let text = std::fs::read_to_string(&path).expect("a source file"); for line in text.lines() { let code = line.trim_start(); if code.starts_with("//") || code.starts_with("pub fn") || code.starts_with("fn ") { continue; } if code.contains("changes_since(") || code.contains("changes_since_in(") { callers.push(format!("{}: {}", path.strip_prefix(&crates).unwrap_or(&path).display(), code)); } } } } callers.sort(); assert_eq!( callers, vec![ "cotton-store/src/changes.rs: changes_since_in(db, author, since_hlc, limit_rows, None)".to_string(), "cotton-store/src/exchange.rs: let page = changes_since_in(db, &author, &since, take, lane)?;".to_string(), ], "a page is dealt only by exchange::deal" ); } /// RULE: An exchange answer never exceeds the byte budget it is dealt, whatever the backlog — a turn that would overrun is taken smaller, a row that does not fit waits for the next exchange, and only the first row of an otherwise empty answer goes whatever it costs — because the sum of every database's page once outgrew the phone's 32 MB answer ceiling and the phone discarded every answer for hours (14 Oct 2026). #[test] fn an_answer_never_exceeds_its_budget_and_a_spent_budget_deals_nothing() { let peer = seeded("device:server"); wide_act(&peer, "device:b", 30); for budget in [600 * 1024, 1024 * 1024, 3 * 1024 * 1024 + 7] { let page = answer_within( &peer, &BTreeMap::new(), 500, &Handled::default(), PageBudget { bytes: budget, first_goes_whole: false }, ) .expect("a page"); assert!(wire(&page.ops) <= budget, "{} bytes in a budget of {budget}", wire(&page.ops)); assert!(!page.ops.is_empty(), "a budget wider than a row deals a row"); assert!(page.has_more, "what did not fit is more"); } // Nothing left: nothing dealt, every author still owed, no cursor moved. let spent = answer_within( &peer, &BTreeMap::new(), 500, &Handled::default(), PageBudget { bytes: 0, first_goes_whole: false }, ) .expect("a page"); assert!(spent.ops.is_empty() && spent.has_more); assert!( spent.cursors.values().all(String::is_empty), "a page that carried nothing moves no cursor: {:?}", spent.cursors ); // A row wider than what is left waits, unless it is the answer's first. let narrow = PageBudget { bytes: 10 * 1024, first_goes_whole: false }; let waits = answer_within(&peer, &BTreeMap::new(), 500, &Handled::default(), narrow).expect("a page"); assert!(waits.ops.is_empty() && waits.has_more, "a 200 KB row does not fit 10 KB"); let first = PageBudget { first_goes_whole: true, ..narrow }; let goes = answer_within(&peer, &BTreeMap::new(), 500, &Handled::default(), first).expect("a page"); assert_eq!(goes.ops.iter().filter(|op| op.table == "cotton_todos").count(), 1, "the first row goes whole"); } /// RULE: A replica given partial answers advances its cursor by each and converges through repeated exchanges — forty thousand receipts minted in one act (a schema move's carry) reach a replica completely, every row once, through answers each inside the exchange budget — so a server that bounds its answer needs no new client to catch a device up (14 Oct 2026). #[test] fn forty_thousand_fresh_receipts_reach_a_replica_through_bounded_answers() { const N: usize = 40_000; let mut server = Peer::new("device:server"); let filler = "m".repeat(400); let changes: Vec = (0..N).map(|i| todo(&format!("t{i:05}"), &filler)).collect(); write(&server.db, "device:server", &changes); // A budget the size of a few hundred rows, so the walk takes many answers. let budget = 256 * 1024; server.budget = PageBudget { bytes: budget, first_goes_whole: true }; let replica = seeded("device:phone"); let mut handover = Handover::default(); let mut exchanges = 0; let mut last_cursors = crate::cursors::read_cursors(&replica).expect("cursors"); loop { let exchanged = exchange_once(&replica, &mut server, WS, None, NOW, &mut handover).expect("an exchange"); exchanges += 1; let cursors = crate::cursors::read_cursors(&replica).expect("cursors"); if exchanged.has_more { assert_ne!(cursors, last_cursors, "exchange {exchanges}: a partial answer moved the cursor"); } last_cursors = cursors; if !exchanged.has_more { break; } assert!(exchanges < 2 * N, "the walk never ended"); } let held = replica .get("SELECT COUNT(*) AS n FROM cotton_todos WHERE id LIKE 't%'", &[]) .expect("a count") .and_then(|row| row.int("n")); assert_eq!(held, Some(N as i64), "every receipt arrived"); assert!(exchanges > 10, "the backlog took many bounded answers, took {exchanges}"); } /// RULE: What the asker does not keep never spends the page — the keep filter runs as the page is dealt, so a backlog of rows a phone's rules leave out costs no bytes, the row it keeps behind them comes on the same page, and the cursors and the `passed` count still move past every row left out — because a phone whose rules left mail out was answered pages of budget spent on nothing it would keep, 95 KB a pass for no row (16 Oct 2026). #[test] fn a_row_left_out_spends_none_of_the_page() { let peer = seeded("device:server"); wide_act(&peer, "device:b", 30); write(&peer, "device:b", &[todo("k1", "kept")]); let budget = PageBudget { bytes: 600 * 1024, first_goes_whole: false }; let page = answer_keeping(&peer, &BTreeMap::new(), 500, &Handled::default(), budget, &mut |ops| { Ok(ops.into_iter().filter(|op| !op.row_id.starts_with('w')).collect()) }) .expect("a page"); let rows: Vec<&str> = page.ops.iter().filter(|op| op.table == "cotton_todos").map(|op| op.row_id.as_str()).collect(); assert_eq!(rows, vec!["k1"], "the kept row comes behind thirty left out"); assert!(page.passed.get("cotton_todos").copied().unwrap_or(0) >= 31, "passed counts the rows left out"); let next = answer_keeping(&peer, &page.cursors, 500, &Handled::default(), budget, &mut Ok).expect("a page"); assert!( next.ops.iter().all(|op| op.table != "cotton_todos"), "the cursors moved past what was left out" ); }