Cotton code
1384 lines · 58.3 KB · RustRaw
//! ONE PASS: one exchange, looped while either side has more.//!//! There is no "pull then push" any more, because there are no longer two//! calls to order. A device hands over what it wrote and says how far it has//! seen each AUTHOR, and the same answer carries the writes it has not seen —//! `cotton_store::exchange` is the whole protocol and this file is the SCHEDULE//! around it.//!//! What the old order bought is still bought, and for free: the peer folds this//! device's ops BEFORE it builds the answer, so a row this device wrote and a//! row it is about to learn about cannot cross.//!//! **The pass hands over everything the peer has not seen, not just the queue.**//! `_outbox` is what this device wrote and has not pushed YET; a device that//! already synced its rows to another Mac has an empty one and a full file. So//! the pass carries a [`Handover`] — the peer's position per author, read off//! each answer — and the ops of every call are the outbox batch plus the next//! page of what the peer is behind on. There is no second sync path and no//! join-shaped special case: a device behind on nothing sends nothing extra.use std::collections::BTreeMap;use std::sync::{Arc, Mutex};use cotton_store::driver::Driver;use cotton_store::exchange::{    exchange_once, exchange_request, fold_answer, note_transport_failure, ExchangeReport,    Handover, SyncError, SyncTransport,};use cotton_store::outbox::pending_count;use cotton_store::protocol::types::{ExchangeSectionsRequest, SectionAnswer, SectionRefusal};use cotton_store::rejected::PARK_SWEEP_OPS;use crate::Replica;use super::time_box::TimeBox;use crate::connection::held::{HeldNote, HeldNotes};use crate::connection::terminal_device_sentence;use crate::transport::{RefusalAware, ServerRefusal};/// How many exchanges one pass may run before it reports `behind` and lets the/// loop breathe.////// TEN, and it is the old catch-up cap for the old reason: one pass must not/// hold the loop (and with it the next write's round trip) for an unbounded/// time. A device a month behind catches up over several passes rather than in/// one that never ends.pub const EXCHANGE_PAGES: u32 = 10;/// What one pass did.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct CycleReport {    /// The last answer asked this holder to push originals; use the hot tick.    pub wanted: bool,    /// ROWS this device took in — the report's own sum, never an op count.    pub pulled: usize,    /// ROWS the peer took in from us — the PEER's answer, never our count.    pub pushed: usize,    /// The pass hit its page cap and there is more waiting.    pub behind: bool,    /// Which tables the fold touched — what a screen's refresh is keyed on.    /// The report's own keys; there is no second piece of bookkeeping.    pub tables: Vec<String>,    /// Rows per table, both directions. What a merge sentence reads.    pub report: ExchangeReport,    /// Holds the peer answered rather than takes, per reason word    /// (`cotton_store::protocol::types::PushRejection::code`), summed over    /// the pass's pages — a write re-offered on a later page counts again,    /// so this is "how often", never "how many". `server_behind` is a Mac    /// older than this build; the status line says so off this key.    pub held: BTreeMap<String, usize>,    /// The newest schema a page's peer said its file is at; None when no page    /// said. Above this build's own is "this device is behind" — served all    /// the same, and the status line says so off this field.    pub peer_schema: Option<u32>,    /// The Mac that answered the pass's last page, as it named itself    /// (`ExchangeResponse::answered_by`); `None` when no answer said.    pub answered_by: Option<cotton_store::protocol::types::AnsweredBy>,    /// How many changes the serving Mac said are still waiting for this    /// device after the pass's LAST answer — what remains, never what moved;    /// counted by the Mac in full. `None` when no answer said.    pub remaining: Option<u64>,    /// What the serving Mac counted this device was owed when the catch-up    /// it is in BEGAN — counted exactly, once per catch-up, outside the Mac's    /// write hold, and said on every answer from then until the device is    /// level. Part of the whole a catch-up's percent is measured against    /// (`sync::line`). `None` until the Mac has counted, and when no answer    /// said.    pub owed_at_start: Option<u64>,    /// The same whole by table (`ExchangeResponse::owed_by_table`), from    /// whichever answer carried it: what the device's own page says each    /// tool still has coming is a share of. `None` until the Mac has counted.    pub owed_by_table: Option<BTreeMap<String, u64>>,    /// ROWS still in this device's outbox when the pass ended — with    /// `pushed`, the outbox as it stood when the pass began: the other part    /// of that whole.    pub unsent: u64,    /// Why the serving Mac could not wake this device the last time it tried,    /// in the Mac's own sentence (never key material); `None` when no answer    /// carried one.    pub wake_refusal: Option<String>,    /// THE WHOLE FILE IS FASTER: the serving Mac offered this device a copy    /// cut for it (`ExchangeResponse::copy`), and the pass stopped paging the    /// moment it did — the section reports `behind`, since it is. Only ever    /// set for a database the transport said it would take a copy of    /// (`RefusalAware::takes_copy`); the loop hands it to whoever replaces    /// the file (`SyncLoopInput::on_copy`).    pub copy: Option<cotton_store::protocol::types::CopyOffer>,}/// Why a pass did not finish.#[derive(Debug, Clone, PartialEq, Eq)]pub enum CycleFailure {    /// The server refused THIS DEVICE, and the next minute's retry would be    /// refused the same way. The loop STOPS and says the true sentence; a    /// person pairs again and it starts fresh.    TerminalDevice {        code: String,        /// What happened, and what a person does about it.        sentence: String,        /// The server's own message, kept for the log.        message: String,        /// The refusing machine's `x-cotton-server` tag, when it named itself.        refuser: Option<String>,        /// Who removed this device, by name, when a `device_revoked` said.        removed_by: Option<String>,    },    /// Everything else — a 5xx, a timeout, no network at all. Back off.    ///    /// A 404 lands here too, and that is the whole safety of a protocol change:    /// a build one release behind calls `/v1/sync/push`, is told the route does    /// not exist, reads it as transient and KEEPS ITS OUTBOX. Delay, never    /// data.    Transient {        message: String,        retry_after_seconds: Option<u32>,    },    /// A typed route refusal is an answer from the Mac, not lost contact.    Refused { message: String, retry_after_seconds: Option<u32> },    /// The server answered `426 upgrade_required`: this build's schema is    /// older than the file's, and nothing moves in either direction until    /// the app is updated. Not terminal — the loop keeps its ladder and its    /// outbox, because an update is a relaunch and the next pass after one    /// drains everything written meanwhile — and not a plain transient    /// either: the status names it (`SyncStatus::schema`) so Home can say    /// "update Cotton" instead of a spinner that never lands.    PhoneBehind { message: String },    /// The mirror case: the serving Mac's file is on an OLDER schema than    /// this build (`ServerRefusal::is_mac_behind`), so it takes nothing from    /// this device until the Mac is updated. Not terminal and not a ladder to    /// climb: what is unsent stays unsent, the loop asks again at its    /// ordinary interval, and the first pass after the Mac's update sends it    /// all without a tap. The status names it (`SchemaStanding::ServerBehind`)    /// and never carries the server's sentence.    MacBehind { message: String },    /// The server's list of this device's databases does not name this one    /// (`connection::list`). Nothing was sent and the file was not opened for    /// the pass. Not terminal and not a failure to back off from: the loop    /// keeps asking at its ordinary interval, and the pass after the id comes    /// back carries on from the kept replica.    Unlisted { message: String },}/// What an unlisted database's status says.pub const NOT_AVAILABLE_NOW: &str = "Not available right now";/// What a [`CycleFailure::MacBehind`] is said as wherever a sentence is/// asked of it — never the Mac's own "schemaVersion must be N".pub const MAC_BEHIND_SENTENCE: &str = "This device is ahead of your Mac \u{00B7} update your Mac";impl CycleFailure {    pub fn message(&self) -> &str {        match self {            CycleFailure::TerminalDevice { message, .. }            | CycleFailure::Transient { message, .. }            | CycleFailure::Refused { message, .. }            | CycleFailure::PhoneBehind { message }            | CycleFailure::MacBehind { message }            | CycleFailure::Unlisted { message } => message,        }    }    pub fn retry_after_seconds(&self) -> Option<u32> {        match self {            CycleFailure::TerminalDevice { .. }            | CycleFailure::PhoneBehind { .. }            | CycleFailure::MacBehind { .. }            | CycleFailure::Unlisted { .. } => None,            CycleFailure::Transient {                retry_after_seconds,                ..            } | CycleFailure::Refused { retry_after_seconds, .. } => *retry_after_seconds,        }    }    /// Which build is behind, when the failure is the serving Mac and this    /// build disagreeing about the schema.    pub fn standing(&self) -> Option<super::SchemaStanding> {        match self {            CycleFailure::PhoneBehind { .. } => Some(super::SchemaStanding::PhoneBehind),            CycleFailure::MacBehind { .. } => Some(super::SchemaStanding::ServerBehind),            _ => None,        }    }    /// Is there anything a retry could change?    ///    /// The stopping failure answers `false`: a refused device gets the same    /// answer every minute for ever, and a loop spending a pass on one is a    /// loop hiding a sentence somebody needs to read.    #[must_use]    pub fn is_terminal(&self) -> bool {        matches!(self, CycleFailure::TerminalDevice { .. })    }    pub fn answered(&self) -> bool {        matches!(self, Self::Refused { .. } | Self::PhoneBehind { .. } | Self::MacBehind { .. } | Self::Unlisted { .. })    }}/// What a store failure MEANS, once the transport has been asked what it saw.////// The store hands back a message and nothing else — right for the store, and/// not enough here: a refusal of this device is told from a bad afternoon by/// its CODE. `RefusalAware::last_refusal` is where that code comes from, and a/// transport that has none (the embedded one) can only ever answer transient,/// which is correct: the server in this process verifies nothing from itself.pub fn classify(error: SyncError, transport: &dyn RefusalAware) -> CycleFailure {    if let SyncError::CopyReplaced { .. } = &error {        return copy_replaced(error.to_string());    }    classify_refusal(error.to_string(), transport.last_refusal())}/// The stop a replica of another night of the owner's Dev copy ends in/// (`exchange::fold_answer`'s `CopyReplaced`). Terminal, like a refusal of/// this device: every pass would get the same answer until the copy is/// fetched again, which the shell does on seeing [`COPY_REPLACED`].pub fn copy_replaced(message: String) -> CycleFailure {    CycleFailure::TerminalDevice {        code: COPY_REPLACED.to_string(),        sentence: "Last night's copy of your databases has replaced this one, so it is fetched \                   afresh."            .to_string(),        message,        refuser: None,        removed_by: None,    }}/// The stopped code of [`copy_replaced`].pub const COPY_REPLACED: &str = "copy_replaced";/// [`classify`], given the refusal itself — a whole call's, off the/// transport, or ONE section's, off the answer.fn classify_refusal(message: String, refusal: Option<ServerRefusal>) -> CycleFailure {    let answered = refusal.as_ref().is_some_and(|refusal| refusal.status > 0);    classify_response(message, refusal, answered)}fn classify_response(message: String, refusal: Option<ServerRefusal>, answered: bool) -> CycleFailure {    match refusal {        Some(refusal) if refusal.is_terminal_device_refusal() => {            let code = refusal.code.clone().unwrap_or_default();            CycleFailure::TerminalDevice {                sentence: terminal_device_sentence(&code)                    .unwrap_or_else(|| refusal.message.clone()),                code,                message,                refuser: refusal.server.clone(),                removed_by: refusal.removed_by.clone(),            }        }        Some(refusal) if refusal.is_upgrade_required() => CycleFailure::PhoneBehind { message },        Some(refusal) if refusal.is_mac_behind() => CycleFailure::MacBehind { message },        Some(refusal) if answered && refusal.code.is_some() => CycleFailure::Refused {            message, retry_after_seconds: refusal.retry_after_seconds,        },        Some(ServerRefusal {            retry_after_seconds,            ..        }) => CycleFailure::Transient {            message,            retry_after_seconds,        },        None => CycleFailure::Transient {            message,            retry_after_seconds: None,        },    }}/// THE PROBE BEFORE ANY PUSH: is this pass's database listed?////// Asked first, before the file is lent or the outbox read, so an unlisted/// place's file is not touched at all — no batch read, no attempt written on/// an op that never left. A probe that could not be answered is classified/// like any other transport failure: a refusal of this device stops the/// loop, a network that is down backs off.fn ensure_listed(    transport: &mut dyn crate::transport::SyncingTransport,) -> Result<(), CycleFailure> {    match transport.listed() {        Ok(true) => Ok(()),        Ok(false) => Err(CycleFailure::Unlisted {            message: NOT_AVAILABLE_NOW.to_string(),        }),        Err(message) => Err(classify(SyncError::Transport(message), &*transport)),    }}/// One report out of an accumulated exchange.fn reported(    report: ExchangeReport,    behind: bool,    held: BTreeMap<String, usize>,    peer_schema: Option<u32>,    standing: Standing,    unsent: u64,) -> CycleReport {    CycleReport {        wanted: false,        pulled: report.total_received(),        pushed: report.total_sent(),        behind,        tables: report.tables(),        report,        held,        peer_schema,        answered_by: standing.answered_by,        remaining: standing.remaining,        owed_at_start: standing.owed_at_start,        owed_by_table: standing.owed_by_table,        unsent,        wake_refusal: standing.wake_refusal,        copy: standing.copy,    }}/// Where the serving Mac's latest answer said this device stands. The LATEST/// answer wins, never a sum or a maximum over pages: each page's count is of/// what was left after it. What the Mac counted the catch-up owed at its/// start is kept from whichever answer said it.#[derive(Default)]struct Standing {    remaining: Option<u64>,    owed_at_start: Option<u64>,    owed_by_table: Option<BTreeMap<String, u64>>,    wake_refusal: Option<String>,    /// The serving Mac's offer of the whole file, once made: no page is asked    /// of this section after it.    copy: Option<cotton_store::protocol::types::CopyOffer>,    /// The Mac behind the latest answer that named one.    answered_by: Option<cotton_store::protocol::types::AnsweredBy>,}impl Standing {    /// One more answer of the pass.    fn heard(        &mut self,        remaining: Option<u64>,        owed: (Option<u64>, Option<BTreeMap<String, u64>>),        wake_refusal: Option<String>,    ) {        self.remaining = remaining;        self.owed_at_start = owed.0.or(self.owed_at_start);        if owed.1.is_some() {            self.owed_by_table = owed.1;        }        self.wake_refusal = wake_refusal;    }}/// Rows still in the outbox of a file a pass has finished with; a file that/// has gone has nothing left to send.fn unsent(db: &Driver) -> u64 {    current_pending(db).and_then(|pending| u64::try_from(pending).ok()).unwrap_or(0)}/// Sum one exchange's holds into the pass's.fn absorb_held(into: &mut BTreeMap<String, usize>, held: &BTreeMap<String, usize>) {    for (code, count) in held {        *into.entry(code.clone()).or_default() += count;    }}/// The whole cycle, for a caller that holds the file across the round trip.////// **Only for a file nobody else reads while it runs** — a test's replica, a/// merge's private handle, the conformance drivers. A file a screen, a route or/// a worker shares goes through [`run_cycle_lent`].pub fn run_cycle(    db: &Driver,    transport: &mut dyn crate::transport::SyncingTransport,    workspace_id: &str,    now: &str,) -> Result<CycleReport, CycleFailure> {    ensure_listed(transport)?;    let mut report = ExchangeReport::default();    let mut behind = true;    let mut pages = 0u32;    // ONE handover for the whole pass: it learns where the peer is from the    // first answer and advances as pages are built, so no row goes twice.    let mut handover = Handover::default();    let mut held_by_code: BTreeMap<String, usize> = BTreeMap::new();    let mut peer_schema: Option<u32> = None;    let mut standing = Standing::default();    while behind && pages < EXCHANGE_PAGES {        let exchanged = exchange_once(            db,            &mut Wrapped(&mut *transport),            workspace_id,            None,            now,            &mut handover,        )        .map_err(|error| classify(error, &*transport))?;        pages += 1;        report.absorb(&exchanged.report);        absorb_held(&mut held_by_code, &exchanged.held);        peer_schema = peer_schema.max(exchanged.peer_schema);        standing.answered_by = exchanged.answered_by.or(standing.answered_by);        standing.heard(            exchanged.remaining,            (exchanged.owed_at_start, exchanged.owed_by_table),            exchanged.wake_refusal,        );        behind = exchanged.has_more;        if behind && transport.rests() {            break;        }    }    drain_parked(db, now);    release_refused_uploads(db, now);    Ok(reported(report, behind, held_by_code, peer_schema, standing, unsent(db)))}/// ONE DRAIN PER PASS: offer the oldest parked pulls to the fold again.////// The exchange retries the parked writes of the rows each PAGE names, which/// heals a row whose ops arrived in two pages. It cannot heal a park waiting on/// a DIFFERENT row — a foreign key whose parent came and went in a page the/// peer will never send again — and it cannot heal a file that was already/// carrying parks before this device ever ran this build, because nothing is/// going to name those rows. So the pass ends by walking/// `rejected::PARK_SWEEP_OPS` of them, never-tried first, and the rotation is/// what makes an existing replica converge on its own instead of waiting for/// somebody to press something.////// ONE LINE PER PASS THAT OFFERED SOMETHING, never one per op and never one/// for a pass that offered nothing: a file holding twenty thousand parks/// would otherwise write twenty thousand lines an hour into a log a person is/// supposed to be able to read, and a conflict tried at this shape waits for/// its row or the shape without a word (`rejected::sweep_parked`).////// A sweep that fails does NOT fail the pass. The exchange already landed; the/// drain is housekeeping on top of it, and turning a housekeeping error into a/// sync failure would back the loop off from the traffic that was working.fn drain_parked(db: &Driver, now: &str) {    match cotton_store::rejected::sweep_parked(db, PARK_SWEEP_OPS, now) {        Ok(swept) if swept.is_empty() || swept.retried == 0 => {}        Ok(swept) => {            eprintln!(                "[cotton-sync] parked writes: {} parked, {} offered again, {} landed, {} on the owner's board",                swept.parked, swept.retried, swept.cleared, swept.shown            );        }        Err(error) => eprintln!("[cotton-sync] the parked-write sweep could not run: {error}"),    }}/// AFTER EVERY EXCHANGE: an upload the server refused as dead bytes is due/// again (slice 7, `media_ledger::park_until_exchange`). The exchange is what/// carried this device's row naming the key again, if it has one, so the/// refusal may not hold any more; if the key is dead here too, the unlink/// pass takes the entry with its file. Housekeeping, so a failure is a line,/// never a failed pass.fn release_refused_uploads(db: &Driver, now: &str) {    if let Err(error) = cotton_store::media_ledger::release_after_exchange(db, now) {        eprintln!("[cotton-sync] uploads refused as erased could not be asked again: {error}");    }}/// FOLD THE FILE'S WRITE-AHEAD LOG BACK IN after a pass, lent like every/// other step and without waiting for anybody.////// A phone whose passes time out never reached the one checkpoint it had/// (`sync.background`), and carried a `-wal` that grew for days — every read/// walking it, and the launch after a force-quit recovering all of it. So a/// pass folds after itself, finished or abandoned. A reader in the way is/// [`Folded::Busy`](cotton_store::Folded::Busy): the log stays and the next/// pass folds it. Only a store error is said, and it is never the pass's.pub fn fold_wal(file: &dyn LendsFile, database: &str) -> Option<cotton_store::Folded> {    let mut folded = None;    file.lend(&mut |db| match db.checkpoint_truncate_unwaited() {        Ok(answer) => folded = Some(answer),        Err(error) => eprintln!("[cotton-sync] {database}'s write-ahead log was not folded: {error}"),    });    folded}/// Something that lends the file for one piece of work and takes it back.////// Two lenders: the phone's replica behind its `Mutex`, and a Mac's SERVED/// file behind the file store's own handle (`cotton-ffi`'s `Served`). Both are/// shared with every read of the file, and neither may be held while anything/// outside it is asked — [`run_cycle_lent`] asks for the file per step, never/// per pass, and so do the Code tool's passes (`crate::session_host`), which/// let it go for the helper's socket, `pnpm worktree:new` and a clone.pub trait LendsFile {    /// Run `work` over the file, then give the file back.    fn lend(&self, work: &mut dyn FnMut(&Driver));}impl LendsFile for Mutex<Replica> {    fn lend(&self, work: &mut dyn FnMut(&Driver)) {        // MARKED by `held`, like the served file's own hold: a step that waits        // inside this lend is every screen and the sync loop waiting behind it.        let replica = held(self);        work(&replica.driver);    }}/// A driver nobody else reads, lent to itself.////// **Only for a file nobody else shares** — a suite's replica, a private/// handle. It still MARKS THE THREAD for the length of each lend, so a suite/// driving a pass over a bare driver trips `cotton_store::held::must_not_wait`/// exactly where a shared file would stall.impl LendsFile for Driver {    fn lend(&self, work: &mut dyn FnMut(&Driver)) {        let _held = cotton_store::held::holding("the file");        work(self);    }}/// One step over a lent file, with its answer./// Why a pass sent nothing for a database whose file another connection was/// writing for longer than SQLite's busy wait: a NAMED failure, so the line/// and Me say the copy is busy rather than that the Mac did not answer.pub const COPY_BUSY: &str = "the copy is busy being brought up to date";/// Whether `error` is SQLite's "the file is locked by another writer".pub fn copy_busy(error: &cotton_store::StoreError) -> bool {    matches!(        error,        cotton_store::StoreError::Sqlite(rusqlite::Error::SqliteFailure(failure, _))            if matches!(failure.code, rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked)    )}pub fn borrowed<T>(file: &dyn LendsFile, work: impl FnOnce(&Driver) -> T) -> T {    let mut work = Some(work);    let mut answer = None;    file.lend(&mut |db| {        if let Some(work) = work.take() {            answer = Some(work(db));        }    });    answer.expect("a lender runs the work it is given exactly once")}/// The whole cycle, holding the file only while it is USED.////// [`run_cycle`] takes a driver the caller already holds, so the loop that/// calls it held the replica's mutex for the whole pass: ten round trips and/// folds. Every `read.*` on the phone takes that same mutex, so a screen opened/// while a pass was running waited for the pass — seconds on a good day, and/// after an app update long enough for every screen to sit on its skeleton. The/// person read it as "the database is slow"; the database was idle behind a/// lock nobody needed for the network.////// This one takes the mutex twice per exchange — the cursors and the outbox/// batch, then the fold after the round trip — so a read arriving mid-pass/// waits for one fold at most. The report is the same report; `cycle_tests.rs`/// holds that the lock is FREE while the transport is asked.pub fn run_cycle_paged(    replica: &Mutex<Replica>,    transport: &mut dyn crate::transport::SyncingTransport,    workspace_id: &str,    now: &str,) -> Result<CycleReport, CycleFailure> {    run_cycle_lent(replica, transport, workspace_id, now)}/// [`run_cycle_paged`] inside a [`TimeBox`]: no page is started without room/// for it, and the report says `behind` when the box closed first.pub fn run_cycle_paged_within(    replica: &Mutex<Replica>,    transport: &mut dyn crate::transport::SyncingTransport,    workspace_id: &str,    now: &str,    time_box: &TimeBox,) -> Result<CycleReport, CycleFailure> {    lent_within(replica, transport, workspace_id, now, time_box)}/// [`run_cycle_paged`] over any [`LendsFile`] — the form a Mac's peer sync/// runs over the file its own server serves.////// **THE FIVE SILENT MINUTES.** On 29 Sep 2026 (04:11:51Z–04:16:53Z) one Mac's/// server wrote nothing at all while its uplink crawled. The standby's peer/// pass ran [`run_cycle`] inside the served file's lock, and the sample showed/// that thread in a TLS handshake to the relay — a dial, a handshake and up to/// ten pages of reads, each allowed its full ceiling — while the session host/// and every route that reads the file queued on the same lock. Now the file/// is lent for the batch and for the fold, and the network is asked with the/// file in nobody's hands.pub fn run_cycle_lent(    file: &dyn LendsFile,    transport: &mut dyn crate::transport::SyncingTransport,    workspace_id: &str,    now: &str,) -> Result<CycleReport, CycleFailure> {    lent_within(file, transport, workspace_id, now, &TimeBox::open())}fn lent_within(    file: &dyn LendsFile,    transport: &mut dyn crate::transport::SyncingTransport,    workspace_id: &str,    now: &str,    time_box: &TimeBox,) -> Result<CycleReport, CycleFailure> {    // ONE SECTION of the pass over every held database: the same schedule,    // the same lends, and — through a transport that speaks for one file —    // the same single call per page.    ensure_listed(transport)?;    let lent: Arc<dyn LendsFile + '_> = Arc::new(Lent(file));    let mut passes = cycle_many(        &[workspace_id.to_string()],        &|_| Ok(Arc::clone(&lent)),        None,        &|_| false,        transport,        now,        false,        time_box,    )?;    passes        .pop()        .expect("one database asked, one pass answered")        .outcome}/// A file somebody else owns, lent on through the pass.struct Lent<'a>(&'a dyn LendsFile);impl LendsFile for Lent<'_> {    fn lend(&self, work: &mut dyn FnMut(&Driver)) {        self.0.lend(work);    }}/// Opens one held database's file for the pass, by id. Called only for a/// database that has something to hand over or something to fold.pub type OpensHeld<'a> = dyn Fn(&str) -> Result<Arc<dyn LendsFile + 'a>, String> + 'a;/// What the pass over every held database made of ONE of them.#[derive(Debug)]pub struct DatabasePass {    pub database: String,    /// Whether this database's file was opened by the pass. An idle database    /// answered with nothing is not.    pub opened: bool,    pub outcome: Result<CycleReport, CycleFailure>,    /// A section that failed AFTER the Mac had answered it at least once:    /// what the pages it folded reported, `behind`, since it is. A pass that    /// moved rows is an answer — what a screen says sync by reads this when    /// the outcome is a failure, and only a section the Mac never answered    /// is unanswered. `None` for an `Ok` outcome and for a section with no    /// answer at all.    pub folded: Option<CycleReport>,}/// ONE EXCHANGE PER CYCLE, OVER EVERY DATABASE THIS DEVICE HOLDS.////// Each page is one call carrying a section per database that still has/// something to say. A database whose note says it is idle/// ([`HeldNotes::idle_section`]) is spoken for WITHOUT opening its file, and/// an answer that changes nothing leaves it closed — so an idle database/// costs a few hundred bytes of one request and nothing else. A database with/// a queue, an unfinished pass or no note is opened, and its section is/// exactly what [`run_cycle_lent`] would have sent alone.////// `open_now` says which files are ALREADY open — the device's own, one a/// window is drawing. Such a file answers for itself and its note is not/// asked: a write may have landed in it since the note was written, and the/// open the note exists to save is already paid.////// `Err` is the CALL failing — no network, the device refused at the door —/// and is every database's answer. A section the server refused is that one/// database's [`DatabasePass::outcome`]; the others still fold.pub fn run_cycle_many<'a>(    databases: &[String],    opener: &OpensHeld<'a>,    notes: &HeldNotes,    open_now: &dyn Fn(&str) -> bool,    transport: &mut dyn crate::transport::SyncingTransport,    now: &str,) -> Result<Vec<DatabasePass>, CycleFailure> {    run_cycle_many_within(databases, opener, notes, open_now, transport, now, &TimeBox::open())}/// [`run_cycle_many`] inside a [`TimeBox`] — what the loop runs, so that a/// phone given thirty seconds in the background stops BETWEEN pages.////// **A STOPPED PASS HAS LOST NOTHING.** Every page it folded is in its file/// with its cursor — one transaction per page — and every write it handed/// over that the peer took is out of the outbox by the same transaction. What/// it did not reach is still asked for by the next pass, from the folded/// point: a section the box closed on reports `behind`, and its idle note is/// written "not caught up", so the next pass opens the file rather than/// trusting a note from before.pub fn run_cycle_many_within<'a>(    databases: &[String],    opener: &OpensHeld<'a>,    notes: &HeldNotes,    open_now: &dyn Fn(&str) -> bool,    transport: &mut dyn crate::transport::SyncingTransport,    now: &str,    time_box: &TimeBox,) -> Result<Vec<DatabasePass>, CycleFailure> {    cycle_many(databases, opener, Some(notes), open_now, transport, now, true, time_box)}/// One database's half of the pass.struct Section<'a> {    database: String,    file: Option<Arc<dyn LendsFile + 'a>>,    handover: Handover,    report: ExchangeReport,    held: BTreeMap<String, usize>,    peer_schema: Option<u32>,    /// Where the Mac's latest answer said this device stands.    standing: Standing,    /// Where the peer's last folded answer said the peer is.    seen: BTreeMap<String, String>,    behind: bool,    failure: Option<CycleFailure>,    /// The Mac answered this section at least once in this pass.    answered: bool,}impl<'a> Section<'a> {    /// The file, opened on first need.    fn opened(&mut self, opener: &OpensHeld<'a>) -> Result<Arc<dyn LendsFile + 'a>, CycleFailure> {        if let Some(file) = &self.file {            return Ok(Arc::clone(file));        }        let file = opener(&self.database).map_err(|message| CycleFailure::Transient {            message,            retry_after_seconds: None,        })?;        self.file = Some(Arc::clone(&file));        Ok(file)    }    fn stop(&mut self, failure: CycleFailure) {        self.failure = Some(failure);        self.behind = false;    }}/// What one section sent on this page.struct Sent {    index: usize,    handed: cotton_store::exchange::Handed,    /// The note that spoke for a file left closed.    spoke: Option<HeldNote>,}fn cycle_many<'a>(    databases: &[String],    opener: &OpensHeld<'a>,    notes: Option<&HeldNotes>,    open_now: &dyn Fn(&str) -> bool,    transport: &mut dyn crate::transport::SyncingTransport,    now: &str,    probe: bool,    time_box: &TimeBox,) -> Result<Vec<DatabasePass>, CycleFailure> {    let mut sections: Vec<Section<'a>> = Vec::with_capacity(databases.len());    for database in databases {        let mut section = Section {            database: database.clone(),            file: None,            handover: Handover::default(),            report: ExchangeReport::default(),            held: BTreeMap::new(),            peer_schema: None,            standing: Standing::default(),            seen: BTreeMap::new(),            behind: true,            failure: None,            answered: false,        };        // THE PROBE BEFORE ANY PUSH, per database: an unlisted one sends no        // section and its file is not touched.        if probe {            match transport.listed_database(database) {                Ok(true) => {}                Ok(false) => section.stop(CycleFailure::Unlisted {                    message: NOT_AVAILABLE_NOW.to_string(),                }),                Err(message) => {                    let failure = classify(SyncError::Transport(message), &*transport);                    if failure.answered() {                        section.stop(failure);                    } else {                        return Err(failure);                    }                }            }        }        sections.push(section);    }    let mut pages = 0u32;    // THE BOX IS READ BEFORE EVERY PAGE, the first included: a page started    // without room for it is a request cut in the air. Stopping here leaves    // every section that still had something to say `behind`, which is the    // truth and is what brings the next pass.    while pages < EXCHANGE_PAGES && time_box.room_for_a_page() {        let mut sent: Vec<Sent> = Vec::new();        for (index, section) in sections.iter_mut().enumerate() {            // OFFERED THE WHOLE FILE: the pages stop here, and the copy is            // what catches this database up (`CycleReport::copy`).            if !section.behind || section.standing.copy.is_some() {                continue;            }            // SPOKEN FOR BY ITS NOTE — first page only, and only a file this            // pass has not opened: after that the file itself answers.            if pages == 0 && section.file.is_none() && !open_now(&section.database) {                if let Some((note, request)) = notes.and_then(|notes| {                    let note = notes.read(&section.database).filter(HeldNote::idle)?;                    Some((note, notes.idle_section(&section.database)?))                }) {                    sent.push(Sent {                        index,                        handed: cotton_store::exchange::Handed {                            request,                            queued: Default::default(),                        },                        spoke: Some(note),                    });                    continue;                }            }            let file = match section.opened(opener) {                Ok(file) => file,                Err(failure) => {                    section.stop(failure);                    continue;                }            };            let database = section.database.clone();            let handover = &mut section.handover;            // A write held while this device had no server time leaves with            // this page once judge time is known (`release_held_writes`).            match borrowed(&*file, |db| {                cotton_store::exchange::release_held_writes(db, now)?;                exchange_request(db, &database, None, handover)            }) {                Ok(mut handed) => {                    // An exchange runs only over an existing replica. Whole copies                    // belong exclusively to bootstrap when its path is absent.                    handed.request.takes_copy = false;                    sent.push(Sent {                        index,                        handed,                        spoke: None,                    });                }                Err(error) if copy_busy(&error) => section.stop(CycleFailure::Transient {                    message: COPY_BUSY.to_string(),                    retry_after_seconds: Some(5),                }),                Err(error) => section.stop(classify_refusal(SyncError::from(error).to_string(), None)),            }        }        if sent.is_empty() {            break;        }        // The network, with every file in nobody's hands. ONE WAIT: the        // request's ceiling is the route's own sixty seconds, never cut to        // what is left of the box — the box decides whether a page STARTS        // (`room_for_a_page`), and a read cut short throws away a page the        // Mac already answered (13 Oct 2026: a read inside a 25 s background        // slice gave up after ~18 s).        time_box.doing(Some(format!(            "asking for page {} of {} database(s)",            pages + 1,            sent.len()        )));        let request = ExchangeSectionsRequest {            sections: sent.iter().map(|sent| sent.handed.request.clone()).collect(),        };        let answered = transport.exchange_many(&request).and_then(|answer| {            if answer.sections.len() == sent.len() {                Ok(answer.sections)            } else {                Err(format!(                    "{} sections were answered for the {} asked — nothing in them was taken",                    answer.sections.len(),                    sent.len()                ))            }        });        let answers = match answered {            Ok(answers) => answers,            // THE BOX CLOSED ON A REQUEST IN THE AIR, after at least one page            // had landed. That is the pass ending, not the network failing:            // the pages before it are folded and are reported, the ops that            // were in the air stay queued (a peer that took them says so on            // the next page asked), and the loop climbs no ladder for a limit            // this device set itself. A pass that landed NOTHING and failed            // is still a failure, said as one.            Err(_) if pages > 0 && !time_box.room_for_a_page() => break,            // THE CALL FAILED AFTER PAGES HAD LANDED (a page's ceiling, the            // network dropping mid catch-up): what was folded stands and is            // reported, the sections in the air carry the failure — their            // ops stay queued with the attempt written on them — and the            // loop backs off on it. Anything worse than a transient failure            // is still the whole call's answer.            Err(message) if pages > 0 => {                let failure = classify(SyncError::Transport(message.clone()), &*transport);                if !matches!(failure, CycleFailure::Transient { .. } | CycleFailure::Refused { .. }) {                    return Err(failure);                }                for sent in &sent {                    let section = &mut sections[sent.index];                    let failure = match &section.file {                        Some(file) => borrowed(&**file, |db| {                            failed_in_the_air(db, &sent.handed, message.clone(), &*transport)                        }),                        None => failure.clone(),                    };                    section.stop(failure);                }                break;            }            Err(message) => {                // The whole call failed: every queued op that was in the air                // stays, with the attempt written on it.                let mut failure = None;                for sent in &sent {                    if let Some(file) = &sections[sent.index].file {                        failure = Some(borrowed(&**file, |db| {                            failed_in_the_air(db, &sent.handed, message.clone(), &*transport)                        }));                    }                }                return Err(failure                    .unwrap_or_else(|| classify(SyncError::Transport(message), &*transport)));            }        };        pages += 1;        time_box.doing(Some(format!("folding page {pages}: {}", page_mix(&answers))));        for (sent, answer) in sent.into_iter().zip(answers) {            let section = &mut sections[sent.index];            // THE ANSWER CHECK: a section that names another file than the one            // asked is a misrouted answer, and folding it would write one            // database's rows into another's replica. Nothing in it is taken.            let response = if answer.workspace_id() != section.database {                Err((                    format!(                        "the answer came from database {}, not {} — nothing in it was taken",                        answer.workspace_id(),                        section.database                    ),                    None,                ))            } else {                match answer {                    SectionAnswer::Refused(refused) => Err((                        refused.refused.message.clone(),                        Some(section_refusal(&refused.refused)),                    )),                    SectionAnswer::Answered(response) => Ok(response),                }            };            let response = match response {                Ok(response) => response,                Err((message, refusal)) => {                    if let Some(file) = &section.file {                        if let Err(error) = borrowed(&**file, |db| {                            note_transport_failure(db, &sent.handed, &message)                        }) {                            section.stop(classify_refusal(SyncError::from(error).to_string(), None));                            continue;                        }                    }                    section.stop(classify_response(                        SyncError::Transport(message).to_string(),                        refusal,                        true,                    ));                    continue;                }            };            // AN IDLE DATABASE, ANSWERED WITH NOTHING: the file stays closed.            if sent.spoke.as_ref().is_some_and(|note| note.unchanged_by(&response)) {                section.peer_schema = section.peer_schema.max(response.schema_version);                section.standing.answered_by =                    response.answered_by.clone().or(section.standing.answered_by.take());                section.standing.heard(                    response.behind_by,                    (response.owed_at_start, response.owed_by_table.clone()),                    response.wake_refusal.clone(),                );                section.behind = false;                section.answered = true;                continue;            }            let file = match section.opened(opener) {                Ok(file) => file,                Err(failure) => {                    section.stop(failure);                    continue;                }            };            let handover = &mut section.handover;            let folding = std::time::Instant::now();            let folded = borrowed(&*file, |db| fold_answer(db, &sent.handed, &response, now, handover));            if crate::transport::object::sync_times() {                eprintln!("[sync-times] fold ops={} ms={}", response.ops.len(), folding.elapsed().as_millis());            }            match folded {                Ok(exchanged) => {                    transport.folded();                    section.report.absorb(&exchanged.report);                    absorb_held(&mut section.held, &exchanged.held);                    section.peer_schema = section.peer_schema.max(exchanged.peer_schema);                    section.standing.answered_by =                        exchanged.answered_by.or(section.standing.answered_by.take());                    section.standing.heard(                        exchanged.remaining,                        (exchanged.owed_at_start, exchanged.owed_by_table),                        exchanged.wake_refusal,                    );                    section.behind = exchanged.has_more;                    section.seen = response.seen;                    section.answered = true;                }                Err(error) => {                    // A PAGE THAT WOULD NOT FOLD names what it held, so the                    // next stall reads from the Mac's log alone.                    let failure = match classify(error, &*transport) {                        CycleFailure::Transient { message, retry_after_seconds } => CycleFailure::Transient {                            message: format!(                                "{message} — this device could not fold a page of {}",                                ops_mix(&response.ops)                            ),                            retry_after_seconds,                        },                        other => other,                    };                    section.stop(failure);                }            }        }        // THE PAGE ASKS THE PASS TO REST (`RefusalAware::rests`): what it        // folded is told to the screens as the pass ends, and every section        // still behind brings the next pass straight back.        if transport.rests() {            break;        }    }    time_box.doing(None);    Ok(sections        .into_iter()        .map(|section| {            let opened = section.file.is_some();            // A database the pass never opened handed nothing over and had            // nothing to: its outbox is empty.            let mut left = 0;            if let Some(file) = &section.file {                // Lent for the drain and given back, like every fold above.                borrowed(&**file, |db| {                    left = unsent(db);                    if section.failure.is_none() {                        drain_parked(db, now);                        release_refused_uploads(db, now);                    }                    if let Some(notes) = notes {                        let caught_up = section.failure.is_none() && !section.behind;                        // Rows folded — on a page that failed after them too —                        // are rows whose bytes this device may not hold yet.                        let pulled = section.report.total_received() > 0;                        if let Err(error) = notes.note_pass(                            &section.database,                            db,                            caught_up,                            &section.seen,                            pulled,                        ) {                            // The note is a saving, never a debt: without it                            // the next pass opens the file.                            eprintln!("[cotton-sync] the held note was not written: {error}");                        }                    }                });            }            let answered = section.answered;            let report = reported(                section.report,                section.behind,                section.held,                section.peer_schema,                section.standing,                left,            );            let (outcome, folded) = match section.failure {                None => (Ok(report), None),                Some(failure) => (                    Err(failure),                    answered.then_some(CycleReport { behind: true, ..report }),                ),            };            DatabasePass { database: section.database, opened, outcome, folded }        })        .collect())}/// A page as a log reads it: its rows, its size on the wire, and its largest/// tables ("500 rows, 0.8 MB: cotton_media_holdings 282, cotton_msg_messages/// 94, …").fn ops_mix(ops: &[cotton_store::protocol::types::CottonOp]) -> String {    let mut by_table: BTreeMap<&str, usize> = BTreeMap::new();    let mut bytes = 0usize;    for op in ops {        *by_table.entry(op.table.as_str()).or_default() += 1;        bytes += serde_json::to_vec(op).map_or(0, |body| body.len());    }    let mut tables: Vec<(&str, usize)> = by_table.into_iter().collect();    tables.sort_by(|left, right| right.1.cmp(&left.1).then(left.0.cmp(right.0)));    let named: Vec<String> = tables.iter().take(4).map(|(table, n)| format!("{table} {n}")).collect();    let more = if tables.len() > 4 { ", …" } else { "" };    format!(        "{} rows, {:.1} MB: {}{more}",        ops.len(),        bytes as f64 / 1_048_576.0,        named.join(", ")    )}/// Every answered section of a page, as one [`ops_mix`].fn page_mix(answers: &[SectionAnswer]) -> String {    let ops: Vec<cotton_store::protocol::types::CottonOp> = answers        .iter()        .filter_map(|answer| match answer {            SectionAnswer::Answered(response) => Some(response.ops.iter().cloned()),            SectionAnswer::Refused(_) => None,        })        .flatten()        .collect();    ops_mix(&ops)}/// One section's refusal, as the refusal the single-database call would have/// been — so its CODE is judged by the same rule ([`classify`]).fn section_refusal(refusal: &SectionRefusal) -> ServerRefusal {    ServerRefusal {        message: refusal.message.clone(),        // The call itself was answered; the status a lone exchange would have        // carried is not on the wire, and nothing below reads it but the 426.        status: 0,        code: Some(refusal.code.clone()),        existing_connection_id: None,        retry_after_seconds: refusal            .extra            .get("retryAfterSeconds")            .and_then(serde_json::Value::as_u64)            .and_then(|seconds| u32::try_from(seconds).ok()),        server: None,        removed_by: refusal            .extra            .get("removedBy")            .and_then(serde_json::Value::as_str)            .map(str::trim)            .filter(|name| !name.is_empty())            .map(str::to_string),    }}/// The transport failed with a page in the air: the ops stay, the attempt is/// written on them, and the failure is classified — the same three things/// `exchange_once` does, for a caller that let go of the file to ask.fn failed_in_the_air(    db: &Driver,    handed: &cotton_store::exchange::Handed,    message: String,    transport: &dyn RefusalAware,) -> CycleFailure {    if let Err(error) = note_transport_failure(db, handed, &message) {        return classify(error.into(), transport);    }    classify(SyncError::Transport(message), transport)}/// The replica, taken — and the thread MARKED as holding it for as long as/// the answer lives.////// A poisoned mutex is a panic on another thread, not a corrupt file: the/// replica behind it is still the replica, and the loop carries on with it.////// Every hold of the replica in this crate that is not a lend goes through/// here, so the mark cannot be forgotten at one of them: the replica is the/// phone's file and every screen's read, and a hold that waits on the network/// is every screen waiting on it too (`cotton_store::held`). The media drain/// is the other taker (`media::drain`).pub(crate) fn held(replica: &Mutex<Replica>) -> HeldReplica<'_> {    let guard = replica        .lock()        .unwrap_or_else(|poisoned| poisoned.into_inner());    HeldReplica {        guard,        _mark: cotton_store::held::holding("the replica"),    }}/// The replica's lock and the thread's mark, owned together so one cannot/// outlive the other. Fields drop in order: the lock is let go first, then/// the mark comes off.pub(crate) struct HeldReplica<'a> {    guard: std::sync::MutexGuard<'a, Replica>,    _mark: cotton_store::held::Holding,}impl std::ops::Deref for HeldReplica<'_> {    type Target = Replica;    fn deref(&self) -> &Replica {        &self.guard    }}/// Hand over what is queued now, holding the file only while it is USED.////// [`push_only`] with [`run_cycle_paged`]'s discipline: the outbox batch is/// read under the mutex, the server is asked with the file in nobody's hands,/// and the answer is folded under the mutex again. **This is the form every/// schedule runs** — the loop's push-only pass, the re-hydrate's drain — because/// a screen's read shares that mutex, and until 2026-09-24 every write on the/// phone held it across its own push: a todo ticked while the Mac was asleep/// blocked every read behind a 60 s request ceiling/// (`transport::REQUEST_CEILING_MS`). The answer is [`push_only`]'s;/// `cycle_tests.rs` holds that the file is FREE while the transport is asked.pub fn push_only_paged(    replica: &Mutex<Replica>,    transport: &mut dyn crate::transport::SyncingTransport,    workspace_id: &str,    now: &str,) -> Result<usize, CycleFailure> {    ensure_listed(transport)?;    let mut handover = Handover::shut();    let handed = {        let replica = held(replica);        cotton_store::exchange::release_held_writes(&replica.driver, now)            .and_then(|_| exchange_request(&replica.driver, workspace_id, None, &mut handover))            .map_err(|error| classify(error.into(), &*transport))?    };    let response = match asked(&mut *transport, &handed.request) {        Ok(response) => response,        Err(message) => {            let replica = held(replica);            return Err(failed_in_the_air(&replica.driver, &handed, message, &*transport));        }    };    let replica = held(replica);    fold_answer(&replica.driver, &handed, &response, now, &mut handover)        .map(|exchanged| exchanged.report.total_sent())        .map_err(|error| classify(error, &*transport))}/// Hand over what is queued now — and take whatever comes back with it.////// Deliberately not a whole cycle. An import calls this after every batch, and/// a full import of this Mac is 3,421 batches: looping to exhaustion on each of/// them would be thousands of round trips asking for news that arrives, at/// most, once. ONE exchange, and the answer is folded because there is no way/// to send without receiving any more — which is the point of one verb.////// **For a caller that already holds the file** — the in-process ingest tests/// and the conformance drivers. A schedule sharing the replica with a screen/// takes [`push_only_paged`] instead.pub fn push_only(    db: &Driver,    transport: &mut dyn crate::transport::SyncingTransport,    workspace_id: &str,    now: &str,) -> Result<usize, CycleFailure> {    // A SHUT handover: this hands over the queue and nothing else. That is the    // point — an import's 3,421 batches must not each read this file's ceiling    // looking for what the server has not seen. The minute's cycle does that,    // once per pass.    ensure_listed(transport)?;    exchange_once(        db,        &mut Wrapped(&mut *transport),        workspace_id,        None,        now,        &mut Handover::shut(),    )    .map(|exchanged| exchanged.report.total_sent())    .map_err(|error| classify(error, &*transport))}/// How many ops are still queued — or `None` if the file has gone.////// A cycle can still be in the air when the person disconnects: the loop stops/// and the replica is closed straight after, so the flight that was already/// running finds a closed handle. That is a shutdown, not a failure, and a/// thrown "database is not open" out of a status update would surface as a sync/// error on a Mac that is simply signing out.////// UNSENT IS THE QUEUE AND THE HELD WRITES: a write made before this device/// had the Mac's time is applied here and kept out of the queue until judge/// time releases it, and a count of the queue alone said 0 while one waited.pub fn current_pending(db: &Driver) -> Option<i64> {    Some(pending_count(db).ok()? + current_held(db)?)}/// The writes this file holds for the Mac's time (`held = 1`), counted/// through the held indexes.pub fn current_held(db: &Driver) -> Option<i64> {    cotton_store::mint::clock::held_count(db).ok()}/// The store's `SyncTransport` takes `&mut impl SyncTransport`, and this module/// holds a `&mut dyn` so it can ask the same object for its last refusal/// afterwards. This is the one-line bridge between the two.struct Wrapped<'a>(&'a mut dyn crate::transport::SyncingTransport);impl SyncTransport for Wrapped<'_> {    fn exchange(        &mut self,        request: &cotton_store::protocol::types::ExchangeRequest,    ) -> Result<cotton_store::protocol::types::ExchangeResponse, String> {        asked(&mut *self.0, request)    }}/// THE ANSWER CHECK: ask the peer, and refuse an answer that came out of a/// different file than the one this request named.////// A device holding several databases sends each one's exchange down a/// transport bound to it, and a page that names another file is a misrouted/// answer — folding it would write one database's rows into another's/// replica. It is refused like a transport failure: nothing in it is taken,/// the handed-over writes stay queued, and the next pass asks again.fn asked(    transport: &mut dyn crate::transport::SyncingTransport,    request: &cotton_store::protocol::types::ExchangeRequest,) -> Result<cotton_store::protocol::types::ExchangeResponse, String> {    let response = transport.exchange(request)?;    if response.workspace_id != request.workspace_id {        return Err(format!(            "the answer came from database {}, not {} — nothing in it was taken",            response.workspace_id, request.workspace_id        ));    }    Ok(response)}#[cfg(test)]#[path = "cycle_tests.rs"]mod tests;#[cfg(test)]#[path = "cycle_many_tests.rs"]mod many_tests;#[cfg(test)]#[path = "slice_tests.rs"]mod slice_tests;