Cotton code
2007 lines · 90.6 KB · RustRaw
//! ONE SYMMETRIC VERB. Two files hand each other what the other has not seen.//!//! There is no push and no pull any more, and no server sequence to tail. A//! caller sends what it wrote and a map of how far it has seen each AUTHOR//! ([`crate::cursors`]); the responder folds those ops, answers with pages of//! [`crate::changes::changes_since`] for every author the caller is behind on,//! and says where the caller's cursors now sit. The caller folds THAT and//! advances its own `_cursors`. Both sides run [`crate::fold::fold_ops`] — one//! implementation of who wins, which is the whole reason the two halves live in//! one module of one crate rather than one in a server and one in a client//! ([one-implementation-of-who-wins-the-same-schema-and-conflict-rule]).//!//! **A PAGE IS A WHOLE NUMBER OF ROWS.** Every op of a row is emitted together//! and the cursor advances by the row's stamp, so a row never straddles a page//! and a peer never folds half of one. The budget is spent in rows across every//! author in one answer, so a page is bounded whatever the shape of the file.//!//! **BOTH SIDES HAND OVER, AND NEITHER FROM A QUEUE.** The `_outbox` is what//! this file wrote and has not pushed YET — it is not what the peer has not//! seen. A device that had already synced its rows to some other Mac has an//! EMPTY outbox and a full file, and on a join it would hand over nothing at//! all. So the answer carries the responder's own position per author//! ([`ExchangeResponse::seen`]), and the caller hands over//! [`crate::changes::changes_since`] pages for every author its file holds//! writes for that the peer is behind on — the same `ops` field, folded by the//! same fold, in the ordinary cycle rather than in a join-shaped second path.//! [`Handover`] is that state, and it lives for one pass.//!//! **A refused op is PARKED, and retried the moment its row is NAMED again.**//! The cursor has to advance past a rejection (or the page arrives for ever),//! so the op is kept whole in `_parked` ([`crate::rejected`]) and every//! page re-offers the parked ops of the rows it names ([`named_rows`]) —//! whatever the fold made of them, because a row whose CREATION was refused//! never has an applied op and would otherwise be parked for ever. That is what//! makes "a row whose ops split across two pages" a delay rather than a loss.//! The retry also reaches the parks whose foreign key names a row the page//! named, and repeats with what it landed until nothing more does: an answer//! is NOT causal across pages (one author's page before another's, a row//! written before version 8 at its last edit's stamp, unstamped rows by table//! name), so a child can arrive pages before its parent. A park nothing will//! name again is the cycle's bounded sweep ([`crate::rejected::sweep_parked`]).//!//! **What a merge is reported from.** [`ExchangeReport`] counts ROWS off the//! FOLD — `received` off this file's own `FoldResult::applied_rows`, `sent` off//! the PEER's `appliedRows` — and never off a row count before and after. One//! row arrives as several ops, so counting ops over-reports; and two devices//! that converged on the same derived id move the row count by zero while a row//! really did move.use std::collections::{BTreeMap, BTreeSet};use rusqlite::types::Value as SqlValue;use crate::changes::{changes_since_in, late_cursor_key, Lane};use crate::cursors::{    advance_cursor, cursor_ceiling, raised_by, read_cursors,};use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::fold::{fold_ops, fold_pulled_judged};use crate::stored::outbox_row;use crate::rejected::{    clear_delivered_pushes, park, requeue_touched_pushes, retry_touched_rows, Class, Direction,};use crate::protocol::types::{    CottonOp, ExchangeRequest, ExchangeResponse, PushRejection, EXCHANGE_PAGE_ROWS,    MAX_EXCHANGE_PAGE_ROWS, REJECTION_AUTHOR_WAITING, REJECTION_DEFERRED, REJECTION_FUTURE,};use crate::schema::ddl::SCHEMA_VERSION;/// A transport failure is not a store failure, and the two must not be one/// type: the transport's message is written to `_outbox.last_error` verbatim,/// and a caller backs off on it rather than treating the file as broken.#[derive(Debug, thiserror::Error)]pub enum SyncError {    /// Whatever the transport said. The string IS the message a caller sees.    #[error("{0}")]    Transport(String),    #[error(transparent)]    Store(#[from] StoreError),    /// The answer came from a Mac whose serving term is older than the one    /// this file has already heard of. Nothing of it was applied and the    /// outbox is as it was.    #[error(        "an old Mac is answering: this device has heard of serving epoch {held} and the answer \         is from {}", answered.map_or("a Mac with none".to_string(), |epoch| format!("epoch {epoch}"))    )]    OldServing { held: i64, answered: Option<i64> },    /// The answer came from a Dev server serving the owner's copy, which has    /// been restored afresh since this replica was made: `night` is the copy    /// it serves now. Nothing was applied; the replica is a copy of a file    /// that no longer exists, and a Dev phone fetches tonight's instead.    #[error("the owner's copy was restored again (night {night}): this copy is fetched afresh")]    CopyReplaced { night: String },}/// What a file says to a reader that folds schema `reader`.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Admission {    /// Served: every rise between the two stamps is additive.    Serve,    /// The reader is below the file's floor — a rise between them rebuilt a    /// table, so its build must update before they exchange (426).    ReaderBehind,    /// The reader is ahead of the file: the file's Mac is the one to update.    FileBehind,}/// THE FLOOR RULE — one implementation, read by the serving Mac's gate and by/// the op screen beside it. Two builds interoperate iff the NEWER side's floor/// ([`crate::schema::move_intents::floor_of`]) is at or below the OLDER side's/// stamp: every rise between them only added, so a receipt of the older shape/// folds into the newer file as it stands. Until 12 Oct 2026 only an equal/// stamp was served, so every phone behind a Mac cut stopped syncing until it/// updated, even across rises that only added a nullable column.////// A reader AHEAD of the file is the newer side, so its own floor/// (`reader_floor`, the `schemaFloor` it sends) is the one that must reach/// down to the file — and it is served only by a file that parks a receipt of/// a shape it cannot hold yet as `newer-shape` (`keeps_newer`,/// [`crate::rejected::keeps_newer_shape`]) rather than folding it. A reader/// that says no floor is refused, as every reader ahead was before.#[must_use]pub fn admission(file: u32, reader: u32, reader_floor: Option<u32>, keeps_newer: bool) -> Admission {    if reader > file {        if keeps_newer && reader_floor.is_some_and(|floor| floor <= file) {            Admission::Serve        } else {            Admission::FileBehind        }    } else if crate::schema::move_intents::floor_of(file) <= reader {        Admission::Serve    } else {        Admission::ReaderBehind    }}/// THE seam. One call, both directions.pub trait SyncTransport {    fn exchange(        &mut self,        request: &ExchangeRequest,    ) -> std::result::Result<ExchangeResponse, String>;    /// One call carrying a section per database    /// (`crate::protocol::types::ExchangeSectionsRequest`).    ///    /// The default asks [`Self::exchange`] once per section, which is right    /// for a transport that speaks for ONE file — a peer, the server in this    /// process, a fake — and is how a single-database pass stays one call. A    /// failure there fails the call, as it always did. A transport to a server    /// holding several files overrides this with the one request.    fn exchange_many(        &mut self,        request: &crate::protocol::types::ExchangeSectionsRequest,    ) -> std::result::Result<crate::protocol::types::ExchangeSectionsResponse, String> {        let mut sections = Vec::with_capacity(request.sections.len());        for section in &request.sections {            sections.push(crate::protocol::types::SectionAnswer::Answered(                self.exchange(section)?,            ));        }        Ok(crate::protocol::types::ExchangeSectionsResponse { sections })    }}// ---------------------------------------------------------------------------// The report// ---------------------------------------------------------------------------/// What an exchange moved, in ROWS per table.////// `received` is what THIS file applied; `sent` is what the PEER applied. Never/// before/after row counts, and never op counts — see the module header. Two/// pages of one cycle are summed per key, so the sentence a person reads is the/// whole pass and not its last page.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct ExchangeReport {    pub received: BTreeMap<String, usize>,    pub sent: BTreeMap<String, usize>,    /// CHANGES (receipts), not rows: how many the peer's answers moved this    /// file past, by table — what the peer said (`ExchangeResponse::passed`),    /// or from a peer that does not say, the receipts its pages carried. A    /// row arrives as several receipts and some receipts are never sent (a    /// phone's keep rules), so this — never `received` — is what a share of    /// "what was owed" is counted in.    pub passed: BTreeMap<String, usize>,    /// CHANGES (receipts) of this file's own outbox handed to the peer.    pub handed: usize,}impl ExchangeReport {    /// Add another page's counts to this one, per key.    pub fn absorb(&mut self, other: &ExchangeReport) {        for (table, rows) in &other.received {            *self.received.entry(table.clone()).or_default() += rows;        }        for (table, rows) in &other.sent {            *self.sent.entry(table.clone()).or_default() += rows;        }        for (table, receipts) in &other.passed {            *self.passed.entry(table.clone()).or_default() += receipts;        }        self.handed += other.handed;    }    /// Changes (receipts) the peer's answers moved this file past, over    /// every table.    #[must_use]    pub fn total_passed(&self) -> usize {        self.passed.values().sum()    }    /// Rows this file took in, over every table.    #[must_use]    pub fn total_received(&self) -> usize {        self.received.values().sum()    }    /// Rows the peer took in, over every table.    #[must_use]    pub fn total_sent(&self) -> usize {        self.sent.values().sum()    }    /// The tables a screen has to repaint — the keys of `received`, which is    /// the only bookkeeping there is. A table the fold did not touch is not a    /// key, so an empty report repaints nothing.    #[must_use]    pub fn tables(&self) -> Vec<String> {        self.received.keys().cloned().collect()    }}/// The `(table, row)` pairs a page NAMES, deduped, in the order they appear.////// Not the rows it applied. A page's parked-op retry is scoped by this/// ([`crate::rejected::retry_touched_rows`]) because a park is cleared by the/// ARRIVAL of the rest of a row, and an arrival that the fold itself refused/// is still an arrival: the creation of a row whose parent was missing is/// refused, parked, and the only event that can ever fold it is a later op for/// that same row — which, being an op the fold also refuses while the creation/// is parked, would never have counted as "applied".#[must_use]pub fn named_rows(ops: &[CottonOp]) -> Vec<(String, String)> {    let mut seen: BTreeSet<(String, String)> = BTreeSet::new();    let mut out: Vec<(String, String)> = Vec::new();    for op in ops {        let row = (op.table.clone(), op.row_id.clone());        if seen.insert(row.clone()) {            out.push(row);        }    }    out}/// Tally a fold's applied ROWS per table./// The ISO instant a stamp was written at — the only time a clockless fold/// has for a receipt.fn stamp_time(hlc: &str) -> String {    crate::protocol::hlc::hlc_parts(hlc)        .ok()        .and_then(|parts| crate::protocol::js::to_iso_string(parts.ms))        .unwrap_or_default()}/// The receipts an answer moved this file past, by table: the peer's own/// count, or from a peer that does not count, the receipts the page carried.fn passed(response: &ExchangeResponse) -> BTreeMap<String, usize> {    match &response.passed {        Some(passed) => passed            .iter()            .map(|(table, receipts)| (table.clone(), usize::try_from(*receipts).unwrap_or(usize::MAX)))            .collect(),        None => {            let mut carried: BTreeMap<String, usize> = BTreeMap::new();            for op in &response.ops {                *carried.entry(op.table.clone()).or_default() += 1;            }            carried        }    }}fn tally(applied_rows: &[(String, String)]) -> BTreeMap<String, usize> {    let mut out: BTreeMap<String, usize> = BTreeMap::new();    for (table, _row_id) in applied_rows {        *out.entry(table.clone()).or_default() += 1;    }    out}// ---------------------------------------------------------------------------// The responder half// ---------------------------------------------------------------------------/// What one side answers a caller's cursor map with.#[derive(Debug, Clone, PartialEq, Default)]pub struct Answered {    pub ops: Vec<CottonOp>,    /// The caller's map, advanced by exactly what `ops` carries.    pub cursors: BTreeMap<String, String>,    pub has_more: bool,    /// How far THIS file has seen each author ([`crate::cursors::seen_ceiling`])    /// — what the caller hands over from.    pub seen: BTreeMap<String, String>,    /// How many receipts this page was dealt, by table — what `cursors` moved    /// the caller past, counted before anything is left out of `ops`    /// (`ExchangeResponse::passed`).    pub passed: BTreeMap<String, u64>,}/// Everything in THIS file that `seen` has not seen, at most `limit_rows` rows.////// The authors are taken from [`cursor_ceiling`] — read from the FILE, so an/// author nobody has a cursor for is still answered for, and an author whose/// ceiling the caller already holds costs one string comparison and no query./// They are visited in name order, so a caller that keeps asking walks the same/// authors in the same order and cannot starve one.////// The answered cursors are the page's own resume points, NOT the ceiling: with/// `has_more` true the ceiling would skip everything between this page and it./// When `has_more` is false they are the same thing.pub fn answer(    db: &Driver,    seen: &BTreeMap<String, String>,    limit_rows: usize,) -> Result<Answered> {    answer_excluding(db, seen, limit_rows, &Handled::default())}/// What one page may carry in receipt bytes, and whether its first row/// travels whatever it costs.////// `first_goes_whole` is what keeps a single row wider than the budget from/// stalling a caller for ever: the first row of an otherwise empty ANSWER goes/// regardless. A page that is not the first thing in its answer — the second/// database of an exchange over all of them — has no such licence: a row that/// does not fit waits for the next exchange, and the page says `has_more`.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct PageBudget {    pub bytes: usize,    pub first_goes_whole: bool,}impl PageBudget {    /// One database's page on its own: [`PAGE_BYTES`], first row whole.    pub const PAGE: PageBudget = PageBudget { bytes: PAGE_BYTES, first_goes_whole: true };}/// THE WHOLE ANSWER OF AN EXCHANGE OVER EVERY DATABASE is bounded, not only/// each database's page in it (14 Oct 2026: a serving Mac's schema move minted/// ~28k receipts across the owner's databases; each section stayed inside/// [`PAGE_BYTES`] and their sum outgrew the phone's 32 MB answer ceiling on/// every exchange, so the phone discarded every answer and never moved). The/// sections share this budget in the order they were asked, each still at most/// [`PAGE_BYTES`]; whatever does not fit is `has_more`.pub const EXCHANGE_ANSWER_BYTES: usize = 8 * 1024 * 1024;/// The receipt bytes a page carries on the wire — what a budget is spent in.#[must_use]pub fn page_bytes(ops: &[CottonOp]) -> usize {    ops.iter().map(wire_bytes).sum()}/// The (table, row, stamp) triples a caller handed over in the same breath.pub type Handled = BTreeSet<(String, String, String)>;/// What [`answer_excluding`] takes: the triples of a batch of ops.#[must_use]pub fn handled(ops: &[CottonOp]) -> Handled {    ops.iter()        .map(|op| (op.table.clone(), op.row_id.clone(), op.hlc.clone()))        .collect()}/// THE PAGE IS BOUNDED IN BYTES as well as in rows. A row travels whole, and/// a few tables hold rows of tens of kilobytes, so five hundred of them were/// tens of megabytes: through the relay to a phone at about 1.5 MB/s that is/// most of the request's sixty-second ceiling before the phone has read a/// byte of the fold (13 Oct 2026). A page stops dealing once it carries this/// much; `has_more` carries the rest. At 1.5 MB/s it is under three seconds,/// and a phone on a poor link at 300 KB/s still reads it in fifteen.pub const PAGE_BYTES: usize = 4 * 1024 * 1024;/// The most rows one author is dealt in one turn of a round.const ROWS_PER_TURN: usize = 50;/// A page's first turn, before it knows how wide its rows are.const FIRST_TURN_ROWS: usize = 4;/// How many rows the next turn may take: what is left of [`PAGE_BYTES`] at/// the page's average row so far, so a page overshoots its budget by about/// one row rather than by a turn of wide ones.fn turn_rows(share: usize, dealt: usize, bytes: usize, budget: usize) -> usize {    let room = if dealt == 0 {        FIRST_TURN_ROWS    } else {        let average = (bytes / dealt).max(1);        budget.saturating_sub(bytes).div_ceil(average)    };    share.min(room).clamp(1, ROWS_PER_TURN)}/// The bytes one op adds to a page, as it travels.fn wire_bytes(op: &CottonOp) -> usize {    serde_json::to_vec(op).map_or(0, |bytes| bytes.len())}/// Deal one [`Lane`] of every author still behind into the page, and answer/// who is still behind on it.////// EVERY AUTHOR THE CALLER IS BEHIND ON GETS A SHARE OF EVERY PAGE.////// The authors are walked by name, and a page that went to the first of/// them until it was drained starved the rest: a phone pulling from empty/// cursors (§C3) spent every page for the better part of a day on the Mac's/// own archive — audit rows, the imported life — while six meetings the/// server had transcribed sat under `server:meetings`, an author whose turn/// was three hundred thousand rows away. The writes a person is waiting for/// are nearly always the small, recent streams, and name order put them/// last.////// So a page is dealt in rounds: each author still behind gets an equal/// share of what is left, a drained author leaves the round, and the room/// it did not use goes round again. A stream of six rows lands on the first/// page whatever else is owed; the big one still takes everything nobody/// else needs. The share is at least one ROW, and `changes_since` answers/// whole rows, so every round either drains an author or spends budget —/// the loop cannot spin.////// A lane with nothing more past where the page stopped is moved to the/// author's TOP: the other lane's receipts below it are the other lane's to/// send, and a cursor left short would walk past them again on every page.////// THE ONE DEALER (architect, 13 Oct 2026: a bound that applies to one path/// is no bound). Every page of receipts one side sends the other — an/// exchange answer of any database, a first pull, a catch-up, and a device's/// own hand-over ([`Handover::take`]) — is dealt here, and the [`Room`] it is/// dealt into carries the ceilings: rows, [`PAGE_BYTES`], and the ops a/// responder takes. One act's receipts alone are cut inside their stamp/// (`changes::inside_stamp`), so no act outgrows a page. `moved` is told/// where each author's lane now stands.////// WHAT THE ASKER DOES NOT KEEP NEVER SPENDS THE PAGE. `keep` is asked of/// each turn's receipts before they are weighed, so only what travels costs/// bytes; a phone whose rules leave mail out once got pages of nothing but/// budget spent on mail, 95 KB a pass for no row (16 Oct 2026). Every receipt/// read still counts as read — rows, `room.passed`, the cursors — because the/// caller is moved past it.fn deal(    db: &Driver,    mut behind: Vec<(String, String, String)>,    lane: Option<Lane>,    room: &mut Room,    out: &mut Vec<CottonOp>,    moved: &mut dyn FnMut(&str, String),    keep: &mut dyn FnMut(Vec<CottonOp>) -> Result<Vec<CottonOp>>,) -> Result<Vec<(String, String, String)>> {    let mut dealt = 0usize;    while room.rows > 0 && room.bytes < room.budget && !room.full && !behind.is_empty() {        let share = (room.rows / behind.len()).clamp(1, ROWS_PER_TURN);        let mut still: Vec<(String, String, String)> = Vec::with_capacity(behind.len());        for (author, since, top) in behind {            if room.rows == 0 || room.bytes >= room.budget || room.full {                still.push((author, since, top));                continue;            }            // A TURN THAT WOULD OVERRUN THE BUDGET IS TAKEN SMALLER, down to            // one row, and a row that still does not fit waits for the next            // page: the budget is a ceiling, not an aim. Only the first row of            // an empty answer goes whatever it costs (`PageBudget`).            let mut take = turn_rows(share.min(room.rows), dealt, room.bytes, room.budget);            let (page, kept, cost) = loop {                let page = changes_since_in(db, &author, &since, take, lane)?;                let kept = keep(page.ops.clone())?;                let cost = page_bytes(&kept);                if room.bytes + cost <= room.budget || take == 1 {                    break (page, kept, cost);                }                take = (take / 2).max(1);            };            if room.bytes + cost > room.budget && !(room.first_goes_whole && out.is_empty()) {                room.full = true;                still.push((author, since, top));                continue;            }            // The responder's own cap on ops: an author whose page will not            // fit waits for the next call rather than costing everybody a            // refused body. The first page goes whatever it costs.            if room.ops.is_some_and(|ops| !out.is_empty() && out.len() + kept.len() > ops) {                room.full = true;                still.push((author, since, top));                continue;            }            room.rows = room.rows.saturating_sub(page.rows);            dealt += page.rows;            room.bytes += cost;            for op in &page.ops {                *room.passed.entry(op.table.clone()).or_default() += 1;            }            out.extend(kept);            if page.has_more && page.rows > 0 {                if let Some(next) = page.next_hlc {                    moved(&author, next.clone());                    still.push((author, next, top));                }            } else {                // Drained: nothing of this lane past where it stopped, so                // the lane stands at the author's top.                let at = match page.next_hlc {                    Some(next) if next > top => next,                    _ => top,                };                moved(&author, at);            }        }        behind = still;    }    Ok(behind)}/// What a page is dealt into ([`deal`]): the rows still to spend, the bytes/// already dealt, and — for a hand-over the responder caps — the most ops.struct Room {    rows: usize,    bytes: usize,    /// The most bytes the page may carry ([`PageBudget::bytes`]).    budget: usize,    /// Whether the page's first row goes whatever it costs.    first_goes_whole: bool,    ops: Option<usize>,    full: bool,    /// Every receipt dealt, by table, kept or left out.    passed: BTreeMap<String, u64>,}impl Room {    fn rows(rows: usize, budget: PageBudget) -> Room {        Room {            rows: rows.max(1),            bytes: 0,            budget: budget.bytes,            first_goes_whole: budget.first_goes_whole,            ops: None,            full: false,            passed: BTreeMap::new(),        }    }}/// [`answer`], minus the writes the caller handed over in the SAME call.////// The responder folds a caller's ops before it builds the answer, so every row/// that just arrived is now in this file at a stamp above the caller's own/// cursor — and would be answered straight back to the device that wrote it./// One round trip's worth of that was the old push's echo and nobody noticed;/// a join hands over a whole life, and receiving it back doubles the wire and/// the fold for no possible gain.////// The match is the WHOLE triple and never `(table, row)`: a peer may hold a/// NEWER write of the same row than the one the caller just sent, and dropping/// that would lose it. An identical stamp is an identical write.////// The cursors still advance past what was dropped, which is honest: the caller/// has those rows — it sent them.pub fn answer_excluding(    db: &Driver,    seen: &BTreeMap<String, String>,    limit_rows: usize,    already: &Handled,) -> Result<Answered> {    answer_within(db, seen, limit_rows, already, PageBudget::PAGE)}/// [`answer_excluding`] inside a byte budget the caller sets — the exchange/// over every database spends one [`EXCHANGE_ANSWER_BYTES`] across its/// sections. A budget with nothing left deals nothing and says `has_more`/// for every author still behind, so the caller's cursors stay where they are.pub fn answer_within(    db: &Driver,    seen: &BTreeMap<String, String>,    limit_rows: usize,    already: &Handled,    budget: PageBudget,) -> Result<Answered> {    answer_keeping(db, seen, limit_rows, already, budget, &mut Ok)}/// [`answer_within`] for an asker that keeps less than everything: `keep`/// takes out what it does not keep AS THE PAGE IS DEALT ([`deal`]), so a/// left-out receipt moves the cursors and the `passed` count and spends none/// of the page.pub fn answer_keeping(    db: &Driver,    seen: &BTreeMap<String, String>,    limit_rows: usize,    already: &Handled,    budget: PageBudget,    keep: &mut dyn FnMut(Vec<CottonOp>) -> Result<Vec<CottonOp>>,) -> Result<Answered> {    let mut room = Room::rows(limit_rows, budget);    let mut answered = Answered::default();    let ceiling = cursor_ceiling(db)?;    answered.seen = raised_by(ceiling.clone(), read_cursors(db)?);    // TWO LANES PER AUTHOR (`changes::LATE_TABLES`): everything but mail    // first, mail after, each resumed from its own cursor. A reader that has    // never been told of the late lane resumes it where its author cursor    // stands — the position it asked from covers every table — and that    // position is written down as the late lane's own the first time this    // answer moves the author's cursor, so moving the first lane never moves    // the mail lane with it.    let late_since = |author: &str| -> String {        seen.get(&late_cursor_key(author))            .or_else(|| seen.get(author))            .cloned()            .unwrap_or_default()    };    // Every author the caller is behind on, with where to resume each from.    // A string comparison, and it is exact: a cursor and a ceiling are the same    // kind of token for the same author, stamps for a device and    // `origin:<table>:<row>` for the unstamped rows.    let first: Vec<(String, String, String)> = ceiling        .iter()        .filter_map(|(author, top)| {            let since = seen.get(author).map_or("", String::as_str);            crate::changes::is_behind(top, since).then(|| (author.clone(), since.to_string(), top.clone()))        })        .collect();    for (author, since, _) in &first {        let key = late_cursor_key(author);        if !seen.contains_key(&key) && !since.is_empty() {            answered.cursors.insert(key, since.clone());        }    }    let late: Vec<(String, String, String)> = ceiling        .iter()        .filter_map(|(author, top)| {            let since = late_since(author);            crate::changes::is_behind(top, &since).then(|| (author.clone(), since, top.clone()))        })        .collect();    // The first lanes, then — only once every first lane is drained — the mail.    let mut ops = Vec::new();    let mut cursors: Vec<(String, String)> = Vec::new();    let first_left = deal(        db,        first,        Some(Lane::First),        &mut room,        &mut ops,        &mut |author, at| cursors.push((author.to_string(), at)),        keep,    )?;    let late_left = if first_left.is_empty() {        deal(            db,            late,            Some(Lane::Late),            &mut room,            &mut ops,            &mut |author, at| cursors.push((late_cursor_key(author), at)),            keep,        )?    } else {        late    };    answered.ops.extend(ops);    answered.cursors.extend(cursors);    // Somebody is still behind and this page has no room left for them.    answered.has_more = !first_left.is_empty() || !late_left.is_empty();    // WHAT THE PAGE MOVED THE CALLER PAST, counted as it was dealt: every    // receipt, before the caller's build, its keep rules or its own echo take    // any out of `ops`. The cursors move past all of them, and so does a    // percent of what was owed.    answered.passed = room.passed;    // STAMP ORDER ACROSS THE WHOLE PAGE, not just inside one author's stream.    //    // A row's oldest op is the one that carries the whole row (`changes::row_ops`),    // and the authors are visited by NAME, so a second author's amendment to a    // column can otherwise precede the op that creates the row. A bare    // amendment folded into a file that has never seen that row is an INSERT of    // two columns, refused by the first NOT NULL it meets. Sorting by stamp is    // also just causal order, which is the order the fold would have seen had    // the writes arrived as they happened.    answered.ops.sort_by(|left, right| left.hlc.cmp(&right.hlc));    if !already.is_empty() {        answered.ops.retain(|op| {            !already.contains(&(op.table.clone(), op.row_id.clone(), op.hlc.clone()))        });    }    Ok(answered)}/// Fold what a caller sent, and say what LANDED in rows per table.////// The responder's half of the report. `rejected` is per op and final: one bad/// op must never cost its neighbours their write.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct Folded {    pub applied_rows: BTreeMap<String, usize>,    /// The same rows, NAMED — `(table, row_id)`, deduped, in the order they    /// first changed.    ///    /// `applied_rows` is this tallied per table, which is what the wire wants    /// and is not enough for the one caller that has to act on WHICH rows    /// moved: the responder's parked-op retry    /// ([`crate::rejected::retry_touched_rows`]) is scoped by exactly these    /// pairs, and a count cannot name a row.    pub applied_pairs: Vec<(String, String)>,    pub rejected: Vec<PushRejection>,    /// The ops the fold decided a NEWER write already answered.    ///    /// For a DEVICE exchange this is ordinary traffic — losing to a newer write    /// is what two replicas disagreeing looks like. For a SERVER write it is a    /// bug in the write clock: there is no second writer to lose to, and    /// swallowing it would drop a write and report success. So it is CARRIED    /// and each caller decides.    pub skipped_stale: Vec<String>,    /// The receipts this fold parked `waiting` for their author's fact, or    /// `newer-shape` above this file's schema, as held    /// [`REJECTION_AUTHOR_WAITING`] refusals — told only to a caller    /// that parks them ([`ExchangeRequest::parks_waiting`]), so it stops    /// offering them on every pass (16 Oct 2026: 95 KB a pass, no row).    pub waiting: Vec<PushRejection>,}/// Fold a peer's ops into this file, in one transaction.////// A receipt minted above this file's schema is parked `newer-shape` before/// the fold and is NOT a rejection: the pusher's build is simply ahead, and/// this file folds it once it moves ([`crate::rejected::park_newer_shape`])./// In a file that cannot park that class it is held, retryable and coded/// `server_behind`, and stays queued on its device.pub fn fold_incoming(db: &Driver, ops: &[CottonOp]) -> Result<Folded> {    let parkable = crate::rejected::keeps_newer_shape(db)?;    let stamp = crate::meta::file_schema_version(db)?;    let mut held: Vec<PushRejection> = Vec::new();    // WHAT THIS FILE PARKED newer-shape is told to a pusher that parks    // (`waiting`, below), not refused: the Mac holds the receipt and folds it    // once it moves, and its `seen` never names a parked receipt — so a    // pusher not told hands the same page over on every pass, for as long as    // the Mac is behind it (20 Oct 2026: 980 facts a minute from one Mac    // client, folded and parked again each time, 8 s inside the file).    let mut newer_shape: Vec<PushRejection> = Vec::new();    let ops: Vec<CottonOp> = if parkable {        let rest = crate::rejected::park_newer_shape(db, ops, |op| stamp_time(&op.hlc))?;        let kept: std::collections::BTreeSet<&str> = rest.iter().map(|op| op.op_id.as_str()).collect();        for op in ops.iter().filter(|op| !kept.contains(op.op_id.as_str())) {            newer_shape.push(PushRejection::held(                op.op_id.clone(),                crate::rejected::newer_shape_reason(op.schema_version, stamp),                REJECTION_AUTHOR_WAITING,            ));        }        rest    } else {        ops.iter()            .filter(|op| {                let ahead = op.schema_version > stamp;                if ahead {                    held.push(PushRejection::held(                        op.op_id.clone(),                        format!(                            "this change is stamped schema {} and this Mac's file is at {stamp}; it is \                             kept on your device and lands once this Mac is updated",                            op.schema_version                        ),                        crate::protocol::types::REJECTION_SERVER_BEHIND,                    ));                }                !ahead            })            .cloned()            .collect()    };    let ops = ops.as_slice();    let result = fold_ops(db, ops)?;    // A receipt whose author has no fact here is parked whole, waiting, and    // is NOT a rejection the pusher hears about: the pusher did nothing    // wrong, and the fact that frees it is on its way. `at` is the receipt's    // own time — this half of the exchange carries no clock (spec R7), and    // how long a write has waited is counted from when it was written.    let mut waiting: Vec<PushRejection> = newer_shape;    for held in &result.waiting {        if let Some(op) = ops.iter().find(|op| op.op_id == held.op_id) {            waiting.push(PushRejection::held(                op.op_id.clone(),                crate::rejected::waiting_reason(&held.author),                REJECTION_AUTHOR_WAITING,            ));            let at = stamp_time(&op.hlc);            // `Pull`: in `_parked` that is "a write that exists on the            // OTHER side and this file has not taken", which is what a held            // receipt is whichever way it arrived; `Push` would read as this            // file's own write for the peer to take again.            park(db, op, Direction::Pull, Class::Waiting, &crate::rejected::waiting_reason(&held.author), &at)?;        }    }    // And what the fold parked itself, waiting for the serving fact that lets    // its author write for another device: the same wait, freed the same way    // (`retry_waiting_for`).    for parked in &result.parked {        if parked.reason.starts_with(crate::rejected::WAITING_FOR_SERVING) {            waiting.push(PushRejection::held(parked.op_id.clone(), parked.reason.clone(), REJECTION_AUTHOR_WAITING));        }    }    for author in &result.announced {        let at = ops            .iter()            .find(|op| op.table == crate::fold::AUTHORS_TABLE && op.row_id == *author)            .map(|op| stamp_time(&op.hlc))            .unwrap_or_default();        crate::rejected::retry_waiting_for(db, author, &at)?;    }    Ok(Folded {        applied_rows: tally(&result.applied_rows),        applied_pairs: result.applied_rows.clone(),        rejected: held            .into_iter()            .chain(                result                    .rejected                    .iter()                    .map(|rejection| PushRejection::final_reason(&rejection.op_id, &rejection.reason)),            )            .collect(),        skipped_stale: result.skipped_stale.clone(),        waiting,    })}// ---------------------------------------------------------------------------// The caller half// ---------------------------------------------------------------------------// ---------------------------------------------------------------------------// The handover: everything the peer has not seen// ---------------------------------------------------------------------------/// How many ROWS of catch-up one exchange carries.////// Smaller than the answer's page (500) on purpose: the catch-up rides ALONGSIDE/// the outbox in the same body, and a request is capped at/// [`EXCHANGE_OPS_BATCH`] ops. A row is one op in the ordinary case and several/// when its columns came from several writes, so 200 rows leaves room for a/// full drain beside it and for a file whose rows are unusually split.pub const HANDOVER_PAGE_ROWS: usize = 200;/// What this file must hand over because the peer's own cursors say it has not/// seen it — the state of ONE pass.////// **Why this exists.** An exchange is caller-driven and the caller's queue is/// its `_outbox`: what it wrote and has not pushed yet. That is not the same/// set as "what the peer has not seen". A device that had already synced its/// rows to another Mac has an empty outbox and a full file, so on a join it/// would hand over NOTHING — the known limit this type closes.////// **The rule.** For every author this file holds writes for/// ([`cursor_ceiling`], `origin` included), the peer's position is what its/// answer said ([`ExchangeResponse::seen`]) — and an author it does not mention/// is an author it has never heard of, so from ZERO. Everything after that/// position goes as the `ops` of the next exchange, page by page, until no/// author is behind.////// **It is the ordinary cycle that does this**, not a join-shaped second path:/// the pass drains the outbox and hands over the rest in the same call, and on/// a device that is behind on nothing the catch-up is empty and costs one/// string comparison per author.////// One pass owns one of these. Its positions are advanced as pages are BUILT,/// so a pass never hands the same row over twice; they are re-read from the/// peer at the start of the next pass, which is where a row the peer HELD/// gets another chance. A row it refused as final is parked, and from then/// on travels only as a park ([`crate::rejected::travels_only_as_park`]) — as/// does a receipt this file holds and parked as a pull.#[derive(Debug, Default)]pub struct Handover {    /// Where the PEER is, per author, as far as this pass knows.    peer: BTreeMap<String, String>,    /// What THIS file holds, per author. Read once per pass: the rows arriving    /// during the pass came FROM the peer, so raising it by them would only    /// offer them straight back.    ours: Option<BTreeMap<String, String>>,    /// Never hand anything over, whatever the peer says.    shut: bool,    /// THE EPOCH THIS PASS HANDS OVER TO (slice 12), once an answer named a    /// serving epoch above this file's `_meta.handed_over_epoch`. Inside such    /// a pass the peer's positions start at the restore point and move only    /// as pages are built — never up to a later answer's `seen`.    handing_over_to: Option<i64>,    /// What such a pass carries of `_parked` and has not sent yet    /// ([`crate::rejected::parked_for_handover`]), in stamp order: each goes    /// once, at its stamp in its author's stream.    parked: Vec<CottonOp>,}impl Handover {    /// A handover that never opens — for a caller that is DRAINING and nothing    /// else.    ///    /// Not the same thing as a fresh one that has learnt nothing yet. Reading    /// this file's ceiling is a `GROUP BY` per replicated table, and an import    /// calls [`crate::exchange::exchange_once`] once per batch — 3,421 times for    /// this Mac's messages. A pass pays that once; a drain must not pay it at    /// all, and the minute's cycle hands over whatever the drain did not.    #[must_use]    pub fn shut() -> Handover {        Handover {            shut: true,            ..Handover::default()        }    }    /// Read the peer's position off an answer.    ///    /// An answer naming a serving epoch above this file's    /// `_meta.handed_over_epoch` starts a HAND-OVER PASS to it (slice 12):    /// each author starts at `min(restored, seen)`, an author absent from    /// `restored` at nothing, and an answer with no `restored` (an epoch with    /// no restore point) at `seen`. From then on the pass's positions move    /// only as pages are built: `seen` rises with every receipt the new Mac    /// folds, and raising to it would skip what the old Mac applied and its    /// backup lacked.    pub fn learn(&mut self, db: &Driver, response: &ExchangeResponse) -> Result<()> {        if self.shut {            return Ok(());        }        if let Some(epoch) = response.serving_epoch {            if self.handing_over_to != Some(epoch)                && handed_over_epoch(db)?.is_none_or(|mark| mark < epoch)            {                self.peer = start_positions(response);                self.ours = Some(cursor_ceiling(db)?);                self.handing_over_to = Some(epoch);                self.parked = crate::rejected::parked_for_handover(db, &self.peer, epoch)?;                return Ok(());            }        }        if self.handing_over_to.is_none() {            for (author, at) in &response.seen {                self.raise(author, at);            }        }        if self.ours.is_none() {            self.ours = Some(cursor_ceiling(db)?);        }        Ok(())    }    /// The epoch this pass is handing over to, once an answer started one.    #[must_use]    pub fn handing_over_to(&self) -> Option<i64> {        self.handing_over_to    }    /// Forwards only: two answers in one pass can name the same author, and the    /// later one is not always the larger.    fn raise(&mut self, author: &str, at: &str) {        let entry = self.peer.entry(author.to_string()).or_default();        if at > entry.as_str() {            *entry = at.to_string();        }    }    /// The authors this file holds writes for that the peer is behind on, with    /// the position to resume each from.    fn behind(&self) -> Vec<(String, String, String)> {        let Some(ours) = self.ours.as_ref() else {            return Vec::new();        };        ours.iter()            .filter_map(|(author, top)| {                let since = self.peer.get(author).map_or("", String::as_str);                crate::changes::is_behind(top, since).then(|| {                    (author.clone(), since.to_string(), top.clone())                })            })            .collect()    }    /// Is there anything left to hand over?    #[must_use]    pub fn outstanding(&self) -> bool {        !self.behind().is_empty() || !self.parked.is_empty()    }    /// The next page of what the peer has not seen: at most `rows` ROWS and,    /// beyond the first author, at most `ops_room` ops.    ///    /// Authors are walked in name order — the same order the answer walks them    /// — so a pass that keeps asking cannot starve one.    pub fn take(&mut self, db: &Driver, rows: usize, ops_room: usize, bytes: usize) -> Result<Vec<CottonOp>> {        // DEALT BY THE ONE DEALER ([`deal`]), in rounds and inside the same        // ceilings as an answer — rows, bytes, and the responder's cap on ops.        let mut out: Vec<CottonOp> = Vec::new();        let mut room = Room {            rows: rows.max(1),            bytes,            budget: PAGE_BYTES,            // The queue already in the page spent the first-row licence.            first_goes_whole: bytes == 0,            ops: Some(ops_room),            full: false,            passed: BTreeMap::new(),        };        let mut raised: Vec<(String, String)> = Vec::new();        deal(            db,            self.behind(),            None,            &mut room,            &mut out,            &mut |author, at| raised.push((author.to_string(), at)),            &mut Ok,        )?;        for (author, at) in raised {            self.raise(&author, &at);        }        // NOT A PARK: a parked push (refused by the peer as final) or a held        // receipt parked as a pull travels only as a park — requeued at most        // `PUSH_RETRY_CEILING` times, or offered by a hand-over pass at most        // `HANDOVER_OFFER_CEILING` times per epoch. The stream re-sent it on        // every pass that started below it, for ever, and a pull beside its        // park. The position still moves past it: the park list carries it.        let mut kept = Vec::with_capacity(out.len());        for op in out {            if !crate::rejected::travels_only_as_park(db, &op.op_id)? {                kept.push(op);            }        }        let mut out = kept;        // THE PARKS A HAND-OVER PASS CARRIES, at their stamps: one goes once        // its author's stream has passed its stamp here, or that author has        // nothing left behind; within the page's room, the first whatever it        // costs. One the stream already put in this page went with it.        if !self.parked.is_empty() {            let positions: BTreeMap<String, String> =                self.behind().into_iter().map(|(author, since, _)| (author, since)).collect();            let mut left: Vec<CottonOp> = Vec::new();            for op in std::mem::take(&mut self.parked) {                let due = positions                    .get(&op.device_id)                    .is_none_or(|since| op.hlc.as_str() <= since.as_str());                if !due || (!out.is_empty() && out.len() >= ops_room) {                    left.push(op);                } else if !out.iter().any(|sent| sent.op_id == op.op_id) {                    out.push(op);                }            }            self.parked = left;        }        // Stamp order across the whole page, for `answer`'s own reason: the op        // that carries the whole row is its oldest, and a bare amendment        // arriving first is an INSERT of two columns.        out.sort_by(|left, right| left.hlc.cmp(&right.hlc));        Ok(out)    }}/// Where a hand-over pass starts the peer, per author: `min(restored, seen)`,/// an author absent from `restored` from nothing (absent from the map, which/// [`Handover::behind`] reads as `""`), and with no `restored` at all, `seen`.fn start_positions(response: &ExchangeResponse) -> BTreeMap<String, String> {    let Some(restored) = &response.restored else {        return response.seen.clone();    };    restored        .iter()        .map(|(author, at)| {            let seen = response.seen.get(author).map_or("", String::as_str);            (author.clone(), at.as_str().min(seen).to_string())        })        .collect()}/// This file's `_meta.handed_over_epoch`: the last serving epoch it handed/// over to, `None` when it never has.pub fn handed_over_epoch(db: &Driver) -> Result<Option<i64>> {    Ok(db        .get("SELECT handed_over_epoch FROM _meta", &[])?        .and_then(|row| row.int("handed_over_epoch")))}/// One exchange's outgoing half: the request, and where its two kinds of op/// part company.#[derive(Debug, Clone, PartialEq)]pub struct Handed {    pub request: ExchangeRequest,    /// The op ids of `request.ops` that came off the `_outbox`. The rest are    /// the catch-up, and the split is load-bearing: only the outbox half is a    /// QUEUE a response settles. By id, never by position: the page is sorted    /// into stamp order across both halves, so a catch-up op can sort before a    /// queued one.    pub queued: BTreeSet<String>,}impl Handed {    /// Nothing was sent — what a caller folding an answer it did not ask for    /// passes.    #[must_use]    pub fn nothing(workspace_id: &str) -> Handed {        Handed {            request: ExchangeRequest {                workspace_id: workspace_id.to_string(),                cursors: BTreeMap::new(),                ops: Vec::new(),                limit: None,                schema_version: Some(crate::schema::ddl::SCHEMA_VERSION),                schema_floor: Some(crate::schema::move_intents::floor()),                handed_over_epoch: None,                handing_over_to: None,                serving_author: None,                takes_copy: false,                parks_waiting: false,            },            queued: BTreeSet::new(),        }    }    /// The queued writes this call carried.    #[must_use]    pub fn outbox_ops(&self) -> Vec<&CottonOp> {        self.request.ops.iter().filter(|op| self.queued.contains(&op.op_id)).collect()    }    /// The catch-up rows this call carried — held here already, never queued.    #[must_use]    pub fn handed_over(&self) -> Vec<&CottonOp> {        self.request.ops.iter().filter(|op| !self.queued.contains(&op.op_id)).collect()    }}/// How many of this file's own ops one exchange carries.////// The responder refuses more than `MAX_OPS_PER_EXCHANGE` (1,000), and an/// import of 32k messages is the first workload that ever reaches the ceiling.pub const EXCHANGE_OPS_BATCH: i64 = 1_000;/// What one exchange did to this file.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct Exchanged {    pub report: ExchangeReport,    /// The PEER has more to hand over.    pub peer_has_more: bool,    /// Ops still queued here after this call — a drain that filled its batch.    pub pending: i64,    /// Whether another exchange now would move anything: either half.    pub has_more: bool,    /// Writes the peer HELD rather than took, per reason word    /// (`PushRejection::code`; a hold with no word counts under `""`). A    /// screen reads which side is behind off the key, never off a sentence.    pub held: BTreeMap<String, usize>,    /// The schema the peer's file is at, when it said. Above this build's    /// `SCHEMA_VERSION` means THIS device is the one to update — and it was    /// still served: whatever this fold could not read is parked, not lost.    pub peer_schema: Option<u32>,    /// How many changes the peer says this file is still behind after this    /// answer (`ExchangeResponse::behind_by`, counted up to 10,000); `None`    /// from a peer that does not count.    pub remaining: Option<u64>,    /// What this file owed the peer when its catch-up began, counted in full    /// once by the peer outside its write hold (`ExchangeResponse::    /// owed_at_start`): what a catch-up's percent is a share of. `None`    /// while level, before the peer's count has finished, or from a peer    /// that does not keep it.    pub owed_at_start: Option<u64>,    /// The same whole by table (`ExchangeResponse::owed_by_table`), once the    /// peer has counted it.    pub owed_by_table: Option<BTreeMap<String, u64>>,    /// Why the serving Mac could not wake this device last time it tried    /// (`ExchangeResponse::wake_refusal`), as the peer said it.    pub wake_refusal: Option<String>,    /// The serving Mac's offer of the whole file    /// (`ExchangeResponse::copy`), as it made it.    pub copy: Option<crate::protocol::types::CopyOffer>,    /// Which Mac answered (`ExchangeResponse::answered_by`), as it named    /// itself.    pub answered_by: Option<crate::protocol::types::AnsweredBy>,}/// THE WHOLE FILE IS FASTER (sync programme lane C, 12 Oct 2026): the serving/// Mac's offer to a caller that said it would take a copy/// ([`ExchangeRequest::takes_copy`] — a phone, on any network) and is more than [`COPY_FASTER_PAST`] changes behind `position`,/// where the answer just left it. `file_bytes` is the served file's size, the/// offer's "about".////// The count STOPS one past the line ([`crate::changes::receipts_past`]'s/// cap), so it is a bounded index walk whatever the caller owes, and it is/// not asked at all of a caller that cannot take a copy or has nothing more/// coming — every other exchange pays nothing for it.pub fn copy_offer(    db: &Driver,    takes_copy: bool,    has_more: bool,    position: &BTreeMap<String, String>,    file_bytes: u64,) -> Result<Option<crate::protocol::types::CopyOffer>> {    use crate::protocol::types::{CopyOffer, COPY_FASTER_PAST};    if !takes_copy || !has_more {        return Ok(None);    }    let past = crate::changes::receipts_past(db, position, COPY_FASTER_PAST + 1)?;    Ok((past > COPY_FASTER_PAST).then_some(CopyOffer { bytes: file_bytes }))}/// Build the request: this file's cursors, a batch of its outbox, and the rows/// the peer's own cursors say it has not seen.////// Split out of [`exchange_once`] so a caller that serialises access to the/// file can take the cursors under its lock, RELEASE the lock for the round/// trip, and take it again for the fold. The ops are answered alongside so the/// fold half knows which outbox rows the answer is about — and which ops were/// never queued at all.////// The `handover` is the PASS's, not the call's: it learns where the peer is/// from each answer and advances as pages are built, which is what stops one/// pass handing the same row over twice. On the first call of a pass it knows/// nothing and the request is the outbox alone.pub fn exchange_request(    db: &Driver,    workspace_id: &str,    limit_rows: Option<u32>,    handover: &mut Handover,) -> Result<Handed> {    // WALKER296 NEXT PASS: a Reader pulls only. A copied file holds the Mac's    // historical receipts in `_writes`; after the first answer a normal handover    // would offer those receipts back, and the server correctly refuses every    // nonempty Reader request. Do not even inspect its outbox: a Reader cannot    // settle or drain a stale queue, but it still sends its cursors and folds news.    if db.device_scope() == Some(crate::device_scope::DeviceScope::Reader) {        *handover = Handover::shut();        return pull_request(db, workspace_id, limit_rows, handover);    }    crate::outbox::drop_local_ops(db)?;    // THE HAND-OVER BEFORE THE OUTBOX (slice 12): while a pass to a new epoch    // still has receipts to send, the queue waits — its writes are in this    // file's own author's stream, and draining them first would hand the new    // Mac this device's latest writes before the older ones it lacks.    let outbox_waits = handover.handing_over_to().is_some() && handover.outstanding();    let rows = if outbox_waits {        Vec::new()    } else {        db.all(            // IN WRITE ORDER. `hlc` is the stamp the write was minted at and            // `op_id` breaks a tie; `op_id` ALONE was the order until version 25,            // and it is the one thing on a queued op that carries no order at all            // — this crate mints no op ids (spec R7) and the Mac's source is a            // random UUID, so a page could hand a row's ops over backwards. The            // fold sorts NOTHING — it applies a batch in the order it is given, so            // the order is this side's to get right (`tests/page_order.rs`); this            // is the half that decides which ops are in the page at all, and a            // batch that CUT a row's stream in the middle would leave the older            // half for the next exchange.            "SELECT op_id, bytes, sig, tbl, row_id, queued_at FROM _outbox ORDER BY hlc, op_id LIMIT ?",            &[SqlValue::Integer(EXCHANGE_OPS_BATCH)],        )?    };    // QUEUE BAD OP: a queued op that does not read is set aside (a refused push, shown with Let go) and leaves the    // queue; the pass goes on with the rest. It used to refuse the whole pass, on every pass, for good.    let mut ops: Vec<CottonOp> = Vec::with_capacity(rows.len());    for row in &rows {        match outbox_row(row) {            Ok(op) => ops.push(op),            Err(error) => {                let op_id = row.text("op_id").unwrap_or_default().to_string();                let blob = |name: &str| match row.get(name) {                    Some(SqlValue::Blob(bytes)) => Some(bytes.clone()),                    Some(SqlValue::Text(text)) => Some(text.as_bytes().to_vec()),                    _ => None,                };                // Stuck since it was queued: the store reads no clock of its own.                let at = row.text("queued_at").unwrap_or_default().to_string();                db.transaction(|db| {                    crate::rejected::set_aside_undecodable(db, &op_id, blob("bytes").as_deref(), blob("sig").as_deref(), row.text("tbl").unwrap_or_default(), row.text("row_id").unwrap_or_default(), &error, &at)?;                    // not a copy: the server answered it, or it is set aside or parked in the same transaction first.                    db.run("DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op_id.clone())])?;                    Ok(())                })?;            }        }    }    // THE PAGE CEILING IN BYTES holds for the queue too: the first write goes    // whatever it costs, and the queue stops where the page is full.    let mut bytes = 0usize;    let fits = ops        .iter()        .position(|op| {            let full = bytes >= PAGE_BYTES;            bytes += wire_bytes(op);            full        })        .unwrap_or(ops.len());    ops.truncate(fits.max(1).min(ops.len()));    let bytes: usize = ops.iter().map(wire_bytes).sum();    let from_outbox = ops.len();    let queued: BTreeSet<String> = ops.iter().map(|op| op.op_id.clone()).collect();    // THE OUTBOX FIRST, and the catch-up in whatever room is left. A full batch    // means this device is mid-drain and the queue is the urgent half; the    // rows the peer has not seen have been waiting anyway and go on the next    // call. The cap is the responder's (`MAX_OPS_PER_EXCHANGE`, which    // `EXCHANGE_OPS_BATCH` is the near side of) — a body over it is a 413 that    // costs the drain too.    let room = usize::try_from(EXCHANGE_OPS_BATCH)        .unwrap_or(usize::MAX)        .saturating_sub(from_outbox);    if room > 0 && bytes < PAGE_BYTES {        // A write still queued here goes once, from the queue: the catch-up        // can name it too — a re-date queues the writes of an author the        // peer has never seen — and a page carrying it twice would settle it        // once.        ops.extend(            handover                .take(db, HANDOVER_PAGE_ROWS.min(room), room, bytes)?                .into_iter()                .filter(|op| !queued.contains(&op.op_id)),        );    }    // STAMP ORDER ACROSS THE WHOLE PAGE, for `answer`'s own reason and at the    // matching moment: a page is ordered where it is BUILT, because the fold    // applies a batch in the order it is given (and records `applied` /    // `skipped_stale` from it). The oldest op of a row carries the whole row    // and a later one is an amendment of two columns, so a page handed over    // backwards INSERTs the amendment and is refused by the first NOT NULL it    // meets — parked, and the row missing on the peer until something retries    // it.    //    // TWO SOURCES, and neither one alone is enough. The `_outbox` half is read    // in `hlc` order now, but until version 25 it was read by `op_id` — the one    // thing on a queued op that carries NO order, since this crate mints no op    // ids (spec R7) and the Mac's source is a random UUID. And the catch-up    // half is simply appended after it, so even two sorted halves are one    // unsorted page. A STABLE sort: two ops at one stamp are one write's, and    // the order between them is the order they were minted in.    ops.sort_by(|left, right| left.hlc.cmp(&right.hlc));    request_with_ops(db, workspace_id, limit_rows, handover, ops, queued)}/// Build an ordinary pull request, with the caller's cursors and admission/// marks but no operation source. Reader replicas use this for every page.fn pull_request(    db: &Driver,    workspace_id: &str,    limit_rows: Option<u32>,    handover: &Handover,) -> Result<Handed> {    request_with_ops(db, workspace_id, limit_rows, handover, Vec::new(), BTreeSet::new())}fn request_with_ops(    db: &Driver,    workspace_id: &str,    limit_rows: Option<u32>,    handover: &Handover,    ops: Vec<CottonOp>,    queued: BTreeSet<String>,) -> Result<Handed> {    Ok(Handed {        request: ExchangeRequest {            workspace_id: workspace_id.to_string(),            cursors: read_cursors(db)?,            ops,            limit: Some(                limit_rows                    .filter(|limit| *limit > 0)                    .unwrap_or(EXCHANGE_PAGE_ROWS)                    .min(MAX_EXCHANGE_PAGE_ROWS),            ),            // Declared so a peer holding a NEWER file refuses this call instead            // of sending ops this build would park in `_parked` and never            // see.            schema_version: Some(SCHEMA_VERSION),            // And how far down this build folds a file without a rebuild, so            // a Mac whose file is BELOW this build's schema can still serve it            // (`admission`): the newer side's floor is the one that decides.            schema_floor: Some(crate::schema::move_intents::floor()),            // The two marks a server at epoch E folds by (slice 12): this            // file's last hand-over, and the pass's target once an answer            // started one.            handed_over_epoch: handed_over_epoch(db)?,            handing_over_to: handover.handing_over_to(),            serving_author: crate::serving::serving_fact(db, workspace_id)?                .map(|fact| fact.author_id),            // Set by the pass, which knows the network (`cotton-client`'s            // cycle); a file knows nothing of where its phone is.            takes_copy: false,            // This file parks what the Mac parked waiting            // (`settle_waiting`), so it asks to be told.            parks_waiting: true,        },        queued,    })}/// Fold the peer's answer, advance the cursors, and settle the outbox — all in/// one transaction.////// One transaction because the three are one fact: a file that folded the/// answer but did not move its cursors would fold it again, and a file that/// moved its cursors but kept the outbox rows would push the same writes for/// ever.pub fn fold_answer(    db: &Driver,    handed: &Handed,    response: &ExchangeResponse,    now: &str,    handover: &mut Handover,) -> std::result::Result<Exchanged, SyncError> {    let mut report = ExchangeReport {        received: BTreeMap::new(),        sent: response.applied_rows.clone(),        passed: passed(response),        handed: handed.queued.len(),    };    let mut held: BTreeMap<String, usize> = BTreeMap::new();    // BEFORE anything is folded or settled: a Mac that served an earlier term    // and came back does not know it was replaced. Taking its answer would    // settle this device's outbox against a file nobody reads any more, so the    // whole answer is refused — nothing applied, no cursor moved, the outbox    // kept for the Mac that serves now. "Heard of" is the newest epoch a fact    // OR an earlier answer named (`serving::heard_epoch`); a file that has    // heard of none takes any answer.    // FIRST OF ALL: a copy of a night the server no longer serves. Its epoch    // may be anything, so this is asked before the old-Mac check.    if let Some(night) = &response.copy_night {        let ours = crate::serving::serving_fact(db, &handed.request.workspace_id)?            .map(|fact| fact.author_id);        if ours.as_deref() != Some(night.as_str()) {            return Err(SyncError::CopyReplaced {                night: night.clone(),            });        }    }    if let Some(held) = crate::serving::heard_epoch(db, &handed.request.workspace_id)? {        if response.serving_epoch.is_none_or(|answered| answered < held) {            return Err(SyncError::OldServing {                held,                answered: response.serving_epoch,            });        }    }    // An answer this file takes records the epoch it names, BEFORE the fold    // and outside its transaction: the epoch was named whether or not the    // fold below goes through, and a replica that has heard of a newer Mac    // owes it a hand-over from this moment (`owes_hand_over`). Never lowered —    // the check above has already refused anything below it.    if let Some(answered) = response.serving_epoch {        db.run(            "UPDATE _meta SET heard_serving_epoch = ? \             WHERE heard_serving_epoch IS NULL OR heard_serving_epoch < ?",            &[                rusqlite::types::Value::Integer(answered),                rusqlite::types::Value::Integer(answered),            ],        )?;    }    // THE JUDGE'S WORD, before anything is folded (slice 1). A replica takes    // a reading from every answer's `serverTime` and from every `future`    // refusal's, under the rules every reading is taken by.    let wall_ms = crate::protocol::js::parse_date_ms(now)        .ok_or_else(|| StoreError::encode(format!("the exchange's time {now:?} is unreadable")))?;    let replica_judge = db.replica_judge().cloned();    let futures: Vec<&PushRejection> = response        .rejected        .iter()        .filter(|rejection| rejection.code.as_deref() == Some(REJECTION_FUTURE))        .filter(|rejection| handed.request.ops.iter().any(|op| op.op_id == rejection.op_id))        .collect();    if let Some(judge) = &replica_judge {        for time in response            .server_time            .iter()            .chain(futures.iter().filter_map(|rejection| rejection.server_time.as_ref()))        {            judge.offer(time, wall_ms).map_err(StoreError::refused)?;        }    }    // The writes this answer's refusals settled here — re-dated or parked —    // whose outbox rows are already gone.    let mut settled: BTreeSet<String> = BTreeSet::new();    let _whole = crate::spans::span("answer::transaction");    db.transaction(|db| {        let _body = crate::spans::span("answer::body");        // THE RELEASE PASS, ONE TRANSACTION WITH THE FOLD: folding this page        // is the acceptance of its judge time, so what the file held while        // Unchecked is released or re-dated and queued here, and goes out in        // this same pass. Asked of the file, never of the handle's memory: a        // page that folds always releases, and one that rolls back released        // nothing.        { let _span = crate::spans::span("answer::release_held"); release_held_writes_at(db, wall_ms)?; }        if let Some(judge) = &replica_judge {            // THE REFUSALS BEFORE THE OPS: a `future` refusal is re-dated to            // when its write was made, under one fresh author for the answer,            // and goes out again in this same pass.            if let Some(first) = futures.first() {                let judge_ms = first                    .server_time                    .as_deref()                    .and_then(crate::protocol::js::parse_date_ms)                    .ok_or_else(|| {                        StoreError::encode(format!(                            "the serving Mac refused {} as `future` without a readable judge time",                            first.op_id                        ))                    })?;                let mut clock = judge.mint_clock(wall_ms).map_err(StoreError::refused)?;                clock.judge = crate::mint::JudgeTime::At(judge_ms);                let refused: Vec<String> = futures.iter().map(|rejection| rejection.op_id.clone()).collect();                let redated = db                    .with_replica_ids(|ids| crate::mint::clock::redate_refused(db, &clock, &refused, ids, now))                    .ok_or_else(|| StoreError::refused("this replica's judge was handed no op ids"))??;                if !redated.redated.is_empty() {                    eprintln!(                        "[cotton-sync] the serving Mac refused {} write(s) as ahead of its time — re-dated to \                         when they were made",                        redated.redated.len()                    );                }                settled = redated.settled;            }        }        if !response.ops.is_empty() {            // PULLED: the answer of the peer this file syncs from, which is            // the one arrival a write-once column may take a restatement from            // (`fold::Arrival::Pulled`). APPLIED WHATEVER ITS STAMP: a replica            // never parks its server's answer for a stamp; judge time only            // bounds how far it moves `last_hlc` (H1).            let judge_ms = db.judge().and_then(|judge| judge.now());            // A receipt minted above this file's schema waits, parked            // `newer-shape`, until this file moves; the cursor passes it.            let foldable = { let _span = crate::spans::span("answer::park_newer_shape"); crate::rejected::park_newer_shape(db, &response.ops, |_| now.to_string())? };            let result = fold_pulled_judged(db, &foldable, judge_ms)?;            report.received = tally(&result.applied_rows);            // Held back for an author this file has no fact for yet: parked            // whole, waiting, never refused; the fact frees them.            { let _span = crate::spans::span("answer::park_waiting"); crate::rejected::park_waiting(db, &response.ops, &result.waiting, Direction::Pull, now)?; }            for author in &result.announced {                crate::rejected::retry_waiting_for(db, author, now)?;            }            // The cursor moves past a refused op — it has to, or this file            // re-asks for the same page for ever and never sees another write.            // But that makes the row PERMANENTLY missing here while the peer            // still has it, which is a divergence nobody would otherwise learn            // about. Park it, WITH ITS PATCH, so the retry below — and every            // later page that moves this row — can offer it to the fold again.            for rejection in &result.rejected {                if let Some(op) = response                    .ops                    .iter()                    .find(|op| op.op_id == rejection.op_id)                {                    // Said once, when it is first parked: the same write                    // arriving again is the same refusal, already said.                    if park(db, op, Direction::Pull, Class::of_refusal(&rejection.reason), &rejection.reason, now)? {                        eprintln!(                            "[cotton-sync] this device refused a peer's write and has parked it: \                             {} {} {} — {}",                            op.kind.as_str(),                            op.table,                            op.row_id,                            rejection.reason                        );                    }                }            }            // AND NOW THE ONES THAT WERE ALREADY PARKED. A row whose ops land            // in two pages reaches a file that has never seen it as an            // amendment before its creation; the amendment is refused, parked,            // and the creation arrives here on the NEXT page. Offering the            // parked ops of the rows this page NAMED is what turns "parked"            // into "folded when the rest arrived" — and scoping it to those            // rows is what stops it being a sweep of every write this device            // has ever lost, run on every page of every cycle.            //            // NAMED, never APPLIED, and the difference is the whole of the            // bug this scope used to have. A row whose CREATION was refused            // has no applied op — ever — so it never appeared in            // `applied_rows`, and the one thing that could clear its park was            // the one thing that could not happen. A standby Mac reached            // 23,841 parked ops with `retries = 0` on every one of them: the            // mechanism had never run. The rows a page named are the rows            // whose parks this page could have unblocked, whatever the fold            // made of them — together with every park whose foreign key names            // one of them, retried until a round lands nothing            // (`retry_touched_rows`): the child that came pages before its            // parent.            //            // Inside the same transaction as the fold that unblocked them: a            // retry that landed while the page it belongs to rolled back would            // be a row from an answer this file never took.            //            // Not this page's own refusals, though: the fold above has just            // refused or held them, and only a park that lands below can            // change that. An op it applied (or found stale) is offered: a            // park of that same op ends with it.            let resolved: BTreeSet<&str> = result                .applied                .iter()                .chain(&result.skipped_stale)                .chain(&result.skipped_retired)                .map(String::as_str)                .collect();            let judged: BTreeSet<&str> = response                .ops                .iter()                .map(|op| op.op_id.as_str())                .filter(|id| !resolved.contains(id))                .collect();            { let _span = crate::spans::span("answer::retry_touched_rows"); retry_touched_rows(db, &named_rows(&response.ops), &judged, now)?; }            // AND THE WRITES THIS FILE STILL OWES THE PEER. The mirror image:            // a push the peer refused is missing THERE, and the row moving            // again is the one event that can make the same op land — the            // constraint it lost to was about the row, not about the op. It            // goes back in the `_outbox` rather than through the fold, because            // a fold here would only answer "stale".            { let _span = crate::spans::span("answer::requeue_touched_pushes"); requeue_touched_pushes(db, &result.applied_rows, now)?; }        }        // FORWARDS ONLY, and per author: two pages of one author's stream can        // be folded in either order after a retry, and a rewound cursor        // re-asks for writes this file has already folded.        for (author, hlc_seen) in &response.cursors {            advance_cursor(db, author, hlc_seen, now)?;        }        // A refused CATCH-UP op is not a lost write — the row is still here —        // but the peer will never hold it, and a divergence nobody records is        // one nobody can fix. It is parked with its patch, under its own op id,        // and from then on travels only as a park: the stream leaves a parked        // push out (`Handover::take`).        //        // RETRYABLE ones are not parked: "the peer's schema is older than this        // client" is a late deploy, not a refusal, and the next pass offers the        // row again anyway — the peer's own position on that author has not        // moved, which is exactly what "it did not take it" looks like.        for rejection in &response.rejected {            if rejection.retryable.unwrap_or(false) {                continue;            }            if let Some(op) = handed                .handed_over()                .into_iter()                .find(|op| op.op_id == rejection.op_id)            {                park(db, op, Direction::Push, Class::of_refusal(&rejection.reason), &rejection.reason, now)?;                eprintln!(                    "[cotton-sync] the peer refused a row this device handed over — it stays \                     here and the peer will not have it: {} {} {} — {}",                    op.kind.as_str(),                    op.table,                    op.row_id,                    rejection.reason                );            }        }        // A PARKED PUSH THE PEER TOOK, handed over in a pass (or caught up        // from the stream), is no longer a write the peer lacks.        let taken: Vec<String> = handed            .handed_over()            .into_iter()            .filter(|op| !response.rejected.iter().any(|rejection| rejection.op_id == op.op_id))            .map(|op| op.op_id.clone())            .collect();        clear_delivered_pushes(db, &taken)?;        // AND EVERY PARK IT CARRIED THAT IS STILL PARKED counts one offer to        // the pass's epoch — a refused one, or a pull the peer took (it stays        // parked here): a pass that never completes is rebuilt every cycle,        // and without the count each rebuild offers the same parks again for        // ever. A push the peer took ended above and matches nothing.        if let Some(epoch) = handed.request.handing_over_to {            let offered: Vec<String> = handed                .handed_over()                .into_iter()                .map(|op| op.op_id.clone())                .collect();            crate::rejected::count_handover_offers(db, &offered, epoch)?;        }        // WHAT THE MAC PARKED WAITING for its author's fact        // (`REJECTION_AUTHOR_WAITING`): it has the receipt and folds it itself        // once the fact arrives, so it is neither held in the queue — a hold        // stops the drain — nor sent again on every pass, which is what it        // was (16 Oct 2026: 95 KB a pass, no row). Parked here push-side, it        // travels only as a park (`travels_only_as_park`): requeued or handed        // over inside their ceilings, and ended once the Mac's `seen` passes        // it (`end_waiting_pushes_the_peer_holds`).        for rejection in response            .rejected            .iter()            .filter(|rejection| rejection.code.as_deref() == Some(REJECTION_AUTHOR_WAITING))        {            let Some(op) = handed.request.ops.iter().find(|op| op.op_id == rejection.op_id) else {                continue;            };            park(db, op, Direction::Push, Class::Waiting, &rejection.reason, now)?;            // not a copy: the server answered it, or it is set aside or parked in the same transaction first.            db.run("DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.op_id.clone())])?;            settled.insert(op.op_id.clone());        }        // WHAT THE PEER DID NOT REACH (`REJECTION_DEFERRED`): still queued as        // it is, with no attempt counted, and not a hold — a hold stops the        // drain, and these are the drain's next exchange.        for rejection in response            .rejected            .iter()            .filter(|rejection| rejection.code.as_deref() == Some(REJECTION_DEFERRED))        {            if handed.outbox_ops().iter().any(|op| op.op_id == rejection.op_id) {                settled.insert(rejection.op_id.clone());            }        }        let unsettled: Vec<PushRejection> = response            .rejected            .iter()            .filter(|rejection| !settled.contains(&rejection.op_id))            .cloned()            .collect();        held = settle_outbox(db, handed, &unsettled, &settled, now)?;        Ok(())    })?;    let held_count: usize = held.values().sum();    // Where the peer is, from its own answer — and this file's ceiling, once.    handover.learn(db, response)?;    crate::rejected::end_waiting_pushes_the_peer_holds(db, &response.seen)?;    let pending = crate::outbox::pending_count(db)?;    // THE PASS COMPLETES HERE (slice 12): a request that carried the pass's    // target was folded, nothing of it was held, no author is still behind    // and the queue is empty — only then is the mark written. Earlier, a    // crash would leave a file that says it handed over what it never sent.    if let Some(target) = handover.handing_over_to() {        if handed.request.handing_over_to == Some(target)            && held_count == 0            && pending == 0            && !handover.outstanding()        {            db.run(                "UPDATE _meta SET handed_over_epoch = ? \                 WHERE handed_over_epoch IS NULL OR handed_over_epoch < ?",                &[SqlValue::Integer(target), SqlValue::Integer(target)],            )?;        }    }    Ok(Exchanged {        peer_schema: response.schema_version,        remaining: response.behind_by,        owed_at_start: response.owed_at_start,        owed_by_table: response.owed_by_table.clone(),        wake_refusal: response.wake_refusal.clone(),        copy: response.copy,        answered_by: response.answered_by.clone(),        peer_has_more: response.has_more,        // Another call moves something if the peer has more, or if this file        // filled its batch, or if an op is queued that this call did not carry,        // or if the peer is still behind on an author this file holds.        //        // NOT while anything was HELD. A hold is the peer saying it cannot take        // this file's writes yet — a build behind, the same for every op this        // file stamps — so neither the queue nor the catch-up moves until the        // peer has caught up, and a pass that asked again would spin on the        // same refusal. The peer's own backlog (`response.has_more`) still        // counts: a behind server keeps SERVING this device while it holds.        has_more: response.has_more            || (held_count == 0 && (pending > 0 || handover.outstanding())),        pending,        report,        held,    })}/// Take the pushed ops off the queue, park what will never land, hold what/// might. Answers what was HELD, counted per reason word — a non-zero hold/// stops the drain.fn settle_outbox(    db: &Driver,    handed: &Handed,    rejected: &[PushRejection],    settled: &BTreeSet<String>,    now: &str,) -> Result<BTreeMap<String, usize>> {    let sent = handed.outbox_ops();    // Only rejections naming an op we ACTUALLY sent count. A response is free    // to be wrong; one naming an op that is not in this batch cannot be acted    // on at all — there is no op to park and no outbox row to bump. A rejection    // of a CATCH-UP op is ours and is dealt with by the caller, so it is not a    // stray either.    let ours: Vec<&PushRejection> = rejected        .iter()        .filter(|rejection| sent.iter().any(|op| op.op_id == rejection.op_id))        .collect();    let mine = rejected        .iter()        .filter(|rejection| {            handed                .request                .ops                .iter()                .any(|op| op.op_id == rejection.op_id)        })        .count();    let strays = rejected.len() - mine;    // A refusal this answer already settled — re-dated or parked — names an    // op that was sent and is neither delivered nor held.    if strays > 0 {        eprintln!(            "[cotton-sync] the peer rejected {strays} op(s) this device did not send — \             ignoring them; this is a peer-side bug"        );    }    // NOT every rejection is final. A CHECK or UNIQUE violation will never be    // accepted, so retrying it for ever would wedge every write behind it. But    // "the server schema is older than this client" is TRANSIENT, and dropping    // those would mean every write made on a new app build, for however long    // the deploy is late, is silently gone.    let (retryable, finals): (Vec<_>, Vec<_>) = ours        .into_iter()        .partition(|rejection| rejection.retryable.unwrap_or(false));    for rejection in &finals {        // The write IS gone, so it is PARKED in the file before the outbox row        // is deleted. A log line was the whole trace before, and in a shipped        // build that reaches nothing durable.        if let Some(op) = sent.iter().find(|op| op.op_id == rejection.op_id) {            park(db, op, Direction::Push, Class::of_refusal(&rejection.reason), &rejection.reason, now)?;            eprintln!(                "[cotton-sync] the peer refused a write and will never hold it — it is parked \                 here with its patch: {} {} {} — {}",                op.kind.as_str(),                op.table,                op.row_id,                rejection.reason            );        }    }    let held: BTreeSet<&str> = retryable        .iter()        .map(|rejection| rejection.op_id.as_str())        .collect();    for rejection in &retryable {        // Stays queued. `attempts` is recorded for a human to read, never read        // back to decide anything: there is no ceiling here and there must not        // be one.        // The refusal's code goes first ("seal_key_missing: …", UNSENT SEEN, 26 Nov 2026), so what waits can be        // counted by code without reading a reason (`outbox::waiting`).        db.run(            "UPDATE _outbox SET attempts = attempts + 1, last_error = ? WHERE op_id = ?",            &[                SqlValue::Text(crate::outbox::coded(rejection.code.as_deref(), &rejection.reason)),                SqlValue::Text(rejection.op_id.clone()),            ],        )?;        // When it was first refused for a reason that lasts (UNSENT HEAL 2): what "waited a day" counts from.        crate::outbox::note_refused(db, &rejection.op_id, rejection.code.as_deref(), now)?;    }    let refused: BTreeSet<&str> = finals        .iter()        .map(|rejection| rejection.op_id.as_str())        .collect();    let mut delivered: Vec<String> = Vec::new();    for op in sent {        if held.contains(op.op_id.as_str()) || settled.contains(&op.op_id) {            continue;        }        if !refused.contains(op.op_id.as_str()) {            delivered.push(op.op_id.clone());        }        db.run(            // not a copy: the server answered it, or it is set aside or parked in the same transaction first.            "DELETE FROM _outbox WHERE op_id = ?",            &[SqlValue::Text(op.op_id.clone())],        )?;    }    // A REQUEUED PUSH THAT LANDED is no longer a write this file lacks. Without    // this the parked row it was re-offered from would outlive the loss it    // records, and `_parked` would stop meaning what a person reads it as.    clear_delivered_pushes(db, &delivered)?;    if !retryable.is_empty() {        eprintln!(            "[cotton-sync] holding {} write(s) in the outbox: {}. They will go as soon as the \             peer can take them.",            retryable.len(),            retryable[0].reason        );    }    crate::outbox::forget_refused_gone(db)?;    let mut by_code: BTreeMap<String, usize> = BTreeMap::new();    for rejection in &retryable {        *by_code            .entry(rejection.code.clone().unwrap_or_default())            .or_default() += 1;    }    Ok(by_code)}/// THE RELEASE AT A PASS'S EDGE: a replica whose judge has judge time/// releases every write its file holds (`held = 1`) — released at its own/// stamp or re-dated, and queued — before the pass reads its outbox, so a/// write held while this device had no server time goes out in the first/// page of the next pass that opens the file: a foreground open, a catch-up/// wake, a timer. Asked of the file through its held indexes, never of the/// handle's memory of an earlier pass. Nothing on a handle with no replica/// judge, with no judge time yet, or holding nothing. Says how many writes it/// queued.pub fn release_held_writes(db: &Driver, now: &str) -> Result<usize> {    let wall_ms = crate::protocol::js::parse_date_ms(now)        .ok_or_else(|| StoreError::encode(format!("the pass's time {now:?} is unreadable")))?;    db.transaction(|db| release_held_writes_at(db, wall_ms))}fn release_held_writes_at(db: &Driver, wall_ms: i64) -> Result<usize> {    let Some(judge) = db.replica_judge() else {        return Ok(0);    };    if judge.now().is_none() {        return Ok(0);    }    // A set-aside change that reads now (a later build) is held again here, so the release re-dates it (QUEUE BAD OP 3).    crate::rejected::try_set_aside_again(db, None)?;    if crate::mint::clock::held_count(db)? == 0 {        return Ok(0);    }    let release = db        .with_replica_ids(|ids| crate::mint::clock::release_now(db, wall_ms, ids))        .ok_or_else(|| StoreError::refused("this replica's judge was handed no op ids"))??;    Ok(release.released.len() + release.redated.len() + usize::from(release.author.is_some()))}/// ONE exchange, for a caller that holds the file across the round trip.////// The paged loop in `cotton-client` does not use this — it takes the file/// three times instead, so a screen's read never waits for the network — but/// the shape is identical and this is what a test and an import drive.pub fn exchange_once(    db: &Driver,    transport: &mut impl SyncTransport,    workspace_id: &str,    limit_rows: Option<u32>,    now: &str,    handover: &mut Handover,) -> std::result::Result<Exchanged, SyncError> {    release_held_writes(db, now)?;    let handed = exchange_request(db, workspace_id, limit_rows, handover)?;    let request = &handed.request;    let response = match transport.exchange(request) {        Ok(response) => response,        Err(message) => {            note_transport_failure(db, &handed, &message)?;            return Err(SyncError::Transport(message));        }    };    fold_answer(db, &handed, &response, now, handover)}/// The transport failed with this request in the air: record the attempt.////// On a transport failure the ops STAY — that is the entire point of the/// queue — and the attempt is written on each so a person reading `_outbox`/// can see it was tried. The QUEUED half only: a catch-up op has no outbox/// row to record an attempt on, and the next pass reads where the peer is/// again anyway.////// Its own function because TWO schedules make this call: [`exchange_once`],/// which holds the file across the round trip, and `cotton-client`'s paged/// passes, which take the file back only after the transport has answered./// The bookkeeping is the same either way and it must not drift between them.pub fn note_transport_failure(db: &Driver, handed: &Handed, message: &str) -> Result<()> {    db.transaction(|db| {        for op in handed.outbox_ops() {            db.run(                "UPDATE _outbox SET attempts = attempts + 1, last_error = ? WHERE op_id = ?",                &[                    SqlValue::Text(message.to_string()),                    SqlValue::Text(op.op_id.clone()),                ],            )?;        }        Ok(())    })}#[cfg(test)]#[path = "exchange_tests.rs"]mod tests;