//! The schedule half of `apps/cotton/__tests__/client/sync.test.ts`.//!//! The TypeScript asserted the timer by handing the loop a fake `setTimeout`//! and reading the milliseconds it was called with. Here the arithmetic is a//! pure function ([`next_delay`]) and the loop's own behaviour is asserted//! through the status it publishes — which is the thing the menu bar actually//! draws, and the reason a test that waited for wall-clock seconds would be//! slower AND weaker.use std::sync::Arc;usesuper::*;usecrate::seams::{FixedClock, Random, SeededRandom};usecrate::test_support::{open_test_replica, queue_one_change, Call, FakeTransport, WORKSPACE};usecrate::transport::ServerRefusal;/// A jitter source pinned at the ladder's midpoint, so the numbers below are/// the store's own base and not a range.#[derive(Debug)]structMidpoint;implRandomforMidpoint {fn fill(&self, out: &mut [u8]) {let bytes = ((1u64 << 52) << 11).to_le_bytes();for (slot, byte) in out.iter_mut().zip(bytes) { *slot = byte; } }}fn transient(retry_after_seconds: Option<u32>) -> CycleFailure {CycleFailure::Transient { message: "offline".to_string(), retry_after_seconds, }}// ── the arithmetic ──────────────────────────────────────────────────────────#[test]fn it_schedules_the_next_cycle_at_the_interval_when_a_pass_succeeds() {let interval = std::time::Duration::from_millis(PULL_INTERVAL_MS); assert_eq!(next_delay(None, false, 0, interval, &Midpoint), interval);}#[test]fn a_pass_that_is_still_behind_comes_straight_back_rather_than_waiting_a_minute() {let interval = std::time::Duration::from_millis(PULL_INTERVAL_MS); assert_eq!( next_delay(None, true, 0, interval, &Midpoint), std::time::Duration::from_secs(1) );}#[test]fn it_waits_exactly_as_long_as_the_servers_retry_after_said_not_its_own_ladder() {let interval = std::time::Duration::from_millis(PULL_INTERVAL_MS); assert_eq!( next_delay(Some(&transient(Some(120))), false, 4, interval, &Midpoint), std::time::Duration::from_secs(120) );}#[test]fn it_falls_back_to_the_stores_own_ladder_when_the_server_named_no_wait() {let interval = std::time::Duration::from_millis(PULL_INTERVAL_MS); assert_eq!( next_delay(Some(&transient(None)), false, 0, interval, &Midpoint), std::time::Duration::from_secs(30) ); assert_eq!( next_delay(Some(&transient(None)), false, 2, interval, &Midpoint), std::time::Duration::from_secs(120) );// The ceiling holds however long the outage lasts. assert_eq!( next_delay(Some(&transient(None)), false, 40, interval, &Midpoint), std::time::Duration::from_secs(300) );}#[test]fn an_unlisted_database_is_asked_again_at_the_interval_and_never_climbs_the_ladder() {let interval = std::time::Duration::from_millis(PULL_INTERVAL_MS);let unlisted = CycleFailure::Unlisted { message: cycle::NOT_AVAILABLE_NOW.to_string(), }; assert_eq!(next_delay(Some(&unlisted), false, 6, interval, &Midpoint), interval);}#[test]fn synced_means_every_database_has_an_empty_outbox_and_none_has_stopped() {let level = |database: &str, pending: i64| SyncStatus { database: database.to_string(), pending, ..SyncStatus::default() }; assert!(all_synced(&[level("mine", 0), level("place", 0)])); assert!(!all_synced(&[level("mine", 0), level("place", 1)]));let stopped = SyncStatus { stopped_code: Some("device_revoked".to_string()), ..level("place", 0) }; assert!(!all_synced(&[level("mine", 0), stopped]));}// ── the loop's own behaviour ────────────────────────────────────────────────fn loop_over( replica: crate::Replica, transport: Arc<FakeTransport>,) -> (SyncLoop, Arc<std::sync::Mutex<Vec<SyncStatus>>>) {let seen: Arc<std::sync::Mutex<Vec<SyncStatus>>> = Arc::default();let sink = Arc::clone(&seen);let factory: TransportFactory = Arc::new(move || {let transport = Arc::clone(&transport);Ok(Box::new(OwnedFake(transport)) asBox<dyncrate::transport::SyncingTransport>) });let sync = SyncLoop::new(SyncLoopInput { on_copy: None, replica: Arc::new(std::sync::Mutex::new(replica)), workspace_id: WORKSPACE.to_string(), transport: factory, clock: Arc::new(FixedClock::default_start()), random: Arc::new(SeededRandom::default()), interval_ms: Some(60_000), on_status: Some(Arc::new(move |status| { sink.lock().expect("the log").push(status.clone()); })), on_tables: None, on_sent: None, held: None, time_box: TimeBox::open(), }); (sync, seen)}/// The factory hands out an OWNED transport per pass; this is the one-line/// wrapper that lets several passes share one recorder.#[derive(Debug)]structOwnedFake(Arc<FakeTransport>);implcrate::transport::RefusalAwareforOwnedFake {fn last_refusal(&self) -> Option<ServerRefusal> {let inner: &FakeTransport = &self.0;crate::transport::RefusalAware::last_refusal(&inner) }}impl cotton_store::exchange::SyncTransportforOwnedFake {fn exchange( &mutself, request: &cotton_store::protocol::types::ExchangeRequest, ) -> Result<cotton_store::protocol::types::ExchangeResponse, String> {letmut inner: &FakeTransport = &self.0; cotton_store::exchange::SyncTransport::exchange(&mut inner, request) }}#[tokio::test]asyncfn a_pull_now_is_a_whole_cycle_and_leaves_the_loop_idle_with_a_stamp() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let transport = Arc::new(FakeTransport::default());let (sync, _seen) = loop_over(replica, Arc::clone(&transport));let report = sync.pull_now().await.expect("a pass"); assert_eq!(report.pushed, 2, "the author's fact, then the change"); assert_eq!(transport.calls(), vec![Call::Exchange { ops: 2 }]);let status = sync.status(); assert_eq!(status.state, SyncState::Idle); assert_eq!(status.pending, 0); assert_eq!(status.failures, 0); assert_eq!( status.last_pull_at.as_deref(),Some("2026-09-08T10:00:00.000Z") ); assert_eq!( status.last_push_at.as_deref(),Some("2026-09-08T10:00:00.000Z") );}/// RULE: While a background slice's time box is closed every sync pass observes it, whoever started the pass, and bringing the app to the front lifts the limit.#[tokio::test]asyncfn a_slices_time_box_stops_the_loops_pass_and_a_foreground_open_lifts_it() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let transport = Arc::new(FakeTransport::default());let (sync, _seen) = loop_over(replica, Arc::clone(&transport));// The time is gone: the pass asks nothing and says there is more. sync.time_box().close_in(std::time::Duration::ZERO);let stopped = sync.pull_now().await.expect("a pass that had no time is not a failure"); assert!(stopped.behind); assert!(transport.calls().is_empty(), "no request without room for its answer"); assert_eq!(sync.status().failures, 0, "a limit this device set climbs no ladder"); assert_eq!(sync.status().pending, 2, "and the writes wait");// The app comes to the front — the box a frozen slice never lifted is gone. sync.wake_and_reset();let level = sync.pull_now().await.expect("a pass"); assert!(!level.behind); assert_eq!(transport.calls(), vec![Call::Exchange { ops: 2 }]); assert_eq!(sync.status().pending, 0);}#[tokio::test]asyncfn push_now_is_one_exchange_and_never_throws_at_the_import() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");let transport = Arc::new(FakeTransport::default()); transport.refuse(ServerRefusal::offline("offline"));let (sync, _seen) = loop_over(replica, Arc::clone(&transport));// Zero pushed, and no panic: the ops stay queued and the loop's own cycle// retries on the ladder. assert_eq!(sync.push_now().await, 0);// The author's fact rides ahead of the change. assert_eq!(transport.calls(), vec![Call::Exchange { ops: 2 }]); assert_eq!(sync.status().last_error.as_deref(), Some("offline")); assert_eq!(sync.status().pending, 2);}#[tokio::test]asyncfn it_stops_for_good_when_the_server_refuses_this_device_and_says_what_a_person_does() {let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default()); transport .refuse(ServerRefusal::new("server 403: revoked", 403).with_code("device_revoked"));let (mut sync, _seen) = loop_over(replica, Arc::clone(&transport)); sync.start();// The first pass fails terminally, and the loop takes itself off the air.// The wait is for the loop's own stop, not a budget on the pass: a first// pass over a fresh test copy is debug-build genesis work before the// server ever answers (5.4 s measured on the loaded Linux runner, 8 Nov// 2026), and a timing test for that pass lives with the copy's maker,// not here. Sixty seconds is a ceiling a hung loop fails, not a target.for _ in0..6000 {if sync.status().state == SyncState::Stopped && sync.status().stopped_reason.is_some() {break; } tokio::time::sleep(std::time::Duration::from_millis(10)).await; }let status = sync.status(); assert_eq!(status.state, SyncState::Stopped); assert_eq!(status.next_attempt_at, None);let reason = status.stopped_reason.expect("a reason"); assert!(reason.contains("pair it again"), "{reason}"); assert_eq!(status.failures, 1);}#[tokio::test]asyncfn a_transient_failure_leaves_the_loop_waiting_with_the_servers_own_words() {let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default()); transport.refuse(ServerRefusal::offline("the network is not there"));let (sync, _seen) = loop_over(replica, Arc::clone(&transport));let failure = sync.pull_now().await.expect_err("a refusal"); assert!(matches!(failure, CycleFailure::Transient { .. }));let status = sync.status(); assert_eq!(status.state, SyncState::Waiting); assert_eq!(status.failures, 1); assert_eq!( status.last_error.as_deref(),Some("the network is not there") ); assert_eq!( status.stopped_reason, None,"a bad afternoon is not a verdict on this device" );}#[tokio::test]asyncfn it_says_it_is_stopped_once_it_is_and_a_persons_own_stop_names_no_reason() {let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default());let (mut sync, _seen) = loop_over(replica, transport); assert_eq!(sync.status().state, SyncState::Stopped); sync.start(); sync.stop();let status = sync.status(); assert_eq!(status.state, SyncState::Stopped); assert_eq!(status.next_attempt_at, None); assert_eq!(status.stopped_reason, None);}#[tokio::test]asyncfn every_pass_is_reported_to_whoever_is_watching_the_status() {let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default());let (sync, seen) = loop_over(replica, transport); sync.pull_now().await.expect("a pass");let states: Vec<SyncState> = seen .lock() .expect("the log") .iter() .map(|status| status.state) .collect(); assert!(states.contains(&SyncState::Syncing), "{states:?}"); assert_eq!(states.last(), Some(&SyncState::Idle));}/// RULE: A pass says when it began while it runs, and nothing once the loop is idle, so a screen can show catching up without flickering for a short pass.#[tokio::test]asyncfn a_pass_says_when_it_began_while_it_runs_and_not_after() {let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default());let (sync, seen) = loop_over(replica, transport); sync.pull_now().await.expect("a pass");let log = seen.lock().expect("the log").clone();let running: Vec<_> = log.iter().filter(|status| status.state == SyncState::Syncing).collect(); assert!(!running.is_empty(), "a pass ran"); assert!(running.iter().all(|status| status.pass_started_at.is_some()), "{running:?}");let last = log.last().expect("a status"); assert_eq!(last.state, SyncState::Idle); assert_eq!(last.pass_started_at, None);let frame = serde_json::to_value(&running[0].clone()).expect("serialises"); assert!(frame["passStartedAt"].is_string(), "{frame}");}#[tokio::test]asyncfn two_callers_asking_at_once_take_turns_rather_than_interleaving_one_file() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "one"); queue_one_change(&replica, "two");let transport = Arc::new(FakeTransport::default());let (sync, _seen) = loop_over(replica, Arc::clone(&transport));let (cycle, _pushed) = tokio::join!(sync.pull_now(), sync.push_now()); cycle.expect("a pass");// One turn at a time, so the queued ops (the author's fact and the two// changes) leave in ONE exchange and the other call finds an empty queue// — never two calls carrying the same op.let calls = transport.calls();let ops: usize = calls .iter() .map(|call| match call {Call::Exchange { ops } => *ops, }) .sum(); assert_eq!(ops, 3, "{calls:?}");}// ── coalescing (P14b §1.4) ──────────────────────────────────────────────────/// A transport that HOLDS its first pass until a test lets go, so callers can/// pile up behind a flight that is genuinely in the air.////// The hold is a channel rather than a sleep: a test that raced a timer would/// be the kind of flake that only fails on a loaded build machine.#[derive(Debug)]structGate {/// Told the moment the first pass is inside the transport. entered: std::sync::mpsc::Sender<()>,/// The first pass waits here. release: std::sync::Mutex<Option<std::sync::mpsc::Receiver<()>>>, calls: std::sync::atomic::AtomicUsize,/// Set to refuse every call, for the failed-flight case. refuse: std::sync::atomic::AtomicBool,}implGate {fn new() -> (Arc<Gate>, std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>, ) {let (entered, entered_rx) = std::sync::mpsc::channel();let (release_tx, release_rx) = std::sync::mpsc::channel(); (Arc::new(Gate { entered, release: std::sync::Mutex::new(Some(release_rx)), calls: std::sync::atomic::AtomicUsize::new(0), refuse: std::sync::atomic::AtomicBool::new(false), }), entered_rx, release_tx, ) }fn hold(&self) {let taken = self .release .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .take();ifletSome(waiting) = taken {let _ = self.entered.send(());let _ = waiting.recv(); } }fn calls(&self) -> usize {self.calls.load(std::sync::atomic::Ordering::SeqCst) }}#[derive(Debug)]structHeld(Arc<Gate>);implcrate::transport::RefusalAwareforHeld {fn last_refusal(&self) -> Option<ServerRefusal> {None }}impl cotton_store::exchange::SyncTransportforHeld {fn exchange( &mutself, request: &cotton_store::protocol::types::ExchangeRequest, ) -> Result<cotton_store::protocol::types::ExchangeResponse, String> {self.0 .calls .fetch_add(1, std::sync::atomic::Ordering::SeqCst);self.0.hold();ifself.0.refuse.load(std::sync::atomic::Ordering::SeqCst) {returnErr("the server is not answering".to_string()); }Ok(crate::test_support::accepted(request, false)) }}fn gated_loop(replica: crate::Replica, gate: Arc<Gate>) -> SyncLoop {let factory: TransportFactory = Arc::new(move || {Ok(Box::new(Held(Arc::clone(&gate))) asBox<dyncrate::transport::SyncingTransport>) });SyncLoop::new(SyncLoopInput { on_copy: None, replica: Arc::new(std::sync::Mutex::new(replica)), workspace_id: WORKSPACE.to_string(), transport: factory, clock: Arc::new(FixedClock::default_start()), random: Arc::new(SeededRandom::default()), interval_ms: Some(60_000), on_status: None, on_tables: None, on_sent: None, held: None, time_box: TimeBox::open(), })}#[test]fn full_is_wider_than_push_only_and_that_is_the_whole_coalescing_rule() { assert_eq!(Pass::Full.widest(Pass::PushOnly), Pass::Full); assert_eq!(Pass::PushOnly.widest(Pass::Full), Pass::Full); assert_eq!(Pass::PushOnly.widest(Pass::PushOnly), Pass::PushOnly); assert!(Pass::Full > Pass::PushOnly);}#[test]fn two_passes_add_their_pushes_because_two_batches_really_did_go() {let first = Done::Cycle(CycleReport { pushed: 3, pulled: 1, behind: false, tables: vec!["cotton_todos".to_string()], report: Default::default(), held: Default::default(), peer_schema: None, ..Default::default() });let extra = Done::Cycle(CycleReport { pushed: 4, pulled: 0, behind: true, tables: Vec::new(), report: Default::default(), held: Default::default(), peer_schema: None, ..Default::default() });let both = first.and_then(extra); assert_eq!(both.pushed(), 7);// Everything else is the LATER pass's — it is the more recent truth. assert_eq!( both,Done::Cycle(CycleReport { pushed: 7, pulled: 0, behind: true, tables: Vec::new(), report: Default::default(), held: Default::default(), peer_schema: None, ..Default::default() }) );}#[test]fn a_push_only_flight_that_a_full_caller_joined_still_reports_as_a_cycle() {let done = Done::Pushed(2).and_then(Done::Cycle(CycleReport { pushed: 1, pulled: 5, behind: false, tables: vec!["cotton_notes".to_string()], report: Default::default(), held: Default::default(), peer_schema: None, ..Default::default() })); assert!(matches!(done, Done::Cycle(report) if report.pushed == 3 && report.pulled == 5));}#[tokio::test(flavor = "multi_thread", worker_threads = 4)]asyncfn a_hundred_callers_arriving_mid_flight_cost_exactly_one_extra_pass() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "one");let (gate, entered, release) = Gate::new();let sync = Arc::new(gated_loop(replica, Arc::clone(&gate)));// The flight: it blocks inside the transport's pull.let flying = {let sync = Arc::clone(&sync); tokio::spawn(asyncmove { sync.pull_now().await }) }; entered.recv().expect("the flight is in the air");// A hundred callers, every one of them arriving mid-flight.let joiners: Vec<_> = (0..100) .map(|_| {let sync = Arc::clone(&sync); tokio::spawn(asyncmove { sync.push_now().await }) }) .collect();// Every one of them has to have ARRIVED before the flight is let go, or// this would sometimes be a test about three callers.while sync.inner.joined.load(std::sync::atomic::Ordering::SeqCst) < 100 { tokio::task::yield_now().await; } release.send(()).expect("let go"); flying.await.expect("a task").expect("a pass");for joiner in joiners { joiner.await.expect("a task"); } assert_eq!( gate.calls(),2,"the flight's own exchange, and exactly ONE more for all hundred — and \ the extra pass found the outbox already empty, which is what makes \ queueing merely slower rather than wrong, and coalescing merely cheaper" ); assert_eq!( sync.inner.joined.load(std::sync::atomic::Ordering::SeqCst),100 );}#[tokio::test(flavor = "multi_thread", worker_threads = 4)]asyncfn a_failed_flight_schedules_nothing_and_hands_everybody_the_same_refusal() {// Running an extra pass into a server that just refused is how one outage// becomes a spin.let (_dir, _layout, replica) = open_test_replica();let (gate, entered, release) = Gate::new(); gate.refuse.store(true, std::sync::atomic::Ordering::SeqCst);let sync = Arc::new(gated_loop(replica, Arc::clone(&gate)));let flying = {let sync = Arc::clone(&sync); tokio::spawn(asyncmove { sync.pull_now().await }) }; entered.recv().expect("the flight is in the air");let joiners: Vec<_> = (0..8) .map(|_| {let sync = Arc::clone(&sync); tokio::spawn(asyncmove { sync.pull_now().await }) }) .collect();while sync.inner.joined.load(std::sync::atomic::Ordering::SeqCst) < 8 { tokio::task::yield_now().await; } release.send(()).expect("let go"); assert!(flying.await.expect("a task").is_err());for joiner in joiners { assert!( joiner.await.expect("a task").is_err(),"every joiner is handed the flight's own failure" ); } assert_eq!(gate.calls(), 1, "nothing was scheduled behind the failure");}/// RULE: A sync always pulls before it pushes, so one person never becomes two contacts.#[tokio::test(flavor = "multi_thread", worker_threads = 4)]asyncfn a_full_caller_joining_a_push_only_flight_still_gets_its_pull() {// A `PushOnly` caller folds into a `Full` flight happily; a `Full` caller// may NOT fold into a `PushOnly` one. Both are exchanges now, so both bring// news — but `push_only` is ONE of them and a full cycle keeps going while// either side has more, so a caller that asked to be caught up has not// been. The extra pass is the WIDEST anybody asked for.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "one");let (gate, entered, release) = Gate::new();let sync = Arc::new(gated_loop(replica, Arc::clone(&gate)));let flying = {let sync = Arc::clone(&sync); tokio::spawn(asyncmove { sync.push_now().await }) }; entered.recv().expect("the flight is in the air");let asking = {let sync = Arc::clone(&sync); tokio::spawn(asyncmove { sync.pull_now().await }) };while sync.inner.joined.load(std::sync::atomic::Ordering::SeqCst) < 1 { tokio::task::yield_now().await; } release.send(()).expect("let go"); flying.await.expect("a task"); asking.await.expect("a task").expect("a whole cycle"); assert_eq!( gate.calls(),2,"the push-only flight is ONE exchange; the extra pass — a Full one — is \ the loop that keeps going while either side has more" );}// ── the ladder, reset ───────────────────────────────────────────────────────#[tokio::test]asyncfn an_explicit_sync_now_puts_the_backoff_ladder_back_on_its_bottom_rung() {// Six failures is thirty-two minutes to the next try. A person pressing// "sync now" — or an app coming back to the front — is saying the// conditions changed, and answering with "in half an hour" is an app that// looks broken while working exactly as written.let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default()); transport.refuse(ServerRefusal::offline("no network"));let (mut sync, _seen) = loop_over(replica, Arc::clone(&transport)); sync.pull_now().await.expect_err("a failure"); assert_eq!(sync.status().failures, 1); sync.start(); sync.wake_and_reset(); assert_eq!(sync.status().failures, 0); assert_eq!(sync.status().next_attempt_at, None);}#[tokio::test]asyncfn a_reset_never_clears_a_refusal_only_the_server_can_reverse() {let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default()); transport.refuse(ServerRefusal::new("this device was removed", 403).with_code("device_revoked"), );let (sync, _seen) = loop_over(replica, Arc::clone(&transport)); sync.pull_now().await.expect_err("a refusal");let stopped = sync.status().stopped_reason.clone(); assert!(stopped.is_some(), "the loop stopped and said why"); sync.wake_and_reset(); sync.foreground(); assert_eq!( sync.status().stopped_reason, stopped,"a wake is not a way back in — pairing again is" ); assert_eq!(sync.status().state, SyncState::Stopped);}#[tokio::test]asyncfn going_to_the_background_leaves_the_timer_alone() {// iOS gives a backgrounded app time it did not ask for — a background// fetch, a push arriving — and a loop that had stopped itself would waste// it. What closes is the SOCKET, and that is the live channel's own call.let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default());let (mut sync, _seen) = loop_over(replica, Arc::clone(&transport)); sync.start(); sync.background(None); assert_ne!(sync.status().state, SyncState::Stopped);}// ── A write's push is the loop's, and the loop never holds the file for it ──//// `ClientController::write` queues the op and wakes this loop; it does not// push. Three things have to hold for that to be a fix rather than a move: the// loop's push-only pass must not hold the replica across the round trip (or// the screen's read would queue behind the loop instead of behind the write);// a wake must actually run a pass that carries the op; and a wake during a// backoff must NOT run one, or every edit on a train would climb the ladder.//// Time is tokio's paused clock throughout: a wait is on a message the loop// sends, never on the wall, and "the interval never came" is a fact about the// clock rather than about how long the test happened to take./// A transport that notes, on every round trip, whether the replica is free,/// tells a test how many ops the trip carried, and refuses when told to.#[derive(Debug)]structWatching { replica: Arc<std::sync::Mutex<crate::Replica>>, free: Arc<std::sync::Mutex<Vec<bool>>>, carried: tokio::sync::mpsc::UnboundedSender<usize>, refuse: Arc<AtomicBool>,}implcrate::transport::RefusalAwareforWatching {fn last_refusal(&self) -> Option<ServerRefusal> {ifself.refuse.load(Ordering::SeqCst) {Some(ServerRefusal::offline("offline")) } else {None } }}impl cotton_store::exchange::SyncTransportforWatching {fn exchange( &mutself, request: &cotton_store::protocol::types::ExchangeRequest, ) -> Result<cotton_store::protocol::types::ExchangeResponse, String> {let free = self.replica.try_lock().is_ok();self.free.lock().expect("the log").push(free);let _ = self.carried.send(request.ops.len());ifself.refuse.load(Ordering::SeqCst) {returnErr("offline".to_string()); }Ok(crate::test_support::accepted(request, false)) }}/// A loop over a watched transport, and every handle a test reads it by.structWatched { sync: SyncLoop, replica: Arc<std::sync::Mutex<crate::Replica>>,/// One entry per round trip: was the file free while the server was asked? free: Arc<std::sync::Mutex<Vec<bool>>>,/// How many ops each round trip carried, as they happen. carried: tokio::sync::mpsc::UnboundedReceiver<usize>,/// Every status the loop published, as it happens. statuses: tokio::sync::mpsc::UnboundedReceiver<SyncStatus>,/// Flip to make the server refuse every exchange from then on. refuse: Arc<AtomicBool>,}/// An interval a test's paused clock never reaches on its own: a pass that/// ran before it is a pass a wake ran.const AN_HOUR_MS: u64 = 3_600_000;fn watched_loop(replica: crate::Replica) -> Watched {let replica = Arc::new(std::sync::Mutex::new(replica));let free: Arc<std::sync::Mutex<Vec<bool>>> = Arc::default();let refuse = Arc::new(AtomicBool::new(false));let (carried, carried_rx) = tokio::sync::mpsc::unbounded_channel();let (statuses, statuses_rx) = tokio::sync::mpsc::unbounded_channel();let factory: TransportFactory = {let replica = Arc::clone(&replica);let free = Arc::clone(&free);let refuse = Arc::clone(&refuse);Arc::new(move || {Ok(Box::new(Watching { replica: Arc::clone(&replica), free: Arc::clone(&free), carried: carried.clone(), refuse: Arc::clone(&refuse), }) asBox<dyncrate::transport::SyncingTransport>) }) };let sync = SyncLoop::new(SyncLoopInput { on_copy: None, replica: Arc::clone(&replica), workspace_id: WORKSPACE.to_string(), transport: factory, clock: Arc::new(FixedClock::default_start()), random: Arc::new(SeededRandom::default()), interval_ms: Some(AN_HOUR_MS), on_status: Some(Arc::new(move |status| {let _ = statuses.send(status.clone()); })), on_tables: None, on_sent: None, held: None, time_box: TimeBox::open(), });Watched { sync, replica, free, carried: carried_rx, statuses: statuses_rx, refuse, }}/// The next status the loop publishes that satisfies `want`.asyncfn status_where( statuses: &mut tokio::sync::mpsc::UnboundedReceiver<SyncStatus>, want: implFn(&SyncStatus) -> bool,) -> SyncStatus {loop {let status = statuses.recv().await.expect("the loop is still publishing");if want(&status) {return status; } }}#[tokio::test]asyncfn the_loops_push_only_pass_leaves_the_file_free_while_the_server_is_asked() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo");letWatched { sync, replica, free, .. } = watched_loop(replica); assert_eq!(sync.push_now().await, 2, "the author's fact, then the change"); assert_eq!( free.lock().expect("the log").clone(), vec![true],"the replica was nobody's while the transport was asked" );let replica = replica.lock().expect("the replica"); assert_eq!( cotton_store::outbox::pending_count(&replica.driver).expect("a count"),0 );}#[tokio::test(start_paused = true)]asyncfn a_wake_runs_a_pass_that_carries_what_was_queued_after_the_last_one() {let (_dir, _layout, replica) = open_test_replica();letWatched {mut sync, replica,mut carried,mut statuses, .. } = watched_loop(replica); sync.start();// The loop's own first pass, all the way to its fold: one exchange of// nothing, then the Idle it publishes AFTER the blocking work returned —// told apart from `start()`'s and `run()`'s Idle by the stamp only a// finished pass carries. assert_eq!(carried.recv().await, Some(0)); status_where(&mut statuses, |status| { status.state == SyncState::Idle && status.last_pull_at.is_some() }) .await;// Queued AFTER that request was built and folded, so no pass already// running can be the one that carries it — and the interval is an hour// of paused time away. {let replica = replica.lock().expect("the replica"); queue_one_change(&replica, "queued after the last pass"); }let woken_at = tokio::time::Instant::now(); assert!(sync.wake(), "a healthy loop is woken");// The file's first write: its author's fact rides ahead of the op. assert_eq!( carried.recv().await,Some(2),"the very next exchange carries the op" );// The fold, not the send: `last_push_at` is stamped by the pass that// folded a peer's answer saying it applied something. status_where(&mut statuses, |status| status.last_push_at.is_some()).await; assert!( woken_at.elapsed() < Duration::from_millis(AN_HOUR_MS),"the clock never reached the interval: this was the wake's pass" );let replica = replica.lock().expect("the replica"); assert_eq!( cotton_store::outbox::pending_count(&replica.driver).expect("a count"),0,"nothing is left in the outbox for the timer" ); sync.stop();}/// RULE (23 Nov 2026): a burst of wakes while the loop/// sleeps is ONE pass, not one for the burst and one for the permit it left./// The object's `{ t: "rows" }` frames during a Mac's import come in bursts,/// and each asks for a pass (`chat.rows`).#[tokio::test(start_paused = true)]asyncfn a_burst_of_wakes_while_asleep_is_one_pass() {let (_dir, _layout, replica) = open_test_replica();letWatched {mut sync,mut carried,mut statuses, .. } = watched_loop(replica); sync.start(); assert_eq!(carried.recv().await, Some(0)); status_where(&mut statuses, |status| { status.state == SyncState::Idle && status.last_pull_at.is_some() }) .await;for _ in0..50 { assert!(sync.wake(), "a healthy loop is woken"); } assert_eq!(carried.recv().await, Some(0), "the burst's pass");let more = tokio::time::timeout(Duration::from_millis(AN_HOUR_MS / 2), carried.recv()).await; assert!(more.is_err(), "no second pass for the same burst: {more:?}"); sync.stop();}#[tokio::test]asyncfn a_wake_during_a_backoff_is_refused_and_a_reset_is_what_lets_one_through() {// The rule, without a running schedule: `wake` answers whether the loop// was asked, and while the ladder is climbed it is not.let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default()); transport.refuse(ServerRefusal::offline("no network"));let (sync, _seen) = loop_over(replica, Arc::clone(&transport)); sync.pull_now().await.expect_err("a failure"); assert_eq!(sync.status().failures, 1); assert!(!sync.wake(), "a write during an outage does not start a pass"); sync.wake_and_reset(); assert!(sync.wake(), "a person's own reset is what lets the next one through");}#[tokio::test(start_paused = true)]asyncfn writes_during_an_outage_do_not_climb_the_ladder() {// Ten edits on a train, the Mac unreachable: the scheduled attempt is the// next thing that reaches the server, at its scheduled time, and the// failure count is the count of SCHEDULED attempts — never ten rungs// higher because ten writes each asked.let (_dir, _layout, replica) = open_test_replica();letWatched {mut sync, replica,mut carried,mut statuses, refuse, .. } = watched_loop(replica); refuse.store(true, Ordering::SeqCst); sync.start(); assert_eq!(carried.recv().await, Some(0));let failed = status_where(&mut statuses, |status| status.state == SyncState::Waiting).await; assert_eq!(failed.failures, 1);let queued_at = tokio::time::Instant::now();for edit in0..10 { {let replica = replica.lock().expect("the replica"); queue_one_change(&replica, &format!("edit {edit} on the train")); } assert!(!sync.wake(), "edit {edit}: deferred to the scheduled attempt"); }// The next exchange is the SCHEDULED one: the clock had to advance to// reach it, and it carries all ten (and the author's fact the first of// them was minted behind). assert_eq!(carried.recv().await, Some(11)); assert!( queued_at.elapsed() >= Duration::from_secs(1),"no pass ran at the moment of a write; the ladder's own delay passed first" );let failed_again = status_where(&mut statuses, |status| status.failures >= 2).await; assert_eq!( failed_again.failures,2,"two scheduled attempts failed; the ten writes added no rung" ); sync.stop();}// ── a schema mismatch is a WORD on the status, never a stop ─────────────────#[tokio::test]asyncfn a_426_leaves_the_loop_waiting_with_its_outbox_and_says_the_phone_is_behind() {// The server's file is newer than this build. Before this the loop climbed// its ladder in silence for as long as the phone went un-updated — the// owner's phone spent twelve hours that way on 2026-08-25 — and the app// could be walled over the file by the same code at boot. Now: the write// stays queued, the loop keeps its ladder, and the status carries the one// word Home needs.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "written on the older build");let transport = Arc::new(FakeTransport::default()); transport.refuse(ServerRefusal::new("server 426: this build folds schema 34; the file is at 35", 426) .with_code("upgrade_required"), );let (sync, _seen) = loop_over(replica, Arc::clone(&transport));let failure = sync.pull_now().await.expect_err("a refusal"); assert!(matches!(failure, CycleFailure::PhoneBehind { .. }), "{failure:?}");let status = sync.status(); assert_eq!(status.state, SyncState::Waiting, "a backoff, not a stop"); assert_eq!(status.stopped_reason, None); assert_eq!(status.stopped_code, None); assert_eq!(status.schema, Some(SchemaStanding::PhoneBehind)); assert_eq!(status.pending, 2, "the write (and its author's fact) is still queued"); assert_eq!(status.failures, 1);}/// RULE: A Mac whose file is on an OLDER schema than this build ("schemaVersion must be N", N below this build's, or coded mac_behind) leaves the loop waiting at its ordinary interval with its outbox whole, says ServerBehind and never the Mac's sentence, and the first pass the Mac answers sends everything with no tap (phone 254, 12 Oct 2026).#[tokio::test]asyncfn a_mac_behind_this_build_holds_the_outbox_and_the_pass_after_its_update_sends_it() {let older = cotton_store::schema::ddl::SCHEMA_VERSION - 2;let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "written on the newer build");let transport = Arc::new(FakeTransport::default()); transport.refuse(ServerRefusal::new(format!("server 400: schemaVersion must be {older}"), 400).with_code("bad_request"), );let (sync, _seen) = loop_over(replica, Arc::clone(&transport));let failure = sync.pull_now().await.expect_err("the Mac is behind"); assert!(matches!(failure, CycleFailure::MacBehind { .. }), "{failure:?}");let interval = std::time::Duration::from_secs(30); assert_eq!(next_delay(Some(&failure), false, 5, interval, &Midpoint), interval, "never a ladder");let status = sync.status(); assert_eq!(status.state, SyncState::Waiting); assert_eq!(status.schema, Some(SchemaStanding::ServerBehind)); assert_eq!(status.last_error, None, "never the Mac's sentence"); assert_eq!(status.failures, 0); assert_eq!(status.pending, 2, "the write (and its author's fact) is still queued");// The Mac is updated: the next pass sends it all and the word goes. *transport.refusal.lock().expect("the slot") = None; sync.pull_now().await.expect("the Mac takes this schema now");let status = sync.status(); assert_eq!(status.pending, 0); assert_eq!(status.schema, None);}/// RULE: The build line says the serving Mac's name, version and schema only as the Mac said them: an answer names the Mac, and a 400 "schemaVersion must be N" puts N on the line beside the name last heard.#[tokio::test]asyncfn a_400_schema_refusal_puts_the_macs_schema_beside_the_name_last_heard() {let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default()); transport.says_schema(131); transport.says_answered_by("mac-c", "0.29.37");let (sync, _seen) = loop_over(replica, Arc::clone(&transport)); sync.pull_now().await.expect("a pass");let heard = sync.status().peer; assert_eq!(heard.name.as_deref(), Some("mac-c")); assert_eq!(heard.version.as_deref(), Some("0.29.37")); assert_eq!(heard.schema, Some(131)); transport.refuse(ServerRefusal::new("server 400: schemaVersion must be 132", 400)); sync.pull_now().await.expect_err("a refusal");let heard = sync.status().peer; assert_eq!(heard.schema, Some(132), "the refusal's number is the Mac's schema"); assert_eq!(heard.name.as_deref(), Some("mac-c"), "the name stays as last heard");// A refusal that names no schema leaves the line as it was. transport.refuse(ServerRefusal::new("server 400: schemaVersion must be a u32 integer", 400)); sync.pull_now().await.expect_err("a refusal"); assert_eq!(sync.status().peer.schema, Some(132));}/// The Debug group's exchanges: every pass leaves one line, a refusal's/// words cleaned like the reported state's, and only the last/// `EXCHANGES_KEPT` are kept.#[tokio::test]asyncfn every_pass_leaves_one_exchange_line_and_only_the_last_twenty_are_kept() {let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default());let (sync, _seen) = loop_over(replica, Arc::clone(&transport)); sync.pull_now().await.expect("a pass");let first = sync.exchanges(); assert_eq!(first.len(), 1); assert_eq!(first[0].answer, "ok"); transport.refuse(ServerRefusal::new("server 401: Bearer abc123 was refused", 401)); sync.pull_now().await.expect_err("a refusal");let refused = sync.exchanges().pop().expect("the refusal's line"); assert!(!refused.answer.contains("abc123"), "{}", refused.answer);for _ in0..crate::sync::EXCHANGES_KEPT + 3 {let _ = sync.pull_now().await; } assert_eq!(sync.exchanges().len(), crate::sync::EXCHANGES_KEPT);}#[test]fn a_426_names_the_files_schema_too() { assert_eq!(crate::sync::schema_in_refusal("server 426: this app folds schema 134; the file is at 135 — update the app"),Some(135) ); assert_eq!(crate::sync::schema_in_refusal("offline"), None);}#[tokio::test]asyncfn a_mac_on_a_newer_schema_still_serves_this_device_and_the_word_says_the_phone_is_behind() {// The 426 used to stop everything here. Now the Mac serves a behind// device in both directions and SAYS its schema; the loop reads that as// "update this phone" — a word on the status, never a stop, never a// ladder — and the write still lands.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "written on the older build");let transport = Arc::new(FakeTransport::default()); transport.says_schema(cotton_store::schema::ddl::SCHEMA_VERSION + 1);let (sync, _seen) = loop_over(replica, Arc::clone(&transport));let report = sync.pull_now().await.expect("a pass"); assert_eq!(report.pushed, 2, "served, not refused (the author's fact and the write)"); assert_eq!(report.peer_schema, Some(cotton_store::schema::ddl::SCHEMA_VERSION + 1));let status = sync.status(); assert_eq!(status.state, SyncState::Idle); assert_eq!(status.failures, 0); assert_eq!(status.schema, Some(SchemaStanding::PhoneBehind)); assert_eq!(status.pending, 0);// A peer at this build's own schema, or one that does not say, clears it. transport.says_schema(cotton_store::schema::ddl::SCHEMA_VERSION); sync.pull_now().await.expect("a pass"); assert_eq!(sync.status().schema, None); transport.says_schema(cotton_store::schema::ddl::SCHEMA_VERSION + 1); sync.pull_now().await.expect("a pass"); assert_eq!(sync.status().schema, Some(SchemaStanding::PhoneBehind)); transport.says_no_schema(); sync.pull_now().await.expect("a pass"); assert_eq!(sync.status().schema, None, "a peer that does not say is not a peer that is ahead");}#[tokio::test]asyncfn a_server_that_holds_every_write_as_behind_is_a_clean_pass_that_says_so() {// The other direction: this build is newer than the Mac's. The pass// SUCCEEDS — pulls land, the ladder stays down — and the word says the// Mac is the one to update.let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "written on the newer build");let transport = Arc::new(FakeTransport::default()); transport.hold_as(cotton_store::protocol::types::REJECTION_SERVER_BEHIND);let (sync, _seen) = loop_over(replica, Arc::clone(&transport));let report = sync.pull_now().await.expect("a pass"); assert_eq!(report.pushed, 0);// Counted per page, and a pass re-offers a held write on its next page// — so "at least once", never exactly once. assert!( report .held .get(cotton_store::protocol::types::REJECTION_SERVER_BEHIND) .is_some_and(|held| *held >= 1),"{:?}", report.held );let status = sync.status(); assert_eq!(status.state, SyncState::Idle); assert_eq!(status.failures, 0); assert_eq!(status.schema, Some(SchemaStanding::ServerBehind)); assert_eq!(status.pending, 2, "the write (and its author's fact) waits for the Mac's update");// And the word clears the moment a pass moves both ways. transport.hold_as_nothing();let report = sync.pull_now().await.expect("a pass"); assert_eq!(report.pushed, 2);let status = sync.status(); assert_eq!(status.schema, None); assert_eq!(status.pending, 0);}// ── every held database in one pass ─────────────────────────────────────────const PLACE: &str = "66666666-6666-4666-8666-666666666666";// RULE: The personal sync loop syncs every database the device holds in one pass — a write queued in a shared database leaves on the loop's next cycle.#[tokio::test]asyncfn the_loop_syncs_every_held_database_in_one_pass() {let (dir, layout, replica) = open_test_replica();let place = crate::test_support::open_replica_for(&layout, dir.path(), PLACE);crate::test_support::queue_one_change_for(&place, PLACE, "a synthetic todo in a shared database");let place = Arc::new(std::sync::Mutex::new(place));let transport = Arc::new(FakeTransport::default());let factory: TransportFactory = {let transport = Arc::clone(&transport);Arc::new(move || {Ok(Box::new(OwnedFake(Arc::clone(&transport)))asBox<dyncrate::transport::SyncingTransport>) }) };let closed: Arc<std::sync::atomic::AtomicUsize> = Arc::default();let after = Arc::clone(&closed);let lent = Arc::clone(&place);let passes: Arc<std::sync::Mutex<Vec<(String, Option<Reported>)>>> = Arc::default();let told = Arc::clone(&passes);let sync = SyncLoop::new(SyncLoopInput { on_copy: None, replica: Arc::new(std::sync::Mutex::new(replica)), workspace_id: WORKSPACE.to_string(), transport: factory, clock: Arc::new(FixedClock::default_start()), random: Arc::new(SeededRandom::default()), interval_ms: Some(60_000), on_status: None, on_tables: None, on_sent: None, held: Some(HeldFiles { ids: Arc::new(|| vec![WORKSPACE.to_string(), PLACE.to_string()]), open: Arc::new(move |database| { assert_eq!(database, PLACE, "the own file is never asked of the opener");Ok(Arc::clone(&lent)) }), open_now: Arc::new(|_| false), notes: HeldNotes::beside(&dir.path().join("connection.json")), after_pass: Some(Arc::new(move || { after.fetch_add(1, std::sync::atomic::Ordering::SeqCst); })), on_tables: None, on_sent: None, on_report: Some(Arc::new(move |report| { told.lock().expect("told").push((report.database.to_string(), report.reported)); })), }), time_box: TimeBox::open(), }); sync.pull_now().await.expect("a pass");// RULE: a screen says sync only by what a pass REPORTED — every database a full pass carried is told once, as the pass ends, what its section reported (rows each way and whether it is behind); nothing is said when a pass starts.let told = passes.lock().expect("told").clone(); assert_eq!(told.iter().map(|(database, _)| database.as_str()).collect::<Vec<_>>(), vec![WORKSPACE, PLACE], "{told:?}");let reported = told[1].1.expect("the place's section answered"); assert!(reported.pushed >= 1 && !reported.behind, "the shared write moved: {told:?}");let waiting = {let place = place.lock().expect("the file"); cotton_store::outbox::pending_count(&place.driver).expect("counted") }; assert_eq!(waiting, 0, "the shared database's write left with the pass"); assert_eq!(wal_bytes(&layout, PLACE), 0, "every file the pass opened folded its log"); assert_eq!(closed.load(std::sync::atomic::Ordering::SeqCst), 1, "told once the pass let go");let statuses = sync.statuses(); assert_eq!( statuses.iter().map(|status| status.database.as_str()).collect::<Vec<_>>(), vec![WORKSPACE, PLACE] ); assert!(statuses[1].last_push_at.is_some(), "{:?}", statuses[1]);}/// RULE: A holder with wanted uploads asks again within five seconds; an empty answer restores the minute cadence without polling a phone viewer.#[test]fn wanted_uploads_select_the_hot_tick_only_while_wanted() { assert_eq!(super::readthrough_delay(true, std::time::Duration::from_secs(60)), std::time::Duration::from_secs(5)); assert_eq!(super::readthrough_delay(false, std::time::Duration::from_secs(60)), std::time::Duration::from_secs(60));}/// RULE: A pass the loop stopped waiting for (its 120 s ceiling) is never overtaken: while it is still running on its own thread no new pass starts — a second pass would ask from the same cursor for the same page and fold it twice — and the loop says the last pass is still finishing; a pass that ends, however it ends, lets the next one run (architect, 13 Oct 2026).#[tokio::test]asyncfn a_pass_left_to_finish_is_never_overtaken() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "one");let (gate, _entered, release) = Gate::new(); drop(release);let sync = Arc::new(gated_loop(replica, Arc::clone(&gate)));// A pass still running on its own thread, which the cut does not end// inside what this pass may spend (a box with just past a page's floor). sync.inner.straggling.store(true, std::sync::atomic::Ordering::SeqCst); sync.inner .time_box .close_in(std::time::Duration::from_millis(super::super::time_box::PAGE_FLOOR_MS + 200));let refused = sync.pull_now().await.expect_err("no second pass while the first runs"); assert!(refused.message().contains("still finishing"), "{}", refused.message()); assert_eq!(gate.calls(), 0, "nothing was asked");// It ended. sync.inner.time_box.lift(); sync.inner.straggling.store(false, std::sync::atomic::Ordering::SeqCst); sync.pull_now().await.expect("the next pass runs"); assert_eq!(gate.calls(), 1); assert!( !sync.inner.straggling.load(std::sync::atomic::Ordering::SeqCst),"a pass that ended lowers the mark itself" );}/// A transport whose FIRST exchange is a read on a line that died while iOS/// froze the process: it waits until its socket is shut — through the gate,/// the way a real read's socket is — and then fails. Every later exchange/// answers.#[derive(Debug)]structDeadLine { gate: Arc<crate::transport::records_first::RecordsFirst>, first: Arc<std::sync::atomic::AtomicBool>, entered: std::sync::mpsc::Sender<()>, exchanged: Arc<std::sync::atomic::AtomicUsize>,}implcrate::transport::RefusalAwareforDeadLine {fn last_refusal(&self) -> Option<ServerRefusal> {None }fn gate(&self) -> Option<Arc<crate::transport::records_first::RecordsFirst>> {Some(Arc::clone(&self.gate)) }}impl cotton_store::exchange::SyncTransportforDeadLine {fn exchange( &mutself, request: &cotton_store::protocol::types::ExchangeRequest, ) -> Result<cotton_store::protocol::types::ExchangeResponse, String> {ifself.first.swap(false, std::sync::atomic::Ordering::SeqCst) {let read = self.gate.reading();let (shut, shut_rx) = std::sync::mpsc::channel::<()>(); read.over(Some(Box::new(move || {let _ = shut.send(()); })));let _ = self.entered.send(());// No answer ever comes on this line; only the shut ends the wait.let _ = shut_rx.recv();returnErr("the connection was closed".to_string()); }self.exchanged.fetch_add(1, std::sync::atomic::Ordering::SeqCst);Ok(crate::test_support::accepted(request, false)) }}/// RULE: A wake that arrives while a frozen pass is still on the wire reaches an exchange inside its budget: the pass the loop stopped waiting for is cut — no further page, its read's socket shut — and waited for, never left to keep every later wake at "still finishing" for its sixty-second read (onetransport, 13 Oct 2026: build 265 made no exchange from 07:28Z although the Mac woke it twice).#[tokio::test]asyncfn a_wake_while_a_pass_is_frozen_on_the_wire_still_exchanges() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic write waiting to leave");let gate = Arc::new(crate::transport::records_first::RecordsFirst::default());let first = Arc::new(std::sync::atomic::AtomicBool::new(true));let exchanged: Arc<std::sync::atomic::AtomicUsize> = Arc::default();let (entered, entered_rx) = std::sync::mpsc::channel();let factory: TransportFactory = {let (gate, first, exchanged) = (Arc::clone(&gate), Arc::clone(&first), Arc::clone(&exchanged));let entered = std::sync::Mutex::new(entered);Arc::new(move || {Ok(Box::new(DeadLine { gate: Arc::clone(&gate), first: Arc::clone(&first), entered: entered.lock().expect("entered").clone(), exchanged: Arc::clone(&exchanged), }) asBox<dyncrate::transport::SyncingTransport>) }) };let sync = SyncLoop::new(SyncLoopInput { on_copy: None, replica: Arc::new(std::sync::Mutex::new(replica)), workspace_id: WORKSPACE.to_string(), transport: factory, clock: Arc::new(FixedClock::default_start()), random: Arc::new(SeededRandom::default()), interval_ms: Some(60_000), on_status: None, on_tables: None, on_sent: None, held: None, time_box: TimeBox::open(), });// The timer's pass reads on a dead line; the loop stops waiting for it at// its ceiling (shortened here) and it is left on its own thread. sync.inner.ceiling_ms.store(300, std::sync::atomic::Ordering::SeqCst);let abandoned = sync.pull_now().await.expect_err("the frozen pass is not waited for"); assert!(abandoned.message().contains("left to finish on its own"), "{}", abandoned.message()); entered_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("the read is on the wire"); assert!(sync.inner.straggling.load(std::sync::atomic::Ordering::SeqCst));// The ceiling back to its own: the wake is held by its slice alone, and a// loaded machine's pass past 300 ms is not a wake that failed to exchange. sync.inner.ceiling_ms.store(crate::sync::CYCLE_CEILING_MS, std::sync::atomic::Ordering::SeqCst);// The catch-up wake: a slice of twenty-five seconds.let budget = std::time::Duration::from_secs(25);let until = sync.inner.time_box.close_in(budget);let began = std::time::Instant::now(); sync.pull_now().await.expect("the wake exchanges"); assert!(began.elapsed() < budget, "inside the slice's budget: {:?}", began.elapsed()); assert_eq!(exchanged.load(std::sync::atomic::Ordering::SeqCst), 1, "the wake's own exchange went"); assert!(!sync.inner.straggling.load(std::sync::atomic::Ordering::SeqCst), "the straggler ended"); sync.inner.time_box.lift_if(until);}/// RULE: Going to the back closes the time box at the time iOS gives, and that time running out cuts the running pass at once — no further page and its read's socket shut — so a pass is never frozen mid-read to wake as a straggler (onetransport, 13 Oct 2026); the foreground lifts the box.#[tokio::test]asyncfn the_background_time_running_out_cuts_the_pass_on_the_wire() {let (_dir, _layout, replica) = open_test_replica();let transport = Arc::new(FakeTransport::default());let (sync, _seen) = loop_over(replica, Arc::clone(&transport));let gate = Arc::new(crate::transport::records_first::RecordsFirst::default()); *sync.inner.passing.lock().expect("passing") = Some(Arc::clone(&gate));let read = gate.reading();let (shut, shut_rx) = std::sync::mpsc::channel::<()>(); read.over(Some(Box::new(move || {let _ = shut.send(()); }))); sync.background(Some(std::time::Duration::from_secs(25))); assert!(sync.time_box().left().is_some_and(|left| left <= std::time::Duration::from_secs(25))); assert!(sync.time_box().room_for_a_page(), "a page may still start with the time left"); assert!(shut_rx.try_recv().is_err(), "nothing is cut while time is left");// The time runs out with nobody to say so (iOS froze the expiry handler// out): the cut armed at the box's end still comes. sync.background(Some(std::time::Duration::from_millis(200))); shut_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("the read's socket was shut at the box's end"); assert!(!sync.time_box().room_for_a_page(), "no further page");// And iOS's expiry says it at once. sync.time_box().uncut(); sync.background(Some(std::time::Duration::ZERO)); assert!(!sync.time_box().room_for_a_page(), "no further page"); shut_rx.try_recv().expect("the read's socket was shut"); sync.foreground(); assert_eq!(sync.time_box().left(), None, "the foreground lifts the box");}/// How many bytes `workspace_id`'s write-ahead log holds on disk.fn wal_bytes(layout: &crate::Layout, workspace_id: &str) -> u64 {letmut wal = layout.replica(workspace_id).into_os_string(); wal.push("-wal"); std::fs::metadata(wal).map_or(0, |meta| meta.len())}/// RULE: A completed fold pass folds the replica's write-ahead log back into the file and truncates it — a phone no longer waits for `sync.background` to checkpoint (row 7, 22 Oct 2026: a phone whose passes timed out carried a WAL that grew for days).#[tokio::test]asyncfn a_completed_fold_pass_leaves_the_write_ahead_log_empty() {let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic todo"); assert!(wal_bytes(&layout, WORKSPACE) > 0, "the write sits in the log");let (sync, _seen) = loop_over(replica, Arc::new(FakeTransport::default())); sync.pull_now().await.expect("a pass"); assert_eq!(wal_bytes(&layout, WORKSPACE), 0, "folded and truncated");}/// RULE: A sync pass the loop stops waiting for still folds the replica's write-ahead log at once, while the straggler is on the wire with the file let go; a reader in the way is busy, never an error.#[tokio::test]asyncfn a_timed_out_pass_folds_the_write_ahead_log_without_waiting_for_the_straggler() {let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "a synthetic write waiting to leave"); assert!(wal_bytes(&layout, WORKSPACE) > 0, "the write sits in the log");let (gate, entered, release) = Gate::new();let sync = gated_loop(replica, Arc::clone(&gate)); sync.inner.ceiling_ms.store(300, std::sync::atomic::Ordering::SeqCst);let abandoned = sync.pull_now().await.expect_err("the held pass is not waited for"); assert!(abandoned.message().contains("left to finish on its own"), "{}", abandoned.message()); entered.recv_timeout(std::time::Duration::from_secs(5)).expect("the straggler is on the wire"); assert_eq!(wal_bytes(&layout, WORKSPACE), 0, "folded while the straggler waits on the wire");// A reader holding a snapshot makes the fold busy, and busy is an answer. {let replica = sync.inner.replica.lock().expect("the file");let reader = replica.open_reader().expect("a reader"); reader.driver.exec("BEGIN").expect("a read"); reader.driver.get("SELECT count(*) AS n FROM sqlite_master", &[]).expect("a snapshot"); queue_one_change(&replica, "written behind the reader"); assert_eq!( replica.driver.checkpoint_truncate_unwaited().expect("not an error"), cotton_store::Folded::Busy ); } drop(release);}