//! The Mac's client replica: the same file format the phone holds, opened with //! the store's own driver. //! //! This is the phone's boot sequence re-hosted — bootstrap from the server's //! snapshot when there is no file, open, read the file's identity, and hand //! back the driver every service reads through. A THIRD write path into //! somebody's database is the thing this repo says no to //! ([one-implementation-of-who-wins-the-same-schema-and-conflict-rule]). //! //! The file lives at `/client//replica.db` — under the //! data dir, beside the embedded server's own `files/`, and never mixed into //! it: this Mac may hold its own server AND be a client of another, and two //! files for two roles is what keeps that unambiguous. //! //! WHAT IS NOT HERE, and why. The TypeScript's `storeGate` is dropped //! (design M14): `initCottonStore` is a process-wide singleton with two //! legitimate holders, so every read there had to run inside `runWithStore`. //! In Rust the driver is a VALUE — the replica owns one, the viewer's reader //! owns another — so there is no singleton to gate and no turn to take. The //! five cases of `storeGate.test.ts` are dropped with it, and this paragraph is //! their written reason. //! //! Opening a replica does not convert a TypeScript-era file. The one-time //! conversion ran on 2026-09-09, when the owner's database moved onto his own //! Mac. A snapshot from a server running this build is already at [`SCHEMA_VERSION`], //! and one that is not is refused by name. use std::path::{Path, PathBuf}; use std::panic::Location; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use std::time::{Duration, Instant}; use cotton_store::driver::Driver; use cotton_store::judge::JudgeSource; use cotton_store::file_identity::{read_file_identity, FileId, FileIdentity, Namespace}; use cotton_store::meta::{read_meta, Meta}; use rusqlite::types::Value as SqlValue; use crate::layout::Layout; use crate::seams::{Clock, Random}; /// `device:`, minted once and kept — the author of every op this Mac /// emits. pub fn device_file_path(layout: &Layout) -> PathBuf { layout.client_dir().join("device.json") } #[derive(Debug, thiserror::Error)] pub enum ReplicaError { #[error("{path}: {source}")] Io { path: String, #[source] source: std::io::Error, }, #[error(transparent)] Store(#[from] cotton_store::StoreError), #[error(transparent)] Connection(#[from] crate::connection::ConnectionFileError), /// The bootstrap ran and left nothing to open. #[error("{0}")] Bootstrap(String), /// The file opened and belongs to nobody. Kept, untouched. #[error("this copy of the database names no database; it is kept as it is")] NoIdentity, /// The file at this database's address is a copy of another database. /// Kept, untouched. #[error("the copy at {asked}'s address is a copy of database {got}; it is kept as it is")] WrongDatabase { asked: String, got: String }, /// This device is a runner: it holds no copy of any database. #[error("{RUNNER_HOLDS_NO_COPY}")] Runner, /// A migration step failed. The file is at `from` — WHOLE, at a version /// some build has shipped — because each step commits its own /// `user_version` and the failed one rolled back. #[error("the database could not be updated to schema {to} (step {version}): {message}")] Migration { version: u32, from: u32, to: u32, message: String, }, /// The copy could not keep a column the kit names on a table it compiles. #[error("{0}")] Shape(String), } fn io(path: &Path) -> impl Fn(std::io::Error) -> ReplicaError + '_ { move |source| ReplicaError::Io { path: path.display().to_string(), source, } } /// This device's id as its identity file holds it, or `None` when there is /// none yet — read, never minted. pub(crate) fn known_device_id(layout: &Layout) -> Option { let text = std::fs::read_to_string(device_file_path(layout)).ok()?; let parsed = serde_json::from_str::(&text).ok()?; let id = parsed.get("deviceId")?.as_str()?; id.starts_with("device:").then(|| id.to_string()) } /// This install's device id. /// /// STABLE is the whole requirement: the id is the author of every op, so a new /// one on each launch would make the file's history read as a fleet of Macs and /// would re-fold this device's own writes on the next pull. /// /// It is NOT the device id the SERVER admits — that one is the public half of /// the Ed25519 key (`identity::DeviceIdentity::device_id`), 43 base64url /// characters, and it names a machine to a server. This one names an AUTHOR to /// a file. Two ids, two questions, and conflating them would put a credential /// in every op's `device_id` column. pub fn resolve_device_id( layout: &Layout, clock: &dyn Clock, random: &dyn Random, ) -> Result { let path = device_file_path(layout); if let Some(id) = known_device_id(layout) { return Ok(id); } // A file holding something that is not a device id is a file this // build cannot use. Minted over rather than refused, unlike the KEY // seed: an author id has no credential in it, so a fresh one costs a // second row in the file's device list and nothing else. // 16 bytes: the ULID randomness the store's own generator takes. let mut randomness = [0u8; 16]; random.fill(&mut randomness); let ulid = cotton_store::protocol::ulid::new_ulid(clock.now().timestamp_millis(), &randomness)?; let minted = format!("device:{ulid}"); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(io(parent))?; } let body = format!("{{\n \"deviceId\": \"{minted}\"\n}}\n"); // not a copy: the device id file. std::fs::write(&path, body).map_err(io(&path))?; Ok(minted) } /// Where each source got to, kept IN the replica. /// /// `_meta` is a fixed single-row table with no slot for this, and adding one /// would be a store change every phone would carry for a Mac's benefit. So the /// cursors are a device-local table of this file, in the `_media` family: never /// synced, never folded, never in an op. /// /// In the replica rather than beside it, deliberately. A cursor is an /// optimisation — every row carries its source's own stable id, so a re-read is /// free — but a cursor that OUTLIVED the file it describes is not harmless: a /// deleted replica re-bootstrapped from a snapshot would resume from a position /// the new file has no rows for and skip everything before it. pub const CURSOR_DDL: &str = "CREATE TABLE IF NOT EXISTS _ingest_cursors ( source TEXT PRIMARY KEY, cursor TEXT NOT NULL, updated_at TEXT NOT NULL )"; pub fn read_ingest_cursor(db: &Driver, source: &str) -> cotton_store::Result> { Ok(db .get( "SELECT cursor FROM _ingest_cursors WHERE source = ?", &[SqlValue::Text(source.to_string())], )? .and_then(|row| row.text("cursor").map(str::to_string))) } pub fn write_ingest_cursor( db: &Driver, source: &str, cursor: &str, now: &str, ) -> cotton_store::Result<()> { db.run( "INSERT INTO _ingest_cursors (source, cursor, updated_at) VALUES (?, ?, ?)\n ON CONFLICT(source) DO UPDATE SET cursor = excluded.cursor, updated_at = excluded.updated_at", &[ SqlValue::Text(source.to_string()), SqlValue::Text(cursor.to_string()), SqlValue::Text(now.to_string()), ], )?; Ok(()) } /// The open replica. pub struct Replica { pub driver: Driver, /// The author of every op this Mac emits — `device:`. pub device_id: String, pub workspace_id: String, pub owner_id: String, /// Which file this is and which namespace its derived ids are made under, /// read once at open ([`read_file_identity`]) — see [`Replica::namespace`] /// and [`Replica::file_id`]. pub identity: FileIdentity, pub path: PathBuf, /// True when this open had to fetch the file first. pub bootstrapped: bool, /// What this open took, step by step, in ms — "fetch", "open", "claim", /// "ladder", "identity" (the Debug group's opens). pub opened: Vec<(&'static str, u64)>, /// This open file's holds written under its AUTHOR id have all been /// retired (`crate::media::holds::keep_holds_level`), so the passes stop /// asking. Per open, in memory: a re-bootstrap is a new open, and it asks /// again. pub author_holds_level: bool, } impl std::fmt::Debug for Replica { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Replica") .field("path", &self.path) .field("workspace_id", &self.workspace_id) .field("device_id", &self.device_id) .field("bootstrapped", &self.bootstrapped) .finish_non_exhaustive() } } impl Replica { /// Rebuild the computed-column index if it is not this build's — after /// the open, in the background, never on the open's path. True when it /// rebuilt. A fold that meets a stale index rebuilds it too. A caller /// holding a replica mutex should instead copy its path and release it /// before calling `derive::ensure_file_current`. pub fn bring_index_current(&self) -> Result { Ok(cotton_tools::derive::ensure_file_current(&self.path, &self.workspace_id, |_| {})?.is_some()) } pub fn meta(&self) -> cotton_store::Result> { read_meta(&self.driver) } /// Run the next step of this copy's schema move, if one is under way — /// one table in its own transaction, after the open and never on its /// path (passivemove rule 1) — and say where the move stands for every /// reader ([`crate::moves`]). The last step stamps the file and its /// write-ahead log is folded in. pub fn move_step(&self) -> Result, ReplicaError> { let stepped = cotton_store::shape_move::move_step(&self.driver)?; if stepped.as_ref().is_some_and(|stepped| stepped.finished) { self.driver.checkpoint_truncate()?; } crate::moves::note(&self.workspace_id, cotton_store::shape_move::left(&self.driver)?); Ok(stepped) } /// Whether this copy's schema move is still under way. pub fn moving(&self) -> bool { crate::moves::left(&self.workspace_id).is_some() } /// What a derived record id in this file is made under. pub fn namespace(&self) -> &Namespace { self.identity.namespace() } /// This file's own id — what a media key is made under. pub fn file_id(&self) -> &FileId { self.identity.id() } /// A READ connection to this same file, for the screens. /// /// The replica's own `driver` is the WRITER — the sync fold, the outbox, /// the migrations — and it lives behind one mutex because there is one /// writer. A read taken through that mutex queued behind every fold a sync /// pass ran, so a list a person opened waited on a write they never asked /// for. This is the other half of WAL: a read-only connection /// ([`Driver::open_reader`]) whose transactions see the last committed /// snapshot and never wait on the writer. /// /// Opened FROM an open replica on purpose: the replica's open has already /// run the migration ladder and put the file in WAL, so the reader never /// meets a file mid-ladder or in another journal mode. pub fn open_reader(&self) -> cotton_store::Result { Ok(ReadReplica { driver: Driver::open_reader(&self.path)?, device_id: self.device_id.clone(), workspace_id: self.workspace_id.clone(), owner_id: self.owner_id.clone(), identity: self.identity.clone(), }) } /// The screens' READ connections to this file: a pool of up to /// [`READERS_PER_DATABASE`], so one read never queues behind another. /// /// One reader behind one mutex made a board of tiles a line: every tile's /// read waited for the one before it, and a slow count held the list the /// person opened. WAL readers never block each other, so the pool holds /// several and a read takes any free one ([`ReadPool::take`]). /// /// The first connection opens here, so a file a reader cannot open is a /// refusal at open rather than at the first screen; the rest open as reads /// overlap, so an idle database holds one. pub fn open_read_pool(&self) -> cotton_store::Result { let first = self.open_reader()?; Ok(ReadPool { path: self.path.clone(), device_id: self.device_id.clone(), workspace_id: self.workspace_id.clone(), owner_id: self.owner_id.clone(), identity: self.identity.clone(), shared: Lane::new(READERS_PER_DATABASE, READ_WAIT_LIMIT, Some(READ_DEADLINE), vec![first]), short: Lane::new( SHORT_READERS_PER_DATABASE, SHORT_READ_WAIT_LIMIT, Some(SHORT_READ_DEADLINE), Vec::new(), ), }) } } impl ReadReplica { /// One read-only connection on a held copy that nothing in this process /// has opened yet, for ONE short read, under the short lane's deadline /// ([`SHORT_READ_DEADLINE`], refused [`ReadRefused::TooLong`] past it). /// /// A copy's open takes its turn, walks the ladder and rebuilds what its /// computed columns need, and a catch-up holds that turn across its folds; /// Home, its catalogue and Today read a few rows and never wait on any of /// that — after a switch on 290 the fan stood on Me and Tools for /// 1.5–1.8 s while the database opened (readpool, 16 Oct 2026). The file is /// read as it is on disk: a read that does not fit a file this build has /// not laddered fails, and the screen tries again once the open is done. pub fn open_short(path: &Path, device_id: &str) -> cotton_store::Result { let mut driver = Driver::open_reader(path)?; let (Some(meta), Some(identity)) = (read_meta(&driver)?, read_file_identity(&driver)?) else { return Err(cotton_store::StoreError::refused("this copy names no database yet")); }; let until = Instant::now() + SHORT_READ_DEADLINE; driver .connection_mut() .progress_handler( DEADLINE_STEPS, Some(move || { let cut = Instant::now() >= until; if cut { REFUSED.with(|refused| refused.set(Some(ReadRefused::TooLong))); } cut }), ) .map_err(|error| { cotton_store::StoreError::refused(format!("a short read's deadline could not be set on its connection: {error}")) })?; Ok(ReadReplica { driver, device_id: device_id.to_owned(), workspace_id: meta.workspace_id, owner_id: meta.owner_id, identity, }) } } /// A read-only connection to an open replica's file, with the ids a read /// needs — see [`Replica::open_reader`]. It writes nothing and folds nothing; /// it lives and dies with the replica it was opened from. pub struct ReadReplica { pub driver: Driver, /// The author id of the replica it reads — a read never authors an op, but /// a tool's context names the device it runs on. pub device_id: String, pub workspace_id: String, pub owner_id: String, /// The replica's own, as [`Replica::identity`]. pub identity: FileIdentity, } /// How many read connections one open database keeps at most. /// /// Enough that a board's tiles and the list under them read side by side; few /// enough that a handful of open databases is not dozens of page caches. pub const READERS_PER_DATABASE: usize = 4; /// How long a read waits for a connection before it is refused, naming who /// holds them all. /// /// A read is a few statements; one that waits this long is behind a holder /// that is not giving its connection back, and waiting on is how a whole app /// stood still: on 12 Oct 2026 a standby's status read ran a whole-file scan /// on every data event, 64 reads queued on four connections, the sync loop /// and the quit queued behind them, and nothing in the log said who held /// them (standbyhang). Refused, the read's caller says so and the next one /// tries again; the line names the holders. pub const READ_WAIT_LIMIT: Duration = Duration::from_secs(30); /// How long one read may run on the SHARED lane before SQLite stops it. /// /// Every read is bounded inside the Rust call, so a read the app has given up /// on stops instead of holding its connection on (the app's own cancel never /// reaches a running statement): on 16 Oct 2026 reads held every connection of /// the owner's Personal for 14–43 s each and Home was refused behind them /// (readpool). Past this a list is cut and answers could-not-read, too long. pub const READ_DEADLINE: Duration = Duration::from_secs(20); /// How often a waiting read writes who it is waiting behind. const READ_WAIT_SAY_EVERY: Duration = Duration::from_secs(5); /// Why the pool refused a read on this thread — [`take_read_refusal`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ReadRefused { /// Every connection of its lane was held past the lane's wait. Busy, /// It ran past its lane's deadline and SQLite stopped it. TooLong, } thread_local! { /// The pool's last refusal of a read on THIS thread (a read is answered on /// the thread that asked it), set where it happens — the wait, or the /// progress handler that stops a statement — and read back once by the /// method that answers the app, which says so in its own typed code. static REFUSED: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// The pool's refusal of a read on this thread since the last time this was /// asked, if any — and forget it. Neither is a file that cannot be read: the /// file is fine, and the next try may answer. pub fn take_read_refusal() -> Option { REFUSED.with(|refused| refused.take()) } /// Say that a read on this thread was refused for one of the pool's reasons /// by a caller that keeps its own bound — a single-flight read that is still /// running answers the next ask [`ReadRefused::Busy`]. pub fn note_read_refusal(why: ReadRefused) { REFUSED.with(|refused| refused.set(Some(why))); } /// [`take_read_refusal`] without forgetting it. pub fn peek_read_refusal() -> Option { REFUSED.with(std::cell::Cell::get) } /// How a read refused for want of a connection begins — [`is_busy`]. pub const READ_BUSY: &str = "every read connection of this file is busy"; /// Whether `error` is a read refused because every connection of its lane was /// held past the wait — the file is fine and the next try may answer, which /// is not a file that cannot be read. pub fn is_busy(error: &cotton_store::StoreError) -> bool { matches!(error, cotton_store::StoreError::Refused(said) if said.starts_with(READ_BUSY)) } /// How many connections the SHORT lane keeps ([`ReadPool::take_short`]). /// /// Three, never one (architect, 16 Oct 2026 22:52 IST): Home, its catalogue /// and Today are asked together, and on the 290 walk of the owner's copy one /// connection made a 0.4 s `read.home` cost the catalogue behind it a 5 s /// wait and a refusal. Three are each a reader of their own, so the three /// reads a screen asks at once never queue behind each other. pub const SHORT_READERS_PER_DATABASE: usize = 3; /// How long a short read waits for a short connection before it is refused — /// the lane's 3 s cap ([`SHORT_READ_DEADLINE`]), so a wait and a read are /// bounded alike and Home draws nothing new until then (architect, 22:52). pub const SHORT_READ_WAIT_LIMIT: Duration = SHORT_READ_DEADLINE; /// How long a read may run on the SHORT lane before SQLite stops it — a /// SAFETY CAP, not the lane's measure (architect, 16 Oct 2026 21:58 IST). /// /// The lane is reserved by name for three reads, and that reservation is what /// keeps long reads out; this only catches a bug. A read past it is cut inside /// its statement (a progress handler, so it stops mid-scan, not after it) and /// refused as too long ([`ReadRefused::TooLong`]) — the typed could-not-read /// line, never a Home that waits on. A short read over /// [`SHORT_READ_SLOW`] is a finding the app logs, never a refusal. pub const SHORT_READ_DEADLINE: Duration = Duration::from_secs(3); /// A short read this slow or slower is logged as a finding with its duration /// (device-local, never a refusal), so the household walk gives the real /// numbers and a slow one becomes a lane row, not a stranded Home. pub const SHORT_READ_SLOW: Duration = Duration::from_millis(500); /// How many SQLite virtual-machine steps run between two looks at the clock. const DEADLINE_STEPS: std::os::raw::c_int = 1_000; /// An open file's read connections — see [`Replica::open_read_pool`]. /// /// A read takes a free connection for as long as it runs and gives it back /// when its lease drops. A connection opens only when every open one is in a /// read; past [`READERS_PER_DATABASE`] a read waits for the first one given /// back. Lives and dies with the replica it was opened from. /// /// Two lanes, each with its own connections, so the reads a screen cannot be /// drawn without never queue behind the reads that can take their time: /// the SHARED lane ([`ReadPool::take`]) for every list, page and walk, and /// the SHORT lane ([`ReadPool::take_short`]) for Home's card set, the Tools /// board and Today. On 16 Oct 2026 TestFlight 289 drew only Me and Tools on /// the owner's 9 GB Personal: four long reads held the one lane for 10–30 s /// each, Home's card-set read was refused at 30 s, and the fan fell to its /// two chrome cards (readpool). pub struct ReadPool { path: PathBuf, /// The ids every connection carries, as [`ReadReplica`]'s. device_id: String, workspace_id: String, owner_id: String, identity: FileIdentity, shared: Lane, short: Lane, } /// One lane of a [`ReadPool`]: its own connections, its size, its wait. struct Lane { max: usize, wait_limit: Duration, /// How long one read may run on a connection of this lane. deadline: Option, state: Mutex, returned: Condvar, } struct PoolState { free: Vec, /// Connections open, free or leased. opened: usize, /// Who holds each leased connection: the line that took it, its thread, /// and since when — what a waiting read names. lent: Vec, next_lease: u64, } struct Lent { lease: u64, by: &'static Location<'static>, thread: String, since: Instant, } impl Lent { fn named(&self) -> String { format!( "{} on {} for {:.1} s", self.by, self.thread, self.since.elapsed().as_secs_f64() ) } } impl Lane { fn new(max: usize, wait_limit: Duration, deadline: Option, free: Vec) -> Self { Lane { max, wait_limit, deadline, state: Mutex::new(PoolState { opened: free.len(), free, lent: Vec::new(), next_lease: 0 }), returned: Condvar::new(), } } /// The poison is recovered, not passed on: the state is a list of idle /// connections and a count, and a read that panicked left both whole (its /// lease gave its connection back as it unwound). fn lock(&self) -> MutexGuard<'_, PoolState> { self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } /// A free connection of this lane: an idle one, a new one (opened by /// `open`) while the lane is under its size, or — every one leased — the /// first one given back, for at most the lane's wait. fn take<'a>( &'a self, by: &'static Location<'static>, open: impl FnOnce() -> cotton_store::Result, path: &Path, ) -> cotton_store::Result> { let asked = Instant::now(); let mut said = asked; let mut state = self.lock(); let mut open = Some(open); loop { if let Some(reader) = state.free.pop() { return self.lend(state, reader, by); } if state.opened < self.max { if let Some(open) = open.take() { state.opened += 1; // Opened with the lock let go: another read takes a returned // connection meanwhile instead of waiting on this file open. drop(state); return match open() { Ok(reader) => self.lend(self.lock(), reader, by), Err(error) => { self.lock().opened -= 1; self.returned.notify_one(); Err(error) } }; } } let waited = asked.elapsed(); if waited >= self.wait_limit { REFUSED.with(|refused| refused.set(Some(ReadRefused::Busy))); return Err(cotton_store::StoreError::Refused(format!( "{READ_BUSY} after {:.0} s ({} asked): held by {}", waited.as_secs_f64(), by, holders(&state) ))); } if said.elapsed() >= READ_WAIT_SAY_EVERY { said = Instant::now(); eprintln!( "[cotton-read] {} has waited {:.0} s for a read connection of {}: held by {}", by, waited.as_secs_f64(), path.display(), holders(&state) ); } let slice = (self.wait_limit - waited).min(READ_WAIT_SAY_EVERY); state = self .returned .wait_timeout(state, slice) .unwrap_or_else(|poisoned| poisoned.into_inner()) .0; } } /// Lend `reader`, under its lane's deadline when the lane has one. A /// deadline SQLite would not take is no lease at all — the read is refused /// and the connection goes back — never a short read that runs unbounded. fn lend( &self, mut state: MutexGuard<'_, PoolState>, mut reader: ReadReplica, by: &'static Location<'static>, ) -> cotton_store::Result> { let until = self.deadline.map(|deadline| Instant::now() + deadline); if let Some(until) = until { let bounded = reader.driver.connection_mut().progress_handler( DEADLINE_STEPS, Some(move || { let cut = Instant::now() >= until; if cut { REFUSED.with(|refused| refused.set(Some(ReadRefused::TooLong))); } cut }), ); if let Err(error) = bounded { state.free.push(reader); drop(state); self.returned.notify_one(); return Err(cotton_store::StoreError::refused(format!( "a short read's deadline could not be set on its connection: {error}" ))); } } let lease = state.next_lease; state.next_lease += 1; state.lent.push(Lent { lease, by, thread: std::thread::current().name().unwrap_or("an unnamed thread").to_owned(), since: Instant::now(), }); Ok(ReadLease { lane: self, lease, reader: Some(reader), until, _holding: cotton_store::held::holding("a read connection"), }) } fn give_back(&self, lease: u64, mut reader: ReadReplica) { // Taken off before the connection is free again; if SQLite will not // take it off, the connection is closed rather than lent on with a // deadline that has passed. if self.deadline.is_some() && reader.driver.connection_mut().progress_handler(0, None:: bool>).is_err() { let mut state = self.lock(); state.lent.retain(|lent| lent.lease != lease); state.opened -= 1; drop(state); self.returned.notify_one(); return; } let mut state = self.lock(); state.lent.retain(|lent| lent.lease != lease); state.free.push(reader); drop(state); self.returned.notify_one(); } } impl ReadPool { /// A free connection of the SHARED lane: an idle one, a new one while the /// lane is under [`READERS_PER_DATABASE`], or — every one leased — the /// first one given back, for at most [`READ_WAIT_LIMIT`]. /// /// `#[track_caller]`: the lease remembers the line that asked (through /// every `#[track_caller]` wrapper, such as `with_file`), so a read that /// waits names its holders and a refusal says who they were. #[track_caller] pub fn take(&self) -> cotton_store::Result> { self.shared.take(Location::caller(), || self.open_one(), &self.path) } /// A connection of the SHORT lane, which no list or walk of the file ever /// holds: for the few-row reads a screen cannot be drawn without (Home's /// card set, the Tools board, Today). Waits at most /// [`SHORT_READ_WAIT_LIMIT`]. #[track_caller] pub fn take_short(&self) -> cotton_store::Result> { self.short.take(Location::caller(), || self.open_one(), &self.path) } /// Who holds this pool's connections right now, oldest first per lane — /// the line that took each, its thread and for how long. pub fn holders(&self) -> Vec { let mut named: Vec = self.shared.lock().lent.iter().map(Lent::named).collect(); named.extend(self.short.lock().lent.iter().map(Lent::named)); named } fn open_one(&self) -> cotton_store::Result { Ok(ReadReplica { driver: Driver::open_reader(&self.path)?, device_id: self.device_id.clone(), workspace_id: self.workspace_id.clone(), owner_id: self.owner_id.clone(), identity: self.identity.clone(), }) } /// Connections open right now, free or leased, in both lanes. pub fn opened(&self) -> usize { self.shared.lock().opened + self.short.lock().opened } } fn holders(state: &PoolState) -> String { if state.lent.is_empty() { return "no one (the connections are opening)".into(); } state.lent.iter().map(Lent::named).collect::>().join("; ") } /// One read's hold on a pool connection; dropping it gives the connection back. /// /// It marks its thread as holding a file ([`cotton_store::held::holding`]), /// so a network call, a dial or a child process inside a read is the same /// panic in a debug build as one inside the writer — and, being not `Send`, /// it cannot be held across an `.await` in a spawned task: a read holds its /// connection for a few statements and nothing else. pub struct ReadLease<'a> { lane: &'a Lane, lease: u64, reader: Option, /// When SQLite stops this read — its lane's deadline. until: Option, _holding: cotton_store::held::Holding, } impl ReadLease<'_> { /// Whether this read has run past its lane's deadline — a statement that /// failed now was cut for running too long, not refused by the file. pub fn past_deadline(&self) -> bool { self.until.is_some_and(|until| Instant::now() >= until) } } impl std::ops::Deref for ReadLease<'_> { type Target = ReadReplica; fn deref(&self) -> &ReadReplica { self.reader.as_ref().expect("a lease holds its connection until it drops") } } impl Drop for ReadLease<'_> { fn drop(&mut self) { if let Some(reader) = self.reader.take() { self.lane.give_back(self.lease, reader); } } } /// How the first copy of the file arrives when this Mac has never seen it. /// /// A function of the destination PATH, never of bytes: a snapshot is a whole /// SQLite file and can be hundreds of megabytes, so the caller streams it to /// disk (the phone's own #378 rule, one layer down) and this crate opens what /// landed. In `embedded` mode the same seam takes an in-process backup of the /// server's own file under its write lock. pub type Bootstrap<'a> = &'a mut dyn FnMut(&Path) -> Result<(), String>; /// One rung of the ladder, on its way past. /// /// The migration screen's whole vocabulary (design P16): a `Start` so it can /// paint at all, a `Step` per rung so it can say "Step N of M", a `Done` so it /// can settle. Emitted BEFORE each step runs, because the step blocks from /// start to finish and an event after it would be a screen that says nothing /// for the whole time it matters. #[derive(Debug, Clone, PartialEq, Eq)] pub enum MigrationEvent { Start { from: u32, to: u32, total: usize, }, Step { version: u32, index: usize, total: usize, }, Done { from: u32, to: u32, /// Queued ops dropped because the schema no longer has their table. dropped_from_outbox: usize, /// The pull cursor was rewound and the whole server log will be folded /// again. replayed: bool, }, /// The move could not take the copy: it is exactly as it was, and /// `message` is the mover's own reason, for the page to name. Failed { from: u32, to: u32, message: String, }, } /// JUDGE TIME ON A REPLICA (slice 1): the process's one judge clock, which /// every answer from the serving Mac is a reading for, and the randomness the /// replica mints the op ids of an answer's re-dates with. #[derive(Clone)] pub struct ReplicaJudge { pub judge: Arc, pub random: Arc, } impl std::fmt::Debug for ReplicaJudge { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ReplicaJudge").field("now", &self.judge.now()).finish() } } impl ReplicaJudge { /// `driver`, written by this judge: its writers mint by judge time /// (`cotton_store::mint::clock::writer_clock`) and every answer folded /// into it is a reading. pub fn attach(&self, driver: Driver) -> Driver { driver.replica_judged_by( Arc::clone(&self.judge), Box::new(crate::seams::op_ids(Arc::clone(&self.random))), ) } } /// What [`open_replica_with`] is given. pub struct OpenReplicaInput<'a> { pub layout: &'a Layout, pub workspace_id: &'a str, pub clock: &'a dyn Clock, pub random: &'a dyn Random, /// The judge this replica is written by. `None` is a replica with no /// judge — a test's — whose writers stamp by the wall clock, as a server /// with no relay does. pub judge: Option, pub bootstrap: Bootstrap<'a>, /// Where the migration ladder reports. `None` runs it silently, which is /// right for the Mac (whose file is the server's own and never migrates on /// this path) and wrong for the phone (whose screen is the ladder). pub on_migration: Option<&'a mut dyn FnMut(MigrationEvent)>, /// Run over a file this call BOOTSTRAPPED, straight after it opens and /// BEFORE the migration ladder. Never run over a file that was already /// there. /// /// This is where the snapshot's claim goes, and the order is the point: a /// downloaded file is still stamped with the SERVER'S `device_id` and /// carries the server's `last_server_seq`, its outbox and its media /// ledger. Every migration step that ran before the claim would be running /// against a file that says it belongs to another device — and one that /// enqueued anything would enqueue it under that name. /// /// It takes the driver and THIS device's id, which is read off the identity /// file rather than out of the database, so nothing here needs the file to /// have been corrected first. #[allow(clippy::type_complexity)] pub on_bootstrapped: Option<&'a mut dyn FnMut(&Driver, &str) -> Result<(), ReplicaError>>, /// Where this replica's writer reads the device key that signs its /// receipts (keys slice KS1). An empty slot mints unsigned until the /// process fills it. pub receipt_signer: cotton_store::signed::SignerSlot, } /// Open the replica, fetching it first if this device has never seen it. /// /// A thin wrapper over [`open_replica_with`] for a caller with no migration /// screen and no judge — a test's replica, stamping by the wall clock. pub fn open_replica( layout: &Layout, workspace_id: &str, clock: &dyn Clock, random: &dyn Random, bootstrap: Bootstrap<'_>, ) -> Result { open_replica_with(OpenReplicaInput { layout, workspace_id, clock, random, judge: None, bootstrap, on_migration: None, on_bootstrapped: None, receipt_signer: cotton_store::signed::SignerSlot::default(), }) } /// Why a runner opens no copy. pub const RUNNER_HOLDS_NO_COPY: &str = "this Mac is a runner: it runs jobs and takes placements, and holds no copy of any database"; /// Why an open stopped at a copy that arrived but was never claimed: the app /// was stopped between putting it in place and correcting it for this device. pub const UNCLAIMED_REPLACEMENT: &str = "A fresh copy of your database is in place but was not finished for this device; it is being finished now."; /// Open the replica, fetching it first if this device has never seen it, and /// MIGRATING it if the file is behind this build. /// /// **The migration is in place, and that is the change 4b makes.** Before the /// ladder (`cotton_store::migrate`) there was none to run, so a file at /// another version was refused by name; now a file BEHIND this build is walked /// forward one committed step at a time — resumable by construction, because /// each step commits its own `user_version` and a retry re-plans from what the /// file then says. A file AHEAD of this build is still refused, untouched, /// because the way out of that is a newer app. pub fn open_replica_with(input: OpenReplicaInput<'_>) -> Result { let OpenReplicaInput { layout, workspace_id, clock, random, judge, bootstrap, mut on_migration, mut on_bootstrapped, receipt_signer, } = input; // A RUNNER HOLDS NO COPY. This is the one door every copy is opened // through, so it is where a runner is refused — before a directory is // made or a byte fetched. if crate::connection::holds_no_copy(layout) { return Err(ReplicaError::Runner); } let path = layout.replica(workspace_id); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(io(parent))?; } let mut opened: Vec<(&'static str, u64)> = Vec::new(); let mut step = std::time::Instant::now(); let mut took = |name: &'static str, opened: &mut Vec<(&'static str, u64)>| { opened.push((name, u64::try_from(step.elapsed().as_millis()).unwrap_or(u64::MAX))); step = std::time::Instant::now(); }; let mut bootstrapped = false; if !path.exists() { bootstrap(&path).map_err(ReplicaError::Bootstrap)?; took("fetch", &mut opened); // A bootstrap that wrote nothing — or wrote nothing but a zero-byte // file — is a truncated download, not a fresh start. Opening it would // stamp an empty file as this person's life. let bytes = std::fs::metadata(&path).map(|info| info.len()).unwrap_or(0); if bytes == 0 { let_go_of_empty_download(&path); return Err(ReplicaError::Bootstrap( "the snapshot wrote nothing — nothing to open".to_string(), )); } bootstrapped = true; } // A device's folds never rebuild a stale index: the background does // (`Driver::index_beside`). let driver = Driver::open(&path)?.sharing_signer(receipt_signer).index_beside(); let driver = match &judge { Some(judge) => judge.attach(driver), None => driver, }; // A reader's connection file is written before its first snapshot arrives. // Bind that role before the claim below: the snapshot still names the // serving Mac in `_meta`, so it cannot identify this device's authority. if let Some(connection) = crate::connection::read_connection(&layout.connection_json())? { let scope = cotton_store::device_scope::DeviceScope::parse(connection.device_scope.as_deref()) .map_err(|reason| ReplicaError::Bootstrap(format!("this device's role could not be read: {reason}")))?; driver.set_device_scope(scope); } took("open", &mut opened); // Every replica open owns the same shape move as the serving Mac. The // app's pre-open heal cannot cover a snapshot that arrived during this // very call, and library/phone opens must not depend on process flavour. if let Some(meta) = read_meta(&driver)? { if meta.workspace_id != workspace_id { return Err(ReplicaError::WrongDatabase { asked: workspace_id.to_string(), got: meta.workspace_id }); } } let stamped = cotton_store::migrate::current_version(&driver)?; let mut moving = false; if stamped != 0 && stamped < cotton_store::migrate::SCHEMA_VERSION { let floor = cotton_store::shape_move::LEDGER_BASE; if stamped < floor { // The numbers to the log; the refusal a page can reach names none // (passivemove rule 4). eprintln!( "cotton-client: {workspace_id}: the copy is stamped schema {stamped}, below the fresh-start floor {floor}; this build reads {}", cotton_store::migrate::SCHEMA_VERSION ); return Err(ReplicaError::Store(cotton_store::StoreError::refused( "this phone's copy is older than any this build can update in place. The file is kept unchanged.".to_string(), ))); } // A MOVE UNDER WAY OPENS AS IT IS (passivemove rule 1, 18 Oct 2026): // its first step ran — the file's own tables are fresh — and the // tables it has left move after the open, one per transaction // ([`Replica::move_step`]); the stamp rises with the last. A copy that // is about to be claimed is moved whole first, as before. let fresh_copy = bootstrapped || crate::bootstrap::unclaimed::is_marked(&path) || crate::bootstrap::previous::path(&path).exists(); let left = cotton_store::shape_move::left(&driver)?.filter(|left| left.begun); if let Some(left) = left.filter(|_| !fresh_copy) { crate::moves::note(workspace_id, Some(left)); moving = true; } } if stamped != 0 && stamped < cotton_store::migrate::SCHEMA_VERSION && !moving { let touching = crate::unsent::touching_a_loss(&driver) .map_err(|error| ReplicaError::Store(cotton_store::StoreError::refused(format!("the copy's unsent changes could not be checked before its move: {error}"))))?; if touching != 0 { return Err(ReplicaError::Store(cotton_store::StoreError::refused(format!( "{touching} unsent changes touch what this move removes; they go to the Mac before this copy moves" )))); } // The move's steps, as the ladder's are heard: `done == 0` is the plan // made, its `Start` with the step count. let to = cotton_store::migrate::SCHEMA_VERSION; let moved = cotton_store::shape_move::move_to_current_reporting(&driver, &mut |step| { if let Some(report) = on_migration.as_deref_mut() { report(if step.done == 0 { MigrationEvent::Start { from: stamped, to, total: step.total } } else { MigrationEvent::Step { version: to, index: step.done, total: step.total } }); } }); if let Some(report) = on_migration.as_deref_mut() { report(match &moved { Ok(_) => MigrationEvent::Done { from: stamped, to, dropped_from_outbox: 0, replayed: false }, Err(error) => MigrationEvent::Failed { from: stamped, to, message: error.to_string() }, }); } moved?; took("shape move", &mut opened); } // THE CLAIM BEFORE THE LADDER — see `on_bootstrapped`. Resolved here rather // than at the end because this device's id comes off the identity file, not // out of the database it is about to correct. let device_id = resolve_device_id(layout, clock, random)?; // A copy put in place and never claimed — the app stopped between the // rename and the claim, or the claim refused and the copy was KEPT — still // names the sender's device. It says so on disk (`bootstrap::unclaimed`), // and so does a re-hydrate's replacement with its predecessor beside it. let marked = crate::bootstrap::unclaimed::is_marked(&path); let named = if marked || crate::bootstrap::previous::path(&path).exists() { read_meta(&driver)?.map(|meta| meta.device_id) } else { None }; let unclaimed_replacement = named.as_deref().is_some_and(|named| named != device_id); if marked && !bootstrapped && named.as_deref() == Some(device_id.as_str()) { // The claim committed and the process died before the mark went. crate::bootstrap::unclaimed::clear(&path); } if bootstrapped || unclaimed_replacement { // The shape move above ran before the claim. A copy ahead of this // build is kept unclaimed, without any writes under the phone id. cotton_store::migrate::migration_plan(&driver).map_err(ReplicaError::Store)?; match on_bootstrapped.as_mut() { // A delivered copy now has this build's shape. Claim its author // identity without ever fetching over an existing file. Some(claim) => claim(&driver, &device_id)?, // AN UNCLAIMED REPLACEMENT IS NEVER OPENED WITHOUT ITS CLAIM. An // open with nothing to claim — the app's own attach on the next // launch — would hand out a file that still mints under the // serving Mac's author: two machines, one stream. Refused as a // bootstrap, so the caller takes the bootstrap path, whose claim // resumes over this very file. None if unclaimed_replacement => { return Err(ReplicaError::Bootstrap(UNCLAIMED_REPLACEMENT.to_string())); } None => {} } took("claim", &mut opened); } // A FILE AT THIS DATABASE'S ADDRESS THAT NAMES ANOTHER is refused before // anything writes into it — opened, it would be that database filed and // synced under this one's name. Kept, as every refused file is. if let Ok(Some(meta)) = read_meta(&driver) { if meta.workspace_id != workspace_id { return Err(ReplicaError::WrongDatabase { asked: workspace_id.to_string(), got: meta.workspace_id, }); } } if !moving { migrate(&driver, &mut on_migration)?; crate::moves::note(workspace_id, None); } took("ladder", &mut opened); // The copy keeps the money run's columns from its open, served or not: // a local copy's money rows have a balance to say. if !moving { crate::transport::object::keep_run_columns(&driver).map_err(ReplicaError::Shape)?; crate::transport::object::keep_kit_columns(&driver, crate::transport::object::CHAT_KEPT_COLUMNS).map_err(ReplicaError::Shape)?; crate::transport::object::keep_kit_columns(&driver, crate::transport::object::DAYS_KEPT_COLUMNS).map_err(ReplicaError::Shape)?; crate::transport::object::keep_kit_columns(&driver, crate::transport::object::NOTES_KEPT_COLUMNS).map_err(ReplicaError::Shape)?; // This core opened the copy to write: the newest core that has, kept beside it (a shared copy). crate::copy_keep::stamp_core(&path); // A retired table's local rows are NOT dropped here yet: `transport::object::drop_gone_rows` is wired in on its // own commit, with an ERASES line, once the coordinator says (TABLE DROP 1 review). } // Every fold in this process keeps the computed columns in step. A copy // whose index is not this build's — a fresh snapshot, or an install whose // computed columns moved — opens AS IT IS: the rebuild reads every record // (minutes on a large copy), so it never stands between the open and // Home; it runs after, in the background ([`Replica::bring_index_current`], // or the first fold), and a list that reads a computed column says it is // being worked out until then (phone 296 sat 2:28 on its open, 17 Oct 2026). cotton_tools::derive::install(); let (Some(meta), Some(identity)) = (read_meta(&driver)?, read_file_identity(&driver)?) else { // A file with no identity is refused and KEPT: syncing into it would // be syncing into a file that belongs to nobody, and deleting it would // be the open deciding to fetch over a file that is there (architect, // 12 Oct 2026). The page says so; Leave is the way to a fresh copy. return Err(ReplicaError::NoIdentity); }; driver.exec(CURSOR_DDL)?; took("identity", &mut opened); Ok(Replica { device_id, workspace_id: meta.workspace_id, owner_id: meta.owner_id, identity, driver, path, bootstrapped, author_holds_level: false, opened, }) } /// Walk the file forward, reporting each rung. /// /// **`restateOutboxAcross` is NOT ported, and this is its written reason.** The /// TypeScript re-stated every queued op across a schema change — rewriting its /// patch into the new shape — and had about forty tests saying what each /// rewrite meant. The Rust design replaces restating with one simpler act the /// ladder already owns: the pull cursor is rewound to 0 so the WHOLE server /// log is folded again — which re-applies exactly the ops a behind build had /// parked in `_parked` and skips every other one as stale. A queued op is /// never thrown away (QUEUE BAD OP 7: `outbox::drop_retired_ops` is gone), and /// `migrate_replica`'s own tests hold the rule. /// `apps/cotton/__tests__/replica/outboxRestate.test.ts` is DROPPED with this /// paragraph as its reason. fn migrate( driver: &Driver, on_migration: &mut Option<&mut dyn FnMut(MigrationEvent)>, ) -> Result<(), ReplicaError> { let plan = cotton_store::migrate::migration_plan(driver).map_err(ReplicaError::Store)?; if plan.pending.is_empty() { // An ordinary launch paints NOTHING: no start, no settle, no frame // held for a screen with one step in it. return Ok(()); } if let Some(report) = on_migration.as_deref_mut() { report(MigrationEvent::Start { from: plan.from, to: plan.to, total: plan.pending.len(), }); } let outcome = cotton_store::migrate::migrate_replica_reporting(driver, &mut |step| { // The event BEFORE the step, never the one after it: `took_ms` is // `Some` on the completion event, and a screen that drew only those // would say nothing for the whole time a step is blocking. if step.took_ms.is_none() { if let Some(report) = on_migration.as_deref_mut() { report(MigrationEvent::Step { version: step.version, index: step.index, total: step.total, }); } } }) .map_err(|error| match error { cotton_store::StoreError::Migration { version, from, to, source, } => ReplicaError::Migration { version, from, to, message: source.to_string(), }, other => ReplicaError::Store(other), })?; if let Some(report) = on_migration.as_deref_mut() { report(MigrationEvent::Done { from: outcome.from, to: outcome.to, dropped_from_outbox: outcome.dropped_from_outbox, replayed: outcome.replayed, }); } Ok(()) } #[cfg(test)] #[path = "replica_tests.rs"] mod tests; /// A download that wrote nothing: an empty file holds nothing, and leaves through the one function all the same /// (QUEUE BAD OP 4); anything it does hold keeps it aside. pub(crate) fn let_go_of_empty_download(path: &std::path::Path) { let _ = crate::copy_keep::retire_at(path, crate::copy_keep::Ending::keep("a download that wrote nothing")); }