//! `_parked` — the writes this file could not fold YET, KEPT WHOLE so they //! can be folded again, each with the CLASS that says why (slice 4). //! //! A park is the receipt as it arrived (`bytes`), its verdict (`class`, //! `reason`), when it was first parked (`first_at`) and how often it has been //! offered again (`tried_at`, `tries`). `tbl` and `row_id` are the receipt's //! own address, copied out of the bytes at park time so a touched row finds //! its parks by index; every other reading of the write comes from the bytes //! ([`crate::stored::rejected_row`]). //! //! **The classes.** `waiting`: a parent never seen, an author fact not yet //! arrived, a serving fact not yet arrived that would make its author a //! serving author. `conflict`: a unique clash (also on re-assembly), a constraint //! that will not change by itself, a re-stamp or a fact that lost, a receipt //! refused again after its re-date. `newer-shape`: a receipt minted at a schema //! above this file's stamp (a build ahead of this one), kept off the owner's //! board and folded once this file has moved to that schema //! ([`refold_newer_shape`]). `gone` and `unverified` are allowed by the //! table's CHECK from the start; nothing writes them yet. //! //! **A park is never dropped.** It ends only when it APPLIES, is folded as //! STALE (or retired, or said again by a newer parked write of the same row — //! the fold's own last-writer-wins verdict, [`superseded_by`] — or by its //! writer under the author's new name, [`now_named`]), when the peer //! TAKES a parked push, or when the OWNER discards it ([`discard`]). Every one //! of those goes through [`end_park`], the one `DELETE FROM _parked` in the //! crates; `no_park_is_deleted_except_by_resolution_or_owner` holds it. //! There is no ceiling on retries: a park whose cause never goes away is //! offered on every touch of its row for ever, and the owner sees it //! ([`board`]). //! //! **A `conflict` waits for its row or the shape, not for the clock.** A //! constraint, a fence or a lost fact does not change its mind between two //! passes: what changes it is the row moving (a page naming it, //! [`retry_touched_rows`]) or the file's shape moving (a move, a column or a //! table the copy takes: [`shape_changed`]). So the sweep offers a conflict //! once at each shape — never tried, or not tried since the shape last //! moved — and leaves it parked until one of those happens; the copy says //! why once, when it first parks it (27 Oct 2026: a phone retried 288 served //! rows its schema refused three thousand times each, a line apiece). //! //! **A park is offered again by TWO things, and it needs both.** //! [`retry_touched_rows`] is the page's own: the rows the page NAMED and the //! parks whose foreign key names one of them, retried in the same transaction //! to a fixpoint, which is how the rest of a row — or the parent it waited //! on — arriving heals it at once. [`sweep_parked`] is the cycle's: //! [`PARK_SWEEP_OPS`] of the least-recently-tried parks, rotating, which is //! how a park whose cause no page will ever name again converges. //! Every retry folds through [`crate::fold::arrive`], so it meets every //! arrival check a fresh arrival meets. //! //! **The foreign-key follow-up is BOUNDED by the parent, and a hub is not //! one.** A landed row re-offers only its own parks and the parks whose //! foreign key to a NON-hub parent names it. [`HUB_PARENTS`] — the workspace //! row, which every synced row names — is never followed. //! //! **The two directions are retried DIFFERENTLY.** A `pull` park is a peer's //! write THIS file refused, so the retry is a FOLD. A `push` park is our own //! write, refused by the PEER, so the retry is putting it back in the //! `_outbox` ([`requeue_touched_pushes`]), at most [`PUSH_RETRY_CEILING`] //! times; past that it stays parked, and it is cleared only when the peer //! takes the op. //! //! **The first verdict is the one `first_at` keeps.** `park` is //! `ON CONFLICT(op_id) DO NOTHING`, and a retry that fails again rewrites //! `class`, `reason`, `tried_at` and `tries`, never `first_at`. use std::collections::{BTreeMap, BTreeSet}; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value as JsonValue}; use crate::driver::{Driver, Row}; use crate::error::Result; use crate::fold::{arrive, Arrival}; use crate::protocol::types::{CottonOp, OpKind}; /// Which side of the sync lost the write. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Direction { Push, Pull, } impl Direction { #[must_use] pub fn as_str(self) -> &'static str { match self { Direction::Push => "push", Direction::Pull => "pull", } } } /// Why a write is parked — the `_parked.class` CHECK, in full. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Class { /// It will apply once something arrives: the parent row it names, or its /// author's fact. Waiting, /// It will not apply by itself: a unique clash, a constraint, a fence, a /// re-stamp or a fact that lost, a write refused again after its re-date. Conflict, /// A write at an erased id, or under an erased parent (`crate::erase`): /// never applied, its count kept. Gone, /// A signature this file could not check. Nothing writes it yet (keys). Unverified, /// Minted at a schema above this file's stamp, by a build ahead of this /// one: folded once this file has moved to that schema, never shown to the /// owner meanwhile — nothing is wrong, one side has not updated yet. /// Written only into a file whose `_parked` CHECK admits it /// ([`keeps_newer_shape`]). NewerShape, } impl Class { #[must_use] pub fn as_str(self) -> &'static str { match self { Class::Waiting => "waiting", Class::Conflict => "conflict", Class::Gone => "gone", Class::Unverified => "unverified", Class::NewerShape => "newer-shape", } } /// The class of a fold's refusal, read off its reason: a write at an /// erased id is `gone`; a foreign key whose parent this file has not got, /// or an author with no fact here, is `waiting`; every other refusal is a /// `conflict`. #[must_use] pub fn of_refusal(reason: &str) -> Class { if reason.starts_with(crate::erase::GONE_REFUSAL) { Class::Gone } else if reason.starts_with(NEWER_SHAPE) { Class::NewerShape } else if reason.starts_with(WAITING_FOR_AUTHOR) || reason.starts_with(WAITING_FOR_SERVING) || reason.contains("FOREIGN KEY constraint failed") { Class::Waiting } else { Class::Conflict } } } /// One row in `_parked`: a write that exists on exactly one side, read back /// out of its receipt bytes. /// /// `patch` is `None` for a retract. `table`, `row_id`, `kind`, `patch`, `hlc`, /// `device_id` and `schema_version` are readings of `bytes`; a park whose /// bytes do not decode reads them empty. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RejectedOp { pub op_id: String, pub direction: String, /// `waiting`, `conflict`, `gone` or `unverified` ([`Class`]). pub class: String, pub table: String, pub row_id: String, pub kind: String, /// The LATEST verdict. A retry that fails again rewrites this. pub reason: String, /// The FIRST verdict's time (`first_at`), and it never moves. pub at: String, pub patch: Option>, /// The receipt, as it arrived — what a retry folds, byte for byte. pub bytes: Option>, /// The author's signature over `bytes` (`sig`, 64 raw bytes), carried /// with them whenever the park is offered again; `None` for an unsigned /// receipt. pub sig: Option>, pub hlc: Option, /// Who WROTE it — never who parked it. pub device_id: Option, pub schema_version: Option, /// When something last offered it to the fold again (`tried_at`). pub retried_at: Option, /// How many times it has been offered again (`tries`): a PUSH put back in /// the queue (see [`PUSH_RETRY_CEILING`]), a PULL refused by a retry. pub retries: i64, } /// What one [`retry_rejected`] pass did. /// /// `folded` are op ids whose parks have ENDED: the file no /// longer lacks that write. `still_rejected` pairs each surviving op id with /// the reason it was refused THIS time, which is the string now in the row. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RetryReport { pub folded: Vec, pub still_rejected: Vec<(String, String)>, } impl RetryReport { /// Did this pass change anything? #[must_use] pub fn is_empty(&self) -> bool { self.folded.is_empty() && self.still_rejected.is_empty() } /// Add another pass's outcome to this one. pub fn absorb(&mut self, other: RetryReport) { self.folded.extend(other.folded); self.still_rejected.extend(other.still_rejected); } } /// Park a write this file could not fold, in the file, so it outlives the /// session: the receipt whole, with its class and its verdict. THE ONE /// WRITER of a new `_parked` row. /// /// `ON CONFLICT DO NOTHING`: the first verdict is the interesting one, and a /// replayed batch must not rewrite the time of a loss that already happened. /// Answers whether this parked it now — false for a write parked already, so /// a caller says why once per write, never once per arrival. pub fn park( db: &Driver, op: &CottonOp, direction: Direction, class: Class, reason: &str, at: &str, ) -> Result { // A write the erase hook refused parks `gone`, whatever the caller read // the refusal as: it will never apply. let class = if reason.starts_with(crate::erase::GONE_REFUSAL) { Class::Gone } else { class }; // The writes this one says everything for. Their `first_at` comes with // them: what a person acts on is how long THIS ROW has been stuck. let (dead, since) = superseded_by(db, op, direction)?; let at = match since { Some(earlier) if earlier.as_str() < at => earlier, _ => at.to_string(), }; for op_id in &dead { end_park(db, op_id, Ended::Superseded)?; } let parked = db.run( "INSERT INTO _parked (op_id, direction, class, reason, first_at, tries, bytes, sig, tbl, row_id) \ VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?) \ ON CONFLICT(op_id) DO NOTHING", &[ SqlValue::Text(op.op_id.clone()), SqlValue::Text(direction.as_str().to_string()), SqlValue::Text(class.as_str().to_string()), SqlValue::Text(reason.to_string()), SqlValue::Text(at), SqlValue::Blob(op.receipt.as_bytes().to_vec()), // ITS SIGNATURE WITH IT: a park offered again — requeued, handed // over — travels as the op it was, and the serving Mac's signature // screen refuses an unsigned one outright. crate::receipts::sig_value(op), SqlValue::Text(op.table.clone()), SqlValue::Text(op.row_id.clone()), ], )?; Ok(parked > 0) } /// The code a queued write that does not decode is set aside under (QUEUE BAD OP): the first word of its park's /// reason, and of what UNSENT SEEN counts and the stuck list says. pub const UNDECODABLE: &str = "undecodable"; /// QUEUE BAD OP (coordinator, 26 Nov 2026: one queued op whose receipt did not decode stopped every pass of that copy /// for good, and nothing said why): set it aside as a refused push, its bytes kept as they are, so the pass goes on /// without it and the stuck list shows it with Let go. Nothing reads it as an op again: every push park's reader /// skips one that does not rebuild. The words are the decoder's, for the log and Feedback; a screen says the code. /// Answers whether it was newly set aside. #[allow(clippy::too_many_arguments)] pub fn set_aside_undecodable(db: &Driver, op_id: &str, bytes: Option<&[u8]>, sig: Option<&[u8]>, table: &str, row_id: &str, error: &str, at: &str) -> Result { let words: String = error.chars().take(200).collect(); let parked = db.run( "INSERT INTO _parked (op_id, direction, class, reason, first_at, tries, bytes, sig, tbl, row_id) \ VALUES (?, 'push', 'conflict', ?, ?, 0, ?, ?, ?, ?) ON CONFLICT(op_id) DO NOTHING", &[ SqlValue::Text(op_id.to_string()), SqlValue::Text(format!("{UNDECODABLE}: {words}")), SqlValue::Text(at.to_string()), // Kept whole, even empty, so the stuck list (which shows a park with bytes) names it. SqlValue::Blob(bytes.unwrap_or_default().to_vec()), sig.map_or(SqlValue::Null, |sig| SqlValue::Blob(sig.to_vec())), SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string()), ], )?; // Its receipt here leaves every stream and the release (QUEUE BAD OP 3). mark_receipt_set_aside(db, op_id)?; if parked > 0 { eprintln!("[cotton-sync] a queued change of {table} did not read and was set aside, the pass goes on: {op_id} ({UNDECODABLE})"); } Ok(parked > 0) } /// Whether a park's reason says its write was set aside because it did not decode. pub fn is_undecodable(reason: Option<&str>) -> bool { reason.is_some_and(|reason| reason.starts_with(UNDECODABLE) && reason[UNDECODABLE.len()..].starts_with(':')) } /// `held` of a receipt set aside because it did not decode (QUEUE BAD OP 3): a state of its own. The release reads /// `held = 1` and every stream `held = 0`, so neither meets it; `held_count` counts only `held = 1`, so the phone /// never says it waits for the Mac's time over it; a snapshot strips it as it strips a held one. pub const SET_ASIDE: i64 = 3; /// The receipt of `op_id` in this file, travelling or held, marked set aside. fn mark_receipt_set_aside(db: &Driver, op_id: &str) -> Result { let mut marked = 0; for place in ["_writes", "_tombstones"] { marked += db.run(&format!("UPDATE {place} SET held = ? WHERE op_id = ? AND held IN (0, 1)"), &[SqlValue::Integer(SET_ASIDE), SqlValue::Text(op_id.to_string())])?; } Ok(marked) } /// One change set aside because it did not decode: its park, whole, bytes and all. #[derive(Debug, Clone, PartialEq, Eq)] pub struct SetAside { pub op_id: String, pub reason: String, pub first_at: String, pub bytes: Vec, pub sig: Option>, pub table: String, pub row_id: String, } /// Every change set aside because it did not decode (QUEUE BAD OP 3): what a rebuild of the copy carries into the /// new one, and what makes a database never empty. pub fn set_aside(db: &Driver) -> Result> { if db.get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = '_parked'", &[])?.is_none() { return Ok(Vec::new()); } let blob = |row: &crate::driver::Row, name: &str| match row.get(name) { Some(SqlValue::Blob(bytes)) => Some(bytes.clone()), Some(SqlValue::Text(text)) => Some(text.as_bytes().to_vec()), _ => None, }; Ok(db .all("SELECT op_id, reason, first_at, bytes, sig, tbl, row_id FROM _parked WHERE direction = 'push' AND reason LIKE ? ORDER BY first_at, op_id", &[SqlValue::Text(format!("{UNDECODABLE}:%"))])? .iter() .map(|row| SetAside { op_id: row.text("op_id").unwrap_or_default().to_string(), reason: row.text("reason").unwrap_or_default().to_string(), first_at: row.text("first_at").unwrap_or_default().to_string(), bytes: blob(row, "bytes").unwrap_or_default(), sig: blob(row, "sig"), table: row.text("tbl").unwrap_or_default().to_string(), row_id: row.text("row_id").unwrap_or_default().to_string(), }) .collect()) } /// Set-aside changes carried from a copy that was rebuilt, parked here as they were there. Answers how many landed. pub fn land_set_aside(db: &Driver, carried: &[SetAside]) -> Result { db.transaction(|db| { let mut landed = 0; for change in carried { landed += db.run( "INSERT INTO _parked (op_id, direction, class, reason, first_at, tries, bytes, sig, tbl, row_id) \ VALUES (?, 'push', 'conflict', ?, ?, 0, ?, ?, ?, ?) ON CONFLICT(op_id) DO NOTHING", &[ SqlValue::Text(change.op_id.clone()), SqlValue::Text(change.reason.clone()), SqlValue::Text(change.first_at.clone()), SqlValue::Blob(change.bytes.clone()), change.sig.clone().map_or(SqlValue::Null, SqlValue::Blob), SqlValue::Text(change.table.clone()), SqlValue::Text(change.row_id.clone()), ], )?; } Ok(landed) }) } /// The person let go of a set-aside change: its receipt here leaves and its row is assembled from what remains (as a /// held fact that never travels leaves). The park itself ends by `discard`. Answers how many receipts left. pub fn let_go_set_aside(db: &Driver, op_id: &str) -> Result { db.transaction(|db| { let mut gone = 0; for place in ["_writes", "_tombstones"] { let rows: Vec<(String, String)> = db .all(&format!("SELECT tbl, row_id FROM {place} WHERE op_id = ? AND held = ?"), &[SqlValue::Text(op_id.to_string()), SqlValue::Integer(SET_ASIDE)])? .iter() .filter_map(|row| Some((row.text("tbl")?.to_string(), row.text("row_id")?.to_string()))) .collect(); gone += db.run(&format!("DELETE FROM {place} WHERE op_id = ? AND held = ?"), &[SqlValue::Text(op_id.to_string()), SqlValue::Integer(SET_ASIDE)])?; for (table, row_id) in &rows { crate::fold::reassemble_row(db, table, row_id)?; } } Ok(gone) }) } /// Each set-aside change (`only`: of these ids) tried again, as after an update: one whose receipt here reads now is /// held again (`held = 1`), its park kept, so the release re-dates it, always to a new stamp (`mint_clock`), never /// sending it at its old one behind the author's later writes (QUEUE BAD OP 3). One carried from a rebuilt copy has /// no receipt here and stays for Let go. Answers the ids held again. pub fn try_set_aside_again(db: &Driver, only: Option<&[String]>) -> Result> { migrate_earlier_marks(db)?; let mut again = Vec::new(); for change in set_aside(db)? { if only.is_some_and(|only| !only.contains(&change.op_id)) { continue; } let reads = crate::wire::from_bytes(change.op_id.clone(), &change.bytes).is_ok() && crate::canonical::decode(&change.bytes).is_ok(); if !reads { continue; } let mut held = 0; for place in ["_writes", "_tombstones"] { held += db.run(&format!("UPDATE {place} SET held = 1, bytes = ? WHERE op_id = ? AND held = ?"), &[SqlValue::Blob(change.bytes.clone()), SqlValue::Text(change.op_id.clone()), SqlValue::Integer(SET_ASIDE)])?; } if held > 0 { again.push(change.op_id); } } Ok(again) } /// `held = 2`: what QUEUE BAD OP 2 wrote for a set-aside change the person let go. pub const HELD_LET_GO_BEFORE: i64 = 2; /// QUEUE BAD OP 4 (B3): the marks earlier builds left, brought to today's. A receipt QUEUE BAD OP 1 or 2 set aside kept /// `held = 0` beside its `undecodable` park, so nothing ever tried it again: it is marked set aside (`held = 3`). A /// receipt QUEUE BAD OP 2 marked let go (`held = 2`) was the person's choice: it leaves, its row assembled from what /// remains, as Let go does today. Answers how many receipts moved. pub fn migrate_earlier_marks(db: &Driver) -> Result { let mut moved = 0; for place in ["_writes", "_tombstones"] { if db.get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(place.to_string())])?.is_none() { continue; } moved += db.run( &format!("UPDATE {place} SET held = ? WHERE held = 0 AND op_id IN (SELECT op_id FROM _parked WHERE direction = 'push' AND reason LIKE ?)"), &[SqlValue::Integer(SET_ASIDE), SqlValue::Text(format!("{UNDECODABLE}:%"))], )?; let gone: Vec<(String, String)> = db .all(&format!("SELECT tbl, row_id FROM {place} WHERE held = ?"), &[SqlValue::Integer(HELD_LET_GO_BEFORE)])? .iter() .filter_map(|row| Some((row.text("tbl")?.to_string(), row.text("row_id")?.to_string()))) .collect(); if !gone.is_empty() { moved += db.run(&format!("DELETE FROM {place} WHERE held = ?"), &[SqlValue::Integer(HELD_LET_GO_BEFORE)])?; for (table, row_id) in &gone { crate::fold::reassemble_row(db, table, row_id)?; } } } Ok(moved) } /// Whether `op_id` is a set-aside change held again to be re-dated (its park still says `undecodable`); its park /// ends here, in the release's transaction, as the release takes it. pub(crate) fn taken_again(db: &Driver, op_id: &str) -> Result { // not a copy: a park ends only as it is ended: taken again by the release in the same transaction, taken by the peer, or let go by the person and written down. Ok(db.run("DELETE FROM _parked WHERE op_id = ? AND direction = 'push' AND reason LIKE ?", &[SqlValue::Text(op_id.to_string()), SqlValue::Text(format!("{UNDECODABLE}:%"))])? > 0) } /// How many queued writes were set aside because they did not decode, and wait for the person. pub fn undecodable_count(db: &Driver) -> Result { Ok(db .get("SELECT COUNT(*) AS n FROM _parked WHERE direction = 'push' AND reason LIKE ?", &[SqlValue::Text(format!("{UNDECODABLE}:%"))])? .and_then(|row| row.int("n")) .unwrap_or(0)) } /// THE FILE'S SHAPE MOVED: every parked `conflict` pull is due again, once. /// /// A constraint that refused a write is the file's, and it changes only when /// the shape does — a move to this build's schema, a column the copy takes /// for the object's definition, a table a package brings. Each of those calls /// this in its own transaction, and the sweep offers what it marks (never /// tried at this shape: `tried_at` cleared; `first_at` and `tries` stay). /// Answers how many are due. pub fn shape_changed(db: &Driver) -> Result { db.run( "UPDATE _parked SET tried_at = NULL WHERE direction = 'pull' AND class = 'conflict' AND tried_at IS NOT NULL", &[], ) } /// How a park ended — every way there is. Nothing else removes one. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Ended { /// A retry APPLIED it, or folded it as stale, retired or derived: this /// file no longer lacks the write. Resolved, /// A newer parked write of the same row names every column it names: the /// fold's last-writer-wins makes it stale against that one. Superseded, /// The peer TOOK a parked push. Delivered, /// The owner discarded it. Discarded, } /// End one park — THE ONE `DELETE FROM _parked`, asked only for an [`Ended`]. fn end_park(db: &Driver, op_id: &str, ended: Ended) -> Result { let direction = match ended { Ended::Delivered => " AND direction = 'push'", Ended::Resolved | Ended::Superseded | Ended::Discarded => "", }; db.run( // not a copy: a park ends only as it is ended: taken again by the release in the same transaction, taken by the peer, or let go by the person and written down. &format!("DELETE FROM _parked WHERE op_id = ?{direction}"), &[SqlValue::Text(op_id.to_string())], ) } /// The peer TOOK this parked push: the object holds the write, so the push /// side of its park ends (a phone's adopt marks each receipt it posted, /// `cotton_client::transport::object::mark_delivered`). Answers how many ended. pub fn delivered(db: &Driver, op_id: &str) -> Result { end_park(db, op_id, Ended::Delivered) } /// The OWNER discards these parks: the one end of a park that is not a /// resolution. Answers how many were discarded. pub fn discard(db: &Driver, op_ids: &[String]) -> Result { db.transaction(|db| { let mut discarded = 0; for op_id in op_ids { discarded += end_park(db, op_id, Ended::Discarded)?; } Ok(discarded) }) } /// The parked writes this op says everything for — and the earliest moment any /// of them was lost. /// /// **A row that will never land parks a write on EVERY PASS, and nothing used /// to take the last one away.** A repository whose creation lost an identity /// race is never created here, so the mirror's next `updated_at` arrives as a /// patch of the same ten columns, is INSERTed, meets `NOT NULL created_at`, and /// is parked under a new op id — once a minute, for ever. One standby Mac /// reached 41,112 parked ops for 485 rows: eighty-five copies each of one /// sentence, none of which could tell a person anything the newest did not. /// /// The rule is the fold's own. A column is last-write-wins, so an older upsert /// whose columns are a SUBSET of this one's contributes NOTHING once this one /// folds: every column it names, this one names too, with a newer stamp. Fold /// both or fold this one alone and the row is the same either way — so the /// older is not a write that is missing, it is a write that has been said /// again. /// /// Strictly upsert-over-upsert, strictly older, strictly a subset. A DELETE is /// not a patch and says something no upsert says; a patch that names a column /// this one does not is still the only copy of that column; and a newer parked /// write is not superseded by an older arrival, whatever it names. fn superseded_by( db: &Driver, op: &CottonOp, direction: Direction, ) -> Result<(Vec, Option)> { let Some(patch) = op.patch.as_ref().filter(|_| op.kind == OpKind::Upsert) else { return Ok((Vec::new(), None)); }; let columns: BTreeSet<&str> = patch.keys().map(String::as_str).collect(); let parked = db.all( "SELECT * FROM _parked WHERE direction = ? AND tbl = ? AND row_id = ?", &[ SqlValue::Text(direction.as_str().to_string()), SqlValue::Text(op.table.clone()), SqlValue::Text(op.row_id.clone()), ], )?; let mut dead: Vec = Vec::new(); let mut since: Option = None; for row in &parked { let older = row_to_rejected(row); let Some(hlc) = older.hlc.as_deref() else { continue; }; if older.kind != OpKind::Upsert.as_str() || hlc >= op.hlc.as_str() || older.op_id == op.op_id { continue; } let Some(patch) = older.patch.as_ref() else { continue; }; if !patch.keys().all(|column| columns.contains(column.as_str())) { continue; } if let Some(at) = row.text("first_at") { if since.as_deref().is_none_or(|kept| at < kept) { since = Some(at.to_string()); } } dead.push(older.op_id); } Ok((dead, since)) } /// HOW MANY writes this file knows it lost. /// /// A count rather than `list_parked(..).len()`, because the list is /// deliberately capped — it is a diagnostic screen's page — and a sentence that /// says "200 records need a look" to a file holding nine hundred of them is a /// number nobody can act on. The only caller so far is the join's merge report, /// which says the number and offers no list at all. pub fn count_parked(db: &Driver) -> Result { Ok(db .get("SELECT COUNT(*) AS n FROM _parked WHERE class <> 'newer-shape'", &[])? .and_then(|row| row.int("n")) .unwrap_or(0) .max(0) as usize) } /// Every write this file knows it lost, newest first. A `newer-shape` park is /// not lost — it folds once this file moves — and is not listed. pub fn list_parked(db: &Driver, limit: i64) -> Result> { Ok(db .all( "SELECT * FROM _parked WHERE class <> 'newer-shape' \ ORDER BY first_at DESC, op_id DESC LIMIT ?", &[SqlValue::Integer(limit)], )? .iter() .map(row_to_rejected) .collect()) } /// Every write of one row this file parked as a `conflict`. pub(crate) fn conflicts_of_row(db: &Driver, table: &str, row_id: &str) -> Result> { Ok(db .all( "SELECT * FROM _parked WHERE class = ? AND tbl = ? AND row_id = ?", &[ SqlValue::Text(Class::Conflict.as_str().to_string()), SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string()), ], )? .iter() .map(row_to_rejected) .collect()) } /// One stored row as the record it is: the park's own columns, and the /// write read out of its receipt bytes. fn row_to_rejected(row: &crate::driver::Row) -> RejectedOp { let op_id = row.text("op_id").unwrap_or_default().to_string(); let bytes = match row.get("bytes") { Some(SqlValue::Blob(bytes)) => Some(bytes.clone()), Some(SqlValue::Text(text)) => Some(text.as_bytes().to_vec()), _ => None, }; let op = bytes .as_deref() .and_then(|bytes| crate::wire::from_bytes(op_id.clone(), bytes).ok()); RejectedOp { direction: row.text("direction").unwrap_or_default().to_string(), class: row.text("class").unwrap_or_default().to_string(), table: row.text("tbl").unwrap_or_default().to_string(), row_id: row.text("row_id").unwrap_or_default().to_string(), kind: op.as_ref().map(|op| op.kind.as_str().to_string()).unwrap_or_default(), reason: row.text("reason").unwrap_or_default().to_string(), at: row.text("first_at").unwrap_or_default().to_string(), patch: op.as_ref().and_then(|op| op.patch.clone()), hlc: op.as_ref().map(|op| op.hlc.clone()), device_id: op.as_ref().map(|op| op.device_id.clone()), schema_version: op.as_ref().map(|op| op.schema_version), retried_at: row .text("tried_at") .filter(|at| !at.is_empty()) .map(str::to_string), retries: row.int("tries").unwrap_or(0), bytes, sig: match row.get("sig") { Some(SqlValue::Blob(sig)) => Some(sig.clone()), _ => None, }, op_id, } } /// The newest schema version a parked PULL was minted at — a write this /// build may be too old to fold — or `None` with no parked pull. pub fn newest_parked_schema(db: &Driver) -> Result> { Ok(db .all("SELECT * FROM _parked WHERE direction = 'pull'", &[])? .iter() .filter_map(|row| row_to_rejected(row).schema_version) .max()) } /// The parked row as the op it WAS. /// /// Answers a sentence rather than a partial op when the row cannot be one: a /// row parked by a build before version 8 has no patch, no stamp and no author, /// and inventing any of the three would be a write nobody made. `Ok(None)` is /// the honest answer and its reason travels beside it. /// /// The op id is the ORIGINAL one, not a new one, which is what makes a retry /// idempotent: the fold has already decided this stamp's fate for every column /// it names, so folding it twice costs a stale verdict and never a second /// write. pub fn rebuild(row: &RejectedOp) -> std::result::Result { crate::stored::rejected_row(row) } /// Offer parked writes to the fold again — `None` for every one of them. /// /// In STAMP ORDER, for the reason the exchange sorts a page by stamp: the /// oldest op of a row carries the whole row, so a creation that is itself /// parked has to be folded before the amendment that was parked with it. /// /// ONE FOLD FOR THE WHOLE OFFER, as a page is one fold ([`fold_parked`]): /// every verdict is read back by op id, so one op's refusal is never reported /// against its neighbour, and the fold's own second pass lands a child offered /// beside its parent. pub fn retry_rejected( db: &Driver, ids: Option<&[String]>, now: &str, ) -> Result { let rows = select(db, ids)?; Ok(fold_parked(db, &rows, now)?.0) } /// The reason a receipt minted above this file's schema is parked under. pub const NEWER_SHAPE: &str = "newer-shape: "; /// The parked reason for a receipt minted at `minted` in a file at `stamp`. #[must_use] pub fn newer_shape_reason(minted: u32, stamp: u32) -> String { format!("{NEWER_SHAPE}minted at schema {minted}; this file is at {stamp} and folds it once it moves") } /// Whether this file's `_parked` can hold a `newer-shape` park — its CHECK /// names the class. Read off the file itself, so the parking switches on in /// the build whose rise brings the CHECK (rise 136) and in no build before it: /// until then a receipt above the file meets the fold as it always has. pub fn keeps_newer_shape(db: &Driver) -> Result { Ok(db .get("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = '_parked'", &[])? .and_then(|row| row.text("sql").map(|sql| sql.contains("'newer-shape'"))) .unwrap_or(false)) } /// This file's stamp when it parks receipts above it as `newer-shape`; /// `None` in a file that cannot ([`keeps_newer_shape`]). pub fn newer_shape_stamp(db: &Driver) -> Result> { if keeps_newer_shape(db)? { Ok(Some(crate::meta::file_schema_version(db)?)) } else { Ok(None) } } /// Park, as `newer-shape`, every receipt of `ops` minted above this file's /// schema, and answer the rest — the ones the fold is offered. A file that /// cannot hold the class parks nothing and answers every op. /// /// `Pull` whichever way the receipt arrived: in `_parked` that is "a write /// that exists on the other side and this file has not taken" — what a held /// receipt is — and [`retry_rejected`] folds only pulls. `at` is the time a /// park is dated. pub fn park_newer_shape( db: &Driver, ops: &[CottonOp], at: impl Fn(&CottonOp) -> String, ) -> Result> { let Some(stamp) = newer_shape_stamp(db)? else { return Ok(ops.to_vec()); }; let mut rest = Vec::with_capacity(ops.len()); for op in ops { if op.schema_version > stamp { park( db, op, Direction::Pull, Class::NewerShape, &newer_shape_reason(op.schema_version, stamp), &at(op), )?; } else { rest.push(op.clone()); } } Ok(rest) } /// RIGHT AFTER A SHAPE MOVE: offer every `newer-shape` park to the fold — the /// ones this file now holds the schema for fold, the rest stay parked. The Mac /// calls it from its start-up move (`cotton-server` `startup_schema`), the /// phone from its heal (`cotton-client` `bootstrap::not_moved::clear`). pub fn refold_newer_shape(db: &Driver, now: &str) -> Result { // A package shape this file's definitions declare and it does not hold // yet is taken first — the start-up move and the phone's open are when a // file written by an earlier build catches up — so what waited for it // folds in the same pass (`schema::package_shape`). A refused package // shape changes nothing and its rows keep waiting. crate::schema::package_shape::step_file(db)?; fold_newer_shape(db, now) } /// Offer every `newer-shape` park to the fold, after a step. pub(crate) fn fold_newer_shape(db: &Driver, now: &str) -> Result { let rows: Vec = select(db, None)? .into_iter() .filter(|row| row.class == Class::NewerShape.as_str()) .collect(); Ok(fold_parked(db, &rows, now)?.0) } /// The reason a receipt is parked under while its author has no fact here. pub const WAITING_FOR_AUTHOR: &str = "waiting: author fact for "; /// The parked reason for a receipt of `author`. pub fn waiting_reason(author: &str) -> String { format!("{WAITING_FOR_AUTHOR}{author}") } /// The reason a receipt is parked under while its author, held here, is no /// serving author YET (`serving::awaits_a_serving_fact`): its actor names /// another device, and the serving fact that would let it is not here. pub const WAITING_FOR_SERVING: &str = "waiting: a serving fact naming the Mac of "; /// The parked reason for a receipt of `author` that waits for a serving fact. pub fn waiting_for_serving_reason(author: &str) -> String { format!("{WAITING_FOR_SERVING}{author}, which would let it write for another device") } /// Park the receipts a fold held back for their author's fact, whole, /// `waiting`, under the waiting reason — in the direction they arrived. `at` is when they were /// held back. pub fn park_waiting( db: &Driver, ops: &[CottonOp], waiting: &[crate::fold::Waiting], direction: Direction, at: &str, ) -> Result { let mut parked = 0; for held in waiting { if let Some(op) = ops.iter().find(|op| op.op_id == held.op_id) { park(db, op, direction, Class::Waiting, &waiting_reason(&held.author), at)?; parked += 1; } } Ok(parked) } /// Offer every receipt parked for `author`'s fact to the fold again — called /// the moment that fact applies, so a stream that arrived before its author /// lands as soon as the author does. In stamp order, like every retry. /// /// The same trigger for a receipt waiting for the SERVING fact that makes /// `author` a serving author ([`WAITING_FOR_SERVING`]): the fold announces /// those authors when it takes the fact (`fact_hooks::announced`). A retry /// that finds the author still no serving author parks it `conflict`. pub fn retry_waiting_for(db: &Driver, author: &str, now: &str) -> Result { let rows = db.all( "SELECT op_id FROM _parked WHERE reason IN (?, ?) ORDER BY op_id", &[ SqlValue::Text(waiting_reason(author)), SqlValue::Text(waiting_for_serving_reason(author)), ], )?; let ids: Vec = rows .iter() .filter_map(|row| row.text("op_id").map(str::to_string)) .collect(); if ids.is_empty() { return Ok(RetryReport::default()); } retry_rejected(db, Some(&ids), now) } /// [`retry_rejected`] over these op ids, answering also the ROWS that landed — /// what [`retry_touched_rows`]' next round starts from. fn retry_rows( db: &Driver, ids: &[String], now: &str, ) -> Result<(RetryReport, Vec<(String, String)>)> { let rows = select(db, Some(ids))?; fold_parked(db, &rows, now) } /// Offer these parked rows to the fold, oldest stamp first, in one /// transaction and ONE fold; answers the report and the rows whose ops left /// the table. /// /// **One fold, never one per park** (3 Nov 2026). A fold is a batch's worth of /// work whatever it carries — the batch's reads, the engines a process /// installs ([`crate::derived::after_fold`]: on a phone the money engine works /// every account's run out again when a money row lands) — so a parent that /// unblocked 8,870 money rows, each folded alone, worked the whole book out /// 8,870 times: the pass that held them took 2,680 s against 70–140 s for /// every other, and on the phone no page of it finished before iOS suspended /// the app. Folded together they cost one fold. The parks that cannot reach /// the fold — still above this file's shape, said again under the author's /// new name, unreadable — are settled first, each on its own row. fn fold_parked( db: &Driver, rows: &[RejectedOp], now: &str, ) -> Result<(RetryReport, Vec<(String, String)>)> { if rows.is_empty() { return Ok((RetryReport::default(), Vec::new())); } let report = db.transaction(|db| { let mut report = RetryReport::default(); let held_above = newer_shape_stamp(db)?; let mut offered: Vec<&RejectedOp> = Vec::with_capacity(rows.len()); let mut ops: Vec = Vec::with_capacity(rows.len()); for row in rows { if let Some(op) = offerable(db, row, held_above, now, &mut report)? { offered.push(row); ops.push(op); } } if ops.is_empty() { return Ok(report); } let result = arrive(db, &ops, Arrival::Pulled)?; let verdicts = Verdicts::of(&result); for (row, op) in offered.iter().zip(&ops) { settle_retry(db, row, op, &verdicts, now, &mut report)?; } Ok(report) })?; let folded: BTreeSet<&str> = report.folded.iter().map(String::as_str).collect(); let landed: BTreeSet<(String, String)> = rows .iter() .filter(|row| folded.contains(row.op_id.as_str())) .map(|row| (row.table.clone(), row.row_id.clone())) .collect(); Ok((report, landed.into_iter().collect())) } /// The automatic pass: retry only what the rows a fold JUST TOUCHED could have /// unblocked — and then what THAT unblocked, until nothing more lands. /// /// Scoped, never a full sweep. A page that named eleven rows must not walk a /// list of every write this device has ever lost — most of them are waiting on /// something nothing in this page touched, and the sweep would run on every /// page of every cycle for ever. /// /// **TOUCHED, not APPLIED.** The caller passes the rows the page NAMED /// ([`crate::exchange::named_rows`]) or the rows a local write moved. Scoping /// this to what the fold APPLIED is what made the mechanism a no-op on the /// files that needed it most: a row whose CREATION is refused — a foreign key /// pointing at a parent this file has not got, a unique key a local twin /// holds — never has an applied op, so it was never in the scope, so its park /// was never re-offered, so the row could never heal even after the blocker /// went away. On one standby Mac every one of 23,841 parked ops still read /// `retries = 0`. /// /// **A touched row reaches the parks WAITING ON IT, not only its own.** The /// scope is a touched row's own parked ops PLUS every parked pull whose /// foreign key names it ([`waiting_on`]) — the child that arrived pages before /// its parent. An exchange answer is not causal across pages: one author's /// page is answered before another's. Without this the child waited for the /// drain, 500 parks a minute. /// /// **To a fixpoint.** The rows a retry LANDS are touched too, so the next /// round offers what waited on them — a message waiting on a thread that was /// itself waiting on a contact lands in the same transaction as the contact. /// Each round folds at least one parked op or ends, so it ends; and every /// verdict is the fold's own ([`fold_pulled`], one implementation of who wins). /// /// **The bound.** A landed row re-offers its own parks and only the parks /// whose foreign key to a NON-hub parent names it. A key to one of /// [`HUB_PARENTS`] is never followed, so touching the workspace row (a rename, /// a join's first page) re-offers nothing but that row's own parks; a park /// that waits on its workspace is [`sweep_parked`]'s. /// /// **What the caller's fold just refused is not offered again by the first /// round** (`judged`: the op ids that fold refused or held). Nothing has moved /// since that verdict, so the same fold would give it again — a page of 5,000 /// refusals used to fold each of them twice. Only a park that LANDS in a round /// moves anything, and the next round, which offers everything waiting on what /// landed, offers them too. pub fn retry_touched_rows( db: &Driver, touched_rows: &[(String, String)], judged: &BTreeSet<&str>, now: &str, ) -> Result { if touched_rows.is_empty() || count_pulls(db)? == 0 { return Ok(RetryReport::default()); } let keys = parked_foreign_keys(db)?; let mut folded: Vec = Vec::new(); let mut refused: BTreeMap = BTreeMap::new(); let mut frontier: Vec<(String, String)> = touched_rows.to_vec(); let mut first = true; while !frontier.is_empty() { let mut ids: BTreeSet = BTreeSet::new(); for_each_parked(db, "pull", &frontier, "op_id", None, |row| { ids.insert(row.text("op_id").unwrap_or_default().to_string()); Ok(()) })?; ids.extend(waiting_on(db, &keys, &frontier)?); if std::mem::take(&mut first) { let (now_judged, rest): (BTreeSet, BTreeSet) = ids.into_iter().partition(|id| judged.contains(id.as_str())); judged_at(db, &now_judged, now)?; ids = rest; } if ids.is_empty() { break; } let ids: Vec = ids.into_iter().collect(); let (pass, landed) = retry_rows(db, &ids, now)?; for op_id in &pass.folded { refused.remove(op_id); } refused.extend(pass.still_rejected); folded.extend(pass.folded); frontier = landed; } Ok(RetryReport { folded, still_rejected: refused.into_iter().collect(), }) } /// The caller's fold judged these parks at `now`: that verdict is their try /// at this shape (`tried_at`, which the sweep's once-at-each-shape reads for a /// `conflict`). `tries` counts offers AGAIN, and this was none. fn judged_at(db: &Driver, ids: &BTreeSet, now: &str) -> Result<()> { let ids: Vec<&String> = ids.iter().collect(); for chunk in ids.chunks(ROW_CHUNK) { let holes = vec!["?"; chunk.len()].join(", "); let mut params = vec![SqlValue::Text(now.to_string())]; params.extend(chunk.iter().map(|id| SqlValue::Text((*id).clone()))); db.run(&format!("UPDATE _parked SET tried_at = ? WHERE op_id IN ({holes})"), ¶ms)?; } Ok(()) } /// Parents whose foreign keys [`retry_touched_rows`] never follows. /// /// `cotton_workspaces` is the one: every synced row names its workspace (over /// a hundred foreign keys point at it), so following it would turn ONE touched /// row — a rename, the first page of a join — into a re-fold of every parked /// creation in the file, inside a local write, an exchange page or the /// server's ingest lock. And it buys nothing: the workspace row is seeded or provisioned /// before any row that points at it, so it never lands late in a fold. A park /// that really is waiting on its workspace is left to [`sweep_parked`]. pub const HUB_PARENTS: &[&str] = &["cotton_workspaces"]; /// One single-column foreign key of a table that has parked pulls: the parked /// op's `column` names a row of `parent` by the parent's `referenced` column /// (`None` for its primary key). #[derive(Debug, Clone)] struct WaitingKey { child: String, column: String, parent: String, referenced: Option, } /// The foreign keys of every table this file holds parked pulls for — read /// off the FILE (`pragma_foreign_key_list`), so a phone at an older version /// answers with its own schema's keys, less every key to one of /// [`HUB_PARENTS`]. Read once per [`retry_touched_rows`]: /// one `DISTINCT` over `idx_parked_row`'s `(direction, tbl)` prefix, then one /// pragma per parked table. fn parked_foreign_keys(db: &Driver) -> Result> { let tables: Vec = db .all( "SELECT DISTINCT tbl FROM _parked WHERE direction = 'pull'", &[], )? .iter() .filter_map(|row| row.text("tbl").map(str::to_string)) .collect(); let mut keys = Vec::new(); for child in tables { for row in db.all( "SELECT \"from\" AS col, \"table\" AS parent, \"to\" AS referenced \ FROM pragma_foreign_key_list(?)", &[SqlValue::Text(child.clone())], )? { let (Some(column), Some(parent)) = (row.text("col"), row.text("parent")) else { continue; }; if HUB_PARENTS.contains(&parent) { continue; } keys.push(WaitingKey { child: child.clone(), column: column.to_string(), parent: parent.to_string(), referenced: row .text("referenced") .filter(|column| !column.is_empty()) .map(str::to_string), }); } } Ok(keys) } /// The parked pulls whose foreign key names one of `rows` — the children that /// were refused because one of these rows was not here yet. /// /// Per CHILD TABLE, one pass over its parks (`idx_parked_row`'s /// `(direction, tbl)` prefix), each read out of its receipt ONCE and matched /// in memory against every key of that table whose parent `rows` touch — never /// one pass per key: a money row has a key per account, category, person and /// statement, and a page naming a row of each read every park four times. An /// amendment whose patch does not name the column is not matched here; it is /// its own row's park, and that row landing reaches it next round. fn waiting_on( db: &Driver, keys: &[WaitingKey], rows: &[(String, String)], ) -> Result> { let mut by_table: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); for (table, row_id) in rows { by_table.entry(table.as_str()).or_default().push(row_id.as_str()); } // Each child table's keys whose parent this round touched, with the // values that parent's touched rows answer to. let mut wanted: BTreeMap<&str, Vec<(&str, BTreeSet)>> = BTreeMap::new(); for key in keys { let Some(row_ids) = by_table.get(key.parent.as_str()) else { continue; }; let values = key_values(db, key, row_ids)?; if !values.is_empty() { wanted.entry(key.child.as_str()).or_default().push((key.column.as_str(), values)); } } let mut waiting = BTreeSet::new(); for (child, columns) in wanted { for row in db.all( "SELECT * FROM _parked WHERE direction = 'pull' AND tbl = ?", &[SqlValue::Text(child.to_string())], )? { let parked = row_to_rejected(&row); let Some(patch) = parked.patch.as_ref() else { continue; }; let names_one = columns.iter().any(|(column, values)| { let parent = match patch.get(*column) { Some(JsonValue::String(text)) => Some(text.clone()), Some(JsonValue::Number(n)) => Some(n.to_string()), _ => None, }; parent.is_some_and(|parent| values.contains(&parent)) }); if names_one { waiting.insert(parked.op_id); } } } Ok(waiting) } /// The values a child's foreign key holds for these parent rows: the row ids /// themselves when the key references the primary key, else the referenced /// column read off each parent row. fn key_values(db: &Driver, key: &WaitingKey, row_ids: &[&str]) -> Result> { let Some(spec) = crate::schema::specs::spec_for(&key.parent) else { return Ok(BTreeSet::new()); }; let referenced = match key.referenced.as_deref() { None => return Ok(row_ids.iter().map(|id| (*id).to_string()).collect()), Some(column) if column == spec.pk => { return Ok(row_ids.iter().map(|id| (*id).to_string()).collect()) } Some(column) => column, }; let mut values = BTreeSet::new(); for chunk in row_ids.chunks(ROW_CHUNK) { let holes = vec!["?"; chunk.len()].join(", "); for row in db.all( &format!( "SELECT \"{referenced}\" AS v FROM \"{parent}\" WHERE \"{pk}\" IN ({holes})", parent = key.parent, pk = spec.pk, ), &chunk .iter() .map(|id| SqlValue::Text((*id).to_string())) .collect::>(), )? { match row.text("v") { Some(text) => { values.insert(text.to_string()); } None => { if let Some(n) = row.int("v") { values.insert(n.to_string()); } } } } } Ok(values) } /// How many parked pulls one [`sweep_parked`] offers to the fold. /// /// FIVE HUNDRED, and it is a rate rather than a limit: the sweep runs once per /// sync cycle (a minute). Large enough that a parent and the children that /// were parked waiting for it are nearly always in the SAME batch — the batch /// is offered in stamp order — and small enough that a file nothing can heal /// never spends a whole cycle discovering that again. pub const PARK_SWEEP_OPS: usize = 500; /// What one [`sweep_parked`] found and what it did about it. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct SweepReport { /// Parked PULLS in the file when the sweep started. pub parked: usize, /// How many of them this sweep offered to the fold. pub retried: usize, /// How many of those ended — applied, stale or retired, which all mean /// this file no longer lacks the write. pub cleared: usize, /// Parks the owner's board names after the sweep ([`board`]): every /// `conflict`, and every `waiting` older than [`WAITING_SHOWN_AFTER_DAYS`]. pub shown: usize, } impl SweepReport { /// Did this sweep have anything to say? #[must_use] pub fn is_empty(self) -> bool { self.parked == 0 && self.shown == 0 } } /// THE DRAIN: a bounded, rotating pass over every parked pull, run once a /// cycle. /// /// [`retry_touched_rows`] answers "the rest of this row has arrived" and "the /// row this one POINTS AT has arrived", for the rows a page or a write moves. /// It cannot answer for a park nothing will ever name again — the peer's /// cursor is past it. /// /// So each cycle takes [`PARK_SWEEP_OPS`] of them, NEVER-TRIED FIRST and then /// least-recently-tried, and inside that in STAMP ORDER — a creation before the /// amendment that was parked with it, a parent before the child whose foreign /// key wanted it. A retry that fails stamps `tried_at` and counts one more /// `tries`, and so goes to the back of the queue; one that lands ends its park. /// A park is never dropped for being refused often, however often; it stays /// until it applies, is folded as stale, or the owner discards it. /// /// A `conflict` is offered ONCE AT EACH SHAPE: a tried one is left parked /// until its row moves ([`retry_touched_rows`]) or the shape does /// ([`shape_changed`]), since nothing a clock does changes a constraint. /// The rotation is the waiting parks', whose cause can arrive in any page. pub fn sweep_parked(db: &Driver, limit: usize, now: &str) -> Result { let parked = count_pulls(db)?; let shown = board(db, now)?.len(); if parked == 0 { return Ok(SweepReport { shown, ..SweepReport::default() }); } // NULLS FIRST, then oldest attempt, then oldest park. No index answers // this order, so it is a scan of `_parked` once per cycle. let ids: Vec = db .all( "SELECT op_id FROM _parked WHERE direction = 'pull' \ AND (class <> 'conflict' OR tried_at IS NULL) \ ORDER BY (tried_at IS NOT NULL), tried_at, first_at, op_id LIMIT ?", &[SqlValue::Integer(i64::try_from(limit.max(1)).unwrap_or(i64::MAX))], )? .iter() .map(|row| row.text("op_id").unwrap_or_default().to_string()) .collect(); let report = retry_rejected(db, Some(&ids), now)?; Ok(SweepReport { parked, retried: ids.len(), cleared: report.folded.len(), shown: board(db, now)?.len(), }) } /// How old a `waiting` park is before the owner's board names it. pub const WAITING_SHOWN_AFTER_DAYS: i64 = 7; /// The owner's board: ONE LINE per park the owner should see — every /// `conflict`, and every `waiting` first parked more than /// [`WAITING_SHOWN_AFTER_DAYS`] days before `now`. Oldest first. pub fn board(db: &Driver, now: &str) -> Result> { let rows = db.all( "SELECT * FROM _parked \ WHERE class = 'conflict' \ OR (class = 'waiting' AND julianday(?) - julianday(first_at) > ?) \ ORDER BY first_at, op_id", &[ SqlValue::Text(now.to_string()), SqlValue::Integer(WAITING_SHOWN_AFTER_DAYS), ], )?; Ok(rows .iter() .map(|row| { let parked = row_to_rejected(row); format!( "A {} write to {} {} is parked {} since {}: {}", parked.direction, parked.table, parked.row_id, parked.class, parked.at, parked.reason ) }) .collect()) } /// How many parked PULLS the file holds — the sweep's own denominator. fn count_pulls(db: &Driver) -> Result { Ok(db .get( "SELECT COUNT(*) AS n FROM _parked WHERE direction = 'pull'", &[], )? .and_then(|row| row.int("n")) .unwrap_or(0) .max(0) as usize) } /// How many row ids go into one `IN (…)`. /// /// A bound, not a tuning knob: SQLite refuses a statement past its variable /// ceiling, and `applied_rows` is however many rows one exchange page moved. const ROW_CHUNK: usize = 400; /// The parked ops of the rows a fold just moved — ONE query per table, never /// one per row. /// /// Grouped by table so `idx_parked_row` is READ the way it is built — /// `direction` and `tbl` pinned, `row_id` the range. /// /// The rows arrive in no particular order; a caller that needs stamp order /// sorts what it collected, because the order that matters spans tables and no /// single query has all of them. fn for_each_parked( db: &Driver, direction: &str, applied_rows: &[(String, String)], columns: &str, max_retries: Option, mut visit: impl FnMut(&Row) -> Result<()>, ) -> Result<()> { let mut by_table: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); for (table, row_id) in applied_rows { by_table .entry(table.as_str()) .or_default() .insert(row_id.as_str()); } for (table, row_ids) in by_table { let row_ids: Vec<&str> = row_ids.into_iter().collect(); for chunk in row_ids.chunks(ROW_CHUNK) { let holes = vec!["?"; chunk.len()].join(", "); let ceiling = if max_retries.is_some() { " AND tries < ?" } else { "" }; let sql = format!( "SELECT {columns} FROM _parked \ WHERE direction = ? AND tbl = ? AND row_id IN ({holes}){ceiling}" ); let mut params: Vec = Vec::with_capacity(chunk.len() + 3); params.push(SqlValue::Text(direction.to_string())); params.push(SqlValue::Text(table.to_string())); params.extend(chunk.iter().map(|id| SqlValue::Text((*id).to_string()))); if let Some(ceiling) = max_retries { params.push(SqlValue::Integer(ceiling)); } for row in db.all(&sql, ¶ms)? { visit(&row)?; } } } Ok(()) } /// The rows a retry may act on, oldest stamp first. /// /// `direction = 'pull'` is the whole of the filter and the module header says /// why: a `push` row is the PEER's verdict on our own write, and no local fold /// can change it. pub(crate) fn select(db: &Driver, ids: Option<&[String]>) -> Result> { let rows = match ids { None => db.all( "SELECT * FROM _parked WHERE direction = 'pull'", &[], )?, Some([]) => return Ok(Vec::new()), // Chunked, and sorted afterwards rather than by SQLite: a caller can // hand this every parked op of every row one page moved, and a single // `IN (…)` past SQLite's variable ceiling is a statement it refuses // outright — a retry that stops working on exactly the file that needs // it most. Some(ids) => { let mut rows: Vec = Vec::new(); for chunk in ids.chunks(ROW_CHUNK) { let holes = vec!["?"; chunk.len()].join(", "); rows.extend(db.all( &format!( "SELECT * FROM _parked WHERE direction = 'pull' AND \ op_id IN ({holes})" ), &chunk .iter() .map(|id| SqlValue::Text(id.clone())) .collect::>(), )?); } rows } }; let mut parked: Vec = rows.iter().map(row_to_rejected).collect(); parked.sort_by(|a, b| { (a.hlc.as_deref(), a.op_id.as_str()).cmp(&(b.hlc.as_deref(), b.op_id.as_str())) }); Ok(parked) } /// One parked row, readied for the fold — or settled here, on its own row, /// when it cannot reach it: still above this file's shape, said again under /// the author's new name, or no op to rebuild. `Some` is the op the fold is /// offered, THROUGH [`arrive`], as a write taken from the peer's answer, so it /// meets every arrival check a fresh arrival meets. fn offerable( db: &Driver, row: &RejectedOp, held_above: Option, now: &str, report: &mut RetryReport, ) -> Result> { // STILL ABOVE THIS FILE: a receipt of a newer shape is not offered to the // fold until this file has moved to its schema, whatever woke the retry. if let (Some(stamp), Some(minted)) = (held_above, row.schema_version) { if minted > stamp { let reason = newer_shape_reason(minted, stamp); keep(db, &row.op_id, Class::NewerShape, &reason, now)?; report.still_rejected.push((row.op_id.clone(), reason)); return Ok(None); } } // SAID AGAIN UNDER THE AUTHOR'S NEW NAME: the copy's own earlier reading // of a row the writer serves again — this file no longer lacks it. if said_again_under_a_new_name(db, row)? { end_park(db, &row.op_id, Ended::Superseded)?; report.folded.push(row.op_id.clone()); return Ok(None); } match rebuild(row) { Ok(op) => Ok(Some(op)), Err(reason) => { keep(db, &row.op_id, Class::Conflict, &reason, now)?; report.still_rejected.push((row.op_id.clone(), reason)); Ok(None) } } } /// One fold's verdicts, by op id: the first of each kind the fold gave. struct Verdicts<'a> { rejected: BTreeMap<&'a str, &'a str>, waiting: BTreeMap<&'a str, &'a str>, parked: BTreeMap<&'a str, &'a str>, resolved: BTreeSet<&'a str>, } impl<'a> Verdicts<'a> { fn of(result: &'a crate::fold::FoldResult) -> Verdicts<'a> { let mut rejected = BTreeMap::new(); for rejection in &result.rejected { rejected.entry(rejection.op_id.as_str()).or_insert(rejection.reason.as_str()); } let mut waiting = BTreeMap::new(); for held in &result.waiting { waiting.entry(held.op_id.as_str()).or_insert(held.author.as_str()); } let mut parked = BTreeMap::new(); for held in &result.parked { parked.entry(held.op_id.as_str()).or_insert(held.reason.as_str()); } let resolved = result .applied .iter() .chain(&result.skipped_stale) .chain(&result.skipped_retired) .map(String::as_str) .collect(); Verdicts { rejected, waiting, parked, resolved } } } /// What the fold made of one offered park: it ends, or it stays with the /// verdict this fold gave it. fn settle_retry( db: &Driver, row: &RejectedOp, op: &CottonOp, verdicts: &Verdicts<'_>, now: &str, report: &mut RetryReport, ) -> Result<()> { let id = op.op_id.as_str(); if let Some(reason) = verdicts.rejected.get(id) { keep(db, &row.op_id, Class::of_refusal(reason), reason, now)?; report.still_rejected.push((row.op_id.clone(), (*reason).to_string())); return Ok(()); } // Held back for its author's fact: it stays parked `waiting` until that // author announces itself ([`retry_waiting_for`]). if let Some(author) = verdicts.waiting.get(id) { let reason = waiting_reason(author); keep(db, &row.op_id, Class::Waiting, &reason, now)?; report.still_rejected.push((row.op_id.clone(), reason)); return Ok(()); } // Parked by the fold itself — a re-stamp or a fact that lost: `conflict`; // an author waiting for its serving fact: `waiting` (read off the reason). if let Some(reason) = verdicts.parked.get(id) { keep(db, &row.op_id, Class::of_refusal(reason), reason, now)?; report.still_rejected.push((row.op_id.clone(), (*reason).to_string())); return Ok(()); } // APPLIED, STALE or RETIRED — one meaning here: this file no // longer lacks the write, and the park ends. if !verdicts.resolved.contains(id) { let reason = "the fold gave this write no verdict".to_string(); keep(db, &row.op_id, Class::Conflict, &reason, now)?; report.still_rejected.push((row.op_id.clone(), reason)); return Ok(()); } end_park(db, &row.op_id, Ended::Resolved)?; report.folded.push(row.op_id.clone()); Ok(()) } /// The prefix the retired author names carried (slice 2b): an author once /// stamped `server:` is stamped `` now. /// /// A copy mints the receipts of the rows a writer that keeps no receipts /// serves (`mint::served`), under that writer's author name, so a receipt of /// the retired name is this copy's own earlier reading of a row the writer /// still holds and serves again under the new one — never a write that /// exists only on the other side. The personal object was stamped under the /// retired name until 27 Oct 2026 and is `object` since /// (`cotton_client::transport::object::OBJECT_AUTHOR`): on one phone 158 of /// its old receipts sat parked beside the new name's readings of the same /// rows, refused for what the earlier build made of them. pub const RETIRED_AUTHOR_PREFIX: &str = "server:"; /// The name a retired author name is stamped as now, or `None` for a name /// that was never retired. pub fn now_named(author: &str) -> Option<&str> { author.strip_prefix(RETIRED_AUTHOR_PREFIX).filter(|name| !name.is_empty()) } /// Whether `row` is a pulled receipt of a retired author name whose row this /// file holds a receipt of under the name it is stamped as now /// ([`now_named`]), from the same moment or later — folded or itself parked: /// the writer said that row again, and the old reading says nothing the new /// one does not stand for. fn said_again_under_a_new_name(db: &Driver, row: &RejectedOp) -> Result { let Some(hlc) = row.hlc.as_deref().filter(|_| row.direction == Direction::Pull.as_str()) else { return Ok(false); }; let Some(author) = crate::fold::author_of(hlc) else { return Ok(false); }; let Some(now_named) = now_named(author) else { return Ok(false); }; let moment = hlc.get(..13).unwrap_or(hlc); let address = [SqlValue::Text(row.table.clone()), SqlValue::Text(row.row_id.clone())]; let folded = db .get( "SELECT 1 AS n FROM _writes WHERE tbl = ? AND row_id = ? AND substr(hlc, 20) = ? AND substr(hlc, 1, 13) >= ?", &[address[0].clone(), address[1].clone(), SqlValue::Text(now_named.to_string()), SqlValue::Text(moment.to_string())], )? .is_some(); if folded { return Ok(true); } Ok(db .all("SELECT * FROM _parked WHERE direction = 'pull' AND tbl = ? AND row_id = ?", &address)? .iter() .map(row_to_rejected) .filter_map(|parked| parked.hlc) .any(|stamp| crate::fold::author_of(&stamp) == Some(now_named) && stamp.get(..13).unwrap_or(&stamp) >= moment)) } /// How many times a parked PUSH is put back in the queue before this file stops /// asking. /// /// THREE. A push is refused by a constraint on the peer, and a constraint does /// not change its mind — what changes is the row, which is why the retry is /// woken by a local write rather than by a clock. Three of those is enough for /// the case this exists for (the write that lost a race with its own /// neighbour) and few enough that a write which genuinely cannot land stops /// costing an exchange slot on every cycle. Past the ceiling the row stays /// parked with its patch, which is what a person reads. pub const PUSH_RETRY_CEILING: i64 = 3; /// Offer parked PUSHES to the peer again — the ones whose rows a fold JUST /// CHANGED. /// /// The push twin of [`retry_touched_rows`], and the difference is where the /// write is missing. A refused PULL is missing HERE, so the retry is a fold. A /// refused PUSH is missing THERE: this file has the row, the peer does not, and /// nothing a local fold does can change that. The op goes back in the /// `_outbox`, with its ORIGINAL op id and stamp — which is what makes the /// retry idempotent, exactly as [`rebuild`] says: the peer has already decided /// this stamp's fate for every column the op names, so asking twice costs a /// stale verdict and never a second write. /// /// The parked row STAYS. It is cleared by [`clear_delivered_pushes`] when the /// peer takes the op, so a person reading `_parked` is reading writes that are /// still missing rather than writes that were once missing. /// /// Answers the op ids it queued. pub fn requeue_touched_pushes( db: &Driver, applied_rows: &[(String, String)], now: &str, ) -> Result> { if applied_rows.is_empty() { return Ok(Vec::new()); } let mut queued: Vec = Vec::new(); db.transaction(|db| { let mut rows: Vec = Vec::new(); for_each_parked( db, "push", applied_rows, "*", Some(PUSH_RETRY_CEILING), |row| { rows.push(row_to_rejected(row)); Ok(()) }, )?; // One stamp order over the whole batch, not one per row: the ops of two // rows can interleave, and the outbox drains in the order it was given. rows.sort_by(|a, b| { (a.hlc.as_deref(), a.op_id.as_str()).cmp(&(b.hlc.as_deref(), b.op_id.as_str())) }); for row in &rows { // Already queued: a second requeue before the drain reached it // would be the same op twice, and `_outbox.op_id` is a primary // key. let waiting = db .get( "SELECT op_id FROM _outbox WHERE op_id = ?", &[SqlValue::Text(row.op_id.clone())], )? .is_some(); if waiting { continue; } let op = match rebuild(row) { Ok(op) => op, // One set aside because it did not decode keeps its word, so it is still counted and said by it // (QUEUE BAD OP 2). Err(_) if is_undecodable(Some(row.reason.as_str())) => continue, Err(reason) => { // A park with no readable receipt: there is no op to // re-offer. Said once, on the row. keep(db, &row.op_id, Class::Conflict, &reason, now)?; continue; } }; crate::outbox::queue_ops(db, std::slice::from_ref(&op), now)?; db.run( "UPDATE _parked SET tries = tries + 1, tried_at = ? \ WHERE op_id = ?", &[ SqlValue::Text(now.to_string()), SqlValue::Text(row.op_id.clone()), ], )?; queued.push(op.op_id.clone()); } Ok(()) })?; Ok(queued) } /// The PERSON asks for this parked push to be sent again (UNSENT HEAL, 26 Nov 2026): it goes back in the `_outbox` /// with its original op id and stamp, past [`PUSH_RETRY_CEILING`], as [`requeue_touched_pushes`] puts one back. /// The park stays until the peer takes the op. Answers whether it was queued: not when it is queued already, or /// holds no receipt to send. pub fn requeue_push(db: &Driver, op_id: &str, now: &str) -> Result { db.transaction(|db| { let Some(row) = db.get("SELECT * FROM _parked WHERE op_id = ? AND direction = 'push'", &[SqlValue::Text(op_id.to_string())])? else { return Ok(false); }; if db.get("SELECT op_id FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op_id.to_string())])?.is_some() { return Ok(false); } let Ok(op) = rebuild(&row_to_rejected(&row)) else { return Ok(false) }; crate::outbox::queue_ops(db, std::slice::from_ref(&op), now)?; db.run("UPDATE _parked SET tries = tries + 1, tried_at = ? WHERE op_id = ?", &[SqlValue::Text(now.to_string()), SqlValue::Text(op_id.to_string())])?; Ok(true) }) } /// What a HAND-OVER PASS carries of `_parked` (slice 12, the handover): /// every parked PULL whose stamp is above where the pass starts its author — /// a receipt the old Mac served and this file could not fold is still one the /// new Mac may lack — and every parked PUSH once, re-offered at its stamp: /// the old Mac refused it, and the new one judges it afresh. Above its /// author's start too: the author's stream never carries a park /// ([`travels_only_as_park`]), so this list is the one way it reaches the new /// Mac and the one place its offers are counted. In `(stamp, op id)` order; a park /// whose bytes are not a receipt has nothing to offer and is left where it is. /// /// A park already offered to `epoch` [`HANDOVER_OFFER_CEILING`] times is left /// out ([`count_handover_offers`]): a pass that never completes rebuilds this /// list every cycle, and the new Mac that refused it that often will refuse it /// again. It stays parked, on the owner's board; a NEWER epoch offers it again. pub fn parked_for_handover( db: &Driver, start: &BTreeMap, epoch: i64, ) -> Result> { let mut out: Vec = Vec::new(); for row in db.all( "SELECT * FROM _parked WHERE handover_epoch IS NOT ? OR handover_offers < ?", &[SqlValue::Integer(epoch), SqlValue::Integer(HANDOVER_OFFER_CEILING)], )? { let Ok(op) = rebuild(&row_to_rejected(&row)) else { continue; }; let above = op.hlc.as_str() > start.get(&op.device_id).map_or("", String::as_str); let offered = match row.text("direction") { Some("pull") => above, Some("push") => true, _ => false, }; if offered { out.push(op); } } out.sort_by(|a, b| (a.hlc.as_str(), a.op_id.as_str()).cmp(&(b.hlc.as_str(), b.op_id.as_str()))); Ok(out) } /// Does `op_id` travel ONLY as a park — is it in `_parked`, either direction? /// /// A parked PUSH is this file's write, refused by the peer as final: back in /// the `_outbox` at most [`PUSH_RETRY_CEILING`] times /// ([`requeue_touched_pushes`]), and in a hand-over pass at most /// [`HANDOVER_OFFER_CEILING`] times per serving epoch ([`parked_for_handover`]). /// A parked PULL whose receipt this file still holds in `_writes` — a dormant /// row's receipt parked when its re-assembly clashed — is offered by the same /// hand-over list under the same count. The author's stream leaves both out /// (`exchange::Handover::take`), or every pass that starts its author below it /// would offer it again past both bounds — and in the same pass as the park. /// A HELD write is never parked, so it is still retried. pub fn travels_only_as_park(db: &Driver, op_id: &str) -> Result { Ok(db .get("SELECT 1 FROM _parked WHERE op_id = ?", &[SqlValue::Text(op_id.to_string())])? .is_some()) } /// How many times a hand-over pass offers one park to one serving epoch — /// [`PUSH_RETRY_CEILING`]'s bound, counted on its own column because `tries` /// is shared with the sweep and cannot say how often one epoch was asked. pub const HANDOVER_OFFER_CEILING: i64 = PUSH_RETRY_CEILING; /// A hand-over request to `epoch` carried these ops: each that is still a /// park counts one offer to `epoch`, and an offer to a different epoch than /// the last starts the count again at one. Ops that are not parks — and /// pushes the peer took, ended already — match no row. A PULL park the peer /// took counts too: it does not end here (this file still cannot fold it), /// and the new Mac that took it needs it no more often than one refused it. pub fn count_handover_offers(db: &Driver, op_ids: &[String], epoch: i64) -> Result<()> { for op_id in op_ids { db.run( "UPDATE _parked SET \ handover_offers = CASE WHEN handover_epoch IS ? THEN handover_offers + 1 ELSE 1 END, \ handover_epoch = ? \ WHERE op_id = ?", &[ SqlValue::Integer(epoch), SqlValue::Integer(epoch), SqlValue::Text(op_id.clone()), ], )?; } Ok(()) } /// The pushes parked `waiting` that the peer now HOLDS: its `seen` for the /// receipt's author has reached the receipt's stamp, which is the peer saying /// its fact arrived and it folded what waited on it /// ([`retry_waiting_for`]). Each ends as delivered. Answers how many ended. /// /// A park the peer said it parked waiting (`REJECTION_AUTHOR_WAITING`) is not /// a loss and is never re-sent on every pass; this is the one way it ends /// without being offered again. pub fn end_waiting_pushes_the_peer_holds(db: &Driver, seen: &BTreeMap) -> Result { let mut ended = 0; for row in db.all("SELECT * FROM _parked WHERE direction = 'push' AND class = 'waiting'", &[])? { let Ok(op) = rebuild(&row_to_rejected(&row)) else { continue; }; let Some(at) = seen.get(&op.device_id) else { continue; }; if !crate::changes::is_behind(&op.hlc, at) { ended += end_park(db, &op.op_id, Ended::Delivered)?; } } Ok(ended) } /// The peer TOOK it — so this file no longer lacks the write. /// /// Called with the ops an exchange handed over and was not refused for. Without /// it a requeued push that landed would leave its parked row behind for ever, /// and `_parked` would stop meaning "writes that are missing". pub fn clear_delivered_pushes(db: &Driver, op_ids: &[String]) -> Result<()> { for op_id in op_ids { end_park(db, op_id, Ended::Delivered)?; } Ok(()) } /// A retry that failed: the LATEST class and reason, when it was tried, one /// more try — and never the first verdict's `first_at`. fn keep(db: &Driver, op_id: &str, class: Class, reason: &str, now: &str) -> Result<()> { db.run( "UPDATE _parked SET class = ?, reason = ?, tried_at = ?, tries = tries + 1 WHERE op_id = ?", &[ SqlValue::Text(class.as_str().to_string()), SqlValue::Text(reason.to_string()), SqlValue::Text(now.to_string()), SqlValue::Text(op_id.to_string()), ], )?; Ok(()) } #[cfg(test)] #[path = "rejected_tests.rs"] mod tests;