//! **UNSENT HEAL** (coordinator, 26 Nov 2026): the writes this phone made that wait to be sent and will not go by //! themselves, each said to the person with one act: send it again, or let it go. No change is ever dropped //! silently: one the person lets go is written down first ([`crate::unsent::record_discarded`]), and filed as a //! Feedback row once a copy is open, as a discarded copy's changes are. //! //! **Every way a write waits, and whether it heals** (`assets/design/shared/UNSENT-HEAL.md` says the same): //! //! | waits as | why | heals by itself | //! |---|---|---| //! | `_outbox`, never refused (`queued`) | not sent yet | yes, the next pass | //! | `offline`, `unanswered`, a 5xx, a 429 | Cotton not reached | yes, the pass fails and the loop tries again | //! | `version_moved` | the object refused the post: the row moved there past the version this copy read | yes, only because a pull carries the row: its newer version is past this copy's cursor, and the next post goes at it. A row with no version held never waits on this: a list's change reads that one row from the object first (`transport::object`, HIDDEN 6) | //! | `held_row_unread` | a change whose row the server would not hand back readable | waits out a read that doubles from a minute to an hour (`_seal_unread`); said after a day; it goes once the row reads, or the person lets it go | //! | `moved_again` | a change laid over a fresh read, refused as moved three times in a row | waits as `held_row_unread` does (`_seal_moved`); said after a day | //! | `row_gone` | the server holds the row no more (refused as moved, or a list's change of a row made elsewhere) | no: parked, said at once | //! | `merge_waits` | Words merges an edit over newer text | yes, after the pass that brought it | //! | `copy_unwritten` | this phone could not write its note | yes, the next pass | //! | the server's retryable refusals (`server_behind`) | the server is older than this build | yes, at the deploy | //! | `seal_key_missing` | no key yet: not let in, seal keys or the table's definition not read | yes once the key comes; never if this phone is never let in, so it is said a day after its first lasting refusal ([`KEY_SAID_AFTER_MS`]) | //! | `seal_does_not_open` | the row's kept wrap is a former database's | healed only where the post is held to the version read and this device's key is proven (`transport::object`); else said at once | //! | `seal_column_missing`, `seal_column_clash`, `seal_bad_input`, `seal_failed` | the row cannot be sealed as it stands | no: said at once | //! | `unknown_field` | a field this build's kit has that the object's definition lacks (the Worker not deployed yet) | yes, posted again once the object's definitions move (`transport::object::HeldDefinitions`); said after a day | //! | any other refusal code held in `_outbox` | not known to heal | said after a day | //! | `_parked`, push | the server refused it for good (`bad_column`, a constraint, …) | only if the row moves again, three times at most ([`cotton_store::rejected::PUSH_RETRY_CEILING`]); said at once | //! | taken from the queue, kept on this phone | a table this app's kit never carries | by design; written down and counted ([`kept_here_only`]) | //! | taken from the queue, kept on this phone | a table no object table takes (Mac-era) | by design (logged) | //! //! Send again: a queued write is offered as new (its refusal cleared); a parked push goes back in the queue with its //! own id and stamp, past the ceiling. Let go: the write leaves the queue (or its park ends) and is written down. The //! row itself stays on this phone as it is; only its sending ends. use std::collections::BTreeMap; use cotton_store::driver::Driver; use rusqlite::types::Value as SqlValue; use crate::layout::Layout; use crate::unsent::{UnsentChange, Waiting}; /// How long a write refused for want of a key waits before it is said (UNSENT SEEN's day): a phone let in a moment /// later heals it, and the getting-in page asks meanwhile. pub const KEY_SAID_AFTER_MS: i64 = 24 * 60 * 60 * 1000; /// Whether a refusal code heals by itself once its cause goes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Heal { /// Nothing to say: the loop sends it once the cause goes. Itself, /// It heals once the cause goes, but the cause may never go: said once it has waited [`KEY_SAID_AFTER_MS`]. Slowly, /// It waits for good: said at once. Never, } /// The refusal codes a write is held under that never heal by themselves. pub const NEVER_HEALS: [&str; 5] = ["seal_does_not_open", "seal_column_missing", "seal_column_clash", "seal_bad_input", "seal_failed"]; /// What `code` (a queued write's, `cotton_store::outbox::coded`) says of its healing. A refusal that passes /// (`cotton_store::outbox::PASSING_CODES`: on its way, Cotton not answering, a server older than the build, a row /// that moved) heals itself, however old the write. pub fn heal_of(code: &str) -> Heal { if NEVER_HEALS.contains(&code) { Heal::Never } else if cotton_store::outbox::passing(code) { Heal::Itself } else { Heal::Slowly } } /// Why a write let go is written down: its code only, never the server's or the sealer's words, which could quote a /// value (UNSENT HEAL 2, review item 6). fn code_only(code: &str, reason: &str) -> String { if code != "refused" { return code.to_string(); } reason.split_once(':').map(|(word, _)| word.trim()).filter(|word| !word.is_empty() && word.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')).unwrap_or("refused").to_string() } /// Why changes are written down when the person lets them go. pub const LET_GO_WHY: &str = "the person let these go; they could not be sent"; /// Why a change is written down when this app's kit never carries its table: it stays on this phone only. pub const NEVER_CARRIED_WHY: &str = "this app does not send this table; the change stays on this phone only"; /// One write that waits and will not go by itself. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Stuck { pub op_id: String, pub table: String, pub row_id: String, /// The refusal's code: a queued write's, or `refused` for a parked push. pub code: String, /// The server's or the sealer's words, for the log and Feedback, never a screen. pub reason: String, /// When it was queued, or first refused for good. pub since: String, /// Refused for good by the server (`_parked`, push), not held in the queue. pub parked: bool, } fn table_exists(db: &Driver, name: &str) -> Result { db.get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(name.to_string())]).map(|row| row.is_some()).map_err(|error| error.to_string()) } /// The code a queued write's `last_error` says, as `cotton_store::outbox::waiting` counts it. fn code_of(last_error: Option<&str>) -> String { match last_error.filter(|error| !error.is_empty()) { None => "queued".to_string(), Some(error) => match error.split_once(": ") { Some((code, _)) if !code.is_empty() && code.len() <= 48 && code.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') => code.to_string(), _ if error.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') => error.to_string(), _ => "other".to_string(), }, } } /// The writes this copy holds that will not go by themselves, oldest first: queued ones whose code never heals, /// queued ones whose code may never heal once [`KEY_SAID_AFTER_MS`] has passed since they were first refused for a /// reason that lasts (`cotton_store::outbox::refused_since`; a passing refusal never counts, however old the write), /// and every push the server refused for good that is not queued again. Bookkeeping (`cotton_authors`) and history /// are never listed. pub fn stuck(db: &Driver, now_ms: i64) -> Result, String> { let mut out = Vec::new(); let skip = |table: &str| table == "cotton_authors" || table == cotton_store::fact_hooks::HISTORY_TABLE; if table_exists(db, "_outbox")? { // One query, every draw (UNSENT HEAL 2 review, follow-up 3): a write never refused is on its way and never // read here, and its first lasting refusal comes joined, not asked for row by row. let since = if table_exists(db, "_refused_since")? { ("r.since AS refused_since", " LEFT JOIN _refused_since r ON r.op_id = o.op_id") } else { ("NULL AS refused_since", "") }; let sql = format!( "SELECT o.op_id, o.tbl, o.row_id, o.queued_at, o.last_error, {} FROM _outbox o{} \ WHERE o.last_error IS NOT NULL AND o.tbl NOT IN ('cotton_authors', ?) ORDER BY o.queued_at, o.op_id", since.0, since.1 ); for row in db.all(&sql, &[SqlValue::Text(cotton_store::fact_hooks::HISTORY_TABLE.to_string())]).map_err(|error| error.to_string())? { let (Some(op_id), Some(table), Some(row_id), Some(queued_at)) = (row.text("op_id"), row.text("tbl"), row.text("row_id"), row.text("queued_at")) else { continue }; let code = code_of(row.text("last_error")); let refused_since = row.text("refused_since"); let waited = refused_since.and_then(cotton_store::protocol::js::parse_date_ms).is_some_and(|at| now_ms.saturating_sub(at) >= KEY_SAID_AFTER_MS); let said = match heal_of(&code) { Heal::Never => true, Heal::Slowly => waited, Heal::Itself => false, }; if said { out.push(Stuck { op_id: op_id.into(), table: table.into(), row_id: row_id.into(), reason: row.text("last_error").unwrap_or_default().into(), code, since: refused_since.unwrap_or(queued_at).into(), parked: false }); } } } if table_exists(db, "_parked")? { let sql = "SELECT op_id, tbl, row_id, reason, first_at FROM _parked WHERE direction = 'push' AND bytes IS NOT NULL \ AND op_id NOT IN (SELECT op_id FROM _outbox) ORDER BY first_at, op_id"; let sql = if table_exists(db, "_outbox")? { sql.to_string() } else { sql.replace(" AND op_id NOT IN (SELECT op_id FROM _outbox)", "") }; for row in db.all(&sql, &[]).map_err(|error| error.to_string())? { let (Some(op_id), Some(table), Some(row_id)) = (row.text("op_id"), row.text("tbl"), row.text("row_id")) else { continue }; if skip(table) { continue; } out.push(Stuck { op_id: op_id.into(), table: table.into(), row_id: row_id.into(), // A queued write set aside because it did not read says so (QUEUE BAD OP); any other, the server refused. code: if row.text("reason").is_some_and(|reason| reason.starts_with(&format!("{}:", cotton_store::rejected::UNDECODABLE))) { cotton_store::rejected::UNDECODABLE.into() } else { "refused".into() }, reason: row.text("reason").unwrap_or_default().into(), since: row.text("first_at").unwrap_or_default().into(), parked: true, }); } } out.sort_by(|a, b| (a.since.as_str(), a.op_id.as_str()).cmp(&(b.since.as_str(), b.op_id.as_str()))); Ok(out) } fn ms_of(now: &str) -> Result { cotton_store::protocol::js::parse_date_ms(now).ok_or_else(|| format!("the time {now:?} is unreadable")) } /// Whether a parked write of `table`'s row `row_id` would be sent at all: an upsert whose row this phone no longer /// holds, or whose table this file has not, is taken without a request, which would end its park with nothing said. fn would_send(db: &Driver, stuck: &Stuck) -> Result { let kind = db.get("SELECT bytes, sig, op_id FROM _parked WHERE op_id = ?", &[SqlValue::Text(stuck.op_id.clone())]).map_err(|error| error.to_string())? .and_then(|row| cotton_store::stored::outbox_row(&row).ok()).map(|op| op.kind); if kind == Some(cotton_store::protocol::types::OpKind::Delete) { return Ok(true); } if !stuck.table.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') || !table_exists(db, &stuck.table)? { return Ok(false); } Ok(db.get(&format!("SELECT 1 AS here FROM \"{}\" WHERE id = ?", stuck.table), &[SqlValue::Text(stuck.row_id.clone())]).map_err(|error| error.to_string())?.is_some()) } /// Send again the writes named that are stuck now (of [`stuck`]'s at `now`, the same age rule): a queued one is /// offered as new, its refusal and its first lasting refusal forgotten; a parked push goes back in the queue with its /// own id and stamp, whatever its tries. A parked write that would be taken without a request (its row gone from /// this phone, its table not here) is written down and let go instead, never cleared with nothing said. Answers /// `(sent, written down)`. /// One that does not read (`undecodable`) is neither sent nor ended: this build cannot send it, and the answer counts /// it (QUEUE BAD OP 2: Send again never ends a change). Answers `(sent, written down, cannot)`. pub fn send_again(db: &Driver, layout: &Layout, workspace_id: &str, op_ids: &[String], now: &str) -> Result<(usize, usize, usize), String> { let named: Vec = stuck(db, ms_of(now)?)?.into_iter().filter(|stuck| op_ids.contains(&stuck.op_id)).collect(); // Each set-aside one is tried again first, as after an update (QUEUE BAD OP 3): one that reads now is held again // and goes with the next pass, re-dated to a new stamp; one that still does not read cannot be sent by this build. let unreadable: Vec = named.iter().filter(|stuck| stuck.code == cotton_store::rejected::UNDECODABLE).map(|stuck| stuck.op_id.clone()).collect(); let again = if unreadable.is_empty() { Vec::new() } else { cotton_store::rejected::try_set_aside_again(db, Some(&unreadable)).map_err(|error| error.to_string())? }; let cannot = unreadable.len() - again.len(); let named: Vec = named.into_iter().filter(|stuck| stuck.code != cotton_store::rejected::UNDECODABLE).collect(); let mut nowhere = Vec::new(); for stuck in named.iter().filter(|stuck| stuck.parked) { if !would_send(db, stuck)? { nowhere.push(stuck.op_id.clone()); } } let written = if nowhere.is_empty() { 0 } else { write_down_and_end(db, layout, workspace_id, named.iter().filter(|s| nowhere.contains(&s.op_id)).cloned().collect(), now)? }; let sent = db.transaction(|db| { let mut offered = 0; for stuck in named.iter().filter(|stuck| !nowhere.contains(&stuck.op_id)) { if stuck.parked { if !cotton_store::rejected::requeue_push(db, &stuck.op_id, now)? { continue; } } else { db.run("UPDATE _outbox SET last_error = NULL, attempts = 0 WHERE op_id = ?", &[SqlValue::Text(stuck.op_id.clone())])?; cotton_store::outbox::forget_refused(db, std::slice::from_ref(&stuck.op_id))?; } offered += 1; } Ok(offered) }) .map_err(|error| error.to_string())?; Ok((sent + again.len(), written, cannot)) } /// Let go of the writes named that are stuck now (of [`stuck`]'s at `now`, the same age rule): each is written down /// first (`discarded-unsent.json`, filed as a Feedback row, by its code only), then leaves the queue, or its park /// ends. The row stays on this phone as it is. Only the person's act calls this. Answers how many. pub fn let_go(db: &Driver, layout: &Layout, workspace_id: &str, op_ids: &[String], now: &str) -> Result { let named: Vec = stuck(db, ms_of(now)?)?.into_iter().filter(|stuck| op_ids.contains(&stuck.op_id)).collect(); write_down_and_end(db, layout, workspace_id, named, now) } fn write_down_and_end(db: &Driver, layout: &Layout, workspace_id: &str, named: Vec, now: &str) -> Result { if named.is_empty() { return Ok(0); } let mut changes = Vec::new(); let mut reasons = BTreeMap::new(); for stuck in &named { let from = if stuck.parked { "_parked" } else { "_outbox" }; let row = db.get(&format!("SELECT op_id, bytes, sig FROM {from} WHERE op_id = ?"), &[SqlValue::Text(stuck.op_id.clone())]).map_err(|error| error.to_string())?; let change = match row.as_ref().map(cotton_store::stored::outbox_row) { Some(Ok(op)) => UnsentChange::of(&op, if stuck.parked { Waiting::Parked } else { Waiting::Queued }), // A receipt that does not read is still named, by its address. _ => UnsentChange { op_id: stuck.op_id.clone(), table: stuck.table.clone(), row_id: stuck.row_id.clone(), kind: "unknown".into(), made_at: stuck.since.clone(), waiting: if stuck.parked { Waiting::Parked } else { Waiting::Queued } }, }; changes.push(change); reasons.insert(stuck.op_id.clone(), code_only(&stuck.code, &stuck.reason)); } crate::unsent::record_discarded(layout, workspace_id, changes, reasons, LET_GO_WHY, now)?; let parked: Vec = named.iter().filter(|stuck| stuck.parked).map(|stuck| stuck.op_id.clone()).collect(); let queued: Vec = named.iter().filter(|stuck| !stuck.parked).map(|stuck| stuck.op_id.clone()).collect(); db.transaction(|db| { for op_id in &queued { // not a copy: the person's Let go of a queued change, written down first (record_discarded above). db.run("DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op_id.clone())])?; } cotton_store::outbox::forget_refused(db, &queued)?; Ok(()) }) .map_err(|error| error.to_string())?; // A change set aside because it did not read: its receipt here leaves, its row assembled from what remains // (QUEUE BAD OP 3), after it was written down above. for stuck in named.iter().filter(|stuck| stuck.parked && stuck.code == cotton_store::rejected::UNDECODABLE) { cotton_store::rejected::let_go_set_aside(db, &stuck.op_id).map_err(|error| error.to_string())?; } cotton_store::rejected::discard(db, &parked).map_err(|error| error.to_string())?; Ok(named.len()) } /// Where the count of changes kept only on this phone waits to be seen. Its own small file, because what is written /// down for Feedback (`discarded-unsent.json`) is filed and forgotten within a pass, before anyone looks. fn kept_path(layout: &Layout, workspace_id: &str) -> std::path::PathBuf { layout.replica(workspace_id).with_file_name("kept-here.json") } /// One writer of the kept count at a time: a pass noting one and the Sync page marking them seen are both a /// read-then-write of the same file, so they never interleave (and the write itself is atomic, below). static KEPT_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// When the count first had its own file (UNSENT HEAL 3, 0b8f9b55a0). A change written down before it was counted /// only by its entry; one written down since was counted by the file as well, so with no file it was seen (that build /// removed the file at 0) and never counts again. const KEPT_FILE_SINCE: &str = "2026-11-26T16:16:36Z"; /// The kept count as the file says. With no file, what a build before the file left written down and not yet filed /// is the count's start, and it is SAVED at once, so a pass that files those entries next can no longer take it to 0. /// Any error but "no file yet" is an error (an unreadable or garbled file never counts as none). fn kept_read(layout: &Layout, workspace_id: &str) -> Result { match std::fs::read(kept_path(layout, workspace_id)) { Ok(bytes) => serde_json::from_slice::(&bytes) .map_err(|error| format!("the kept count does not read ({error})"))? .get("count") .and_then(serde_json::Value::as_u64) .map(|count| count as usize) .ok_or_else(|| "the kept count holds no count".to_string()), Err(error) if error.kind() == std::io::ErrorKind::NotFound => { let since = chrono::DateTime::parse_from_rfc3339(KEPT_FILE_SINCE).map_err(|error| error.to_string())?; let before_the_file = |at: &str| chrono::DateTime::parse_from_rfc3339(at).is_ok_and(|at| at < since); let count = crate::unsent::discarded(layout, workspace_id).iter().filter(|entry| entry.why == NEVER_CARRIED_WHY && before_the_file(&entry.at)).map(|entry| entry.changes.len()).sum(); kept_write(layout, workspace_id, count)?; Ok(count) } Err(error) => Err(format!("the kept count could not be read ({error})")), } } /// Written whole beside it, then renamed over it: a reader sees the old count or the new, never half a file. fn kept_write(layout: &Layout, workspace_id: &str, count: usize) -> Result<(), String> { let path = kept_path(layout, workspace_id); let fresh = path.with_extension("json.new"); // not a copy: the heal journal. std::fs::write(&fresh, serde_json::json!({ "count": count }).to_string()).map_err(|error| error.to_string())?; // not a copy: the heal journal. std::fs::rename(&fresh, &path).map_err(|error| error.to_string()) } /// `n` more changes this phone keeps only here because this app's kit never carries their table. Called before the /// change is written down for Feedback, so a first call after an upgrade migrates only what an older build left. pub fn note_kept_here(layout: &Layout, workspace_id: &str, n: usize) -> Result<(), String> { let _one = KEPT_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let count = kept_read(layout, workspace_id)? + n; kept_write(layout, workspace_id, count) } /// How many changes this phone keeps only here and the person has not seen said yet (UNSENT HEAL 2, review item 7; /// follow-up 4: the count stays until the Sync page has shown it once). pub fn kept_here_only(layout: &Layout, workspace_id: &str) -> Result { let _one = KEPT_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); kept_read(layout, workspace_id) } /// The Sync page showed `shown` of them: those are seen; any kept since stay counted. The file stays, at 0, so the /// migration never runs twice. pub fn kept_here_seen(layout: &Layout, workspace_id: &str, shown: usize) -> Result<(), String> { let _one = KEPT_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let left = kept_read(layout, workspace_id)?.saturating_sub(shown); kept_write(layout, workspace_id, left) } #[cfg(test)] #[path = "unsent_heal_tests.rs"] mod tests;