//! The schedule around the cycle: a tokio task with a `Notify` wake and an//! interval under it.//!//! Three rules the shape carries, and each is a bug somebody actually had://!//! * **The next attempt is armed before the work, not only after it.** A pass//! that never settles cannot reach a line that follows it, so a schedule//! written only at the end is a schedule one hung request cancels for ever.//! Here that is [`super::CYCLE_CEILING_MS`]: the loop stops WAITING on a pass//! that has run past it and comes back on its own.//! * **A cycle is blocking work.** The store's driver is SQLite and the fold is//! SQLite, so a pass runs on `spawn_blocking` and the runtime's own threads//! stay free — a menu-bar app must answer a click while a catch-up runs.//! * **One pass at a time — single-flight WITH coalescing.** Two passes never//! overlap, and the callers behind the one in flight are not queued: they//! AWAIT it, and the flight — on success — runs exactly ONE more pass for all//! of them together. A hundred `push_now()` calls during one flight cost one//! extra push, not a hundred.//!//! The three rules that make that safe, each of which was the reason this//! took a second attempt://!//! * **The extra pass is the WIDEST anybody asked for.** A `PushOnly` caller//! folds into a `Full` flight happily; a `Full` caller may NOT fold into a//! `PushOnly` one, because it asked for news from the server and a push//! brings none. So the coalesce slot keeps the maximum//! ([`Pass::widest`]) and the extra pass runs THAT — which satisfies//! everyone waiting, in one round trip.//! * **A FAILED flight schedules nothing.** The failure is handed to every//! joiner, the slot is cleared, and the backoff ladder decides when//! anybody tries again. Running an extra pass into a server that just//! refused is the shape that turns one outage into a spin.//! * **A caller that arrived during the EXTRA pass is not lost.** The slot is//! consumed once, so a request landing after it was taken has no flight of//! its own to schedule; instead the loop is woken, and comes straight back.//! Losing it silently would be a `sync_now` that did nothing and said it//! had.use std::collections::BTreeMap;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;use tokio::sync::Notify;usecrate::connection::held::HeldNotes;usecrate::replica::Replica;usecrate::seams::{iso, Clock, Random};usesuper::{ backoff::wait_ms_for, cycle, CycleFailure, CycleReport, SchemaStanding, SyncState,SyncStatus, TimeBox, CYCLE_CEILING_MS, PULL_INTERVAL_MS, STRAGGLER_WAIT_MS,};/// How a transport is obtained for ONE pass.////// A factory rather than a value because the answer can change under the loop:/// the embedded server restarts from the menu bar, and a transport captured/// before the restart would push into a closed LRU. A failure here is a/// transient one — "the server is not running" is a sentence, and the loop/// backs off exactly as it would for a network that is down.pubtypeTransportFactory =Arc<dynFn() -> Result<Box<dyncrate::transport::SyncingTransport>, String> + Send + Sync>;/// Told after every pass, with the status as it now stands.pubtypeStatusListener = Arc<dynFn(&SyncStatus) + Send + Sync>;/// Told which tables a pull touched, so a screen refreshes.pubtypeTablesListener = Arc<dynFn(&[String]) + Send + Sync>;/// Told that the serving Mac offered this device the WHOLE FILE of its own/// database (`CycleReport::copy`): whoever can replace the file fetches it./// Told on every pass that carries an offer; the replacer is single-flight.pubtypeCopyListener = Arc<dynFn(&cotton_store::protocol::types::CopyOffer) + Send + Sync>;/// Told which tables a pull touched in ANOTHER held database, by its id.pubtypeHeldTablesListener = Arc<dynFn(&str, &[String]) + Send + Sync>;/// WHAT ONE FULL PASS REPORTED for one database it carried — the only thing a/// screen says sync by (owner, 11 Oct 2026: the sheet reacts to what a pass/// REPORTED, never to a pass starting, which read as "syncing" under all/// thirteen caps at once). `None` when its section did not answer.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructHeldReport<'a> {pub database: &'a str,/// A typed refusal still proves contact, even when it moved no rows.pub answered: bool,pub reported: Option<Reported>,/// The section went unanswered because the serving Mac and this build/// disagree about the schema — `PhoneBehind` ("update app", the Mac's/// `426`) or `ServerBehind` (the Mac is the older one) — said at once,/// never as a missed pass. `None` for any other unanswered section.pub schema: Option<SchemaStanding>,/// What an answered section moved by table; `None` when it did not/// answer.pub moved: Option<TableMoves<'a>>,}/// An answered section by store table: the changes (receipts) its answers/// moved this device past (`ExchangeReport::passed`), and — once the serving/// Mac has counted it — what the catch-up owed of each table when it began. What the device's own page says each tool still has coming/// (`sync::line::HomeLine::came`).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructTableMoves<'a> {pub received: &'a BTreeMap<String, usize>,pub owed: Option<&'a BTreeMap<String, u64>>,}/// One answered section: rows the peer took, rows taken in, and whether the/// page cap was hit with more waiting.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructReported {pub pushed: usize,pub pulled: usize,pub behind: bool,/// Changes the serving Mac said still wait for this database here, after/// the section's last answer; `None` when it did not say.pub remaining: Option<u64>,/// What the serving Mac counted this database owed here when the/// catch-up it is in began (`CycleReport::owed_at_start`).pub owed_at_start: Option<u64>,/// Rows still in this database's outbox here when the pass ended.pub unsent: u64,/// Changes (receipts) of this database's outbox the section handed over/// (`ExchangeReport::handed`) — what the catch-up's percent counts as/// sent, never `pushed`, which is rows.pub handed: usize,/// Changes (receipts) the section's answers moved this database past/// (`ExchangeReport::total_passed`) — what the percent counts as/// received, never `pulled`, which is rows.pub passed: usize,}implReported {/// What one section's report says, as a screen reads it.pubfn of(report: &CycleReport) -> Reported {Reported { pushed: report.pushed, pulled: report.pulled, behind: report.behind, remaining: report.remaining, owed_at_start: report.owed_at_start, unsent: report.unsent, handed: report.report.handed, passed: report.report.total_passed(), } }}/// Told [`HeldReport`].pubtypeHeldReportListener = Arc<dynFn(HeldReport<'_>) + Send + Sync>;/// Every database this device holds beside its own, as the ONE pass that/// syncs them all needs them.////// A device holds several files and one loop: each full pass is one exchange/// carrying a section per held database ([`cycle::run_cycle_many`]). The/// device's own file is the loop's `replica`, always open; every other one is/// opened through here only when it has something to hand over or to fold.#[derive(Clone)]pubstructHeldFiles {/// The ids held right now. Asked every pass: a database admitted a moment/// ago is in the next exchange.pub ids: Arc<dynFn() -> Vec<String> + Send + Sync>,/// Open another held database's file.pub open: Arc<dynFn(&str) -> Result<Arc<Mutex<Replica>>, String> + Send + Sync>,/// Is that file open already — a window is drawing it? Then it answers/// for itself and its note is not asked.pub open_now: Arc<dynFn(&str) -> bool + Send + Sync>,pub notes: HeldNotes,/// Told when a pass has let go of every file it opened, so the opener can/// close the idle ones.pub after_pass: Option<Arc<dynFn() + Send + Sync>>,pub on_tables: Option<HeldTablesListener>,/// Told the tables a pass HANDED OVER in that database — see/// [`SyncLoopInput::on_sent`].pub on_sent: Option<HeldTablesListener>,/// Told what each database's section of a full pass reported, as the/// pass ends ([`HeldReport`]).pub on_report: Option<HeldReportListener>,}pubstructSyncLoopInput {/// The replica, shared with the ingest queue and the media drain.////// ONE handle on the file, held by turns — which is what the TypeScript's/// single thread gave for free and what this makes explicit. A second/// `Driver` on a WAL file works, and it sees a different snapshot boundary/// and doubles the page cache for a 200 MB file.pub replica: Arc<Mutex<Replica>>,pub workspace_id: String,pub transport: TransportFactory,pub clock: Arc<dynClock>,pub random: Arc<dynRandom>,/// The pull cadence. `None` is [`PULL_INTERVAL_MS`].pub interval_ms: Option<u64>,pub on_status: Option<StatusListener>,pub on_tables: Option<TablesListener>,/// Told the tables a pass HANDED OVER, when it handed any. A push folds/// nothing, so `on_tables` never hears of it — yet a screen that reads/// the outbox ("Waiting to sync") changed all the same, and without this/// it kept its old answer until something else made it read again.pub on_sent: Option<TablesListener>,/// The other databases this device holds. `None` is a loop over one file.pub held: Option<HeldFiles>,/// How long a pass may still run ([`TimeBox`]). The caller keeps a clone/// and closes it for a background slice; an open box — the default — is/// every pass there was before it existed.pub time_box: TimeBox,/// Told when the serving Mac offers the whole file ([`CopyListener`])./// `None` — every loop but a phone's — and no transport says it takes a/// copy either, so none is offered.pub on_copy: Option<CopyListener>,}/// The running loop, and the handle that stops it.pubstructSyncLoop { inner: Arc<Inner>, task: Option<tokio::task::JoinHandle<()>>,}structInner { replica: Arc<Mutex<Replica>>,/// Is the FILE stamped past this build? Read once at construction: a build/// runs no migration over a newer file, so the stamp cannot change under/// it, and a re-hydrate that brings a newer one says so through/// `peer_schema` on the same pass. It is the standing's other source —/// a phone that took a newer Mac's snapshot is behind before its first/// exchange has answered, and Home should already say "update this phone". file_ahead: bool, workspace_id: String, transport: TransportFactory, clock: Arc<dynClock>, random: Arc<dynRandom>, interval: Duration, status: Mutex<SyncStatus>,/// One pass at a time, whoever asked for it — and everybody else waiting on/// the one that is running. flight: Mutex<Flight>, wake: Notify, running: AtomicBool, on_status: Option<StatusListener>, on_tables: Option<TablesListener>, on_sent: Option<TablesListener>, held: Option<HeldFiles>, time_box: TimeBox,/// A pass the loop stopped waiting for is still running on its own/// thread. No new pass starts until it ends: two passes asking from the/// same cursor fetch the same page twice and fold it twice. straggling: Arc<AtomicBool>,/// The gate the running pass's requests go through — what cuts its read/// when it is a straggler in a new pass's way. passing: Arc<Mutex<Option<Arc<crate::transport::records_first::RecordsFirst>>>>,/// The loop's wait on a pass, shortened by a test that needs a straggler. #[cfg(test)] ceiling_ms: std::sync::atomic::AtomicU64, on_copy: Option<CopyListener>,/// How the last pass left each OTHER held database, by id. others: Mutex<BTreeMap<String, SyncStatus>>,/// The last [`super::EXCHANGES_KEPT`] passes, newest last (the Debug group). exchanges: Mutex<std::collections::VecDeque<super::Exchange>>,/// How many callers have joined a flight in progress.////// A test-only counter, and it exists because the property under test is a/// RACE: "a hundred callers arriving mid-flight cost one extra pass" is/// only proved once all hundred have actually arrived, and a suite that/// released the flight after a yield would sometimes be asserting about/// three of them. #[cfg(test)] joined: std::sync::atomic::AtomicUsize,}impl std::fmt::DebugforSyncLoop {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SyncLoop") .field("workspace_id", &self.inner.workspace_id) .field("state", &self.status().state) .finish_non_exhaustive() }}implSyncLoop {/// Build the loop, stopped. `start` puts it on the runtime.pubfn new(input: SyncLoopInput) -> SyncLoop {let file_ahead = {let replica = input .replica .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); cotton_store::meta::file_schema_version(&replica.driver) .is_ok_and(|file| file > cotton_store::schema::ddl::SCHEMA_VERSION) };letmut status = SyncStatus { database: input.workspace_id.clone(), ..SyncStatus::default() };if file_ahead { status.schema = Some(SchemaStanding::PhoneBehind); }SyncLoop { inner: Arc::new(Inner { replica: input.replica, file_ahead, workspace_id: input.workspace_id, transport: input.transport, clock: input.clock, random: input.random, interval: Duration::from_millis(input.interval_ms.unwrap_or(PULL_INTERVAL_MS)), status: Mutex::new(status), flight: Mutex::new(Flight::default()), wake: Notify::new(), running: AtomicBool::new(false), on_status: input.on_status, on_tables: input.on_tables, on_sent: input.on_sent, held: input.held, time_box: input.time_box, straggling: Arc::new(AtomicBool::new(false)), passing: Arc::new(Mutex::new(None)), #[cfg(test)] ceiling_ms: std::sync::atomic::AtomicU64::new(CYCLE_CEILING_MS), on_copy: input.on_copy, others: Mutex::new(BTreeMap::new()), exchanges: Mutex::new(std::collections::VecDeque::new()), #[cfg(test)] joined: std::sync::atomic::AtomicUsize::new(0), }), task: None, } }pubfn status(&self) -> SyncStatus {self.inner.status() }/// The last [`super::EXCHANGES_KEPT`] exchanges, oldest first.pubfn exchanges(&self) -> Vec<super::Exchange> {self.inner .exchanges .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .iter() .cloned() .collect() }/// Every held database's status: the device's own first, then each other/// one the last pass spoke for, in id order.pubfn statuses(&self) -> Vec<SyncStatus> {letmut all = vec![self.inner.status()]; all.extend(self.inner .others .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .values() .cloned(), ); all }/// Put the loop on the runtime. Idempotent.pubfn start(&mutself) {ifself.inner.running.swap(true, Ordering::SeqCst) {return; }self.inner.publish(|status| { status.state = SyncState::Idle; status.stopped_reason = None; status.stopped_code = None; });let inner = Arc::clone(&self.inner);self.task = Some(tokio::spawn(asyncmove { inner.run().await })); }/// Stop the schedule. A pass already in flight finishes on its own — it/// takes the replica for its fold, and abandoning it mid-fold is not a/// thing SQLite offers.pubfn stop(&mutself) {if !self.inner.running.swap(false, Ordering::SeqCst) {return; }self.inner.publish(|status| { status.state = SyncState::Stopped; status.next_attempt_at = None; status.stopped_reason = None; status.stopped_code = None; });self.inner.wake.notify_waiters();ifletSome(task) = self.task.take() { task.abort(); } }/// A whole cycle, now. The caller wants the file current.pubasyncfn pull_now(&self) -> Result<CycleReport, CycleFailure> {self.inner .one_pass(Pass::Full) .await .map(|done| match done {Done::Cycle(report) => report,Done::Pushed(pushed) => CycleReport { pushed, ..CycleReport::default() }, }) }/// Drain the outbox now, and only that — what an import calls after every/// batch. Never fails outward: the ops STAY queued by construction, so a/// failed push here is not a failed import.pubasyncfn push_now(&self) -> usize {matchself.inner.one_pass(Pass::PushOnly).await {Ok(Done::Pushed(pushed)) => pushed,Ok(Done::Cycle(report)) => report.pushed,Err(_) => 0, } }/// Ask the loop to come back straight away rather than at its interval —/// what a write does once its op is in the outbox.////// **A wake during a backoff is a no-op, and that is the rule.** The/// `select!` in [`Inner::run`] ends whatever sleep is in progress on a/// wake, and a pass that fails climbs the ladder (`failures += 1`). So a/// wake honoured while `failures > 0` would make every write during an/// outage an immediate pass into a server that just refused, each one a/// rung higher — after ten edits on a train the loop would be at its/// five-minute ceiling, and the Mac coming back would go unnoticed for/// that long. The op is queued; the attempt already scheduled at/// `next_attempt_at` carries it, and a person's own "sync now" or a/// return to the foreground ([`Self::wake_and_reset`]) is what says the/// conditions changed. Answers whether the loop was asked, so a caller/// (and a test) can tell a wake from a deferral.////// With `failures == 0` the loop is either sleeping its interval — woken/// — or mid-pass, where the `Notify` permit is kept and the loop comes/// straight back after: a hundred writes during one pass are one extra/// pass, the single-flight rule from the other side.pubfn wake(&self) -> bool {ifself.inner.status().failures > 0 {returnfalse; }self.inner.wake.notify_one();true }/// Come back now, from the bottom of the ladder.////// The failure count IS the backoff ladder, so a loop that failed six times/// is thirty-two minutes from its next try. An explicit "sync now" and a/// return to the foreground are both a person saying the conditions/// changed — a train came out of a tunnel, a hotspot came up — and/// answering either with "in half an hour" is the app looking broken while/// working exactly as written.////// It does NOT clear a terminal device refusal: that is a decision only the/// server can reverse, and `stopped_reason` outlives every wake.pubfn wake_and_reset(&self) {// A PERSON LOOKING AT THE APP HAS NO LIMIT. A box a background slice// closed and did not live to lift — the process was frozen inside it// — must not make the first pass of an open app stop after no page.self.inner.time_box.lift();self.inner.publish(|status| {if status.state != SyncState::Stopped { status.failures = 0; status.next_attempt_at = None; } });self.inner.wake.notify_one(); }/// The app came to the front.////// The same as [`Self::wake_and_reset`] from the loop's side; the live/// socket is opened by the caller that owns it (`live::LiveChannel`), which/// is why this is not one call — a loop that owned a socket would be a/// second opinion about when there is one.pubfn foreground(&self) {self.wake_and_reset(); }/// The app went to the back, with `left` of the time iOS gives it before/// it is frozen (`None` when the platform does not say).////// The TIMER STAYS. 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.////// THE BOX CLOSES at what is left, so a pass running now stops between/// pages before the freeze instead of being frozen mid-read and waking/// as a straggler that keeps every later wake at "still finishing". The/// time running out (`left` zero, iOS's expiry) CUTS the pass at once:/// no further page, its read's socket shut.pubfn background(&self, left: Option<Duration>) {match left {None => {}Some(left) if left.is_zero() => {self.inner.time_box.close_in(Duration::ZERO);self.inner.cut_the_pass(); }Some(left) => {// The cut is ARMED here too, at the box's end, rather than// left to iOS's expiry handler alone — which may not get to// run before the freeze. A later box (a slice, the front)// disarms it.let until = self.inner.time_box.close_in(left);let inner = Arc::clone(&self.inner); std::thread::spawn(move || { std::thread::sleep(left);if inner.time_box.closed_at() == Some(until) { inner.cut_the_pass(); } }); } } }/// The loop's time box — the same one its input carried.pubfn time_box(&self) -> TimeBox {self.inner.time_box.clone() }/// A cheap `'static` handle on this loop.////// WHY IT EXISTS. `pull_now` borrows the loop, so its future cannot be/// spawned; and `Handle::block_on` PANICS when the calling thread is/// already inside the runtime — which is exactly what happens when a/// subscriber asks for a sync from inside the `data` event it was just/// handed. Spawning an owned future and waiting on a channel works from/// either side, and that needs a future that owns what it touches.pubfn handle(&self) -> SyncHandle {SyncHandle { inner: Arc::clone(&self.inner), } }}/// A `'static` view of a running loop — see [`SyncLoop::handle`].#[derive(Clone)]pubstructSyncHandle { inner: Arc<Inner>,}impl std::fmt::DebugforSyncHandle {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SyncHandle") .field("workspace_id", &self.inner.workspace_id) .finish_non_exhaustive() }}implSyncHandle {/// A whole cycle, now — the same coalescing pass [`SyncLoop::pull_now`]/// runs, in a future that owns everything it needs.pubasyncfn pull_now(self) -> Result<CycleReport, CycleFailure> {self.inner .one_pass(Pass::Full) .await .map(|done| match done {Done::Cycle(report) => report,Done::Pushed(pushed) => CycleReport { pushed, ..CycleReport::default() }, }) }/// Drain the outbox once, now — [`SyncLoop::push_now`] in an owned future.////// What the re-hydrate's drain runs, one batch at a time, so that a drain/// and a wake-initiated pass are ONE flight rather than two exchanges/// handing the same ops over side by side: a duplicate send is benign to/// the file, but a drain that saw its batch reported as already applied/// would read `moved == 0` with rows still waiting and refuse the/// re-hydrate it was clearing the way for.pubasyncfn push_now(self) -> usize {matchself.inner.one_pass(Pass::PushOnly).await {Ok(Done::Pushed(pushed)) => pushed,Ok(Done::Cycle(report)) => report.pushed,Err(_) => 0, } }}implDropforSyncLoop {fn drop(&mutself) {self.stop(); }}/// How much of a cycle a caller asked for.////// ORDERED, and the order is the coalescing rule: `Full` is wider than/// `PushOnly`, so the widest of everyone waiting is what the extra pass runs.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]enumPass {PushOnly,Full,}implPass {/// The one that answers both questions.fn widest(self, other: Pass) -> Pass {ifself >= other {self } else { other } }}#[derive(Debug, Clone, PartialEq, Eq)]enumDone {Cycle(CycleReport),Pushed(usize),}implDone {fn pushed(&self) -> usize {matchself {Done::Cycle(report) => report.pushed,Done::Pushed(pushed) => *pushed, } }/// The flight's own pass, plus the extra one it ran for everybody waiting.////// The pushes ADD — two passes really did send two batches, and a caller/// reading `pushed` is asking how many of its ops went. Everything else is/// the LATER pass's, because it is the more recent truth about the file.fn and_then(self, extra: Done) -> Done {let pushed = self.pushed() + extra.pushed();match extra {Done::Cycle(report) => Done::Cycle(CycleReport { pushed, ..report }),Done::Pushed(_) => matchself {Done::Cycle(report) => Done::Cycle(CycleReport { pushed, ..report }),Done::Pushed(_) => Done::Pushed(pushed), }, } }}/// What every joiner is handed. `Arc` because one result goes to all of them.typeOutcome = Arc<Result<Done, CycleFailure>>;/// The pass in flight, and what arrived while it was.#[derive(Debug, Default)]structFlight {/// The channel every joiner awaits, or `None` when nothing is running.////// A `watch` rather than a `oneshot`: a hundred callers await ONE flight,/// and a oneshot has exactly one receiver. running: Option<tokio::sync::watch::Receiver<Option<Outcome>>>,/// The widest pass anybody asked for mid-flight. Consumed once, by the/// flight, on success. coalesced: Option<Pass>,}implInner {/// See the field: the file this loop syncs is stamped past this build.fn file_ahead(&self) -> bool {self.file_ahead }fn status(&self) -> SyncStatus {self.status .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .clone() }fn publish(&self, edit: implFnOnce(&mutSyncStatus)) {let snapshot = {letmut status = self .status .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); edit(&mut status);// A pass's start is said only while it runs.if status.state != SyncState::Syncing { status.pass_started_at = None; } status.clone() };// Told with the lock released: a listener that asks the loop for its// status from inside its own callback is exactly what a status line// does.ifletSome(listener) = &self.on_status { listener(&snapshot); } }/// What is unsent and, of it, held for the Mac's time — or the last/// answer if the file has gone.fn pending(&self) -> (i64, i64) {let replica = self .replica .lock() .unwrap_or_else(|poisoned| poisoned.into_inner());match (cycle::current_pending(&replica.driver), cycle::current_held(&replica.driver)) { (Some(pending), Some(held)) => (pending, held), _ => {let status = self.status(); (status.pending, status.held) } } }/// One pass, coalescing.////// Either this call IS the flight — in which case it runs, and then runs/// one more pass for everybody who arrived while it was running — or it/// joins the flight already going and is handed that flight's whole result.asyncfn one_pass(&self, pass: Pass) -> Result<Done, CycleFailure> {// Whether to run or to wait is decided under the lock, in one step: a// gap between "is anything running?" and "then I am running" is two// flights.let joined = {letmut flight = self .flight .lock() .unwrap_or_else(|poisoned| poisoned.into_inner());match flight.running.clone() {Some(waiting) => { flight.coalesced = Some(match flight.coalesced {Some(already) => already.widest(pass),None => pass, });Some(waiting) }None => None, } };ifletSome(mut waiting) = joined { #[cfg(test)]self.joined .fetch_add(1, std::sync::atomic::Ordering::SeqCst);// The flight publishes ONCE, when it and its extra pass are both// done — so what arrives here already includes the pass this caller// asked for.while waiting.borrow().is_none() {if waiting.changed().await.is_err() {// The flight's sender went without publishing. Only a// panicking pass does that, and the honest answer is that// this caller's pass did not run.returnErr(CycleFailure::Transient { message: "the sync pass ended unexpectedly".to_string(), retry_after_seconds: None, }); } }let outcome = waiting.borrow().clone();returnmatch outcome {Some(outcome) => (*outcome).clone(),None => Err(CycleFailure::Transient { message: "the sync pass ended unexpectedly".to_string(), retry_after_seconds: None, }), }; }let (tell, listen) = tokio::sync::watch::channel(None); {letmut flight = self .flight .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); flight.running = Some(listen); flight.coalesced = None; }let first = self.run_pass(pass).await;let outcome = match first {Ok(done) => {let extra = self .flight .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .coalesced .take();match extra {// EXACTLY ONE more, at the widest anybody asked for.Some(extra) => matchself.run_pass(pass.widest(extra)).await {Ok(more) => Ok(done.and_then(more)),// THE FIRST PASS STILL SUCCEEDED, and this answers for// it. The ops it pushed are gone from the outbox// whatever happened next, and telling a caller whose// own pass worked that it failed is a screen showing an// error over a sync that happened.//// Nothing is swallowed: `run_pass` already published// the failure — `last_error`, the failure count, the// next attempt — so the ladder climbs and the banner// says so. What is dropped is only the FORM of the// answer to this one call.Err(_) => Ok(done), },None => Ok(done), } }Err(failure) => {// A FAILED flight schedules nothing. Running an extra pass into// a server that just refused is how one outage becomes a spin.self.flight .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .coalesced = None;Err(failure) } };let late = {letmut flight = self .flight .lock() .unwrap_or_else(|poisoned| poisoned.into_inner());// PUBLISHED BEFORE THE SLOT IS CLEARED, and both under the one// lock. Between clearing `running` and sending, a caller arriving// would find no flight, start its own, and race the pass that had// finished but not yet said so — two folds on one file. Under the// lock the two are a single step: anybody who sees the empty slot// is seeing it after the answer went out.let _ = tell.send(Some(Arc::new(outcome.clone()))); flight.running = None; flight.coalesced.take() };// Somebody asked while the EXTRA pass was running. The slot was already// consumed, so there is no flight left to schedule it — wake the loop// instead, which comes straight back.if late.is_some() {self.wake.notify_one(); } outcome }/// The running pass starts no further page and its read's socket is shut.fn cut_the_pass(&self) {self.time_box.cut();ifletSome(gate) = self.passing.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref() { gate.cut_reads(); } }fn ceiling_ms(&self) -> u64 { #[cfg(test)]returnself.ceiling_ms.load(Ordering::SeqCst); #[cfg(not(test))] CYCLE_CEILING_MS }/// CUT THE PASS THE LOOP STOPPED WAITING FOR and wait for it to end:/// no further page, its read's socket shut. Waited for at most/// [`STRAGGLER_WAIT_MS`], and never past what a slice's box leaves for/// a page of its own. What it folded stays folded; the page it was/// reading is asked again.asyncfn cut_the_straggler(&self) {self.cut_the_pass();let floor = Duration::from_millis(super::time_box::PAGE_FLOOR_MS);let waited = std::time::Instant::now();whileself.straggling.load(Ordering::SeqCst) {let within = waited.elapsed() < Duration::from_millis(STRAGGLER_WAIT_MS);let room = self.time_box.left().is_none_or(|left| left > floor);if !within || !room {return; } tokio::time::sleep(Duration::from_millis(20)).await; } }/// The pass itself: the blocking work, the ceiling on the wait, and what it/// does to the status.asyncfn run_pass(&self, pass: Pass) -> Result<Done, CycleFailure> {// THE LAST PASS IS STILL FOLDING: it keeps every page it folds, and a// second pass now would ask from the same cursor for the same page.// So it is CUT — no further page, and the read it has on the wire is// shut — and waited for, inside what this pass may spend. A pass iOS// froze mid-read wakes on a line that died while it slept; left// alone it waits out its sixty seconds, and every wake in between// would find it "still finishing" and exchange nothing.ifself.straggling.load(Ordering::SeqCst) {self.cut_the_straggler().await; }ifself.straggling.load(Ordering::SeqCst) {returnErr(CycleFailure::Transient { message: format!("the last sync pass is still finishing{}",self.time_box .what_it_is_doing() .map(|doing| format!(" — it is {doing}")) .unwrap_or_default() ), retry_after_seconds: Some(5), }); }self.time_box.uncut();// A DATABASE MID-MOVE IS LEFT ALONE (passivemove rule 1): its tables// not yet moved are in their old shape, and a fold into one would// write a row of this build's shape there. A pass over every held// database leaves out the ones moving; any other waits for its move.let over_held = matches!((pass, &self.held), (Pass::Full, Some(_)));if !over_held && crate::moves::left(&self.workspace_id).is_some() {returnErr(CycleFailure::Transient { message: MOVING_PASS.to_string(), retry_after_seconds: Some(5) }); }let started = self.clock.now_iso();self.publish(|status| {// A pass already on the wire keeps the time it began.if status.state != SyncState::Syncing || status.pass_started_at.is_none() { status.pass_started_at = Some(started); }// Caught up is said again only by this pass ending so: one that fails or stalls leaves it off. status.caught_up = false; status.state = SyncState::Syncing; });let replica = Arc::clone(&self.replica);let factory = Arc::clone(&self.transport);let workspace_id = self.workspace_id.clone();let now = self.clock.now_iso();let held = self.held.clone();let time_box = self.time_box.clone();let waited = self.time_box.clone();let began = std::time::Instant::now();let moved = Arc::new(Mutex::new(crate::transport::Moved::default()));let moved_by_pass = Arc::clone(&moved);let straggling = Arc::clone(&self.straggling); straggling.store(true, Ordering::SeqCst);let finished = Arc::clone(&straggling);let passing = Arc::clone(&self.passing);let work = tokio::task::spawn_blocking(move || {// Lowered when the work ends, however it ends — waited for or not.structEnds(Arc<AtomicBool>, Arc<Mutex<Option<Arc<crate::transport::records_first::RecordsFirst>>>>);implDropforEnds {fn drop(&mutself) { *self.1.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None;self.0.store(false, Ordering::SeqCst); } }let _ends = Ends(finished, Arc::clone(&passing));letmut transport = match factory() {Ok(transport) => transport,Err(message) => {return (Err(CycleFailure::Transient { message, retry_after_seconds: None, }),Vec::new(), ) } };// The copy, lent to the transport for the one write it makes of// its own (`RefusalAware::lend_file`). transport.lend_file(Arc::clone(&replica) asArc<dyn cycle::LendsFile + Send + Sync>); *passing.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = transport.gate();letmut result = match (pass, &held) {// ONE EXCHANGE OVER EVERY HELD DATABASE. Each file is taken// per page and per batch, never for the pass — a screen's read// shares its mutex, and a pass held it across every round trip. (Pass::Full, Some(held)) => { full_over_held(&replica, held, transport.as_mut(), &workspace_id, &now, &time_box) } (Pass::Full, None) => {let pass = cycle::run_cycle_paged_within( &replica, transport.as_mut(), &workspace_id, &now, &time_box, ) .map(Done::Cycle);// Folded after itself, however it ended. cycle::fold_wal(&*replica, &workspace_id); (pass, Vec::new()) }// A push drains the device's own queue. A write in another// held database wakes the loop, and the full pass carries it. (Pass::PushOnly, _) => ( cycle::push_only_paged(&replica, transport.as_mut(), &workspace_id, &now) .map(Done::Pushed),Vec::new(), ), };ifletOk(Done::Cycle(report)) = &mut result.0 { report.wanted = transport.readthrough_pending(); } *moved_by_pass.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = transport.moved(); result });// The ceiling is on the WAIT, not on the work: a blocking task cannot// be cancelled, and pretending otherwise would leave the loop believing// a replica lock it does not hold. What this buys back is the loop.//// THE STRAGGLER TOUCHES NOTHING IT SHOULD NOT. The abandoned pass runs// to its end on its own thread and its return value is dropped here,// so it cannot clear a latch that by then belongs to a later flight// and cannot publish a status about a cycle nobody is waiting for. It// CAN still be on the wire when the next pass starts — both paged// forms let go of the replica for the round trip — and what makes// that an overlap of SENDS rather than of writes is the protocol, not// a lock: the fold takes the mutex, a peer's cursor only moves// forward, and an outbox row is deleted by its `op_id` once the peer// says it applied. Two passes handing over the same batch cost one// duplicate the peer already holds; neither can lose a row. The// identity check the TypeScript needed (`running === mine`) is// structural here: the only thing that knows about this pass is this// await, and it is the thing that gave up.let (outcome, others) =match tokio::time::timeout(Duration::from_millis(self.ceiling_ms()), work).await {Ok(Ok(outcome)) => outcome,Ok(Err(join)) => (Err(CycleFailure::Transient { message: format!("the sync pass ended unexpectedly: {join}"), retry_after_seconds: None, }),Vec::new(), ),Err(_) => {// THE LOG IS FOLDED NOW, not when the straggler ends — it// may never. It lets the file go for every round trip, so// the file is free here unless it is folding a page, and// then the straggler folds after itself when it ends.let replica = Arc::clone(&self.replica);let workspace_id = self.workspace_id.clone();let _ = tokio::task::spawn_blocking(move || {ifletOk(replica) = replica.try_lock() { cycle::fold_wal(&replica.driver, &workspace_id); } }) .await; (Err(CycleFailure::Transient {// What the pass was doing when the loop stopped// waiting: the page it was asking for or folding,// its size and its tables. Each page it folded before// kept its cursor; this one is asked again. message: format!("the sync pass did not finish within {}s and was left to finish on its own{}",self.ceiling_ms() / 1_000, waited .what_it_is_doing() .map(|doing| format!(" — it was {doing}")) .unwrap_or_default() ), retry_after_seconds: None, }),Vec::new(), ) } };let at = iso(self.clock.now());match &outcome {// THE CALL failed, so no database was answered: every other// held database's line says so too, rather than the last good// pass.Err(failure) if others.is_empty() => self.others_unanswered(failure), _ => self.publish_others(others, &at), }match &outcome {Ok(Done::Cycle(report)) => {let tables = report.tables.clone();let pushed = report.pushed;let remaining = report.remaining;let wake_refusal = report.wake_refusal.clone();// A Mac older than this build takes nothing this device offers// and says so per op (`server_behind`). The pass SUCCEEDED —// pulls landed, the ladder stays down — and the word rides the// status so Home says "update the Mac" over a queue that is// otherwise a number going up for no reason anyone can see.// And the other way round: a Mac whose file is on a NEWER// schema than this build still serves this device — what// could not be folded is parked, not lost — and says its// schema on every answer. That word is "update this phone",// said while everything else keeps moving; it goes the// moment a pass sees a peer at or below this build.let phone_behind = self.file_ahead() || report .peer_schema .is_some_and(|peer| peer > cotton_store::schema::ddl::SCHEMA_VERSION);let schema = if phone_behind {Some(SchemaStanding::PhoneBehind) } else { report .held .get(cotton_store::protocol::types::REJECTION_SERVER_BEHIND) .is_some_and(|held| *held > 0) .then_some(SchemaStanding::ServerBehind) };self.publish(|status| { status.state = SyncState::Idle; status.available = true; status.failures = 0; status.last_error = None; status.last_pull_at = Some(at.clone()); status.schema = schema; status.behind_by = remaining; status.caught_up = !report.behind && remaining.is_none_or(|n| n == 0); status.wake_refusal = wake_refusal;if pushed > 0 { status.last_push_at = Some(at.clone()); } });if !tables.is_empty() {ifletSome(listener) = &self.on_tables { listener(&tables); } }let sent: Vec<String> = report.report.sent.keys().cloned().collect();if pushed > 0 && !sent.is_empty() {ifletSome(listener) = &self.on_sent { listener(&sent); } }iflet (Some(offer), Some(listener)) = (&report.copy, &self.on_copy) { listener(offer); } }Ok(Done::Pushed(pushed)) => {let pushed = *pushed;self.publish(|status| { status.available = true; status.last_error = None;if pushed > 0 { status.last_push_at = Some(at.clone()); } }); }Err(CycleFailure::Unlisted { message }) => {// The server's list does not name this database. Not a// failure to climb a ladder over — nothing was refused and// nothing was sent — so the count stays where it is and the// next attempt comes at the ordinary interval: the device// keeps asking, and the pass after the id comes back runs// from the kept replica.let message = message.clone();self.publish(|status| { status.state = SyncState::Waiting; status.available = false; status.last_error = Some(message); }); }Err(CycleFailure::MacBehind { .. }) => {// The serving Mac's file is OLDER than this build. Not a// fault to climb a ladder over and not this device's to fix:// the outbox stays whole, the loop asks again at its ordinary// interval, and the first pass after the Mac's update sends// everything without a tap. The status names the standing and// never the server's sentence ("schemaVersion must be 132"// reached the owner's screen on 12 Oct 2026).self.publish(|status| { status.state = SyncState::Waiting; status.available = true; status.last_error = None; status.schema = Some(SchemaStanding::ServerBehind); }); }Err(CycleFailure::PhoneBehind { message }) => {// The file is newer than this build. NOT a stop — an update is// a relaunch, and the pass after it drains the outbox — and// not a silent wait either: the word rides the status so Home// says "update Cotton" instead of climbing a ladder in the// dark, which is what the owner's phone did for twelve hours// on 2026-08-25.let message = message.clone();self.publish(|status| { status.state = SyncState::Waiting; status.failures += 1; status.last_error = Some(message); status.schema = Some(SchemaStanding::PhoneBehind); }); }Err(CycleFailure::TerminalDevice { sentence, message, code, .. }) => {// Not a network condition, and not something a retry can move:// the server refused THIS DEVICE, so the next minute's pass// gets the same answer.self.running.store(false, Ordering::SeqCst);let sentence = sentence.clone();let message = message.clone();let code = code.clone();self.publish(|status| { status.state = SyncState::Stopped; status.failures += 1; status.last_error = Some(message); status.stopped_reason = Some(sentence); status.stopped_code = Some(code); status.next_attempt_at = None; });// AND THERE IS NO SECOND STOPPING FAILURE ANY MORE. A device// used to be able to fall below the server's prune horizon and// need a fresh snapshot; there is no log and no horizon, so// however long a device has been away, its own cursors catch it// up. }Err(failure) => {let message = failure.message().to_string();self.publish(|status| { status.state = SyncState::Waiting; status.failures += 1; status.last_error = Some(message); }); } }// WHAT THIS DEVICE LAST HEARD FROM ITS MAC, for the build line: the// answer's name, version and schema, or the schema a refusal names.match &outcome {Ok(Done::Cycle(report)) => {let by = report.answered_by.clone();let schema = report.peer_schema;self.publish(|status| status.peer.answered(by.as_ref(), schema, &at)); }Ok(Done::Pushed(_)) => {}Err(failure) => {let message = failure.message().to_string();self.publish(|status| status.peer.refused(&message, &at)); } }self.note_exchange(&outcome, &at, began.elapsed(), &moved);let (pending, held) = self.pending();self.publish(|status| { status.pending = pending; status.held = held; }); outcome }/// One line for the Debug group's exchanges.fn note_exchange( &self, outcome: &Result<Done, CycleFailure>, at: &str, took: Duration, moved: &Mutex<crate::transport::Moved>, ) {let moved = *moved.lock().unwrap_or_else(|poisoned| poisoned.into_inner());let (answer, pushed, pulled) = match outcome {Ok(Done::Cycle(report)) => ("ok".to_string(), report.pushed, report.pulled),Ok(Done::Pushed(pushed)) => ("ok · push".to_string(), *pushed, 0),Err(failure) => (cotton_core::device::reported_state::clean_text(failure.message()), 0, 0), };let exchange = super::Exchange { at: at.to_string(), way: moved.way.map(str::to_string), answer, ms: u64::try_from(took.as_millis()).unwrap_or(u64::MAX), pushed: pushed as u64, pulled: pulled as u64, sent_bytes: moved.sent, received_bytes: moved.received, };letmut kept = self.exchanges.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); kept.push_back(exchange);while kept.len() > super::EXCHANGES_KEPT { kept.pop_front(); } }/// What the pass made of each OTHER held database: its status line, and/// the tables a pull touched in it.////// One database's refusal is that database's line and nobody else's — the/// loop's ladder is climbed by the call failing, never by a section.fn publish_others(&self, passes: Vec<cycle::DatabasePass>, at: &str) {if passes.is_empty() {return; }letmut told = Vec::with_capacity(passes.len()); {letmut others = self .others .lock() .unwrap_or_else(|poisoned| poisoned.into_inner());// A database no longer held has no line. others.retain(|id, _| passes.iter().any(|pass| &pass.database == id));for pass in &passes {let status = others.entry(pass.database.clone()).or_insert_with(|| SyncStatus { database: pass.database.clone(), ..SyncStatus::default() });match &pass.outcome {Ok(report) => { status.state = SyncState::Idle; status.available = true; status.failures = 0; status.last_error = None; status.stopped_reason = None; status.stopped_code = None; status.last_pull_at = Some(at.to_string()); status.behind_by = report.remaining; status.caught_up = !report.behind && report.remaining.is_none_or(|n| n == 0); status.wake_refusal.clone_from(&report.wake_refusal); status.peer.answered(report.answered_by.as_ref(), report.peer_schema, at);if report.pushed > 0 { status.last_push_at = Some(at.to_string()); }if !report.behind { status.pending = 0; } }Err(CycleFailure::Unlisted { message }) => { status.state = SyncState::Waiting; status.available = false; status.last_error = Some(message.clone()); }Err(CycleFailure::MacBehind { message }) => { status.state = SyncState::Waiting; status.last_error = None; status.schema = Some(SchemaStanding::ServerBehind); status.peer.refused(message, at); }Err(CycleFailure::TerminalDevice { sentence, message, code, .. }) => {// Refused in THIS database only: its line says so, and// the loop keeps running for the others. status.state = SyncState::Waiting; status.failures += 1; status.last_error = Some(message.clone()); status.stopped_reason = Some(sentence.clone()); status.stopped_code = Some(code.clone()); }Err(failure) => { status.state = SyncState::Waiting; status.failures += 1; status.last_error = Some(failure.message().to_string()); status.peer.refused(failure.message(), at); } } told.push(status.clone()); } }// Told with the lock released, like the loop's own status.for status in &told {ifletSome(listener) = &self.on_status { listener(status); } }ifletSome(listener) = self.held.as_ref().and_then(|held| held.on_tables.as_ref()) {for pass in &passes {ifletOk(report) = &pass.outcome {if !report.tables.is_empty() { listener(&pass.database, &report.tables); } } } }ifletSome(listener) = self.held.as_ref().and_then(|held| held.on_sent.as_ref()) {for pass in &passes {ifletOk(report) = &pass.outcome {let sent: Vec<String> = report.report.sent.keys().cloned().collect();if report.pushed > 0 && !sent.is_empty() { listener(&pass.database, &sent); } } } } }/// The whole call failed: each other held database waits with the loop.fn others_unanswered(&self, failure: &CycleFailure) {let told: Vec<SyncStatus> = {letmut others = self .others .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); others .values_mut() .map(|status| { status.state = SyncState::Waiting;// A Mac behind this build is a standing, never its// server's sentence.match failure.standing() {Some(SchemaStanding::ServerBehind) => { status.last_error = None; status.schema = Some(SchemaStanding::ServerBehind); } _ => status.last_error = Some(failure.message().to_string()), } status.clone() }) .collect() };ifletSome(listener) = &self.on_status {for status in &told { listener(status); } } }asyncfn run(self: Arc<Self>) {whileself.running.load(Ordering::SeqCst) {// ARMED BEFORE THE WORK. A pass that never settles cannot reach a// line that follows it, so a schedule written only at the end is a// schedule one hung request cancels for ever. This is the ceiling's// own promise, published so a status line can say when the loop// will be back even while a pass is stuck.let ceiling_at = iso(self.clock.now() + chrono::Duration::milliseconds(CYCLE_CEILING_MS as i64));self.publish(|status| status.next_attempt_at = Some(ceiling_at));// A BURST OF WAKES IS ONE PASS. The first wake of a burst ended// the sleep below; the rest left one permit behind, and this pass,// which reads the outbox and pulls only from here on, already// carries everything they were for. Taken now, the permit would// otherwise make a second pass for nothing: the object's rows// frames during a Mac's import, a run of writes before the loop// got the thread. A wake that comes once this pass has begun// keeps its permit, and its one extra pass. tokio::select! { biased; _ = self.wake.notified() => {} _ = std::future::ready(()) => {} }let outcome = self.one_pass(Pass::Full).await;if !self.running.load(Ordering::SeqCst) {break; }// OFFERED THE WHOLE FILE is not "come straight back": the copy is// what catches the device up, and a pass a second later would be// one more page into the file it replaces. The ordinary cadence// asks again, which renews the offer if the copy did not land.let behind = matches!(&outcome, Ok(Done::Cycle(report)) if report.behind && report.copy.is_none());let delay = next_delay( outcome.as_ref().err(), behind,self.status().failures, readthrough_delay(matches!(&outcome, Ok(Done::Cycle(report)) if report.wanted), self.interval),self.random.as_ref(), );let next_at = iso(self.clock.now() + chrono::Duration::from_std(delay).unwrap_or_default());self.publish(|status| status.next_attempt_at = Some(next_at)); tokio::select! { _ = tokio::time::sleep(delay) => {} _ = self.wake.notified() => {} } } }}/// The full pass over every held database: the device's own answer, and what/// was made of each other one.////// The own file's outcome is the loop's — its ladder, its status, its report./// Another database still behind brings the loop straight back, exactly as the/// own one would./// Why a pass left a database alone: its schema move is under way.pubconst MOVING_PASS: &str = "this copy is being brought up to date; it syncs when that is done";fn full_over_held( own: &Arc<Mutex<Replica>>, held: &HeldFiles, transport: &mutdyncrate::transport::SyncingTransport, workspace_id: &str, now: &str, time_box: &TimeBox,) -> (Result<Done, CycleFailure>, Vec<cycle::DatabasePass>) {letmut ids = vec![workspace_id.to_string()];for id in (held.ids)() {if !ids.contains(&id) { ids.push(id); } } ids.retain(|id| crate::moves::left(id).is_none());if ids.is_empty() {return (Err(CycleFailure::Transient { message: MOVING_PASS.to_string(), retry_after_seconds: Some(5) }), Vec::new()); }let opened: std::cell::RefCell<Vec<(String, Arc<dyn cycle::LendsFile>)>> = Default::default();let passes = {let opener = |database: &str| -> Result<Arc<dyn cycle::LendsFile>, String> {let file: Arc<dyn cycle::LendsFile> = if database == workspace_id {Arc::clone(own) asArc<dyn cycle::LendsFile> } else { (held.open)(database)? };// Opened just now and found mid-move: left for the next pass.ifcrate::moves::left(database).is_some() {returnErr(MOVING_PASS.to_string()); } opened.borrow_mut().push((database.to_string(), Arc::clone(&file)));Ok(file) };let open_now = |database: &str| database == workspace_id || (held.open_now)(database); cycle::run_cycle_many_within(&ids, &opener, &held.notes, &open_now, transport, now, time_box) };// Every file the pass opened folds its log back in, however the pass// ended — and before `after_pass`, which may close it.for (database, file) in opened.take() { cycle::fold_wal(&*file, &database); }// Every file the pass opened is back in nobody's hands by here.ifletSome(after_pass) = &held.after_pass { after_pass(); }// Every database the pass carried is told what its section reported,// answered or not.ifletSome(on_report) = &held.on_report {for database in &ids {// A COPY TOO BUSY TO WRITE never asked the Mac: its line keeps// what it last heard, and the status says the copy is busy// ([`cycle::COPY_BUSY`]) — never "the Mac is not answering".let busy = passes.as_ref().ok().is_some_and(|passes| { passes.iter().any(|pass| { &pass.database == database && pass.outcome.as_ref().err().is_some_and(|failure| failure.message() == cycle::COPY_BUSY) }) });if busy {continue; }let reported = passes.as_ref().ok().and_then(|passes| { passes .iter() .find(|pass| &pass.database == database) .and_then(|pass| pass.outcome.as_ref().ok().or(pass.folded.as_ref())) .map(Reported::of) });// The Mac and this build disagreeing about the schema is not a// missed pass: the home says which of them to update, at once.let schema = match &passes {Err(failure) => failure.standing(),Ok(passes) => passes .iter() .filter(|pass| &pass.database == database) .find_map(|pass| pass.outcome.as_ref().err().and_then(CycleFailure::standing)), };let moved = passes.as_ref().ok().and_then(|passes| { passes .iter() .find(|pass| &pass.database == database) .and_then(|pass| pass.outcome.as_ref().ok().or(pass.folded.as_ref())) .map(|report| TableMoves { received: &report.report.passed, owed: report.owed_by_table.as_ref(), }) });let answered = reported.is_some() || match &passes {Err(failure) => failure.answered(),Ok(passes) => passes.iter().find(|pass| &pass.database == database) .and_then(|pass| pass.outcome.as_ref().err()).is_some_and(CycleFailure::answered), }; on_report(HeldReport { database, answered, reported, schema, moved }); } }letmut passes = match passes {Ok(passes) => passes,Err(failure) => return (Err(failure), Vec::new()), };letSome(at) = passes.iter().position(|pass| pass.database == workspace_id) else {return (Err(CycleFailure::Transient { message: "the pass did not answer for this device's own database".to_string(), retry_after_seconds: None, }), passes, ); };let mine = passes.remove(at);let behind_elsewhere = passes .iter() .any(|pass| matches!(&pass.outcome, Ok(report) if report.behind));let answered_elsewhere: Vec<&CycleReport> = passes.iter().filter_map(|pass| pass.outcome.as_ref().ok()).collect();let mine = mine.outcome.map(|mut report| { report.behind |= behind_elsewhere;// THE DEVICE'S WHOLE STANDING on its own line, as `behind` is: what// the Mac said remains over every database it answered for, and its// reason for not waking this device from whichever answer carried it// (one device, one wake, so every answer says the same).for other in &answered_elsewhere {ifletSome(more) = other.remaining { report.remaining = Some(report.remaining.unwrap_or(0) + more); }if report.wake_refusal.is_none() { report.wake_refusal.clone_from(&other.wake_refusal); } }Done::Cycle(report) }); (mine, passes)}/// A holder asks again promptly until the serving Mac has its requested bytes.pubfn readthrough_delay(wanted: bool, ordinary: Duration) -> Duration {if wanted { Duration::from_secs(5) } else { ordinary }}/// How long until the next cycle, from the last outcome and the current cadence.pubfn next_delay( failure: Option<&CycleFailure>, behind: bool, failures: i64, interval: Duration, random: &dynRandom,) -> Duration {match failure {// Asked again at the ordinary cadence, never on a ladder: an unlisted// database is a state the server will change, not a fault this// device is retrying through.Some(CycleFailure::Unlisted { .. }) => interval,// The same for a Mac older than this build: its update is what// changes the answer, and the pass after it must not wait out a// ladder before sending what is held.Some(CycleFailure::MacBehind { .. }) => interval,Some(failure) => Duration::from_millis( wait_ms_for(failure.retry_after_seconds(), failures, random).max(0) as u64, ),// Still behind ⇒ come straight back. A second of breathing room keeps a// long catch-up from monopolising the machine.Noneif behind => Duration::from_secs(1),None => interval, }}/// Is EVERY database synced? Only when every outbox is empty and no loop has/// stopped on its own — one place still holding a write is not "Synced".pubfn all_synced(statuses: &[SyncStatus]) -> bool { statuses .iter() .all(|status| status.pending == 0 && status.stopped_code.is_none())}#[cfg(test)]#[path = "task_tests.rs"]mod tests;