//! Sealed tables on a device (sealing plan §2.4, L3): the data key (DK) this //! device holds, the rows it seals on the way up and opens on the way down, //! what it keeps beside the copy to do both, and the sweep that seals the open //! rows the Worker wrote. //! //! The format is `cotton_core::seal`; this module only decides WHEN and with //! which key. Three rules: //! //! - **No fallback to clear.** A sealed table's row is never sent with a //! sealed column in the clear ([`guard_act`]), and a missing DK is a refusal //! by name ([`SEAL_KEY_MISSING`]): the write waits in the outbox. //! - **A row that does not open is parked, never dropped and never shown //! blank.** It is kept whole as the object served it in `_seal_parked`, with //! its code, and opened again once a key is held ([`Sealer::has_key`]). //! - **The DK lives in the platform's key store** ([`DataKeyStore`]): the //! Keychain or Keystore without user presence, so a background pull opens //! rows. The VMK only opens `dk_enc` once, when the store holds nothing. //! //! Beside the copy (`_seal`), one row per row of a sealed table: whether the //! object holds it sealed, its `dek_enc` and `seal_v` as the object holds //! them (so an edit reuses the row's DEK, and a share keeps opening), and the //! object's version (the sweep's `expect_version`). The plan names these as //! `_dek_enc`, `_seal_v` and `_sealed` columns on each table; a side table //! keeps every compiled table's shape and its receipts untouched. use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; use serde_json::{json, Map, Value}; use cotton_core::definitions::seal::SealSpec; use cotton_core::seal::{self as core, blind, row as stored_row, DataKey, Dek, SealError}; use cotton_core::vault::Vmk; pub mod migrate; pub mod search; pub mod sweep; /// The refusal a write to a sealed table answers while this device holds no /// DK: it stays queued, retryable, until a key is held. pub const SEAL_KEY_MISSING: &str = "seal_key_missing"; /// The refusal [`guard_act`] answers: a sealed column was about to leave this /// device in the clear. pub const SEAL_CLEAR_REFUSED: &str = "seal_clear_refused"; /// The object's table that holds the DK wrap and each table's `seal_v`. pub const SEAL_KEY_TABLE: &str = core::SEAL_KEY_TABLE; /// `seal_key`'s row id for the DK wrap. pub const DK_ROW: &str = "dk"; /// `seal_key`'s row id prefix for a table's current version (`v:message`). pub const VERSION_ROW: &str = "v:"; /// The column a sealed table's row is marked open with for good (Q3): the /// sweep leaves it as it is. pub const KEEP_OPEN: &str = "keep_open"; /// Whether `words` name a sealing refusal by its code (`seal_key_missing: no /// key for …`, a `copy_kept` that carries one in its reason): the core's own /// words, said in the log and never on a screen. The `seal_key` table's name /// alone is not one. pub fn names_a_seal_refusal(words: &str) -> bool { words.match_indices("seal_").any(|(at, _)| { let starts_a_word = !words[..at].chars().next_back().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_'); let token: String = words[at..].chars().take_while(|c| c.is_ascii_lowercase() || *c == '_').collect(); starts_a_word && token.len() > "seal_".len() && token != SEAL_KEY_TABLE }) } /// THE KEY-STORE SEAM. The platform keeps the DK per database: iOS in the /// Keychain (`DataKey.swift`, `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, /// no presence), Android in the Keystore (`DataKeyring.kt`). The core never /// writes the key anywhere else. pub trait DataKeyStore: Send + Sync { /// The DK of `database_id`, or none when this device holds none yet. fn data_key(&self, database_id: &str) -> Result, String>; } /// A [`DataKeyStore`] held in memory: what the phone's shell fills at launch /// from its key store (`seal.useKey`), and what a suite uses. #[derive(Default)] pub struct HeldDataKeys { keys: Mutex>, } impl std::fmt::Debug for HeldDataKeys { /// The databases, never a key. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let held = self.keys.lock().map(|keys| keys.keys().cloned().collect::>()).unwrap_or_default(); f.debug_struct("HeldDataKeys").field("databases", &held).finish() } } impl HeldDataKeys { pub fn new() -> Arc { Arc::new(HeldDataKeys::default()) } /// Hold `key` for `database_id`. pub fn hold(&self, database_id: &str, key: &DataKey) { self.keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(database_id.to_string(), *key.expose()); } /// Let go of `database_id`'s key. Answers whether one was held. pub fn forget(&self, database_id: &str) -> bool { let mut keys = self.keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner); match keys.remove(database_id) { Some(mut key) => { zeroize::Zeroize::zeroize(&mut key); true } None => false, } } } impl Drop for HeldDataKeys { fn drop(&mut self) { if let Ok(keys) = self.keys.get_mut() { for key in keys.values_mut() { zeroize::Zeroize::zeroize(key); } } } } impl DataKeyStore for HeldDataKeys { fn data_key(&self, database_id: &str) -> Result, String> { Ok(self.keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(database_id).map(|key| DataKey::from_bytes(*key))) } } /// One database's sealing on this device: its id (every aad names it), its /// key store, and each sealed table's current `seal_v` as the object last /// said it. Long-lived (one per signed-in database); every pass's transport /// borrows it. pub struct Sealer { database_id: String, keys: Arc, /// Each sealed table's `seal_v`, and whether the object holds its /// `v:` row (an advance updates it) or not yet (one creates it). versions: Mutex>, /// Whether every `seal_key` row the object held has been read /// ([`Sealer::learned_all`]): until then nothing is sealed, so a copy /// that writes before its first pull never seals under a version the /// object has moved past (a version an ended window saw). learned: std::sync::atomic::AtomicBool, /// Whether the object holds this database's arrival key (`seal_key` /// row `arrival`, e2e rulings R2): until it does, a pass that holds the /// DK publishes it ([`Sealer::arrival_row`]). arrival_held: std::sync::atomic::AtomicBool, } #[derive(Debug, Clone, Copy)] struct Version { v: u32, held: bool, } impl std::fmt::Debug for Sealer { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Sealer").field("database_id", &self.database_id).finish_non_exhaustive() } } /// A row sealed for the object: what goes in `args.data`, the blind tokens /// that go in `args.blind`, and what this device keeps of it. #[derive(Debug, Clone)] pub struct Sealed { pub data: Map, pub blind: Vec, pub dek_enc: String, pub seal_v: u32, } impl Sealer { pub fn new(database_id: impl Into, keys: Arc) -> Arc { Arc::new(Sealer { database_id: database_id.into(), keys, versions: Mutex::new(BTreeMap::new()), learned: std::sync::atomic::AtomicBool::new(false), arrival_held: std::sync::atomic::AtomicBool::new(false) }) } pub fn database_id(&self) -> &str { &self.database_id } /// The DK, or [`SEAL_KEY_MISSING`] by name. fn dk(&self) -> Result { match self.keys.data_key(&self.database_id) { Ok(Some(dk)) => Ok(dk), Ok(None) => Err(SealError::KeyMissing(format!("the data key of {} (this device holds none yet)", self.database_id))), Err(why) => Err(SealError::KeyMissing(format!("the data key of {} (the key store said: {why})", self.database_id))), } } /// Whether this device holds the DK now. pub fn has_key(&self) -> bool { matches!(self.keys.data_key(&self.database_id), Ok(Some(_))) } /// `table`'s current `seal_v`: the object's word, or 1 before any advance. pub fn version(&self, table: &str) -> u32 { self.versions.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(table).map_or(1, |held| held.v) } /// Every `seal_key` row the object holds has been taken ([`Sealer::learn`]): /// a pull that reached the object's end, or the rows asked for whole. pub fn learned_all(&self) { self.learned.store(true, std::sync::atomic::Ordering::SeqCst); } /// Whether [`Sealer::learned_all`] was said: the sealer seals only then. pub fn has_learned(&self) -> bool { self.learned.load(std::sync::atomic::Ordering::SeqCst) } /// Take a `seal_key` row the object served (or this copy kept): a /// table's version only ever moves forward here. pub fn learn(&self, id: &str, data: &Map) { if id == core::arrival::ARRIVAL_ROW && data.get("pub").is_some_and(Value::is_string) { self.arrival_held.store(true, std::sync::atomic::Ordering::SeqCst); return; } let Some(table) = id.strip_prefix(VERSION_ROW) else { return }; let Some(v) = data.get("v").and_then(Value::as_u64).and_then(|v| u32::try_from(v).ok()).filter(|v| *v > 0) else { return }; let mut versions = self.versions.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let held = versions.entry(table.to_string()).or_insert(Version { v, held: true }); *held = Version { v: held.v.max(v), held: true }; } /// A stored row of a sealed table, opened: its clear and sealed columns /// as one row, without the blobs. An open row (legacy, or the Worker's) /// is answered as it stands. pub fn open(&self, table: &str, id: &str, data: &Map) -> Result, SealError> { if !stored_row::is_sealed(data) { return Ok(data.clone()); } let opened = if core::arrival::is_arrival(data) { core::arrival::open_arrival(&self.dk()?, &self.database_id, table, id, data)? } else { core::open_row(&self.dk()?, &self.database_id, table, id, data)? }; // The object's changes to the row since it was sealed (arrival patches), folded over it. core::arrival::fold_patches(&self.dk()?, &self.database_id, table, id, data, opened) } /// The act that hands the object this database's arrival public key /// (e2e rulings R2), when this device holds the DK, has read every seal /// key row, and the object holds none: what the object seals its own /// writes to. Taken as held at once; a refusal is learned on the next /// pull. None when there is nothing to publish. pub fn arrival_row(&self) -> Option { if !self.has_learned() || self.arrival_held.load(std::sync::atomic::Ordering::SeqCst) { return None; } let public = core::arrival::arrival_public(&self.dk().ok()?, &self.database_id).ok()?; self.arrival_held.store(true, std::sync::atomic::Ordering::SeqCst); Some(json!({"table": SEAL_KEY_TABLE, "id": core::arrival::ARRIVAL_ROW, "data": {"pub": core::share::key_text(&public)}})) } /// Whether the wrap `dek_enc` of `table`'s row `id`, sealed under version `v`, opens with this device's key: /// what proves the key this device holds is this database's (UNSENT HEAL, 26 Nov 2026). pub fn opens(&self, table: &str, id: &str, v: u32, dek_enc: &str) -> bool { let Ok(dk) = self.dk() else { return false }; core::table_key(&dk, &self.database_id, table, v).and_then(|tk| stored_row::open_dek(&tk, &self.database_id, table, id, v, dek_enc)).is_ok() } /// `row` (the object's columns, plaintext) sealed for the object under /// the table's current version, reusing the row's DEK when this device /// holds its wrap (`held`: `dek_enc` and its `seal_v`). /// Before the object's `seal_key` rows are read, nothing is sealed: the /// table's version is not known, so it is refused as a missing key, by /// name, and the write waits. pub fn seal(&self, table: &str, id: &str, spec: &SealSpec, row: &Map, held: Option<(&str, u32)>) -> Result { if !self.has_learned() { return Err(SealError::KeyMissing(format!("the seal version of {table} (this device has not yet read the object's seal keys)"))); } let dk = self.dk()?; let dek: Option = match held { Some((dek_enc, v)) => { let tk = core::table_key(&dk, &self.database_id, table, v)?; Some(stored_row::open_dek(&tk, &self.database_id, table, id, v, dek_enc)?) } None => None, }; let v = self.version(table); let data = core::seal_row(&dk, &self.database_id, table, id, v, spec, row, dek.as_ref())?; let bk = core::blind_key(&dk, &self.database_id, table)?; let blind = blind::wire(&blind::row_tokens(&bk, spec, row)); let dek_enc = data.get(stored_row::DEK_ENC).and_then(Value::as_str).ok_or(SealError::ColumnMissing(stored_row::DEK_ENC))?.to_string(); Ok(Sealed { data, blind, dek_enc, seal_v: v }) } /// The act that moves `table` to its next `seal_v` after a window ended /// (§3.2 step 8): a `seal_key` row that holds only the number, made by /// the first advance and updated by every later one. Taken here at once, /// so the next seal is under the new version. The object refuses a /// version that does not move forward (`seal_version_back`): a device /// that raced another learns the row on its next pull. pub fn advance(&self, table: &str) -> Value { let mut versions = self.versions.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let now = versions.get(table).copied().unwrap_or(Version { v: 1, held: false }); let next = now.v + 1; versions.insert(table.to_string(), Version { v: next, held: true }); let act = if now.held { "update" } else { "create" }; json!({"act": act, "args": {"table": SEAL_KEY_TABLE, "id": format!("{VERSION_ROW}{table}"), "data": {"v": next}}}) } } /// The namespace derived ids (contacts, threads, calls) are made under once /// any table they land in is sealed: a derived id is a /// hash of the namespace and a phone number, so under the database id (which /// the Worker knows) a number is found again by trying every one; under this /// keyed namespace, which only a holder of the DK makes, it is not. Every /// device makes the same one, so the Mac's import and the phone's land a /// contact on one id. pub fn keyed_namespace(dk: &DataKey, database_id: &str, plain: &str) -> Result { let bk = core::blind_key(dk, database_id, SEAL_KEY_TABLE)?; Ok(blind::keyed_id(&bk, "namespace", plain)) } /// The id a row of a sealed `table` keeps on the object when the engine /// planned it as `planned`: itself when uuid-shaped (it says nothing), else /// the keyed id only the DK makes from it (a reaction's /// `react::`), the same on every device and pass. pub fn keyed_row_id(dk: &DataKey, database_id: &str, table: &str, planned: &str) -> Result { if uuid_shaped(planned) { return Ok(planned.to_string()); } let bk = core::blind_key(dk, database_id, table)?; Ok(blind::keyed_id(&bk, "id", planned)) } /// A row id that reads as a random uuid: 8-4-4-4-12 hex. pub fn uuid_shaped(id: &str) -> bool { id.len() == 36 && id.char_indices().all(|(i, c)| if matches!(i, 8 | 13 | 18 | 23) { c == '-' } else { c.is_ascii_hexdigit() }) } /// Mint this database's DK and its `seal_key` row (`{dk_enc, vmk_version, /// created_at}` under id [`DK_ROW`]). Once per database, by the first vault /// device; the platform stores the key and the row goes to the object. pub fn mint_data_key(vmk: &Vmk, vmk_version: u32, at: &str) -> Result<(DataKey, Map), SealError> { let dk = DataKey::mint(); let row = data_key_row(vmk, vmk_version, &dk, at)?; Ok((dk, row)) } /// The `seal_key` row of a DK this device already holds, wrapped under the /// VMK: what a database takes when a signed-out phone's own key (made with /// no question) becomes its key at the first back-up. pub fn data_key_row(vmk: &Vmk, vmk_version: u32, dk: &DataKey, at: &str) -> Result, SealError> { let dk_enc = core::seal_dk(vmk, vmk_version, dk)?; let mut row = Map::new(); row.insert("dk_enc".into(), json!(dk_enc)); row.insert("vmk_version".into(), json!(vmk_version)); row.insert("created_at".into(), json!(at)); Ok(row) } /// The DK out of the `seal_key` row [`mint_data_key`] made, with the VMK of /// the version the row names. A VMK of another version is refused by name. pub fn open_data_key(vmk: &Vmk, vmk_version: u32, row: &Map) -> Result { let dk_enc = row.get("dk_enc").and_then(Value::as_str).ok_or(SealError::ColumnMissing("dk_enc"))?; let wrapped_under = row.get("vmk_version").and_then(Value::as_u64).ok_or(SealError::ColumnMissing("vmk_version"))?; if u64::from(vmk_version) != wrapped_under { return Err(SealError::KeyMissing(format!("the vault key of version {wrapped_under} (this device holds version {vmk_version})"))); } core::open_dk(vmk, vmk_version, dk_enc) } /// Refuse an act that would carry a sealed column of a sealed table in the /// clear: a `create`, `update` or `seal` whose `data` names one, or a /// `restore` or `import_rows` row that does. Every act a device posts goes through this, so /// no path past [`Sealer::seal`] reaches the object with plaintext. pub fn guard_act(spec_of: impl Fn(&str) -> Option, act: &str, args: &Value) -> Result<(), String> { let check = |table: &str, data: &Value| -> Result<(), String> { let Some(spec) = spec_of(table) else { return Ok(()) }; let Some(data) = data.as_object() else { return Ok(()) }; // A row the person keeps open for good (Q3) goes as it is. if data.get(KEEP_OPEN) == Some(&Value::Bool(true)) { return Ok(()); } let clear: Vec<&str> = data .iter() .filter(|(key, value)| !stored_row::RESERVED.contains(&key.as_str()) && spec.seals(key) && !value.is_null()) .map(|(key, _)| key.as_str()) .collect(); if clear.is_empty() { return Ok(()); } Err(format!("{SEAL_CLEAR_REFUSED}: {table} is sealed, and {} would have left this device in the clear", clear.join(", "))) }; match act { "create" | "update" | "seal" => check(args["table"].as_str().unwrap_or_default(), &args["data"]), "restore" | "import_rows" => args["rows"].as_array().into_iter().flatten().try_for_each(|row| check(row["table"].as_str().unwrap_or_default(), &row["data"])), _ => Ok(()), } } // ── what this device keeps beside the copy ───────────────────────────────── /// The seal state's tables in the copy, made on first use. pub const STATE_DDL: &str = "\ CREATE TABLE IF NOT EXISTS _seal (tbl TEXT NOT NULL, row_id TEXT NOT NULL, sealed INTEGER NOT NULL, dek_enc TEXT, seal_v INTEGER, version INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS _seal_parked (tbl TEXT NOT NULL, row_id TEXT NOT NULL, code TEXT NOT NULL, reason TEXT NOT NULL, row TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS _seal_waiting (tbl TEXT PRIMARY KEY NOT NULL, mark INTEGER NOT NULL) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS _seal_key (id TEXT PRIMARY KEY NOT NULL, data TEXT NOT NULL) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS _seal_unread (tbl TEXT NOT NULL, row_id TEXT NOT NULL, until_ms INTEGER NOT NULL, tries INTEGER NOT NULL, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS _seal_moved (tbl TEXT NOT NULL, row_id TEXT NOT NULL, until_ms INTEGER NOT NULL, tries INTEGER NOT NULL, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS _edit_base (tbl TEXT NOT NULL, row_id TEXT NOT NULL, col TEXT NOT NULL, base TEXT NOT NULL, moved INTEGER NOT NULL DEFAULT 0, theirs TEXT, PRIMARY KEY (tbl, row_id, col)) WITHOUT ROWID;"; /// THE PARKS' KEYS (FIRST SYNC 8, the coordinator's review of FIRST SYNC 7, 26 Nov 2026): every park's key, code and /// `at` in a narrow table of their own, kept by triggers on `_seal_parked` (a delete then a plain insert: an `OR /// REPLACE` in a trigger takes the outer statement's conflict policy, and a park's upsert made it abort), so no reader /// ever reads the wide table to order, count or mark the parks (`at` is stored after the whole row: an index over /// `_seal_parked` reads every park whole to make, and SQLite makes an index in one statement, under the write lock, /// with no way to make it in parts). A copy whose parks an older build made fills the table in slices between passes /// ([`fill_park_keys`], 500 parks a slice, each slice its own short write); until it is full the batches read the /// keys it holds (every park parked since, and those filled so far) and the counts are unknown. /// /// Made whole or not at all (FIRST SYNC 9): every statement here and the fill state's row in one savepoint, and a copy /// counts as set up only with all of them ([`keys_set_up`]); anything less is made again and owes a whole fill. pub const PARK_KEYS_STATEMENTS: [&str; 8] = [ "CREATE TABLE _seal_park_keys (tbl TEXT NOT NULL, row_id TEXT NOT NULL, code TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID", "CREATE INDEX _seal_park_keys_at ON _seal_park_keys (at)", "CREATE INDEX _seal_park_keys_tbl_at ON _seal_park_keys (tbl, at)", "CREATE INDEX _seal_park_keys_code ON _seal_park_keys (code)", // `done` 1 once every park has its key; else the fill's cursor (the last key filled, none yet when NULL). "CREATE TABLE _seal_park_state (k INTEGER PRIMARY KEY CHECK (k = 0), done INTEGER NOT NULL, tbl TEXT, row_id TEXT)", "CREATE TRIGGER _seal_parked_keys_in AFTER INSERT ON _seal_parked BEGIN DELETE FROM _seal_park_keys WHERE tbl = new.tbl AND row_id = new.row_id; INSERT INTO _seal_park_keys (tbl, row_id, code, at) VALUES (new.tbl, new.row_id, new.code, new.at); END", "CREATE TRIGGER _seal_parked_keys_up AFTER UPDATE ON _seal_parked BEGIN DELETE FROM _seal_park_keys WHERE (tbl = old.tbl AND row_id = old.row_id) OR (tbl = new.tbl AND row_id = new.row_id); INSERT INTO _seal_park_keys (tbl, row_id, code, at) VALUES (new.tbl, new.row_id, new.code, new.at); END", "CREATE TRIGGER _seal_parked_keys_out AFTER DELETE ON _seal_parked BEGIN DELETE FROM _seal_park_keys WHERE tbl = old.tbl AND row_id = old.row_id; END", ]; /// Every object [`PARK_KEYS_STATEMENTS`] makes: a copy is set up only with all of them and the state's row. const PARK_KEYS_OBJECTS: [&str; 8] = [ "_seal_park_keys", "_seal_park_keys_at", "_seal_park_keys_tbl_at", "_seal_park_keys_code", "_seal_park_state", "_seal_parked_keys_in", "_seal_parked_keys_up", "_seal_parked_keys_out", ]; /// The indexes FIRST SYNC 5 to 7 made over `_seal_parked` itself, each read nowhere now: dropped once the keys stand. const OLD_PARK_INDEXES: [&str; 3] = ["_seal_parked_at", "_seal_parked_tbl_at", "_seal_parked_code"]; /// At most this many parks an older build made are filled at once, at a note write (well under a second); more wait /// for the slices between passes. pub const PARKS_INLINE: usize = 10_000; /// Parks filled into the keys in one slice: one short write. pub const FILL_SLICE: usize = 500; /// The longest a slice reads and writes before it commits: the bound on a slice's hold of the writer whatever the /// disk, with room under 300 ms for the commit (FIRST SYNC 9b). pub const SLICE_TIME: std::time::Duration = std::time::Duration::from_millis(150); #[cfg(test)] thread_local! { /// Tests (the measure): the last slice's own work and its commit. pub(crate) static LAST_SLICE: std::cell::Cell<(std::time::Duration, std::time::Duration)> = const { std::cell::Cell::new((std::time::Duration::ZERO, std::time::Duration::ZERO)) }; } #[cfg(test)] thread_local! { /// Tests: a slice's write phase is cut after this many keys written, as the clock would. pub(crate) static WRITE_CUT_FOR_TESTS: std::cell::Cell> = const { std::cell::Cell::new(None) }; } #[cfg(test)] thread_local! { /// Tests: a slice's read time in place of [`SLICE_TIME`]. pub(crate) static SLICE_TIME_FOR_TESTS: std::cell::Cell> = const { std::cell::Cell::new(None) }; } fn slice_time() -> std::time::Duration { #[cfg(test)] if let Some(time) = SLICE_TIME_FOR_TESTS.with(|time| time.get()) { return time; } SLICE_TIME } /// The copies whose parks' keys were checked against the parks this process ([`check_park_keys`], once a launch). static PARKS_SETTLED: std::sync::Mutex>> = std::sync::Mutex::new(None); #[cfg(test)] thread_local! { /// Tests: the setup fails after this many of its statements (0: never), as a kill or a failed statement would. pub(crate) static FAIL_SETUP_AFTER: std::cell::Cell = const { std::cell::Cell::new(0) }; } fn object_held(db: &rusqlite::Connection, name: &str) -> Result { db.query_row("SELECT count(*) FROM sqlite_master WHERE name = ?1", [name], |row| row.get::<_, i64>(0)).map(|n| n > 0) } /// Whether the parks' keys are set up whole: every object of [`PARK_KEYS_OBJECTS`] and the fill state's row. fn keys_set_up(db: &rusqlite::Connection) -> Result { let held: i64 = db.query_row( &format!("SELECT count(*) FROM sqlite_master WHERE name IN ({})", PARK_KEYS_OBJECTS.iter().map(|name| format!("'{name}'")).collect::>().join(", ")), [], |row| row.get(0), )?; if held as usize != PARK_KEYS_OBJECTS.len() { return Ok(false); } db.query_row("SELECT count(*) FROM _seal_park_state WHERE k = 0", [], |row| row.get::<_, i64>(0)).map(|n| n == 1) } /// Whether the wide table holds no park (or is not there): one row read at most. fn no_parks(db: &rusqlite::Connection) -> Result { if !object_held(db, "_seal_parked")? { return Ok(true); } db.query_row("SELECT NOT EXISTS (SELECT 1 FROM _seal_parked)", [], |row| row.get(0)) } /// Whether every park of this copy has its key in `_seal_park_keys`: set up whole and the fill done. pub fn park_keys_full(db: &rusqlite::Connection) -> Result { let unread = |error: rusqlite::Error| format!("this copy's parks could not be read ({error})"); if !keys_set_up(db).map_err(unread)? { return Ok(false); } db.query_row("SELECT done FROM _seal_park_state WHERE k = 0", [], |row| row.get::<_, i64>(0)).map(|done| done == 1).map_err(unread) } /// The seal state's tables and the parks' keys. A copy not set up whole ([`keys_set_up`]) has whatever part of the /// keys stands dropped and all of them made again in one savepoint, owing a whole fill of the parks it holds: done /// at once for none or at most [`PARKS_INLINE`] parks, else in slices ([`fill_park_keys`]). Once a launch, a copy /// whose keys are full has them checked against the parks ([`check_park_keys`]). fn ensure_state(db: &rusqlite::Connection) -> Result<(), rusqlite::Error> { db.execute_batch(STATE_DDL)?; if !keys_set_up(db)? { db.execute_batch("SAVEPOINT park_keys_setup")?; match set_up_keys(db) { Ok(()) => db.execute_batch("RELEASE park_keys_setup")?, Err(error) => { let _ = db.execute_batch("ROLLBACK TO park_keys_setup; RELEASE park_keys_setup"); return Err(error); } } } let key = db.path().unwrap_or_default().to_string(); if key.is_empty() || PARKS_SETTLED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().is_some_and(|settled| settled.contains(&key)) { return Ok(()); } let done: i64 = db.query_row("SELECT done FROM _seal_park_state WHERE k = 0", [], |row| row.get(0))?; if done == 1 { settle_full_keys(db)?; PARKS_SETTLED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get_or_insert_with(Default::default).insert(key); } Ok(()) } /// A launch's first look at full keys: the keys are checked against the parks, in one read (a commit from another /// connection between the two tables' reads would look like a disagreement, FIRST SYNC 9b). Keys that disagree owe a /// whole fill again, which mends them a slice at a time ([`fill_one_slice`]): never a DELETE of every key here, at a /// note write inside a pass. Answers whether they agreed. pub(crate) fn settle_full_keys(db: &rusqlite::Connection) -> Result { let alone = db.is_autocommit(); if alone { db.execute_batch("BEGIN")?; } let agreed = check_park_keys(db); if alone { let _ = db.execute_batch("COMMIT"); } if agreed? { return Ok(true); } tracing::warn!("seal: the parks' keys disagreed with the parks; filled again, a slice at a time"); db.execute("UPDATE _seal_park_state SET done = 0, tbl = NULL, row_id = NULL WHERE k = 0", [])?; Ok(false) } /// The keys made from nothing (any part a kill or a failed statement left goes first), owing a whole fill. fn set_up_keys(db: &rusqlite::Connection) -> Result<(), rusqlite::Error> { db.execute_batch( "DROP TRIGGER IF EXISTS _seal_parked_keys_in; DROP TRIGGER IF EXISTS _seal_parked_keys_up; DROP TRIGGER IF EXISTS _seal_parked_keys_out; DROP TABLE IF EXISTS _seal_park_keys; DROP TABLE IF EXISTS _seal_park_state; DROP TABLE IF EXISTS _seal_park_fill;", )?; for (at, statement) in PARK_KEYS_STATEMENTS.iter().enumerate() { db.execute_batch(statement)?; #[cfg(test)] if FAIL_SETUP_AFTER.with(|after| after.get()) == at + 1 { return Err(rusqlite::Error::InvalidQuery); } let _ = at; } let empty = no_parks(db)?; db.execute("INSERT INTO _seal_park_state (k, done, tbl, row_id) VALUES (0, ?1, NULL, NULL)", [empty as i64])?; #[cfg(test)] if FAIL_SETUP_AFTER.with(|after| after.get()) == PARK_KEYS_STATEMENTS.len() + 1 { return Err(rusqlite::Error::InvalidQuery); } if !empty { let few: i64 = db.query_row(&format!("SELECT count(*) FROM (SELECT 1 FROM _seal_parked LIMIT {})", PARKS_INLINE + 1), [], |row| row.get(0))?; if few as usize <= PARKS_INLINE { fill_slices(db, None)?; } } Ok(()) } /// The parks' keys checked against the parks, cheaply (FIRST SYNC 9: the two must never disagree for good): the first /// key of each table and the keys at and after 32 random places, each read off both tables by key (a seek each), /// must be the same parks with the same code and `at`. Answers whether they agree. pub fn check_park_keys(db: &rusqlite::Connection) -> Result { type Key = Option<(String, String, String, String)>; let at_or_after = |table: &str, tbl: &str, row_id: &str| -> Result { let sql = format!("SELECT tbl, row_id, code, at FROM {table} WHERE (tbl, row_id) >= (?1, ?2) ORDER BY tbl, row_id LIMIT 1"); match db.prepare_cached(&sql)?.query_row([tbl, row_id], |row| Ok(Some((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)))) { Ok(key) => Ok(key), Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), Err(error) => Err(error), } }; let both = |tbl: &str, row_id: &str| -> Result { let (keyed, parked) = (at_or_after("_seal_park_keys", tbl, row_id)?, at_or_after("_seal_parked", tbl, row_id)?); if keyed != parked { return Ok(false); } // And the one after it, so a key missing beside a park is seen too. match keyed { Some((tbl, row_id, _, _)) => { let next = format!("{row_id}\u{0}"); Ok(at_or_after("_seal_park_keys", &tbl, &next)? == at_or_after("_seal_parked", &tbl, &next)?) } None => Ok(true), } }; if !both("", "")? { return Ok(false); } let tables: Vec = { let mut statement = db.prepare_cached( "WITH RECURSIVE t(tbl) AS (SELECT min(tbl) FROM _seal_parked UNION ALL SELECT (SELECT min(tbl) FROM _seal_parked WHERE tbl > t.tbl) FROM t WHERE t.tbl IS NOT NULL) SELECT tbl FROM t WHERE tbl IS NOT NULL", )?; let rows = statement.query_map([], |row| row.get(0))?; rows.collect::>()? }; let mut seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|since| since.as_nanos() as u64).unwrap_or(7) | 1; for table in &tables { if !both(table, "")? { return Ok(false); } } if tables.is_empty() { return Ok(true); } for _ in 0..32 { seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17; let table = &tables[(seed % tables.len() as u64) as usize]; // A place among ids of any shape: hex (uuids), digits, and the ids' own first characters. let place = format!("{:016x}", seed.rotate_left(17)); let place = match seed % 3 { 0 => place, 1 => format!("{}", seed % 1_000_000), _ => place.chars().take(2).collect(), }; if !both(table, &place)? { return Ok(false); } } Ok(true) } /// Fill the parks' keys from the parks an older build made, slice by slice, each its own short write (a savepoint /// inside a caller's transaction), until `budget` is spent or the fill is done. Answers whether it is done. Between /// passes, so a pass waits at most one slice for the writer. /// Whether this copy owes a fill of its parks' keys: it holds seal state, and its keys are not full (not set up yet /// counts as owed). pub fn fill_owed(db: &rusqlite::Connection) -> Result { Ok(has_state(db)? && !park_keys_full(db)?) } pub fn fill_park_keys(db: &rusqlite::Connection, budget: std::time::Duration) -> Result { let failed = |error: rusqlite::Error| format!("this copy's parks' keys could not be filled ({error})"); if !has_state(db)? { return Ok(true); } ensure_state(db).map_err(failed)?; fill_slices(db, Some(std::time::Instant::now() + budget)).map_err(failed)?; park_keys_full(db) } fn fill_slices(db: &rusqlite::Connection, until: Option) -> Result<(), rusqlite::Error> { loop { let (done, after_tbl, after_id): (i64, Option, Option) = db.query_row("SELECT done, tbl, row_id FROM _seal_park_state WHERE k = 0", [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?; if done == 1 { return Ok(()); } let alone = db.is_autocommit(); db.execute_batch(if alone { "BEGIN IMMEDIATE" } else { "SAVEPOINT park_fill" })?; #[cfg(test)] let began = std::time::Instant::now(); let work = fill_one_slice(db, after_tbl, after_id); #[cfg(test)] let worked = began.elapsed(); match work { Ok(_) => { db.execute_batch(if alone { "COMMIT" } else { "RELEASE park_fill" })?; #[cfg(test)] LAST_SLICE.with(|last| last.set((worked, began.elapsed() - worked))); } Err(error) => { let _ = db.execute_batch(if alone { "ROLLBACK" } else { "ROLLBACK TO park_fill; RELEASE park_fill" }); return Err(error); } } if until.is_some_and(|until| std::time::Instant::now() >= until) { return Ok(()); } } } /// One slice: the next [`FILL_SLICE`] parks by key after the cursor, their keys written (a park changed since was /// written by its trigger and is read here as it now is), keys in that span with no park removed (keys a self-check /// found wrong), and the cursor moved to the last key written, or the fill marked done. The whole slice, its reads /// and its writes, stops at [`SLICE_TIME`] (FIRST SYNC 9b: the aim is under 300 ms a hold of the writer, commit included); /// at least one park is written, so the fill always moves. The last slice also removes keys past the last park and /// marks every table holding rows waiting for a parent to be woken on the next pass (FIRST SYNC 9: a wake during the /// fill reached only the keys then held). fn fill_one_slice(db: &rusqlite::Connection, after_tbl: Option, after_id: Option) -> Result<(), rusqlite::Error> { let started = std::time::Instant::now(); let out_of_time = || started.elapsed() >= slice_time(); let mut cut = false; let keys: Vec<(String, String, String, String)> = { let mut statement = match after_tbl.as_deref().zip(after_id.as_deref()) { Some(_) => db.prepare_cached("SELECT tbl, row_id, code, at FROM _seal_parked WHERE (tbl, row_id) > (?1, ?2) ORDER BY tbl, row_id LIMIT ?3")?, None => db.prepare_cached("SELECT tbl, row_id, code, at FROM _seal_parked WHERE ?1 IS NULL AND ?2 IS NULL ORDER BY tbl, row_id LIMIT ?3")?, }; let rows = statement.query_map(rusqlite::params![after_tbl, after_id, FILL_SLICE as i64], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)))?; // Each park read is a seek into the wide table's pages: on a busy disk 2,000 of them held the writer 12.6 s. let mut keys = Vec::new(); for row in rows { keys.push(row?); if out_of_time() { cut = true; break; } } keys }; let mut put = db.prepare_cached("INSERT OR REPLACE INTO _seal_park_keys (tbl, row_id, code, at) VALUES (?1, ?2, ?3, ?4)")?; let mut written = 0; for (tbl, row_id, code, at) in &keys { put.execute([tbl, row_id, code, at])?; written += 1; #[cfg(test)] let out_of_time = || out_of_time() || WRITE_CUT_FOR_TESTS.with(|after| after.get()) == Some(written); if written < keys.len() && out_of_time() { cut = true; break; } } let keys = &keys[..written]; // Keys with no park in the span this slice covered: none on a first fill (every key came from a park's trigger); // after a self-check found the keys wrong, what it found is mended here, a span a slice, never all at once. let stale = "NOT EXISTS (SELECT 1 FROM _seal_parked p WHERE p.tbl = _seal_park_keys.tbl AND p.row_id = _seal_park_keys.row_id)"; let last = keys.last().map(|(tbl, row_id, _, _)| (tbl.clone(), row_id.clone())); let lower = match after_tbl.as_deref().zip(after_id.as_deref()) { Some(_) => "(tbl, row_id) > (?1, ?2)", None => "?1 IS NULL AND ?2 IS NULL", }; match last { Some((tbl, row_id)) if cut || keys.len() == FILL_SLICE => { db.prepare_cached(&format!("DELETE FROM _seal_park_keys WHERE {lower} AND (tbl, row_id) < (?3, ?4) AND {stale}"))? .execute(rusqlite::params![after_tbl, after_id, tbl, row_id])?; db.prepare_cached("UPDATE _seal_park_state SET tbl = ?1, row_id = ?2 WHERE k = 0")?.execute([tbl, row_id])?; } _ => { db.prepare_cached(&format!("DELETE FROM _seal_park_keys WHERE {lower} AND {stale}"))?.execute(rusqlite::params![after_tbl, after_id])?; db.execute("UPDATE _seal_park_state SET done = 1, tbl = NULL, row_id = NULL WHERE k = 0", [])?; db.execute( "INSERT INTO _seal_waiting (tbl, mark) SELECT DISTINCT tbl, -1 FROM _seal_park_keys WHERE at >= char(127) ON CONFLICT (tbl) DO UPDATE SET mark = -1", [], )?; } } Ok(()) } /// The first of the old indexes over the wide table this copy still holds once its keys are full, read nowhere now. /// A DROP INDEX is one statement that frees every page of the index (1.0 to 4.4 s each over 280,000 parks on the /// busy box), so it never runs at a note write or between passes: the phone drops one per background step, with /// the indexes a move left (`cotton-ffi` `mail_index::build_later`). pub fn old_park_index_left(db: &rusqlite::Connection) -> Result, rusqlite::Error> { if !keys_set_up(db)? { return Ok(None); } let done: i64 = db.query_row("SELECT done FROM _seal_park_state WHERE k = 0", [], |row| row.get(0))?; if done != 1 { return Ok(None); } for name in OLD_PARK_INDEXES { if db.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'index' AND name = ?1", [name], |row| row.get::<_, i64>(0))? > 0 { return Ok(Some(name)); } } Ok(None) } /// Drop the old index `name` ([`old_park_index_left`]) on its own, outside any transaction. pub fn drop_old_park_index(db: &rusqlite::Connection, name: &str) -> Result<(), rusqlite::Error> { if !OLD_PARK_INDEXES.contains(&name) { return Err(rusqlite::Error::InvalidQuery); } db.execute_batch(&format!("DROP INDEX IF EXISTS {name}")) } /// THE TEXT AN UNSENT EDIT WAS WRITTEN OVER (owner's lost edit, 21 Nov 2026), /// for the columns an app merges (Words' note body): `base` is the text as /// the object last held it when this phone wrote over it — set at the edit, /// moved on by each post the object takes. A post refused because the row /// moved ([`crate::transport::object`]'s `version_moved`) marks it `moved`; /// the pull then keeps the newer text as `theirs`, and the row is not sent /// again until the app has merged its edit over it and cleared `theirs`. /// A row of the table, by its served table name. pub const EDIT_BASE: &str = "_edit_base"; /// [`EDIT_BASE`]'s table, as [`STATE_DDL`] makes it, for an app that keeps a base first. pub const EDIT_BASE_DDL: &str = "CREATE TABLE IF NOT EXISTS _edit_base (tbl TEXT NOT NULL, row_id TEXT NOT NULL, col TEXT NOT NULL, base TEXT NOT NULL, moved INTEGER NOT NULL DEFAULT 0, theirs TEXT, PRIMARY KEY (tbl, row_id, col)) WITHOUT ROWID;"; /// One thing a pass learned of a sealed row, written to the copy once the /// page is read ([`write_notes`]). #[derive(Debug, Clone, PartialEq)] pub enum Note { /// The object holds it sealed: its wrap and version. Sealed { table: String, id: String, dek_enc: String, seal_v: u32, version: i64 }, /// The object holds it open (the sweep's work). Open { table: String, id: String, version: i64 }, /// It did not open: kept whole, by name. Parked { table: String, id: String, code: String, reason: String, row: Value, at: String }, /// Deleted on the object: nothing kept. Gone { table: String, id: String }, /// A `seal_key` row. Key { id: String, data: Map }, /// The object took this phone's post of the row: these columns' text is /// the base of any edit after it ([`EDIT_BASE`]). Taken { table: String, id: String, values: Map }, /// The object refused the post: the row moved since this copy read it. Moved { table: String, id: String }, /// A parked row now stands in the copy, opened and folded: its park goes. Unparked { table: String, id: String }, /// A parked row was tried again once the key was held ([`try_mark`]): it goes to the back of the queue, and /// stays there should its fold refuse it. Tried { table: String, id: String, at: String }, /// A parked row opened and its fold was refused: named so, its opening again is no progress ([`FOLD_REFUSED`]). Refused { table: String, id: String }, /// A parked row opened and folded dormant: its owning parent (a mail's conversation) is not in the copy yet. /// Named [`WAITING_PARENT`] and held out of every batch ([`WAITING`]) until [`Note::Wake`]; its park stays until /// the row stands (FIRST SYNC 6, the coordinator 26 Nov 2026). `mark` is its parent tables' [`parent_mark`] now. Waiting { table: String, id: String, mark: i64 }, /// The rows of `table` waiting for a parent go back to the batches, first among the tried: a row of a parent /// table folded since they waited. `None` (a pull reached the object's end, at most once a /// [`WAKE_AT_END_EVERY_MS`]): every table's, BEHIND every tried row, the wake kept at `at_ms`. `mark` is the /// table's [`parent_mark`] now (0 for `None`): while a fill is owed the table's mark is kept at it, so the rows /// waiting again are woken only once the parent gains another row, never on every pass (FIRST SYNC 9b). Wake { table: Option, at_ms: i64, mark: i64 }, /// The row as a pull brought it while its post stood refused: its newer text. Pulled { table: String, id: String, data: Map }, /// The object would not hand the row back readable: not read again before `until_ms`, after `tries` reads /// ([`unread_wait`], UNSENT HEAL 6). Unread { table: String, id: String, until_ms: i64, tries: u32 }, /// The row read again (opened, or gone): its wait goes. Readable { table: String, id: String }, /// The edit laid over a fresh read was refused as moved again, `tries` times in a row: from the third it is not /// read again before `until_ms` (`until_ms` 0 before then; [`moved_wait`], UNSENT HEAL 7). MovedAgain { table: String, id: String, until_ms: i64, tries: u32 }, /// The edit laid over a fresh read was taken: its count of moves goes. Laid { table: String, id: String }, } /// When `table`'s row `id` may be read from the object again, and how many reads it has had, if it would not open /// ([`Note::Unread`]); `None` for a row that never waited, or a copy that has not made the table yet. pub fn unread_wait(db: &rusqlite::Connection, table: &str, id: &str) -> Result, String> { row_wait(db, "_seal_unread", table, id) } /// When `table`'s row `id` may be read and laid over again, and how many times in a row its edit laid over a fresh /// read was refused as moved ([`Note::MovedAgain`]); `None` for a row whose last laid edit was taken, or never moved. pub fn moved_wait(db: &rusqlite::Connection, table: &str, id: &str) -> Result, String> { row_wait(db, "_seal_moved", table, id) } fn row_wait(db: &rusqlite::Connection, waits: &str, table: &str, id: &str) -> Result, String> { let failed = |error: rusqlite::Error| format!("this copy's waits to read a row could not be read ({error})"); let made: i64 = db.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", [waits], |row| row.get(0)).map_err(failed)?; if made == 0 { return Ok(None); } match db.prepare_cached(&format!("SELECT until_ms, tries FROM {waits} WHERE tbl = ?1 AND row_id = ?2")).map_err(failed)?.query_row([table, id], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, u32>(1)?))) { Ok(wait) => Ok(Some(wait)), Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), Err(error) => Err(failed(error)), } } /// THE SEALED TABLES THIS COPY HAS SEEN (the memory lock, 23 Nov 2026, /// assets/design/shared/MEMORY-LOCK.md). A row is noted in `_seal` only when a /// pull folds it while its table is sealed, and the sweep seals only noted /// rows; so a table the object seals after this copy pulled it (memory, one /// account at a time) holds rows no sweep would ever reach. Each such table /// is owed whole once ([`turned_sealed`]): pulled again, each row lands noted /// open with the object's version, and the sweep seals it. const KNOWN_DDL: &str = "CREATE TABLE IF NOT EXISTS _seal_known (tbl TEXT PRIMARY KEY NOT NULL) WITHOUT ROWID;"; /// The tables of `sealed_now` (each `(object table, copy table, key column)`) /// this copy has not seen sealed yet and holds rows of that no pull noted. /// One holding no such row is taken as seen at once: a copy updated to this /// build pulled its sealed tables sealed, so their rows are noted and nothing /// comes again; one that learned of a seal before this build (memory, locked /// while it ran an older one) still has its rows taken whole, once. pub fn turned_sealed(db: &rusqlite::Connection, sealed_now: &[(String, String, String)]) -> Result, String> { let failed = |error: rusqlite::Error| format!("this copy could not read the sealed tables it has seen ({error})"); ensure_state(db).map_err(failed)?; db.execute_batch(KNOWN_DDL).map_err(failed)?; let mut statement = db.prepare("SELECT tbl FROM _seal_known").map_err(failed)?; let known: std::collections::BTreeSet = statement.query_map([], |row| row.get::<_, String>(0)).map_err(failed)?.collect::>().map_err(failed)?; let mut seen = Vec::new(); let mut turned = Vec::new(); for (table, store, id_column) in sealed_now.iter().filter(|(table, _, _)| !known.contains(table)) { let exists: i64 = db.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", [store], |row| row.get(0)).map_err(failed)?; let unnoted = exists > 0 && db .query_row(&format!("SELECT EXISTS (SELECT 1 FROM \"{store}\" t WHERE NOT EXISTS (SELECT 1 FROM _seal s WHERE s.tbl = ?1 AND s.row_id = t.\"{id_column}\"))"), [table], |row| row.get::<_, i64>(0)) .map_err(failed)? == 1; if unnoted { turned.push(table.clone()) } else { seen.push(table.clone()) } } know_sealed(db, &seen)?; Ok(turned) } /// `tables` are seen sealed: their rows came again whole and are noted. pub fn know_sealed(db: &rusqlite::Connection, tables: &[String]) -> Result<(), String> { let failed = |error: rusqlite::Error| format!("this copy could not keep the sealed tables it has seen ({error})"); db.execute_batch(KNOWN_DDL).map_err(failed)?; for table in tables { db.execute("INSERT OR IGNORE INTO _seal_known (tbl) VALUES (?1)", [table]).map_err(failed)?; } Ok(()) } /// Write `notes` to the copy. A row's park is cleared by any later word of /// it; a sealed row written by this device keeps the version it had. pub fn write_notes(db: &rusqlite::Connection, notes: &[Note]) -> Result<(), String> { write_notes_parks(db, notes, true) } /// The notes of rows opened from their parks ([`parked`]), kept with each /// park left in place: those notes are kept before the pass's ops fold, and /// a parked row has no other copy (the cursor went past it while it waited /// for the key), so a fold that fails must find it parked again on the next /// pass. The park goes once the row stands in the copy ([`Note::Unparked`]). /// Seen on dev, 24 Nov 2026: a first pull of 100,000 mails parked 172,013 /// rows, the key opened, the fold that took them failed, and the copy held /// none of them and parked none. pub fn write_reopened_notes(db: &rusqlite::Connection, notes: &[Note]) -> Result<(), String> { write_notes_parks(db, notes, false) } fn write_notes_parks(db: &rusqlite::Connection, notes: &[Note], unpark: bool) -> Result<(), String> { let failed = |error: rusqlite::Error| format!("this copy could not keep its seal state ({error})"); ensure_state(db).map_err(failed)?; // One commit for every note, inside a pass's transaction or alone (dev, 24 Nov 2026: 172,002 notes of a first pull // of 100,000 mails, each its own commit, took the better part of an hour on a busy disk). db.execute_batch("SAVEPOINT seal_notes").map_err(failed)?; match write_each_note(db, notes, unpark) { Ok(()) => db.execute_batch("RELEASE seal_notes").map_err(failed), Err(error) => { let _ = db.execute_batch("ROLLBACK TO seal_notes; RELEASE seal_notes"); Err(error) } } } /// Each statement prepared once and kept on the connection (`prepare_cached`): a first pull parks every row, a note /// each, and parsing the same statement for each of them was 1.25 ms a row, 42% of a first sync before the key /// (meetings-comms, FIRST SYNC FAST, 26 Nov 2026). fn write_each_note(db: &rusqlite::Connection, notes: &[Note], unpark: bool) -> Result<(), String> { let failed = |error: rusqlite::Error| format!("this copy could not keep its seal state ({error})"); for note in notes { match note { Note::Sealed { table, id, dek_enc, seal_v, version } => { db.prepare_cached("INSERT INTO _seal (tbl, row_id, sealed, dek_enc, seal_v, version) VALUES (?1, ?2, 1, ?3, ?4, ?5) ON CONFLICT (tbl, row_id) DO UPDATE SET sealed = 1, dek_enc = excluded.dek_enc, seal_v = excluded.seal_v, version = max(version, excluded.version)").map_err(failed)?.execute(rusqlite::params![table, id, dek_enc, seal_v, version], ) .map_err(failed)?; if unpark { db.prepare_cached("DELETE FROM _seal_parked WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table, id]).map_err(failed)?; } } Note::Open { table, id, version } => { db.prepare_cached("INSERT INTO _seal (tbl, row_id, sealed, dek_enc, seal_v, version) VALUES (?1, ?2, 0, NULL, NULL, ?3) ON CONFLICT (tbl, row_id) DO UPDATE SET sealed = 0, version = excluded.version").map_err(failed)?.execute(rusqlite::params![table, id, version], ) .map_err(failed)?; if unpark { db.prepare_cached("DELETE FROM _seal_parked WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table, id]).map_err(failed)?; } } Note::Unparked { table, id } => { db.prepare_cached("DELETE FROM _seal_parked WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table, id]).map_err(failed)?; } Note::Tried { table, id, at } => { db.prepare_cached("UPDATE _seal_parked SET at = ?3 WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table, id, at]).map_err(failed)?; } Note::Waiting { table, id, mark } => { db.prepare_cached( "UPDATE _seal_parked SET code = ?3, reason = ?4, at = CASE WHEN at >= char(127) THEN at ELSE char(127) || at END WHERE tbl = ?1 AND row_id = ?2", ) .map_err(failed)? .execute([table.as_str(), id.as_str(), WAITING_PARENT, "it opened and waits for the row it belongs to (a mail for its conversation); tried again once that row comes"]) .map_err(failed)?; db.prepare_cached("INSERT INTO _seal_waiting (tbl, mark) VALUES (?1, ?2) ON CONFLICT (tbl) DO UPDATE SET mark = excluded.mark") .map_err(failed)? .execute(rusqlite::params![table, mark]) .map_err(failed)?; } Note::Wake { table, at_ms, mark } => { // The code kept until the row stands or waits again. While a fill is owed the wake reaches only the // keys held so far: the tables' marks stay (moved to the parent's mark now), so the rows still to be // filled are woken by the fill's last slice, which marks every table holding waiting rows (FIRST // SYNC 9). The daily stamp is kept even then: those marks wake the rest, and with no stamp every // caught-up pass of the fill woke the same rows again (FIRST SYNC 9b). let filling = !park_keys_full(db)?; match table { // A parent came: back among the tried, ahead of them all (`~` sorts before every mark). Some(table) => { let ids = waiting_of(db, Some(table)).map_err(failed)?; let mut wake = db.prepare_cached("UPDATE _seal_parked SET at = '~' WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?; for (tbl, id) in &ids { wake.execute([tbl, id]).map_err(failed)?; } if filling { db.prepare_cached("UPDATE _seal_waiting SET mark = max(mark, ?2) WHERE tbl = ?1").map_err(failed)?.execute(rusqlite::params![table, mark]).map_err(failed)?; } else { db.prepare_cached("DELETE FROM _seal_waiting WHERE tbl = ?1").map_err(failed)?.execute([table]).map_err(failed)?; } } // The daily try at the end of a pull: behind every tried row (the next mark), so orphans whose // parent never comes never hold the other tried parks. None => { let ids = waiting_of(db, None).map_err(failed)?; if !ids.is_empty() { let mark = try_mark(db)?; let mut wake = db.prepare_cached("UPDATE _seal_parked SET at = ?3 WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?; for (tbl, id) in &ids { wake.execute([tbl, id, &mark]).map_err(failed)?; } } if !filling { db.prepare_cached("DELETE FROM _seal_waiting WHERE tbl <> ?1").map_err(failed)?.execute([WOKEN_AT_END]).map_err(failed)?; } db.prepare_cached("INSERT INTO _seal_waiting (tbl, mark) VALUES (?1, ?2) ON CONFLICT (tbl) DO UPDATE SET mark = excluded.mark") .map_err(failed)? .execute(rusqlite::params![WOKEN_AT_END, at_ms]) .map_err(failed)?; } } } Note::Refused { table, id } => { db.prepare_cached("UPDATE _seal_parked SET code = ?3, reason = ?4 WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table.as_str(), id.as_str(), FOLD_REFUSED, "it opened, and this copy refused it as it folded; tried again on a later pass"], ) .map_err(failed)?; } Note::Parked { table, id, code, reason, row, at } => { db.prepare_cached("INSERT INTO _seal_parked (tbl, row_id, code, reason, row, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT (tbl, row_id) DO UPDATE SET code = excluded.code, reason = excluded.reason, row = excluded.row, at = excluded.at").map_err(failed)?.execute(rusqlite::params![table, id, code, reason, row.to_string(), at], ) .map_err(failed)?; } Note::Gone { table, id } => { db.prepare_cached("DELETE FROM _seal WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table, id]).map_err(failed)?; db.prepare_cached("DELETE FROM _seal_parked WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table, id]).map_err(failed)?; } Note::Key { id, data } => { db.prepare_cached("INSERT INTO _seal_key (id, data) VALUES (?1, ?2) ON CONFLICT (id) DO UPDATE SET data = excluded.data").map_err(failed)?.execute(rusqlite::params![id, Value::Object(data.clone()).to_string()], ) .map_err(failed)?; } Note::Taken { table, id, values } => { for (column, value) in values { if let Some(text) = value.as_str() { db.prepare_cached("UPDATE _edit_base SET base = ?4, moved = 0 WHERE tbl = ?1 AND row_id = ?2 AND col = ?3 AND theirs IS NULL").map_err(failed)?.execute(rusqlite::params![table, id, column, text]).map_err(failed)?; } } } Note::Unread { table, id, until_ms, tries } => { db.prepare_cached("INSERT INTO _seal_unread (tbl, row_id, until_ms, tries) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (tbl, row_id) DO UPDATE SET until_ms = excluded.until_ms, tries = excluded.tries").map_err(failed)?.execute(rusqlite::params![table, id, until_ms, tries]).map_err(failed)?; } Note::Readable { table, id } => { db.prepare_cached("DELETE FROM _seal_unread WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table, id]).map_err(failed)?; } Note::MovedAgain { table, id, until_ms, tries } => { db.prepare_cached("INSERT INTO _seal_moved (tbl, row_id, until_ms, tries) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (tbl, row_id) DO UPDATE SET until_ms = excluded.until_ms, tries = excluded.tries").map_err(failed)?.execute(rusqlite::params![table, id, until_ms, tries]).map_err(failed)?; } Note::Laid { table, id } => { db.prepare_cached("DELETE FROM _seal_moved WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table, id]).map_err(failed)?; } Note::Moved { table, id } => { db.prepare_cached("UPDATE _edit_base SET moved = 1 WHERE tbl = ?1 AND row_id = ?2").map_err(failed)?.execute([table, id]).map_err(failed)?; } Note::Pulled { table, id, data } => { for (column, value) in data { if let Some(text) = value.as_str() { db.prepare_cached("UPDATE _edit_base SET theirs = ?4 WHERE tbl = ?1 AND row_id = ?2 AND col = ?3 AND moved = 1 AND base IS NOT ?4").map_err(failed)?.execute(rusqlite::params![table, id, column, text]).map_err(failed)?; } } } } } Ok(()) } /// Whether the copy has made its seal state yet. /// The parks waiting for a parent (`at` past DEL), of `table` or of every table, off the parks' keys. fn waiting_of(db: &rusqlite::Connection, table: Option<&str>) -> Result, rusqlite::Error> { let mut statement = db.prepare_cached("SELECT tbl, row_id FROM _seal_park_keys WHERE at >= char(127) AND (?1 IS NULL OR tbl = ?1)")?; let rows = statement.query_map([table], |row| Ok((row.get(0)?, row.get(1)?)))?; rows.collect() } fn has_state(db: &rusqlite::Connection) -> Result { db.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = '_seal'", [], |row| row.get::<_, i64>(0)) .map(|n| n > 0) .map_err(|error| format!("this copy's seal state could not be read ({error})")) } /// The row's wrap as this copy holds it: `dek_enc` and its `seal_v`. pub fn held_wrap(db: &rusqlite::Connection, table: &str, id: &str) -> Result, String> { if !has_state(db)? { return Ok(None); } db.query_row("SELECT dek_enc, seal_v FROM _seal WHERE tbl = ?1 AND row_id = ?2 AND dek_enc IS NOT NULL", [table, id], |row| Ok((row.get::<_, String>(0)?, row.get::<_, u32>(1)?))) .map(Some) .or_else(|error| if error == rusqlite::Error::QueryReturnedNoRows { Ok(None) } else { Err(format!("this copy's seal state could not be read ({error})")) }) } /// Up to `limit` wraps this copy keeps, other than `table`'s row `id`: `(table, id, dek_enc, seal_v)`. pub fn other_wraps(db: &rusqlite::Connection, table: &str, id: &str, limit: usize) -> Result, String> { if !has_state(db)? { return Ok(Vec::new()); } let mut statement = db .prepare("SELECT tbl, row_id, dek_enc, seal_v FROM _seal WHERE dek_enc IS NOT NULL AND seal_v IS NOT NULL AND NOT (tbl = ?1 AND row_id = ?2) LIMIT ?3") .map_err(|error| format!("this copy's seal state could not be read ({error})"))?; let rows = statement .query_map(rusqlite::params![table, id, limit as i64], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, u32>(3)?))) .map_err(|error| format!("this copy's seal state could not be read ({error})"))?; rows.collect::, _>>().map_err(|error| format!("this copy's seal state could not be read ({error})")) } /// The rows whose post the object refused as moved and whose newer text is /// still to come ([`EDIT_BASE`]), and the columns watched of each. pub fn edit_bases_moved(db: &rusqlite::Connection) -> Result, String> { edit_base_rows(db, "moved = 1 AND theirs IS NULL") } /// Whether the row waits for its app to merge an edit over newer text. pub fn merge_waits(db: &rusqlite::Connection, table: &str, id: &str) -> Result { Ok(edit_base_rows(db, "theirs IS NOT NULL")?.iter().any(|(t, i)| t == table && i == id)) } /// The watched columns of a row ([`EDIT_BASE`]). pub fn edit_base_columns(db: &rusqlite::Connection, table: &str, id: &str) -> Result, String> { if !has_table(db, EDIT_BASE)? { return Ok(Vec::new()); } let unread = |error: rusqlite::Error| format!("this copy's edit bases could not be read ({error})"); let mut statement = db.prepare("SELECT col FROM _edit_base WHERE tbl = ?1 AND row_id = ?2").map_err(unread)?; let columns = statement.query_map([table, id], |row| row.get::<_, String>(0)).map_err(unread)?.collect::, _>>().map_err(unread)?; Ok(columns) } fn edit_base_rows(db: &rusqlite::Connection, filter: &str) -> Result, String> { if !has_table(db, EDIT_BASE)? { return Ok(Vec::new()); } let unread = |error: rusqlite::Error| format!("this copy's edit bases could not be read ({error})"); let mut statement = db.prepare(&format!("SELECT DISTINCT tbl, row_id FROM _edit_base WHERE {filter}")).map_err(unread)?; let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))).map_err(unread)?.collect::, _>>().map_err(unread)?; Ok(rows) } fn has_table(db: &rusqlite::Connection, name: &str) -> Result { db.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", [name], |row| row.get::<_, i64>(0)) .map(|n| n > 0) .map_err(|error| format!("this copy's seal state could not be read ({error})")) } /// The object's version of a row of a sealed table as this copy last read /// it, when it holds one. pub fn held_version(db: &rusqlite::Connection, table: &str, id: &str) -> Result, String> { if !has_state(db)? { return Ok(None); } db.query_row("SELECT version FROM _seal WHERE tbl = ?1 AND row_id = ?2", [table, id], |row| row.get(0)) .map(Some) .or_else(|error| if error == rusqlite::Error::QueryReturnedNoRows { Ok(None) } else { Err(format!("this copy's seal state could not be read ({error})")) }) } /// The `seal_key` rows this copy keeps. pub fn kept_keys(db: &rusqlite::Connection) -> Result)>, String> { if !has_state(db)? { return Ok(Vec::new()); } let unread = |error: rusqlite::Error| format!("this copy's seal keys could not be read ({error})"); let mut statement = db.prepare("SELECT id, data FROM _seal_key ORDER BY id").map_err(unread)?; let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))).map_err(unread)?; let mut out = Vec::new(); for row in rows { let (id, data) = row.map_err(unread)?; if let Ok(Value::Object(data)) = serde_json::from_str::(&data) { out.push((id, data)); } } Ok(out) } /// One parked row, as the object served it. #[derive(Debug, Clone, PartialEq)] pub struct ParkedRow { pub table: String, pub id: String, pub code: String, pub reason: String, pub row: Value, /// When it was parked (the server's time of the page), or [`try_mark`] once tried again. pub at: String, } impl ParkedRow { /// Whether it was tried again since the key was held ([`try_mark`]). pub fn tried(&self) -> bool { self.at.starts_with(TRIED) } } /// A park's code once its row opened and the fold refused it (a rule of the copy's the row breaks): kept, and tried /// again on later passes, but its opening again is no reason to bring a pass straight back. pub const FOLD_REFUSED: &str = "fold_refused"; /// The code of a parked row that opened and folded dormant, its owning parent not in the copy yet ([`Note::Waiting`]): /// not an error, and counted apart from [`FOLD_REFUSED`] wherever parks are counted ([`parked_by_code`]). pub const WAITING_PARENT: &str = "waiting_parent"; /// How the `at` of a row waiting for its parent begins: past every mark ([`TRIED`] is `~`, this is DEL), so neither /// the untried (`at < '~'`) nor the tried (`'~' <= at < WAITING`) batches read it. pub const WAITING: char = '\u{7f}'; /// What a table's owning parents hold now, as one number that grows when a row of one of them is made: the sum of each /// parent table's greatest rowid (its row count for a table without one). A table with no owning parent is 0. pub fn parent_mark(db: &rusqlite::Connection, store: &str) -> Result { let mut mark = 0i64; for (_, _, parent) in cotton_store::schema::table_specs::OWNING_REFS.iter().filter(|(child, _, _)| *child == store) { let by_rowid = db.query_row(&format!("SELECT coalesce(max(rowid), 0) FROM \"{parent}\""), [], |row| row.get::<_, i64>(0)); let held = match by_rowid { Ok(held) => held, Err(_) => db.query_row(&format!("SELECT count(*) FROM \"{parent}\""), [], |row| row.get::<_, i64>(0)).unwrap_or(0), }; mark = mark.saturating_add(held); } Ok(mark) } /// The mark a table's waiting rows are woken at, or none: a parent table that gained a row since they waited /// (`now` past `mark`) wakes them at `now`. A table whose parents this build cannot name (`now` none: the kit no /// longer maps it) wakes them once, at the greatest mark, so a wake kept during a fill does not come again every /// pass (FIRST SYNC 9c); the fill's last slice marks it again to be woken once more. pub fn wake_mark(now: Option, mark: i64) -> Option { match now { Some(now) => (now > mark).then_some(now), None => (mark != i64::MAX).then_some(i64::MAX), } } /// How often a pull that reaches the end wakes every row waiting for a parent: once a day. pub const WAKE_AT_END_EVERY_MS: i64 = 24 * 60 * 60 * 1000; /// Whether the daily try at the end of a pull is due: none made yet, a day since the last, or a last stamped after /// `now_ms` (FIRST SYNC 7 REVIEW: a clock once set forward, then back, would otherwise hold it off until that day /// came round again). The try then stamps the time it is made, so a clock set back counts the day from there. pub fn wake_at_end_due(last: Option, now_ms: i64) -> bool { last.is_none_or(|last| last > now_ms || now_ms - last >= WAKE_AT_END_EVERY_MS) } /// `_seal_waiting`'s row that keeps when the last wake at the end of a pull was (ms), never a table's. const WOKEN_AT_END: &str = "*"; /// When the last wake at the end of a pull was, in ms. pub fn woken_at_end(db: &rusqlite::Connection) -> Result, String> { if !has_state(db)? { return Ok(None); } let made: i64 = db .query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = '_seal_waiting'", [], |row| row.get(0)) .map_err(|error| error.to_string())?; if made == 0 { return Ok(None); } db.query_row("SELECT mark FROM _seal_waiting WHERE tbl = ?1", [WOKEN_AT_END], |row| row.get(0)) .map(Some) .or_else(|error| if matches!(error, rusqlite::Error::QueryReturnedNoRows) { Ok(None) } else { Err(error.to_string()) }) } /// Whether a row of `store` named `id` has a receipt here naming an owning parent this copy does not hold (it /// folded dormant), off the receipts' own projection of their owners (`_writes_owners`). pub fn parent_absent(db: &rusqlite::Connection, store: &str, id: &str) -> Result { let failed = |error: rusqlite::Error| format!("this copy's receipts could not be read for a row's parent ({error})"); // `_writes_owners` keeps each receipt's owning parents' ids under the receipt's own table; the parent tables are // `OWNING_REFS`'s for that table. let parents: Vec<&str> = cotton_store::schema::table_specs::OWNING_REFS.iter().filter(|(child, _, _)| *child == store).map(|(_, _, parent)| *parent).collect(); let mut statement = db .prepare_cached("SELECT DISTINCT o.owner FROM _writes w JOIN _writes_owners o ON o.receipt = w.op_id WHERE w.tbl = ?1 AND w.row_id = ?2") .map_err(failed)?; let owners: Vec = statement.query_map([store, id], |row| row.get(0)).map_err(failed)?.collect::>().map_err(failed)?; for owner in owners { let mut here = false; for parent in &parents { let Some(spec) = cotton_store::schema::specs::spec_for(parent) else { continue }; let found: i64 = db .query_row(&format!("SELECT EXISTS (SELECT 1 FROM \"{parent}\" WHERE \"{}\" = ?1)", spec.pk), [&owner], |row| row.get(0)) .map_err(failed)?; here |= found == 1; } if !here { return Ok(true); } } Ok(false) } /// Whether `store` has an owning parent at all (a row of it can fold dormant). pub fn has_owning_parent(store: &str) -> bool { cotton_store::schema::table_specs::OWNING_REFS.iter().any(|(child, _, _)| *child == store) } /// Each object table with rows waiting for a parent, with the [`parent_mark`] they waited at. pub fn waiting_marks(db: &rusqlite::Connection) -> Result, String> { if !has_state(db)? { return Ok(Vec::new()); } let unread = |error: rusqlite::Error| format!("this copy's waiting parked rows could not be read ({error})"); // A copy whose seal state predates the table (made at its next note) has nothing waiting. let made: i64 = db.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = '_seal_waiting'", [], |row| row.get(0)).map_err(unread)?; if made == 0 { return Ok(Vec::new()); } let mut statement = db.prepare_cached("SELECT tbl, mark FROM _seal_waiting WHERE tbl <> '*'").map_err(unread)?; let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))).map_err(unread)?; rows.collect::>().map_err(unread) } /// The parked rows, counted by code, off the parks' keys (never the rows, which are each a whole mail). `None` (not /// known) while the keys are not yet full ([`fill_park_keys`]): never a count short of the parks held. pub fn parked_by_code(db: &rusqlite::Connection) -> Result>, String> { if !has_state(db)? { return Ok(Some(Vec::new())); } let unread = |error: rusqlite::Error| format!("this copy's parked sealed rows could not be counted ({error})"); if !park_keys_full(db)? { // An idle copy of an older build with no park says none (one row read at most), never "unknown". return Ok(no_parks(db).map_err(unread)?.then(Vec::new)); } let mut statement = db.prepare_cached("SELECT code, count(*) FROM _seal_park_keys GROUP BY code ORDER BY code").map_err(unread)?; let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?.max(0) as u64))).map_err(unread)?; rows.collect::>().map(Some).map_err(unread) } /// How many rows this copy holds parked, off the parks' keys; `None` (not known) while they are not full. Never a /// `COUNT(*)` of `_seal_parked`, which reads every park whole (FIRST SYNC 8). pub fn parked_count(db: &rusqlite::Connection) -> Result, String> { if !has_state(db)? { return Ok(Some(0)); } if !park_keys_full(db)? { return no_parks(db).map(|none| none.then_some(0)).map_err(|error| format!("this copy's parked sealed rows could not be counted ({error})")); } db.query_row("SELECT count(*) FROM _seal_park_keys", [], |row| row.get::<_, i64>(0)) .map(|n| Some(n.max(0) as u64)) .map_err(|error| format!("this copy's parked sealed rows could not be counted ({error})")) } /// Whether any park has `code`, off the parks' keys' code index. While their fill is owed the keys cannot prove there /// is none (the old parks not filled have no key, and the first rows of the wide table are the ones the fill has /// already keyed, so reading them proves nothing either, FIRST SYNC 9c): a copy holding any park then answers yes, as /// unknown counts for the one who asks (`copy_standing::waits_for_key`, asked only while no data key is held: a /// screen that says "still bringing" for the seconds of a fill, never "held" and empty, the 21 Nov pattern). pub fn any_parked_with(db: &rusqlite::Connection, code: &str) -> Result { let unread = |error: rusqlite::Error| format!("this copy's parked sealed rows could not be read ({error})"); if no_parks(db).map_err(unread)? { return Ok(false); } if keys_set_up(db).map_err(unread)? { if db.query_row("SELECT EXISTS (SELECT 1 FROM _seal_park_keys WHERE code = ?1)", [code], |row| row.get::<_, i64>(0)).map_err(unread)? == 1 { return Ok(true); } if park_keys_full(db)? { return Ok(false); } } Ok(true) } /// How a park's `at` begins once tried again: after every time a page names ('2…'), so a tried row sorts behind /// every row not yet tried, whatever the phone's clock says (FIRST SYNC 2 REVIEW). pub const TRIED: char = '~'; /// The mark of the next batch tried again: one more than the last ([`TRIED`] and a counter), so of the rows tried, /// the longest ago comes first. pub fn try_mark(db: &rusqlite::Connection) -> Result { if !has_state(db)? { return Ok(format!("{TRIED}{:020}", 1)); } ensure_state(db).map_err(|error| format!("this copy could not keep its seal state ({error})"))?; // The marks are zero-padded, so the greatest is the last; `_seal_park_keys_at` finds it without a scan. let last: Option = db .query_row("SELECT max(at) FROM _seal_park_keys WHERE at >= '~' AND at < char(127)", [], |row| row.get(0)) .map_err(|error| format!("this copy's parked sealed rows could not be read ({error})"))?; let last: i64 = last.as_deref().and_then(|at| at.strip_prefix(TRIED)).and_then(|n| n.parse().ok()).unwrap_or(0); Ok(format!("{TRIED}{:020}", last + 1)) } /// The rows parked because they did not open. pub fn parked(db: &rusqlite::Connection) -> Result, String> { if !has_state(db)? { return Ok(Vec::new()); } let unread = |error: rusqlite::Error| format!("this copy's parked sealed rows could not be read ({error})"); let mut statement = db.prepare("SELECT tbl, row_id, code, reason, row, at FROM _seal_parked ORDER BY tbl, row_id").map_err(unread)?; let rows = statement .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, String>(3)?, row.get::<_, String>(4)?, row.get::<_, String>(5)?))) .map_err(unread)?; let mut out = Vec::new(); for row in rows { let (table, id, code, reason, row, at) = row.map_err(unread)?; out.push(ParkedRow { table, id, code, reason, row: serde_json::from_str(&row).unwrap_or(Value::Null), at }); } Ok(out) } /// The parked rows to open next, at most `limit`: every table's but `late`'s first, then the longest parked first, /// the rows already tried again ([`TRIED`]) behind every one not yet tried. Each row a batch tries is marked /// ([`Note::Tried`]), opened or not, folded or refused, so it goes to the back and never holds the rest of the queue (FIRST SYNC, dev, 26 Nov 2026: a new phone's first pull parked 70,000 /// mails before the key; opened all in one page, they never folded inside a pass's two minutes, and none ever did). pub fn parked_next(db: &rusqlite::Connection, late: &[String], limit: usize) -> Result, String> { parked_next_in(db, late, &[], limit) } /// [`parked_next`], the untried rows of each table in `first`'s order (a parent before the tables that name it: /// a kit's own list, `email_thread` before `email`). A mail tried before its conversation was refused by the fold (its /// thread not yet there) and tried again: on dev, 26 Nov 2026, 8,190 of 10,301 mails twice over. pub fn parked_next_in(db: &rusqlite::Connection, late: &[String], first: &[String], limit: usize) -> Result, String> { if !has_state(db)? { return Ok(Vec::new()); } let unread = |error: rusqlite::Error| format!("this copy's parked sealed rows could not be read ({error})"); // Untried rows first, the late tables' last among them; then the tried, longest ago first, whatever their table // (FIRST SYNC 3 and 4 REVIEWS: the late tables first put 2,000 stuck rows of any other table ahead of the mail for // good, and among tried rows still did). Keys and rows are read in one read transaction (a savepoint, which nests // in a caller's), so a park let go between them never makes the batch fail. The order is read off // the keys alone (`_seal_parked_at` holds `at` with them): never the rows, which are each a whole mail. db.execute_batch("SAVEPOINT parked_next").map_err(unread)?; let read = parked_rows(db, late, first, limit); let _ = db.execute_batch("RELEASE parked_next"); read } fn parked_rows(db: &rusqlite::Connection, late: &[String], first: &[String], limit: usize) -> Result, String> { let unread = |error: rusqlite::Error| format!("this copy's parked sealed rows could not be read ({error})"); ensure_state(db).map_err(|error| format!("this copy could not keep its seal state ({error})"))?; // Read off the parks' keys alone, never the wide table (FIRST SYNC 5 REVIEW: a lookup per park per page was a // scan of 280,000 parks for each 2,000-row batch at his size; FIRST SYNC 7 REVIEW: so was the query before the // indexes stood): the tables that hold parks by a skip over the key, each table's untried rows oldest first by // `_seal_park_keys_tbl_at`, the tried by `_seal_park_keys_at`. Parks an older build made and not yet filled // ([`fill_park_keys`]) wait for their slice. let held: Vec = { let mut statement = db .prepare_cached( "WITH RECURSIVE t(tbl) AS (SELECT min(tbl) FROM _seal_park_keys UNION ALL SELECT (SELECT min(tbl) FROM _seal_park_keys WHERE tbl > t.tbl) FROM t WHERE t.tbl IS NOT NULL) SELECT tbl FROM t WHERE tbl IS NOT NULL", ) .map_err(unread)?; let tables = statement.query_map([], |row| row.get::<_, String>(0)).map_err(unread)?; tables.collect::>().map_err(unread)? }; // The untried go table by table: `first`'s order (a parent before what names it), then any other, the late last. let rank = |table: &String| (late.contains(table), first.iter().position(|named| named == table).unwrap_or(usize::MAX)); let mut order = held; order.sort_by(|a, b| rank(a).cmp(&rank(b)).then_with(|| a.cmp(b))); let mut keys: Vec<(String, String)> = Vec::new(); { let mut untried = db.prepare_cached("SELECT row_id FROM _seal_park_keys WHERE tbl = ?1 AND at < '~' ORDER BY at, row_id LIMIT ?2").map_err(unread)?; for table in &order { if keys.len() >= limit { break; } let ids = untried.query_map(rusqlite::params![table, (limit - keys.len()) as i64], |row| row.get::<_, String>(0)).map_err(unread)?; for id in ids { keys.push((table.clone(), id.map_err(unread)?)); } } } if keys.len() < limit { let mut tried = db.prepare_cached("SELECT tbl, row_id FROM _seal_park_keys WHERE at >= '~' AND at < char(127) ORDER BY at, tbl, row_id LIMIT ?1").map_err(unread)?; let rows = tried.query_map([(limit - keys.len()) as i64], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))).map_err(unread)?; for row in rows { keys.push(row.map_err(unread)?); } } rows_of_keys(db, keys) } /// The parked rows of `keys`, in order; a key let go since it was read is skipped. fn rows_of_keys(db: &rusqlite::Connection, keys: Vec<(String, String)>) -> Result, String> { let unread = |error: rusqlite::Error| format!("this copy's parked sealed rows could not be read ({error})"); let mut statement = db.prepare_cached("SELECT code, reason, row, at FROM _seal_parked WHERE tbl = ?1 AND row_id = ?2").map_err(unread)?; let mut out = Vec::new(); for (table, id) in keys { let (code, reason, row, at) = match statement.query_row([&table, &id], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, String>(3)?))) { Ok(found) => found, Err(rusqlite::Error::QueryReturnedNoRows) => continue, Err(error) => return Err(unread(error)), }; out.push(ParkedRow { table, id, code, reason, row: serde_json::from_str(&row).unwrap_or(Value::Null), at }); } Ok(out) } /// What a sealed table's served row is to this device: opened, or parked /// with its note. `None` for a row of a table that is not sealed. pub fn unseal(sealer: Option<&Sealer>, spec: Option<&SealSpec>, row: &Value, at: &str) -> Option<(Option, Note)> { spec?; let (table, id) = (row["table"].as_str()?, row["id"].as_str()?); let version = row["version"].as_i64().unwrap_or(0); if row["deleted"] == json!(true) { return Some((Some(row.clone()), Note::Gone { table: table.into(), id: id.into() })); } let data = row["data"].as_object().cloned().unwrap_or_default(); if !stored_row::is_sealed(&data) { return Some((Some(row.clone()), Note::Open { table: table.into(), id: id.into(), version })); } // Sealed at arrival by the object (e2e rulings R2): opened with the // secret the DK derives, and noted open, so the sweep seals it again // under the table's key and a window opens it as every other row. // A row the object sealed at arrival, or one carrying the object's changes // to it (arrival patches): opened with the secret the DK derives, and // noted open, so the sweep seals it again under the table's key, the // patches folded in. if core::arrival::is_arrival(&data) || core::arrival::has_patches(&data) { let park = |error: SealError| Note::Parked { table: table.into(), id: id.into(), code: error.code().into(), reason: error.to_string(), row: row.clone(), at: at.into() }; let Some(sealer) = sealer else { return Some((None, park(SealError::KeyMissing("the data key (this copy has no sealer)".into())))); }; return Some(match sealer.open(table, id, &data) { Ok(opened) => { let mut row = row.clone(); row["data"] = Value::Object(opened); (Some(row), Note::Open { table: table.into(), id: id.into(), version }) } Err(error) => (None, park(error)), }); } let park = |error: SealError| Note::Parked { table: table.into(), id: id.into(), code: error.code().into(), reason: error.to_string(), row: row.clone(), at: at.into() }; let Some(sealer) = sealer else { return Some((None, park(SealError::KeyMissing("the data key (this copy has no sealer)".into())))); }; match sealer.open(table, id, &data) { Ok(opened) => { let note = Note::Sealed { table: table.into(), id: id.into(), dek_enc: data.get(stored_row::DEK_ENC).and_then(Value::as_str).unwrap_or_default().into(), seal_v: stored_row::version_of(&data).unwrap_or(0), version, }; let mut row = row.clone(); row["data"] = Value::Object(opened); Some((Some(row), note)) } Err(error) => Some((None, park(error))), } } /// A table's `seal` block out of its definition, when it has one. pub fn spec_of_definition(definition: &Value) -> Result, String> { match definition.get("seal") { None | Some(Value::Null) => Ok(None), Some(block) => serde_json::from_value(block.clone()).map(Some).map_err(|error| format!("the {} table's seal block does not read ({error})", definition["id"].as_str().unwrap_or("?"))), } } #[cfg(test)] #[path = "mod_tests.rs"] mod tests;