//! The OUTBOX: what this device has folded and not yet sent.//!//! The write itself happens in [`crate::mint`] — one function mints, folds and//! (on a replica) queues, in one transaction, with no network anywhere near//! it. That is what makes a capture land in an aeroplane, and it is why the//! outbox is a TABLE — memory would not survive the force-quit that follows.//! This module holds the queue's own verbs: what is pending, what a retired//! table leaves behind, how long a failed push waits; and [`LocalChange`], the//! shape a writer collects changes in before it hands them to `mint`.//!//! Nothing here reads the clock or a random source (spec R7, the R2//! amendment): `mint` takes a [`crate::mint::Clock`] and an [`IdSource`], and//! every other stamping function takes the ISO string it should write. The//! queue is drained by [`crate::exchange`], the ONE verb that crosses between//! two files.//!//! What a write that could NOT be folded becomes lives in [`crate::rejected`]://! the outbox is what this device has not SENT, and `_parked` is what//! nobody could FOLD. Two tables, two lifetimes, and the only thing they ever//! shared was a file.use std::collections::BTreeMap;use rusqlite::types::ValueasSqlValue;use serde_json::{Map, ValueasJsonValue};usecrate::canonical;usecrate::driver::Driver;usecrate::error::Result;usecrate::mint::Delete;usecrate::presence;usecrate::protocol::types::{CottonOp, OpKind};/// What a caller supplies: the change, not the bookkeeping.#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]pubstructLocalChange {pub kind: OpKind,pub table: String, #[serde(rename = "rowId")]pub row_id: String, #[serde(default)]pub patch: Option<Map<String, JsonValue>>,/// Which kind of delete this is (design 6.2), handed to `mint` as/// [`crate::mint::Change::delete`]: `Some` exactly on a delete, `None` on/// an upsert. Never serialised: what a delete leaves on disk is its minted/// receipt, which carries an Erase's reason in its own bytes. #[serde(skip)]pub delete: Option<Delete>,}implLocalChange {/// An upsert: a create or a change, decided against the file by/// [`crate::mint::changes_of`].pubfn upsert(table: &str, row_id: &str, patch: Map<String, JsonValue>) -> LocalChange {LocalChange { kind: OpKind::Upsert, table: table.to_string(), row_id: row_id.to_string(), patch: Some(patch), delete: None, } }/// A delete of `table`'s `row_id`, which is a change only once it names/// its kind: [`DeleteOf::retract`], [`DeleteOf::erase`],/// [`DeleteOf::source_erase`] or [`DeleteOf::revocation`].pubfn delete(table: &str, row_id: &str) -> DeleteOf {DeleteOf { table: table.to_string(), row_id: row_id.to_string() } }}/// A rule's planned row (`cotton_rules::change`), as this store writes it:/// the rules' only delete is a Retract.implFrom<cotton_rules::change::Change> forLocalChange {fn from(change: cotton_rules::change::Change) -> LocalChange {let cotton_rules::change::Change { kind, table, row_id, patch } = change;let delete = match kind {OpKind::Upsert => None,OpKind::Delete => Some(Delete::Retract), };LocalChange { kind, table, row_id, patch, delete } }}/// A delete that has not yet named its kind — not a change until it does.#[must_use = "a delete is a change only once it names its kind"]#[derive(Debug, Clone, PartialEq)]pubstructDeleteOf { table: String, row_id: String,}implDeleteOf {fn named(self, delete: Delete) -> LocalChange {LocalChange { kind: OpKind::Delete, table: self.table, row_id: self.row_id, patch: None, delete: Some(delete), } }/// A Retract: a later create at the id makes the row live again.pubfn retract(self) -> LocalChange {self.named(Delete::Retract) }/// An Erase: the row and its owned descendants leave for good, on every/// device; `reason` is `bin` or the verb that destroys the bytes.pubfn erase(self, reason: &str) -> LocalChange {self.named(Delete::Erase { reason: reason.to_string() }) }/// A Source-erase: `job` mirrors a deletion made outside Cotton, and/// `_gone.reason` is `source:<job>`.pubfn source_erase(self, job: &str) -> LocalChange {self.named(Delete::SourceErase { job: job.to_string() }) }/// A take-back: Undo of an add, an Erase `mint` judges/// ([`crate::take_back`]); `through` is the last stamp of the add's act.pubfn take_back(self, through: &str) -> LocalChange {self.named(Delete::TakeBack { through: through.to_string() }) }/// A revocation subject's row, retracted beside its fact.pubfn revocation(self) -> LocalChange {self.named(Delete::Revocation) }}/// What a local write can be told, which it cannot infer.pubtraitIdSource {fn next_op_id(&mutself, now_ms: i64) -> Result<String>;}impl<F: FnMut(&mut [u8])> IdSourceforcrate::protocol::ulid::Monotonic<F> {fn next_op_id(&mutself, now_ms: i64) -> Result<String> {self.next(now_ms) }}/// Queue minted ops for the next push — the one door onto `_outbox`, and/// `mint`'s to open: a replica's mint queues what it folded, a served file's/// does not. `pub(crate)`, so no caller queues an op it did not mint.pub(crate) fn queue_ops(db: &Driver, ops: &[CottonOp], queued_at: &str) -> Result<()> {for op in ops {// The same replication rule gates the queue, receipt stream and// pending count. Server-only and device-local rows stay in this file.if !crate::schema::table_specs::is_handed_over(&op.table) {continue; } supersede_presence(db, op)?;// The row is the receipt: its kind and author are read out of the// bytes, so the queue cannot say one thing beside them and another// inside them.let receipt = canonical::decode(op.receipt.as_bytes())?; db.run("INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes, sig)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", &[SqlValue::Text(op.op_id.clone()),SqlValue::Text(receipt.kind.as_str().to_string()),SqlValue::Text(receipt.author.clone()),SqlValue::Text(op.table.clone()),SqlValue::Text(op.row_id.clone()),SqlValue::Text(op.hlc.clone()),SqlValue::Integer(i64::from(op.schema_version)),SqlValue::Text(queued_at.to_string()),SqlValue::Blob(op.receipt.as_bytes().to_vec()),crate::receipts::sig_value(op), ], )?; }Ok(())}/// Drop the queued reading this op stands in for.////// The outbox half of `crate::presence`: a session polling every thirty seconds/// queues the same three readings again and again, and a device that has been/// offline for a day would push a day of them. Only a reading whose columns the/// new op already carries, and whose hlc is older, is removed — see that/// module for why both halves matter.////// This is the ONLY reader of the presence declaration. There was a second —/// the server collapsed its `_ops` log the same way — and it went with the log/// (version 8 stopped writing one, version 11 dropped the table), so the two/// can no longer disagree about what a collapse means.fn supersede_presence(db: &Driver, op: &CottonOp) -> Result<()> {if !presence::is_presence_patch(&op.table, op.patch.as_ref()) {returnOk(()); }let queued = db.all("SELECT op_id, bytes, hlc FROM _outbox WHERE tbl = ? AND row_id = ?", &[SqlValue::Text(op.table.clone()),SqlValue::Text(op.row_id.clone()), ], )?;for row in &queued {// The queued op's patch, read out of its receipt the way `op.patch`// was (`crate::wire`). Bytes that do not decode are un-supersedable// rather than a failed write.let op_id = row.text("op_id").unwrap_or_default().to_string();let old_patch = match row.get("bytes") {Some(SqlValue::Blob(bytes)) => Some(bytes.as_slice()), _ => None, } .and_then(|bytes| crate::wire::from_bytes(op_id.clone(), bytes).ok()) .and_then(|old| old.patch);let old_hlc = row.text("hlc").unwrap_or_default();if presence::supersedes( &op.table, op.patch.as_ref(), &op.hlc, old_patch.as_ref(), old_hlc, ) { db.run(// not a copy: a queued op a newer one of the same row supersedes, one of a table that never goes to a server, or one of a table this build retired."DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op_id)], )?; } }Ok(())}pubfn pending_count(db: &Driver) -> Result<i64> {Ok(db .get(&format!("SELECT COUNT(*) AS n FROM _outbox WHERE {}",crate::schema::table_specs::handed_over_clause("tbl")), &[])? .and_then(|row| row.int("n")) .unwrap_or(0))}/// The things this device changed that wait to be sent, as a person counts/// them: each record once however many writes it queued, and none of the/// bookkeeping a write leaves beside it (its history rows, `cotton_changes`,/// and the device's author fact a first write mints, `cotton_authors`). One/// note written offline is one, not its create, its edits and their receipts/// (sync seen, 26 Nov 2026).pubfn pending_things(db: &Driver) -> Result<i64> {Ok(db .get(&format!("SELECT COUNT(DISTINCT tbl || char(31) || row_id) AS n FROM _outbox WHERE {} AND tbl NOT IN (?, 'cotton_authors')",crate::schema::table_specs::handed_over_clause("tbl")), &[SqlValue::Text(crate::fact_hooks::HISTORY_TABLE.to_string())])? .and_then(|row| row.int("n")) .unwrap_or(0))}/// When the oldest write [`pending_count`] counts was queued (its/// `queued_at`, as written), or none while nothing waits: a glance says a/// change waits to sync only once it has waited a while.pubfn oldest_pending_at(db: &Driver) -> Result<Option<String>> {Ok(db .get(&format!("SELECT MIN(queued_at) AS at FROM _outbox WHERE {}",crate::schema::table_specs::handed_over_clause("tbl")), &[])? .and_then(|row| row.text("at").map(str::to_string)))}/// [`pending_count`] by table: each table this file has writes queued of, and/// how many, by its name here (`cotton_todos`).pubfn pending_by_table(db: &Driver) -> Result<Vec<(String, i64)>> {Ok(db .all(&format!("SELECT tbl, COUNT(*) AS n FROM _outbox WHERE {} GROUP BY tbl ORDER BY tbl",crate::schema::table_specs::handed_over_clause("tbl")), &[])? .iter() .filter_map(|row| Some((row.text("tbl")?.to_string(), row.int("n")?))) .collect())}/// A held write's `last_error`: its refusal's code first, when it has one a code can be (`seal_key_missing: …`),/// so [`waiting`] counts by code and never reads the reason.pubfn coded(code: Option<&str>, reason: &str) -> String {match code.filter(|code| is_code(code)) {// A reason that already says its code ("seal_key_missing: no key for …", or "seal_does_not_open") says it once.Some(code) => format!("{code}: {}", reason.strip_prefix(code).map_or(reason, |rest| rest.trim_start_matches(':').trim_start())),None => reason.to_string(), }}fn is_code(code: &str) -> bool { !code.is_empty() && code.len() <= 48 && code.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')}/// The codes of a refusal that PASSES (UNSENT HEAL 2, review 26 Nov 2026): a write held under one is on its way —/// Cotton not answering, a server older than the build, a hand-over, a row that moved, a merge or a turn to come —/// and never counts toward how long it has waited for good, however old it is.pubconst PASSING_CODES: [&str; 16] = ["queued", "offline", "unanswered", "internal_error", "copy_unwritten", "version_moved", "merge_waits",crate::protocol::types::REJECTION_DEFERRED, crate::protocol::types::REJECTION_SERVER_BEHIND,crate::protocol::types::REJECTION_HAND_OVER, crate::protocol::types::REJECTION_PHONE_BEHIND,crate::protocol::types::REJECTION_AUTHOR_WAITING, crate::signed::REJECTION_AUTHOR_UNKNOWN,crate::protocol::types::REJECTION_FUTURE, "rate_limited", "too_many_requests",];/// Whether `code` is a refusal that passes ([`PASSING_CODES`]).pubfn passing(code: &str) -> bool { PASSING_CODES.contains(&code)}/// When each queued write was FIRST refused by a refusal that lasts (UNSENT HEAL 2): made on first use, device-local,/// one row per write. A passing refusal never writes it; a write that leaves the queue leaves it at the next settle.const REFUSED_SINCE_DDL: &str = "CREATE TABLE IF NOT EXISTS _refused_since (op_id TEXT PRIMARY KEY, code TEXT NOT NULL, since TEXT NOT NULL) WITHOUT ROWID";/// Note that `op_id` was refused under `code` at `now`: kept only for a lasting code, and only the first time.pubfn note_refused(db: &Driver, op_id: &str, code: Option<&str>, now: &str) -> Result<()> {let code = code.filter(|code| is_code(code)).unwrap_or("other");if passing(code) {returnOk(()); } db.run(REFUSED_SINCE_DDL, &[])?; db.run("INSERT INTO _refused_since (op_id, code, since) VALUES (?, ?, ?) ON CONFLICT (op_id) DO NOTHING", &[SqlValue::Text(op_id.to_string()), SqlValue::Text(code.to_string()), SqlValue::Text(now.to_string())], )?;Ok(())}/// Forget when `op_ids` were first refused: offered again as new, or no longer queued.pubfn forget_refused(db: &Driver, op_ids: &[String]) -> Result<()> {if !has_refused_since(db)? {returnOk(()); }for op_id in op_ids { db.run("DELETE FROM _refused_since WHERE op_id = ?", &[SqlValue::Text(op_id.clone())])?; }Ok(())}/// Forget every write no longer queued: a settle's own tidying.pubfn forget_refused_gone(db: &Driver) -> Result<()> {if has_refused_since(db)? { db.run("DELETE FROM _refused_since WHERE op_id NOT IN (SELECT op_id FROM _outbox)", &[])?; }Ok(())}fn has_refused_since(db: &Driver) -> Result<bool> {Ok(db.get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = '_refused_since'", &[])?.is_some())}/// When `op_id` was first refused by a lasting refusal, or none.pubfn refused_since(db: &Driver, op_id: &str) -> Result<Option<String>> {if !has_refused_since(db)? {returnOk(None); }Ok(db.get("SELECT since FROM _refused_since WHERE op_id = ?", &[SqlValue::Text(op_id.to_string())])?.and_then(|row| row.text("since").map(str::to_string)))}/// The SQL for a queued write's code, from its `last_error` ([`coded`]): `queued` for one never refused, `other`/// for a refusal written without a code (an older build's, or one that names none).const CODE_OF: &str = "CASE WHEN last_error IS NULL OR last_error = '' THEN 'queued' \ WHEN instr(last_error, ': ') BETWEEN 2 AND 49 AND substr(last_error, 1, instr(last_error, ': ') - 1) NOT GLOB '*[^a-z0-9_]*' \ THEN substr(last_error, 1, instr(last_error, ': ') - 1) ELSE 'other' END";/// What waits to be sent, in names and counts only (UNSENT SEEN, coordinator, 26 Nov 2026): never a value, a row/// id or a reason. `things` and `ops` as [`pending_things`] and [`pending_count`] count them; `by_table` the/// things of each table; `by_code` the writes of each refusal code ([`coded`]; `queued` for one never refused);/// the oldest write's `queued_at`, and each code's.#[derive(Debug, Clone, Default, PartialEq, Eq)]pubstructWaiting {pub things: i64,pub ops: i64,pub by_table: BTreeMap<String, i64>,pub by_code: BTreeMap<String, i64>,pub oldest_at: Option<String>,pub oldest_by_code: BTreeMap<String, String>,}pubfn waiting(db: &Driver) -> Result<Waiting> {let handed = crate::schema::table_specs::handed_over_clause("tbl");let history = SqlValue::Text(crate::fact_hooks::HISTORY_TABLE.to_string());let by_table = db .all(&format!("SELECT tbl, COUNT(DISTINCT row_id) AS n FROM _outbox WHERE {handed} AND tbl NOT IN (?, 'cotton_authors') GROUP BY tbl"), &[history])? .iter() .filter_map(|row| Some((row.text("tbl")?.to_string(), row.int("n")?))) .collect();letmut by_code = BTreeMap::new();letmut oldest_by_code = BTreeMap::new();for row in db.all(&format!("SELECT {CODE_OF} AS code, COUNT(*) AS n, MIN(queued_at) AS at FROM _outbox WHERE {handed} GROUP BY code"), &[])? {letSome(code) = row.text("code").map(str::to_string) else { continue };ifletSome(at) = row.text("at") { oldest_by_code.insert(code.clone(), at.to_string()); } by_code.insert(code, row.int("n").unwrap_or(0)); }// QUEUE BAD OP: the queued writes set aside because they did not read are counted under their code.let undecodable = crate::rejected::undecodable_count(db)?;if undecodable > 0 { by_code.insert(crate::rejected::UNDECODABLE.to_string(), undecodable); }Ok(Waiting { things: pending_things(db)?, ops: pending_count(db)?, by_table, by_code, oldest_at: oldest_pending_at(db)?, oldest_by_code })}/// Clear receipts queued by a build that still replicated local observations./// The rows and their local receipts stay; only their obligation to send goes./// No schema move is needed to apply the current replication policy.pub(crate) fn drop_local_ops(db: &Driver) -> Result<usize> {// not a copy: a queued op a newer one of the same row supersedes, one of a table that never goes to a server, or one of a table this build retired. db.run(&format!("DELETE FROM _outbox WHERE NOT ({})",crate::schema::table_specs::handed_over_clause("tbl")), &[])}/// The sync loop's retry ladder.////// The floor is the pull interval itself — retrying sooner than the cycle would/// have run anyway buys nothing — and the ceiling is five minutes: long enough/// not to burn the radio, short enough that walking back into signal moves the/// queue without the person reopening anything.////// The JITTER is not decoration. Every device that lost the server at the same/// moment would otherwise retry in the same second, forever, and hit a server/// that has just come back with one synchronised wave.////// `random` is a PARAMETER, and a plain `f64` in `[0, 1)` rather than a/// closure: this crate reads no random source (spec R7), and a test asserts the/// arithmetic rather than a range.pubconst SYNC_BACKOFF_FLOOR_MS: i64 = 30_000;pubconst SYNC_BACKOFF_CEILING_MS: i64 = 300_000;pubfn sync_backoff_ms(failures: i64, random: f64) -> i64 {let steps = failures.clamp(0, 31) as u32;let base = SYNC_BACKOFF_FLOOR_MS .saturating_mul(1i64 << steps) .min(SYNC_BACKOFF_CEILING_MS);// ±20%: `random` at 0.5 is the base, 0 is −20%, 1 is +20%. (base as f64 * (0.8 + 0.4 * random)).round() as i64}#[cfg(test)]#[path = "outbox_tests.rs"]mod tests;