//! `mint`'s CLOCK hook — slice 1's seam (store-clock).//!//! **Every mint is checked** against judge time ([`crate::judge`])://!//! - Checked — the wall clock within 2 minutes of judge time: stamp by the//! wall clock.//! - Corrected — more than 2 minutes off: stamp by judge time, and say so.//! - Unchecked — no judge time yet: stamp by the wall clock and HOLD the//! receipt. A held receipt applies here and never travels (3.8): it is left//! out of the outbox, `changes_since`, a snapshot and `seen`, until the//! release pass (a later step) releases or re-dates it.//!//! Every receipt records the continuous clock and the boot session it was//! minted at (`mint_cont`, `mint_boot`), which is what that pass dates a held//! receipt by. A delete is held like any other write: its receipt is the//! row's tombstone, which carries the same three columns.//!//! **The release pass** ([`release_held`]) runs once judge time is known://! each held receipt, in mint order, is released at its own stamp when that//! stamp is honest — at or below judge time and within 2 minutes of when it//! was minted — and otherwise RE-DATED to when it was minted, under one fresh//! author for the pass. A re-dated receipt is a new receipt naming the one it//! replaces (`restamps`); the fold drops the old one.//!//! No mint makes an unheld stamp above judge time + [`FUTURE_BOUND_MS`]: a//! `last_hlc` that would carry one there is POISONED, and the file moves to a//! fresh author, reason `redate`, whose stream starts at judge time.use std::collections::{BTreeMap, BTreeSet};use rusqlite::types::ValueasSqlValue;usesuper::{coin_author, Author, AuthorReason, Clock, Held, IdSource, JudgeTime};usecrate::canonical::{self, Receipt};usecrate::driver::Driver;usecrate::error::{Result, StoreError};usecrate::fold::{self, Arrival, AUTHORS_TABLE};usecrate::judge::{clock_state, ClockState};usecrate::protocol::hlc::{hlc_parts, next_hlc};usecrate::protocol::js;usecrate::protocol::types::CottonOp;/// How far ahead of judge time an unheld stamp may be — and, at the judge,/// the arrival bound (a receipt further ahead is refused `future`).pubconst FUTURE_BOUND_MS: i64 = 10 * 60_000;/// What a mint does with the clock it was given.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructStamping {pub state: ClockState,/// The milliseconds the mint stamps and dates with.pub ms: i64,/// The receipts are held: minted Unchecked.pub held: bool,}/// Checked stamps by the wall, Corrected by judge time, Unchecked by the wall/// and holds. A [`JudgeTime::WallOnly`] writer is Checked.pubfn stamping(clock: &Clock) -> Stamping {let state = match clock.judge {JudgeTime::WallOnly => ClockState::Checked,JudgeTime::At(judge) => clock_state(Some(judge), clock.wall),JudgeTime::Unheard => ClockState::Unchecked, };match (state, clock.judge_ms()) { (ClockState::Corrected { .. }, Some(judge)) => Stamping { state, ms: judge, held: false, }, (ClockState::Unchecked, _) => Stamping { state, ms: clock.wall, held: true, }, _ => Stamping { state, ms: clock.wall, held: false, }, }}/// The milliseconds a mint stamps and dates with.pub(crate) fn stamp_ms(clock: &Clock) -> i64 { stamping(clock).ms}/// The first 13 digits a stamp may not reach unheld: judge time + the bound,/// plus one. Every stamp whose millisecond is at or below the bound sorts/// below this as a string (the widths are fixed), and every stamp above it/// sorts above.pub(crate) fn bound_prefix(judge_ms: i64) -> String { format!("{:013}", judge_ms + FUTURE_BOUND_MS + 1)}/// The stamp an unheld mint is about to make lies beyond judge time + the/// bound — `last_hlc` is poisoned. `false` when there is no judge time: an/// Unchecked mint holds instead, and a wall-only writer has nothing to judge/// its file's clock by.pub(crate) fn poisoned(clock: &Clock, next_stamp: &str) -> Result<bool> {letSome(judge) = clock.judge_ms() else {returnOk(false); };Ok(hlc_parts(next_stamp)?.ms > judge + FUTURE_BOUND_MS)}pub(crate) const LAST_HLC_BELOW: &str = "SELECT MAX(top) AS top FROM (\ SELECT (SELECT hlc FROM _writes WHERE hlc < ?1 ORDER BY hlc DESC LIMIT 1) AS top \ UNION ALL SELECT (SELECT hlc FROM _tombstones WHERE hlc < ?1 ORDER BY hlc DESC LIMIT 1))";/// `last_hlc` after a move to a fresh author: the new author's last stamp,/// or every stamp this file holds at or below judge time + the bound — in/// `_writes` and in `_tombstones` — whichever is later, so the next local edit/// is never folded stale against a write this file already shows, and never/// stamped beyond the bound.pub(crate) fn last_hlc_after_redate(db: &Driver, first_stamp: &str, judge_ms: i64) -> Result<String> {let below = db .get( LAST_HLC_BELOW, &[SqlValue::Text(bound_prefix(judge_ms))], )? .and_then(|row| row.text("top").map(str::to_string));Ok(match below {Some(top) if top.as_str() > first_stamp => top, _ => first_stamp.to_string(), })}/// Write the mint's clocks beside each op it stored or queued — in `_writes`,/// in `_tombstones` for a delete, and in `_outbox` — so a held receipt can be/// dated by when it was made.pub(crate) fn record(db: &Driver, ops: &[CottonOp], clock: &Clock, held: bool) -> Result<()> {if held && clock.boot.is_none() {returnErr(StoreError::refused("an Unchecked mint holds its receipts, and a held receipt is dated by its boot session — none was given", )); }let boot = clock .boot .as_ref() .map_or(SqlValue::Null, |boot| SqlValue::Text(boot.clone()));let cont = if clock.boot.is_some() {SqlValue::Integer(clock.cont) } else {SqlValue::Null };// A batch's wall-clock mint writes nothing here: its receipts were stored// a moment ago in this transaction with both clocks empty, so writing// them empty again is three statements a row that change nothing.if db.batching() && clock.boot.is_none() {returnOk(()); }for op in ops { set_mint_clocks(db, op, cont.clone(), boot.clone())?; }Ok(())}/// `mint_cont` and `mint_boot` of one receipt, wherever this file keeps it —/// each place by its own key: `_writes` and `_outbox` by the op id, the/// retract by the op's row (`_tombstones` has no index on the op id, and an/// update by it alone read every tombstone of the file per receipt).fn set_mint_clocks(db: &Driver, op: &CottonOp, cont: SqlValue, boot: SqlValue) -> Result<()> {let op_id = SqlValue::Text(op.op_id.clone());for table in ["_writes", "_outbox"] { db.run( &format!("UPDATE {table} SET mint_cont = ?, mint_boot = ? WHERE op_id = ?"), &[cont.clone(), boot.clone(), op_id.clone()], )?; } db.run("UPDATE _tombstones SET mint_cont = ?, mint_boot = ? WHERE tbl = ? AND row_id = ? AND op_id = ?", &[cont, boot, SqlValue::Text(op.table.clone()), SqlValue::Text(op.row_id.clone()), op_id], )?;Ok(())}/// How many of this file's replicated receipts are held, waiting for judge/// time. Local observations never wait to be sent, even without judge time.pubfn held_count(db: &Driver) -> Result<i64> {let travels = crate::schema::table_specs::handed_over_clause("tbl");Ok(db .get( &format!("SELECT (SELECT COUNT(*) FROM _writes WHERE held = 1 AND {travels}) + \ (SELECT COUNT(*) FROM _tombstones WHERE held = 1 AND {travels}) AS n"), &[], )? .and_then(|row| row.int("n")) .unwrap_or(0))}/// The line every device shows while it holds receipts: "N changes are/// waiting for the relay". `None` when nothing is held.pubfn waiting_for_the_relay(db: &Driver) -> Result<Option<String>> {Ok(match held_count(db)? {0 => None,1 => Some("1 change is waiting for the relay".to_string()), n => Some(format!("{n} changes are waiting for the relay")), })}// ---------------------------------------------------------------------------// The release pass (5.2 point 6)// ---------------------------------------------------------------------------/// A held receipt minted in this boot is released at its own stamp only when/// that stamp is within this of when it was minted.pubconst RELEASE_WITHIN_MS: i64 = 2 * 60_000;/// When a receipt was minted, in judge time: `J − (C − mint_cont)` when it was/// minted in this boot session, which is the offset AT MINT — the current/// offset is never read. A receipt from an earlier boot session, or one with/// no `mint_cont`, was minted before this boot started: the boot start/// `B = J − C` is the latest it can have been, and it is what such a receipt/// is dated to.////// Pure, and the same for the release pass (`judge_ms` = judge time) and for/// a replica's refusal path (`judge_ms` = the refusal's judge time `J_r`):/// either way a receipt goes back to when it was made, never to "now".pubfn mint_time(judge_ms: i64, cont: i64, boot: &str, mint_cont: Option<i64>, mint_boot: Option<&str>) -> i64 {match (mint_cont, mint_boot) { (Some(minted), Some(minted_boot)) if minted_boot == boot => judge_ms - (cont - minted), _ => judge_ms - cont, }}/// Whether a held receipt stamped `stamp_ms` is released AS IT IS: minted in/// this boot, its stamp is at or below judge time and within/// [`RELEASE_WITHIN_MS`] of its mint time; minted in an earlier boot, its/// stamp is at or below the boot start. A stamp ahead of judge time is never/// released, whatever the clock says now.pubfn releases_as_it_is( stamp_ms: i64, judge_ms: i64, cont: i64, boot: &str, mint_cont: Option<i64>, mint_boot: Option<&str>,) -> bool {let minted = mint_time(judge_ms, cont, boot, mint_cont, mint_boot);match (mint_cont, mint_boot) { (Some(_), Some(minted_boot)) if minted_boot == boot => { stamp_ms <= judge_ms && (stamp_ms - minted).abs() <= RELEASE_WITHIN_MS } _ => stamp_ms <= minted, }}/// What the release pass did.#[derive(Debug, Clone, Default, PartialEq)]pubstructRelease {/// Held receipts released at their own stamps, in mint order.pub released: Vec<CottonOp>,/// The re-dated receipts, in mint order, each naming the one it replaces/// (`restamps`).pub redated: Vec<CottonOp>,/// The one fresh author the re-dated receipts are minted under (reason/// `redate`); `None` when nothing was re-dated.pub author: Option<Author>,}implRelease {/// The line the device shows after a pass that re-dated anything.pubfn line(&self) -> Option<String> {matchself.redated.len() {0 => None,1 => Some("This device's clock was off; 1 change was re-dated to when it was made.".to_string()), n => Some(format!("This device's clock was off; {n} changes were re-dated to when they were made.")), } }}/// One held receipt, as the pass reads it.structHeldReceipt {/// `_writes`, or `_tombstones` for a delete. place: &'static str, op_id: String, ms: i64, counter: i64, mint_cont: Option<i64>, mint_boot: Option<String>, receipt: Receipt, bytes: Vec<u8>,/// The signature the receipt was minted with, when its handle signed. sig: Option<Vec<u8>>,/// A set-aside change that reads again: re-dated whatever its stamp (QUEUE BAD OP 3). forced: bool,}implHeldReceipt {/// The receipt is an author's own fact.fn is_fact(&self) -> bool {self.receipt.table == AUTHORS_TABLE && self.receipt.row_id == self.receipt.author }}/// `at`: when this pass runs, for a receipt it sets aside (QUEUE BAD OP).fn held_receipts(db: &Driver, at: &str) -> Result<Vec<HeldReceipt>> {letmut held = Vec::new();for place in ["_writes", "_tombstones"] {for row in db.all( &format!("SELECT op_id, hlc, mint_cont, mint_boot, bytes, sig, tbl, row_id FROM {place} WHERE held = 1"), &[], )? {let op_id = row.text("op_id").unwrap_or_default().to_string();let bytes = match row.get("bytes") {Some(SqlValue::Blob(bytes)) => Some(bytes.clone()),Some(SqlValue::Text(text)) => Some(text.as_bytes().to_vec()), _ => None, };// QUEUE BAD OP: a held receipt that does not read is set aside (a refused push, shown with Let go) and// left out of this release, so the release goes on with the rest instead of refusing every pass for good.// It stays HELD (QUEUE BAD OP 2): every reader of an author's stream leaves held receipts out, and one// that reads again (a later build) is released then, its park ended.let read = bytes .as_deref() .ok_or_else(|| "it holds no receipt bytes".to_string()) .and_then(|bytes| canonical::decode(bytes).map_err(|error| error.to_string())) .and_then(|receipt| hlc_parts(&receipt.stamp).map(|parts| (receipt, parts)).map_err(|error| error.to_string()));let (receipt, parts) = match read {Ok(read) => read,Err(error) => {let sig = match row.get("sig") {Some(SqlValue::Blob(sig)) => Some(sig.clone()), _ => None, };crate::rejected::set_aside_undecodable(db, &op_id, bytes.as_deref(), sig.as_deref(), row.text("tbl").unwrap_or_default(), row.text("row_id").unwrap_or_default(), &error, at)?;continue; } };// A set-aside change that reads again (QUEUE BAD OP 3) is always re-dated: never sent at its old stamp.let forced = crate::rejected::taken_again(db, &op_id)?;let bytes = bytes.unwrap_or_default(); held.push(HeldReceipt { place, op_id, ms: parts.ms, counter: parts.counter, mint_cont: row.int("mint_cont"), mint_boot: row.text("mint_boot").map(str::to_string), receipt, bytes, sig: match row.get("sig") {Some(SqlValue::Blob(sig)) => Some(sig.clone()), _ => None, }, forced, }); } }// MINT ORDER IS STAMP ORDER. A held mint stamps above `last_hlc`, and// `last_hlc` only falls at a move to a fresh author, which needs judge// time — which a held mint does not have, and before which this pass// releases everything held. So every held receipt is stamped above every// one held before it, across processes and boots alike (where// `mint_cont` cannot compare). held.sort_by(|a, b| (a.ms, a.counter, &a.op_id).cmp(&(b.ms, b.counter, &b.op_id)));Ok(held)}/// THE RELEASE PASS: once this process has judge time, every held receipt is/// released or re-dated, in one transaction, before anything else is written/// or served (5.2 point 6). The caller runs it under the writer lock when a/// writer first gets judge time.////// With `J` judge time, `C` the continuous clock and `B = J − C` the boot/// start, each held receipt in mint order is released at its own stamp when/// [`releases_as_it_is`] says so and that stamp is above the previous/// receipt's final stamp; otherwise it is re-dated to its [`mint_time`] `m` —/// at `max(m, previous final stamp + 1 counter)`, one running stamp across/// the pass, so a later write never ends below an earlier one, and nothing/// ends above `J`.////// Every re-dated receipt goes under ONE fresh author (reason `redate`), whose/// fact is its stream's first receipt at the lowest re-dated millisecond,/// counter 0. A re-dated receipt keeps the kind, fields, values, actor and/// schema of the one it replaces, gets a new op id and `restamps: <old op/// id>`, and is folded: the fold drops the old one (its own device's/// identical receipt) and assembles the row from what remains — a create/// stays a create, so `_born` is the re-dated create's stamp on every device.////// An author whose own fact is held and cannot be released (a file whose/// first write was made with the clock ahead) never travels: its fact is/// taken out, and every receipt of its is re-dated.////// Released and re-dated receipts enter the outbox on a replica, with the/// mint clocks they were made at (the refusal path dates by them); the/// serving Mac clears them, the judge having it. After a re-date, `last_hlc`/// is `max(the new author's last stamp, every stamp this file holds at or/// below J + the bound)` — never below a stamp that remains.pubfn release_held(db: &Driver, clock: &Clock, ids: &mutdynIdSource, held: Held) -> Result<Release> {letSome(judge) = clock.judge_ms() else {returnErr(StoreError::refused("the release pass dates held writes by judge time, and this clock has none", )); };letSome(boot) = clock.boot.clone() else {returnErr(StoreError::refused("the release pass dates held writes by the boot session, and this clock names none", )); };let cont = clock.cont; db.transaction(|db| {// Each set-aside change tried again, as after an update: one that reads now is held again, re-dated below.crate::rejected::try_set_aside_again(db, None)?;let at = chrono::DateTime::from_timestamp_millis(judge).map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)).unwrap_or_default();let waiting = held_receipts(db, &at)?;if waiting.is_empty() {returnOk(Release::default()); }let honest = |h: &HeldReceipt| { releases_as_it_is(h.ms, judge, cont, &boot, h.mint_cont, h.mint_boot.as_deref()) };let unannounced: BTreeSet<String> = waiting .iter() .filter(|h| h.is_fact() && !honest(h)) .map(|h| h.receipt.author.clone()) .collect();for author in &unannounced {let travelled = db.get("SELECT 1 AS n FROM _writes WHERE author = ?1 AND held = 0 \ UNION ALL SELECT 1 FROM _tombstones WHERE author = ?1 AND held = 0 LIMIT 1", &[SqlValue::Text(author.clone())], )?;if travelled.is_some() {returnErr(StoreError::refused(format!("the author {author}'s own fact is held ahead of judge time, yet some of its writes are not held — \ the release pass runs before any write is made with judge time" ))); } }let meta = db.get("SELECT device_id, workspace_id FROM _meta", &[])?;let device = meta .as_ref() .and_then(|row| row.text("device_id").map(str::to_string)) .unwrap_or_default();let database = meta .as_ref() .and_then(|row| row.text("workspace_id").map(str::to_string)) .unwrap_or_default();let clear_clocks = held != Held::Replica;letmut release = Release::default();letmut dropped_facts: Vec<HeldReceipt> = Vec::new();// (new op, the receipt it replaces)letmut redated: Vec<(CottonOp, HeldReceipt)> = Vec::new();// The running stamp: the last final stamp, released or re-dated.letmut last: Option<String> = None;letmut author: Option<Author> = None;for h in waiting {if h.is_fact() && unannounced.contains(&h.receipt.author) { dropped_facts.push(h);continue; }let above_last = last .as_deref() .map(hlc_parts) .transpose()? .is_none_or(|last| (h.ms, h.counter) > (last.ms, last.counter));if !h.forced && honest(&h) && above_last && !unannounced.contains(&h.receipt.author) { db.run( &format!("UPDATE {} SET held = 0{} WHERE op_id = ?", h.place,if clear_clocks { ", mint_cont = NULL, mint_boot = NULL" } else { "" } ), &[SqlValue::Text(h.op_id.clone())], )?;// Released as it was minted: the same bytes, so the same signature.letmut op = crate::wire::from_bytes(h.op_id.clone(), &h.bytes).map_err(StoreError::encode)?; op.sig = h.sig.as_deref().map(crate::signed::sig_text); release.released.push(op); last = Some(h.receipt.stamp.clone());continue; }// QUEUE BAD OP 4 (B2): a set-aside change that reads again keeps its ORIGINAL time under the fresh author,// never the boot start (after a reboot that would let a day-1 edit beat the person's day-3 edit).let minted = if h.forced { h.ms.min(judge) } else { mint_time(judge, cont, &boot, h.mint_cont, h.mint_boot.as_deref()) };if author.is_none() {let first_ms = match last.as_deref().map(hlc_parts).transpose()? {Some(last) if last.ms >= minted => last.ms, _ => minted, }; author = Some(coin_author(db, &device, None, AuthorReason::Redate, clock, ids, Some(first_ms))?); }let fresh = author.as_ref().expect("coined above");let floor = match last.as_deref() {Some(last) if later(last, &fresh.first_stamp)? => last.to_string(), _ => fresh.first_stamp.clone(), };let stamp = next_hlc(&fresh.id, Some(&floor), minted)?;let receipt = Receipt { stamp: stamp.clone(), author: fresh.id.clone(), restamps: Some(h.op_id.clone()), ..h.receipt.clone() };// New bytes under the fresh author, so a fresh signature by the// same device.let op = crate::signed::seal( db, &database,crate::wire::from_receipt(ids.next_op_id(minted)?, &receipt)?, )?; last = Some(stamp); redated.push((op, h)); }ifletSome(fresh) = author.as_ref() {let batch: Vec<CottonOp> = std::iter::once(fresh.fact.clone()) .chain(redated.iter().map(|(op, _)| op.clone())) .collect();let folded = fold::arrive(db, &batch, Arrival::Local)?;ifletSome(refused) = folded.rejected.first().or(folded.parked.first()) {returnErr(StoreError::refused(format!("the release pass's re-dated write {} was refused by the fold: {}", refused.op_id, refused.reason ))); }if !folded.waiting.is_empty() || !folded.applied.contains(&fresh.fact.op_id) {returnErr(StoreError::refused("the release pass's author fact did not apply — a self-naming fact never waits, so the fold is wrong", )); }if !clear_clocks {for (op, old) in &redated {let cont = old.mint_cont.map_or(SqlValue::Null, SqlValue::Integer);let boot = old.mint_boot.clone().map_or(SqlValue::Null, SqlValue::Text); set_mint_clocks(db, op, cont, boot)?; } } }// An author that never travels: its held fact leaves with nothing of// its left behind.for fact in &dropped_facts { db.run(// not a copy: a change re-dated by the release pass (queued again under its new date), or the held fact of an author that never travels."DELETE FROM _writes WHERE op_id = ?", &[SqlValue::Text(fact.op_id.clone())], )?; fold::reassemble_row(db, AUTHORS_TABLE, &fact.receipt.row_id)?; }let at = js::to_iso_string(stamp_ms(clock)) .ok_or_else(|| StoreError::encode("timestamp out of range".to_string()))?;letmut travelling: Vec<CottonOp> = release.released.clone();ifletSome(fresh) = author.as_ref() { travelling.push(fresh.fact.clone()); } travelling.extend(redated.iter().map(|(op, _)| op.clone()));if held == Held::Replica {crate::outbox::queue_ops(db, &travelling, &at)?;for (op, old) in release .released .iter() .map(|op| (op, None)) .chain(redated.iter().map(|(op, old)| (op, Some(old)))) {let (cont, boot) = match old {Some(old) => (old.mint_cont, old.mint_boot.clone()),None => db .get("SELECT mint_cont, mint_boot FROM _writes WHERE op_id = ?1 \ UNION ALL SELECT mint_cont, mint_boot FROM _tombstones WHERE op_id = ?1", &[SqlValue::Text(op.op_id.clone())], )? .map_or((None, None), |row| (row.int("mint_cont"), row.text("mint_boot").map(str::to_string))), }; db.run("UPDATE _outbox SET mint_cont = ?, mint_boot = ? WHERE op_id = ?", &[ cont.map_or(SqlValue::Null, SqlValue::Integer), boot.map_or(SqlValue::Null, SqlValue::Text),SqlValue::Text(op.op_id.clone()), ], )?; } }// THIS FILE HAS SEEN ITS OWN WRITES, now that they travel.letmut newest: BTreeMap<&str, &str> = BTreeMap::new();for op in &travelling {let top = newest.entry(op.device_id.as_str()).or_insert(op.hlc.as_str());if op.hlc.as_str() > *top { *top = op.hlc.as_str(); } }for (author, stamp) in newest {crate::cursors::advance_cursor(db, author, stamp, &at)?; }ifletSome(fresh) = author.as_ref() {let newest = redated .iter() .map(|(op, _)| op.hlc.as_str()) .chain(std::iter::once(fresh.first_stamp.as_str())) .max() .unwrap_or(fresh.first_stamp.as_str()) .to_string();let trusted = last_hlc_after_redate(db, &newest, judge)?; db.run("UPDATE _meta SET last_hlc = ?", &[SqlValue::Text(trusted)])?; } release.redated = redated.into_iter().map(|(op, _)| op).collect(); release.author = author;Ok(release) })}// ---------------------------------------------------------------------------// The writer's clock (5.2: every mint is checked; the release pass runs when a// writer first gets judge time, before anything is written or served)// ---------------------------------------------------------------------------/// THE CLOCK EVERY WRITER MINTS WITH: the file's judge ([`Driver::judge`]) —/// the serving Mac's, or a replica's ([`Driver::replica_judged_by`]) — read at/// wall clock `wall_ms`, after the release pass. A handle with no judge — a/// server with no relay, a test — mints with [`Clock::wall`], which is what/// the spec's judge-less writer has always been.////// When the judge has judge time and this handle has not yet released, the/// release pass runs first, inside the writer's own transaction and lock, so/// no write is made with judge time while a held one waits (5.2 point 6); on/// a replica it queues what it releases.pubfn writer_clock(db: &Driver, wall_ms: i64, ids: &mutdynIdSource) -> Result<Clock> {letSome(judge) = db.judge() else {returnOk(Clock::wall(wall_ms)); };let clock = judge.mint_clock(wall_ms).map_err(StoreError::refused)?; release_once(db, &clock, ids)?;Ok(clock)}/// What a judged file may answer with: whether a page may go out, and the/// judge time it carries.#[derive(Debug, Clone, PartialEq)]pubenumServing {/// No judge — a server with no relay: it serves as it always has, with no/// judge time on the answer.Unjudged,/// A judge with no judge time yet (Unchecked), whose held receipts cannot/// be released: NO PAGE goes out (`503 releasing`).Releasing,/// Judge time, ms, with every held receipt released or re-dated; the/// pass this call ran, if it ran one — boxed, because a `Release` is/// hundreds of bytes and the other two answers carry nothing/// (clippy::large_enum_variant).At { judge_ms: i64, release: Box<Release> },}/// THE GATE IN FRONT OF EVERY PAGE — the exchange and the snapshot. A judged/// file serves nothing until its release pass has committed (5.2: "an/// Unchecked judge … serves no page"; "503 releasing until the pass/// commits"). Run under the writer lock, like [`release_held`].pubfn serving(db: &Driver, wall_ms: i64, ids: &mutdynIdSource) -> Result<Serving> {letSome(judge) = db.judge() else {returnOk(Serving::Unjudged); };if db.judged_held() != Held::Served {returnErr(StoreError::refused("only the serving Mac's file serves a page — this handle is a replica's", )); }let clock = judge.mint_clock(wall_ms).map_err(StoreError::refused)?;letSome(judge_ms) = clock.judge_ms() else { db.set_released(false);returnOk(Serving::Releasing); };let release = release_once(db, &clock, ids)?;Ok(Serving::At { judge_ms, release: Box::new(release) })}/// The release pass, once per handle per stretch of judge time. A clock with/// no judge time holds its mint, so the next one with judge time runs the/// pass again.////// MARKED DONE AT ANY DEPTH, and forgotten by every rollback. A pass inside a/// caller's transaction that rolls back has released nothing, so the driver/// clears the mark when a transaction or savepoint rolls back. Marking it/// only at depth 0 was the other way to say that, and it made every write in/// one long transaction run the pass again: a scan of the whole `_writes` for/// none held, 26,368 times in one Mac's media pass of 11 Oct 2026, with the/// replica locked for over an hour.fn release_once(db: &Driver, clock: &Clock, ids: &mutdynIdSource) -> Result<Release> {if clock.judge_ms().is_none() { db.set_released(false);returnOk(Release::default()); }if db.released() {returnOk(Release::default()); }let release = release_held(db, clock, ids, db.judged_held())?; db.set_released(true);Ok(release)}/// The release pass NOW, whatever this handle remembers: for a caller that/// has just asked the file whether it holds anything — a fold, a pass's/// start — and must not trust a mark another handle or process could not set./// Nothing when the judge has no judge time.pubfn release_now(db: &Driver, wall_ms: i64, ids: &mutdynIdSource) -> Result<Release> {letSome(judge) = db.judge() else {returnOk(Release::default()); };let clock = judge.mint_clock(wall_ms).map_err(StoreError::refused)?;if clock.judge_ms().is_none() {returnOk(Release::default()); }let release = release_held(db, &clock, ids, db.judged_held())?; db.set_released(true);Ok(release)}// ---------------------------------------------------------------------------// The refusal path (5.2: a replica re-dates a `future` refusal to mint time,// once, under one fresh author per answer)// ---------------------------------------------------------------------------/// The parked reason of a re-dated receipt the judge refused again — parked/// `conflict` (`crate::rejected::Class::Conflict`): a phone whose clock is/// still wrong would only be refused again.pubconst REFUSED_AFTER_REDATE: &str = "refused after re-date";/// What one answer's `future` refusals did to this replica.#[derive(Debug, Clone, Default, PartialEq)]pubstructRedated {/// The re-dated receipts, in mint order, each naming the one it replaces/// (`restamps`), queued for the next push.pub redated: Vec<CottonOp>,/// The ONE fresh author (reason `redate`) they are minted under; `None`/// when nothing was re-dated.pub author: Option<Author>,/// Refused receipts that already carried `restamps`: refused after a/// re-date, parked, never re-dated again.pub parked: Vec<String>,/// Every refused op id this call settled — re-dated, parked, or an/// author fact left behind — whose outbox row is gone.pub settled: BTreeSet<String>,}/// THE REFUSAL PATH, ONCE PER ANSWER: the serving Mac refused these queued/// receipts as `future`, with its judge time `J_r` (`clock.judge`). Each is/// re-dated to its mint time — [`mint_time`] from `mint_cont` at `J_r`, or/// the boot start for one minted in an earlier boot, NEVER `J_r` itself — in/// mint order under ONE fresh author (reason `redate`), with one running/// stamp, exactly as the release pass re-dates; the re-dated receipts replace/// the refused ones in the outbox, carrying the mint clocks they were made at.////// A refused receipt that already carries `restamps` is not re-dated again:/// it is parked ([`REFUSED_AFTER_REDATE`]) and leaves the outbox, so a phone/// whose clock is still wrong never loops minting an author per exchange. A/// refused author fact is not re-dated either — a fact names its own author —/// it leaves the file and the outbox, and its writes go under the fresh one.////// `clock` is the replica's mint clock with judge time set to `J_r`; `ids`/// the replica's own op ids; `at` the time the queue records.pubfn redate_refused(db: &Driver, clock: &Clock, refused: &[String], ids: &mutdynIdSource, at: &str) -> Result<Redated> {letSome(judge) = clock.judge_ms() else {returnErr(StoreError::refused("a `future` refusal is re-dated by the judge's time, and it carried none", )); };letSome(boot) = clock.boot.clone() else {returnErr(StoreError::refused("a `future` refusal is re-dated by the boot session, and this clock names none", )); };let cont = clock.cont; db.transaction(|db| {letmut outcome = Redated::default();letmut waiting: Vec<HeldReceipt> = Vec::new();for op_id in refused {let queued = db .get("SELECT 1 AS n FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op_id.clone())])? .is_some();if !queued {// Not a write this file queued — a catch-up row of an author// the refusal's judge has, or one already settled.continue; }ifletSome(receipt) = stored_receipt(db, op_id)? { waiting.push(receipt); } }if waiting.is_empty() {returnOk(outcome); } waiting.sort_by(|a, b| (a.ms, a.counter, &a.op_id).cmp(&(b.ms, b.counter, &b.op_id)));letmut facts: Vec<HeldReceipt> = Vec::new();letmut redating: Vec<HeldReceipt> = Vec::new();for h in waiting {if h.is_fact() { facts.push(h); } elseif h.receipt.restamps.is_some() {let op = crate::wire::from_bytes(h.op_id.clone(), &h.bytes).map_err(StoreError::encode)?;crate::rejected::park( db, &op,crate::rejected::Direction::Push,crate::rejected::Class::Conflict, &format!("{REFUSED_AFTER_REDATE}: the serving Mac refused this re-dated write as ahead of its time"), at, )?; unqueue(db, &h.op_id)?; outcome.parked.push(h.op_id.clone()); outcome.settled.insert(h.op_id); } else { redating.push(h); } }let meta = db.get("SELECT device_id, workspace_id FROM _meta", &[])?;let device = meta .as_ref() .and_then(|row| row.text("device_id").map(str::to_string)) .unwrap_or_default();let database = meta .as_ref() .and_then(|row| row.text("workspace_id").map(str::to_string)) .unwrap_or_default();letmut last: Option<String> = None;letmut redated: Vec<(CottonOp, HeldReceipt)> = Vec::new();letmut author: Option<Author> = None;// A refused author fact leaves the file, so the file moves to the// fresh author even when none of that author's writes are re-dated// here — the next write must not go out under a fact nobody holds.iflet (true, Some(fact)) = (redating.is_empty(), facts.first()) {let minted = mint_time(judge, cont, &boot, fact.mint_cont, fact.mint_boot.as_deref()); author = Some(coin_author(db, &device, None, AuthorReason::Redate, clock, ids, Some(minted))?); }for h in redating {let minted = mint_time(judge, cont, &boot, h.mint_cont, h.mint_boot.as_deref());if author.is_none() { author = Some(coin_author(db, &device, None, AuthorReason::Redate, clock, ids, Some(minted))?); }let fresh = author.as_ref().expect("coined above");let floor = match last.as_deref() {Some(last) if later(last, &fresh.first_stamp)? => last.to_string(), _ => fresh.first_stamp.clone(), };let stamp = next_hlc(&fresh.id, Some(&floor), minted)?;let receipt = Receipt { stamp: stamp.clone(), author: fresh.id.clone(), restamps: Some(h.op_id.clone()), ..h.receipt.clone() };// New bytes under the fresh author, so a fresh signature by the// same device (keys slice KS1).let op = crate::signed::seal( db, &database,crate::wire::from_receipt(ids.next_op_id(minted)?, &receipt)?, )?; last = Some(stamp); redated.push((op, h)); }ifletSome(fresh) = author.as_ref() {let batch: Vec<CottonOp> = std::iter::once(fresh.fact.clone()) .chain(redated.iter().map(|(op, _)| op.clone())) .collect();let folded = fold::arrive(db, &batch, Arrival::Local)?;ifletSome(refused) = folded.rejected.first().or(folded.parked.first()) {returnErr(StoreError::refused(format!("the re-date of a `future` refusal {} was refused by the fold: {}", refused.op_id, refused.reason ))); }if !folded.waiting.is_empty() || !folded.applied.contains(&fresh.fact.op_id) {returnErr(StoreError::refused("the re-date's author fact did not apply — a self-naming fact never waits, so the fold is wrong", )); }for (_, old) in &redated { unqueue(db, &old.op_id)?; outcome.settled.insert(old.op_id.clone()); }let travelling: Vec<CottonOp> = std::iter::once(fresh.fact.clone()) .chain(redated.iter().map(|(op, _)| op.clone())) .collect();crate::outbox::queue_ops(db, &travelling, at)?;for (op, old) in &redated { set_mint_clocks( db, op, old.mint_cont.map_or(SqlValue::Null, SqlValue::Integer), old.mint_boot.clone().map_or(SqlValue::Null, SqlValue::Text), )?; }let newest = redated .last() .map_or(fresh.first_stamp.as_str(), |(op, _)| op.hlc.as_str()) .to_string();crate::cursors::advance_cursor(db, &fresh.id, &newest, at)?;let trusted = last_hlc_after_redate(db, &newest, judge)?; db.run("UPDATE _meta SET last_hlc = ?", &[SqlValue::Text(trusted)])?; }// A refused fact leaves after the fold: the fold drops a re-dated// receipt's original by the two authors' facts.for fact in &facts { db.run( &format!("DELETE FROM {} WHERE op_id = ?", fact.place), &[SqlValue::Text(fact.op_id.clone())], )?; fold::reassemble_row(db, AUTHORS_TABLE, &fact.receipt.row_id)?; unqueue(db, &fact.op_id)?; outcome.settled.insert(fact.op_id.clone()); } outcome.redated = redated.into_iter().map(|(op, _)| op).collect(); outcome.author = author;Ok(outcome) })}// ---------------------------------------------------------------------------// Changes recovered from a kept copy (QUEUE BAD OP 4)// ---------------------------------------------------------------------------/// What [`send_recovered`] did with the changes it was handed.#[derive(Debug, Clone, Default, PartialEq)]pubstructRecovered {/// The old op ids now queued here under new stamps, or taken here before (their marks are in `_kept_taken`).pub sent: Vec<String>,/// The old op ids whose bytes do not read in this build: they stay where they are kept.pub unreadable: Vec<String>,/// The new stamps' fresh author, when anything was sent this call.pub author: Option<String>,}/// The table that records which kept changes this copy has taken, so a launch stopped between taking them and/// marking them done never sends one twice.const KEPT_TAKEN: &str = "CREATE TABLE IF NOT EXISTS _kept_taken (op_id TEXT PRIMARY KEY, new_op_id TEXT, at TEXT NOT NULL)";/// QUEUE BAD OP 4: changes this device made in a copy that was kept aside (a rebuild, a removal, a waiting copy: the/// copy moved whole, nothing read out of it), each handed as its op id and its signed receipt bytes. Every one that/// reads in this build is minted again here under ONE fresh author (reason `redate`) at its ORIGINAL time (its own/// stamp's millisecond, never the boot start or now: a day-1 edit must not beat the person's day-3 edit of the same/// field), oldest first, folded and queued like any write; one that does not read is answered `unreadable` and left/// alone. Nothing is sent without judge time (answered empty, tried again on the next pass). Once per change: each/// taken op id is written to `_kept_taken` in the same transaction.pubfn send_recovered(db: &Driver, wall_ms: i64, changes: &[(String, Vec<u8>)], ids: &mutdynIdSource, at: &str) -> Result<Recovered> {letSome(judge) = db.judge() else {returnOk(Recovered::default()); };let clock = judge.mint_clock(wall_ms).map_err(StoreError::refused)?; send_recovered_with(db, &clock, changes, ids, at)}/// [`send_recovered`] by the mint clock given (a test's judged clock); nothing without judge time.pubfn send_recovered_with(db: &Driver, clock: &Clock, changes: &[(String, Vec<u8>)], ids: &mutdynIdSource, at: &str) -> Result<Recovered> {let clock = clock.clone();letSome(judge_ms) = clock.judge_ms() else {returnOk(Recovered::default()); }; db.transaction(|db| { db.exec(KEPT_TAKEN)?;letmut outcome = Recovered::default();letmut reading: Vec<(String, Receipt, i64, i64)> = Vec::new();for (op_id, bytes) in changes {if db.get("SELECT 1 AS n FROM _kept_taken WHERE op_id = ?", &[SqlValue::Text(op_id.clone())])?.is_some() { outcome.sent.push(op_id.clone());continue; }let read = crate::wire::from_bytes(op_id.clone(), bytes) .map_err(|error| error.to_string()) .and_then(|_| canonical::decode(bytes).map_err(|error| error.to_string())) .and_then(|receipt| hlc_parts(&receipt.stamp).map(|parts| (receipt, parts)).map_err(|error| error.to_string()));match read {// An author's own fact names an author this copy does not hold; the fresh author's fact stands for it.Ok((receipt, _)) if receipt.table == AUTHORS_TABLE => { db.run("INSERT INTO _kept_taken (op_id, new_op_id, at) VALUES (?, NULL, ?)", &[SqlValue::Text(op_id.clone()), SqlValue::Text(at.to_string())])?; outcome.sent.push(op_id.clone()); }Ok((receipt, parts)) => reading.push((op_id.clone(), receipt, parts.ms.min(judge_ms), parts.counter)),Err(error) => { eprintln!("[cotton-sync] a kept change {op_id} does not read in this build and stays kept ({error})"); outcome.unreadable.push(op_id.clone()); } } }if reading.is_empty() {returnOk(outcome); } reading.sort_by(|a, b| (a.2, a.3, &a.0).cmp(&(b.2, b.3, &b.0)));let meta = db.get("SELECT device_id, workspace_id FROM _meta", &[])?;let device = meta.as_ref().and_then(|row| row.text("device_id").map(str::to_string)).unwrap_or_default();let database = meta.as_ref().and_then(|row| row.text("workspace_id").map(str::to_string)).unwrap_or_default();// A copy made fresh has no author until its first write: it takes its first, and the recovered changes go// under a re-date author after it, whose stream starts at the oldest change's own time.letmut facts: Vec<CottonOp> = Vec::new();ifsuper::meta(db)?.author.is_none() { facts.push(coin_author(db, &device, None, AuthorReason::First, &clock, ids, None)?.fact); }let fresh = coin_author(db, &device, None, AuthorReason::Redate, &clock, ids, Some(reading[0].2))?; facts.push(fresh.fact.clone());letmut last = fresh.first_stamp.clone();letmut minted: Vec<(String, CottonOp)> = Vec::new();for (old, receipt, ms, _) in reading {let stamp = next_hlc(&fresh.id, Some(&last), ms)?;let receipt = Receipt { stamp: stamp.clone(), author: fresh.id.clone(), restamps: None, ..receipt };let op = crate::signed::seal(db, &database, crate::wire::from_receipt(ids.next_op_id(ms)?, &receipt)?)?; last = stamp; minted.push((old, op)); }let batch: Vec<CottonOp> = facts.iter().cloned().chain(minted.iter().map(|(_, op)| op.clone())).collect();let folded = fold::arrive(db, &batch, Arrival::Local)?;ifletSome(refused) = folded.rejected.first() {// Nothing is taken: the whole call rolls back, and the changes stay kept for the next launch.returnErr(StoreError::refused(format!("a kept change {} was refused by the fold: {}", refused.op_id, refused.reason))); }if !folded.applied.contains(&fresh.fact.op_id) {returnErr(StoreError::refused("the recovered changes' author fact did not apply")); }crate::outbox::queue_ops(db, &batch, at)?;for (old, op) in &minted { db.run("INSERT INTO _kept_taken (op_id, new_op_id, at) VALUES (?, ?, ?)", &[SqlValue::Text(old.clone()), SqlValue::Text(op.op_id.clone()), SqlValue::Text(at.to_string())])?; outcome.sent.push(old.clone()); }crate::cursors::advance_cursor(db, &fresh.id, &last, at)?;let trusted = last_hlc_after_redate(db, &last, judge_ms)?; db.run("UPDATE _meta SET last_hlc = ?", &[SqlValue::Text(trusted)])?; outcome.author = Some(fresh.id);Ok(outcome) })}/// One receipt this file stores, as the re-date reads it.fn stored_receipt(db: &Driver, op_id: &str) -> Result<Option<HeldReceipt>> {for place in ["_writes", "_tombstones"] {letSome(row) = db.get( &format!("SELECT op_id, mint_cont, mint_boot, bytes, sig FROM {place} WHERE op_id = ?"), &[SqlValue::Text(op_id.to_string())], )?else {continue; };let bytes = match row.get("bytes") {Some(SqlValue::Blob(bytes)) => bytes.clone(),Some(SqlValue::Text(text)) => text.as_bytes().to_vec(), _ => returnErr(StoreError::encode(format!("receipt {op_id} has no bytes"))), };let receipt = canonical::decode(&bytes)?;let parts = hlc_parts(&receipt.stamp)?;returnOk(Some(HeldReceipt { place, op_id: op_id.to_string(), ms: parts.ms, counter: parts.counter, mint_cont: row.int("mint_cont"), mint_boot: row.text("mint_boot").map(str::to_string), receipt, bytes, sig: match row.get("sig") {Some(SqlValue::Blob(sig)) => Some(sig.clone()), _ => None, }, forced: false, })); }Ok(None)}fn unqueue(db: &Driver, op_id: &str) -> Result<()> {// not a copy: a change re-dated by the release pass (queued again under its new date), or the held fact of an author that never travels. db.run("DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op_id.to_string())])?;Ok(())}/// `a` sorts after `b` by millisecond and counter, whatever their authors.fn later(a: &str, b: &str) -> Result<bool> {let (a, b) = (hlc_parts(a)?, hlc_parts(b)?);Ok((a.ms, a.counter) > (b.ms, b.counter))}#[cfg(test)]mod seek_tests {usesuper::*;use std::time::{Duration, Instant};/// RULE: Clock recovery seeks each receipt's hlc index below the judge bound in under 100 ms on a million-row file, including held receipts; global MAX on the table-row index walks the entire file. #[test]fn million_receipts_clock_recovery_seeks_below_the_bound() {let dir = tempfile::tempdir().unwrap();let db = Driver::open(dir.path().join("synthetic.db")).unwrap();crate::fixtures::build_at_version(&db, crate::migrate::SCHEMA_VERSION); db.exec("WITH RECURSIVE n(x) AS (VALUES(0) UNION ALL SELECT x+1 FROM n WHERE x<999999) INSERT INTO _writes(tbl,row_id,hlc,held) SELECT 'synthetic',printf('%08d',x),printf('%013d:0000:synthetic',x),1 FROM n; INSERT INTO _tombstones(tbl,row_id,hlc,op_id,author,actor,bytes) VALUES ('synthetic','deleted','0000000500000:0000:synthetic','delete','synthetic','synthetic',X'7B7D')").unwrap();for judge in [100_000, 900_000, 2_000_000] {let bound = bound_prefix(judge);let params = [SqlValue::Text(bound.clone())];let plan = db.all(&format!("EXPLAIN QUERY PLAN {LAST_HLC_BELOW}"), ¶ms).unwrap();for index in ["idx_writes_hlc", "idx_tombstones_hlc"] { assert!(plan.iter().any(|r| r.text("detail").is_some_and(|s| s.contains("SEARCH") && s.contains(index))), "{plan:?}"); } assert!(!plan.iter().any(|r| r.text("detail").is_some_and(|s| s.contains("SCAN _writes") || s.contains("SCAN _tombstones") || s.contains("TEMP B-TREE"))), "{plan:?}");let expected = db.get("SELECT MAX(top) AS top FROM (SELECT MAX(hlc) AS top FROM _writes WHERE hlc < ?1 UNION ALL SELECT MAX(hlc) FROM _tombstones WHERE hlc < ?1)", ¶ms).unwrap().unwrap().text("top").unwrap().to_string();let before = db.steps();let start = Instant::now(); assert_eq!(last_hlc_after_redate(&db, "0000000000000:0000:synthetic", judge).unwrap(), expected); assert!(start.elapsed() < Duration::from_millis(100)); assert!(db.steps()-before < 100, "clock seek walked {} steps", db.steps()-before); } db.exec("DELETE FROM _writes; DELETE FROM _tombstones").unwrap(); assert_eq!(last_hlc_after_redate(&db, "0000000000001:0000:synthetic", 0).unwrap(), "0000000000001:0000:synthetic"); }}