//! **A local file stamped by an older build is MOVED in place, first — and a copy the move cannot take STOPS and says why.** //! //! THE MOVE FIRST (architect ruling, 12 Oct 2026, 256). The phone runs the //! Mac's engine, so at a schema bump it moves its copy the way the Mac moves //! its own files at start (`cotton_store::shape_move::move_to_current`) and //! syncs on from it — no snapshot, and no send first: an unsent change moves //! with its copy. The one exception is a change that writes something the //! crossing declares lost — a dropped table or a folded field //! ([`cotton_store::signed::touches_a_loss`]): only the copy it was made in //! can carry it, so that copy is held where it is ([`Heal::Held`]) rather //! than moved. //! //! A MOVE THAT FAILS IS A STOP, NEVER A FALLBACK. The 255 page: the move //! refused, a set-aside refused behind it, and the page said "0 changes … //! kept until they are sent" with the move's reason lost. Now the reason is //! written down first ([`crate::bootstrap::not_moved::mark`]) and the copy //! stays exactly where it is — nothing renamed, nothing fetched — and the open //! that follows names why ([`Heal::explain`]). A move already under way on a //! copy this device holds alone is the exception: it opens at every launch //! and its steps left are tried again ([`heal_stale_replica_leaving_tables`]). A whole copy from the Mac is //! only for a phone with no file, or one far behind in rows (the re-hydrate) //! — and a copy an earlier build's fallback renamed aside is a file: it is put //! back first ([`crate::bootstrap::previous::restore_set_aside`]). //! //! Undeclared processes (crate tests) leave their files alone. use cotton_core::flavor::Flavor; use cotton_store::migrate::{current_version, SCHEMA_VERSION}; use cotton_store::Driver; use crate::layout::Layout; use crate::replica::MigrationEvent; /// Where a move reports its steps: the open's own migration reporter, so the /// boot page names the move and its progress rather than "opening". pub type MoveReporter<'a> = Option<&'a mut dyn FnMut(MigrationEvent)>; /// What was done with a copy stamped by another build. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Heal { /// Moved in place to this build's schema; nothing is fetched. Moved { stamped: u32 }, /// The move's first step has run and its other tables move in the /// background, one per transaction (passivemove rule 1): the copy opens /// as it is, still stamped `stamped` until its last table is moved. Moving { stamped: u32 }, /// The move could not take it: the copy is where it was, untouched, and /// `why` is the move's own reason. NotMoved { stamped: u32, why: String }, /// Not moved yet: `unsent` changes write something this move loses, and /// go to the Mac first (`None`: the unsent changes could not be read, so /// whether they do cannot be told). Held { stamped: u32, unsent: Option }, } impl Heal { /// The refusal the open answered, and the line that says what was done /// with the copy and why. pub fn explain(heal: Option, refusal: String) -> String { match heal { Some(Heal::NotMoved { why, .. }) => format!( "{refusal}\nThis phone's copy could not be updated to this build in place: {why}. Nothing on this phone was changed, set aside or deleted." ), Some(Heal::Held { unsent: Some(n), .. }) => format!( "{refusal}\n{n} {} made on this phone {} something this update removes, so {} to your Mac before this copy is updated.", if n == 1 { "change" } else { "changes" }, if n == 1 { "writes" } else { "write" }, if n == 1 { "it goes" } else { "they go" }, ), Some(Heal::Held { unsent: None, .. }) => format!( "{refusal}\nThe changes made on this phone could not be read, so this copy is not updated until they can be." ), _ => refusal, } } /// The refusal for an open that must not run at all: the move already /// failed on this copy, and the open would run the same move again — /// minutes on a phone — to fail with the same reason. /// /// TYPED, NOT A SENTENCE WITH NUMBERS IN IT (passivemove rule 4): the /// code a page keys its own words on, and the versions as fields for the /// log ([`Stopped::log_line`]). Its `Display` — what an open's `Err` /// carries — names no schema. pub fn stopped(heal: &Option) -> Option { match heal { Some(Heal::NotMoved { stamped, why }) => { let stopped = Stopped { stamped: *stamped, reads: SCHEMA_VERSION, why: why.clone() }; eprintln!("cotton-client: {}", stopped.log_line()); Some(stopped) } _ => None, } } } /// An open stopped because the move already failed on this copy. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Stopped { /// The schema the copy is stamped at — for the log, never a page. pub stamped: u32, /// The schema this build reads — for the log, never a page. pub reads: u32, /// The move's own reason. pub why: String, } impl Stopped { /// The code the page keys its words on (`not_moved`). pub fn code(&self) -> &'static str { crate::bootstrap::NOT_MOVED } /// The line for the log, with the numbers. pub fn log_line(&self) -> String { format!( "{}: the copy is stamped schema {}, this build reads {}: {}", self.code(), self.stamped, self.reads, self.why ) } } impl std::fmt::Display for Stopped { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&Heal::explain( Some(Heal::NotMoved { stamped: self.stamped, why: self.why.clone() }), "This copy was written by another build of Cotton.".to_string(), )) } } /// Move `workspace_id`'s local copy to this build's schema, unless an unsent /// change writes something the move loses. `None`: nothing to judge — an /// undeclared process, no file, a file that will not open, an unstamped file, /// or one at this build's schema. /// /// `on_migration` hears the move as the ladder is heard — `Start`, a `Step` /// per finished step, then `Done` — or `Failed` with the mover's own reason. pub fn heal_stale_replica(layout: &Layout, workspace_id: &str, flavor: Option, on_migration: MoveReporter<'_>) -> Option { heal_replica(layout, workspace_id, flavor, false, on_migration) } /// [`heal_stale_replica`] for an open that never waits for the move /// (passivemove rule 1, 18 Oct 2026): only its FIRST step runs here — new /// tables and columns, carried values, retirements, Money's and the file's own /// `_` tables — and the copy is answered [`Heal::Moving`]; the caller runs /// the steps left after the open ([`crate::replica::Replica::move_step`]). A /// copy whose move is already under way runs nothing here and is answered /// `Moving` again even when a step stopped on an earlier open: only a /// database this device holds alone comes here, no object can make it again, /// so it opens at every launch and its caller tries the steps left once more /// (each is idempotent, and a passing cause such as a full disk clears; /// coordinator, 3 Nov 2026). pub fn heal_stale_replica_leaving_tables(layout: &Layout, workspace_id: &str, flavor: Option) -> Option { heal_replica(layout, workspace_id, flavor, true, None) } fn heal_replica( layout: &Layout, workspace_id: &str, flavor: Option, leaving_tables: bool, mut on_migration: MoveReporter<'_>, ) -> Option { flavor?; // A COPY THE DELETED FALLBACK SET ASIDE IS A FILE: it goes back to its // own name first, so the boot's open never mistakes this device for one // with nothing. crate::bootstrap::previous::restore_set_aside(layout, workspace_id); let path = layout.replica(workspace_id); if !path.exists() { return None; } // A file that will not even open is not this path's to judge: the open // that follows reports it as it always has. // What the unsent changes would lose is read only for a copy that moves (below): reading it decodes every unsent // row, and a phone that never signed in holds all it ever wrote unsent, so at every open of a current copy that // was seconds of a cold launch for nothing (Story's launch, 23 Nov 2026: 9,100 unsent rows, 10 s on an emulator). let (stamped, begun) = { let driver = Driver::open(&path).ok()?; // A FILE THAT NAMES ANOTHER DATABASE is not this copy: nothing here // writes into it, and the open that follows refuses it, kept as it is. if cotton_store::meta::read_meta(&driver).ok().flatten().is_some_and(|meta| meta.workspace_id != workspace_id) { return None; } let stamped = current_version(&driver).ok()?; let begun = cotton_store::shape_move::left(&driver).ok().flatten().is_some_and(|left| left.begun); (stamped, begun) }; if stamped == SCHEMA_VERSION { fold_phones(&path, workspace_id); } if stamped == 0 || stamped == SCHEMA_VERSION { return None; } if leaving_tables && begun { // The move is under way: its first step ran on an earlier open, and // what it loses is already gone. The steps left are the caller's, // tried again at this open even when one stopped on an earlier one: // its `not_moved` note stands until the move is whole. return Some(Heal::Moving { stamped }); } // A PREDECESSOR LEFT FROM AN EARLIER CYCLE never stands in the way: it // goes when it holds nothing this copy lacks. crate::bootstrap::previous::release_if_spent(layout, workspace_id); if !begun { let touching = Driver::open(&path).map_err(|error| error.to_string()).and_then(|driver| crate::unsent::touching_a_loss(&driver)); match touching { Ok(0) => {} Ok(n) => { eprintln!( "cotton-client: {workspace_id} (stamped schema {stamped}, this build reads {SCHEMA_VERSION}): {n} unsent change(s) write what the move loses; sent before it moves" ); return Some(Heal::Held { stamped, unsent: Some(n) }); } Err(reason) => { eprintln!("cotton-client: {workspace_id}: its unsent changes could not be read ({reason}); not moved"); return Some(Heal::Held { stamped, unsent: None }); } } } let mut tell = |event: MigrationEvent| { if let Some(report) = on_migration.as_deref_mut() { report(event); } }; if leaving_tables { return match begin_in_place(&path, stamped) { Ok(()) => { eprintln!("cotton-client: began moving the local copy of {workspace_id} in place; its tables move after the open"); Some(Heal::Moving { stamped }) } Err(why) => { crate::bootstrap::not_moved::mark(layout, workspace_id, stamped, &why); eprintln!("cotton-client: the local copy of {workspace_id} (stamped schema {stamped}, this build reads {SCHEMA_VERSION}) could not begin its move: {why}; it is left as it is"); Some(Heal::NotMoved { stamped, why }) } }; } match move_in_place(&path, stamped, &mut tell) { Ok(report) => { tell(MigrationEvent::Done { from: stamped, to: SCHEMA_VERSION, dropped_from_outbox: 0, replayed: false }); // Moved: an earlier build's reason it could not be is not true now. crate::bootstrap::not_moved::clear(layout, workspace_id); eprintln!("cotton-client: moved the local copy of {workspace_id} in place\n{report}"); Some(Heal::Moved { stamped }) } Err(why) => { // WRITTEN DOWN BEFORE ANYTHING ELSE, so the page and the debug // group can name it whatever happens next. crate::bootstrap::not_moved::mark(layout, workspace_id, stamped, &why); tell(MigrationEvent::Failed { from: stamped, to: SCHEMA_VERSION, message: why.clone() }); eprintln!( "cotton-client: the local copy of {workspace_id} (stamped schema {stamped}, this build reads {SCHEMA_VERSION}) could not be moved in place: {why}; it is left as it is" ); Some(Heal::NotMoved { stamped, why }) } } } /// The phone fold (`cotton_store::phone_fold`) on a copy at this build's /// shape, as the Mac runs it on its files at start. It never stops the open: /// a fold that fails leaves the copy as it was and says so. fn fold_phones(path: &std::path::Path, workspace_id: &str) { let folded = Driver::open(path).and_then(|driver| cotton_store::phone_fold::fold_phones(&driver)); match folded { Ok(report) if report.wrote_nothing() => {} Ok(report) => eprintln!("cotton-client: {workspace_id}: {report}"), Err(why) => eprintln!("cotton-client: {workspace_id}: the phone fold could not run ({why}); the copy is as it was"), } } /// The Mac's shape move, on this phone's copy: one transaction that leaves the /// file at this build's schema or exactly as it was. A copy ahead of this /// build, or one that is not a whole copy, is not moved. fn move_in_place( path: &std::path::Path, stamped: u32, tell: &mut dyn FnMut(MigrationEvent), ) -> Result { // No number in the reason: it reaches the page's log line and the // `not_moved` note, and the stamp is in the heal's own log line. if stamped > SCHEMA_VERSION { return Err("the copy is ahead of this build".to_string()); } let driver = Driver::open(path).map_err(|e| e.to_string())?; match cotton_store::meta::read_meta(&driver) { Ok(Some(_)) => {} _ => return Err("not a whole copy: it names no database".to_string()), } // `done == 0` is the plan made: the move's `Start`, with its step count. let report = cotton_store::shape_move::move_to_current_reporting(&driver, &mut |step| { tell(if step.done == 0 { MigrationEvent::Start { from: stamped, to: SCHEMA_VERSION, total: step.total } } else { MigrationEvent::Step { version: SCHEMA_VERSION, index: step.done, total: step.total } }) }) .map_err(|e| e.to_string())?; driver.checkpoint_truncate().map_err(|e| e.to_string())?; Ok(report) } /// The move's first step on this phone's copy, in its own transaction; the /// steps left are written in the file and run after the open. fn begin_in_place(path: &std::path::Path, stamped: u32) -> Result<(), String> { if stamped > SCHEMA_VERSION { return Err("the copy is ahead of this build".to_string()); } let driver = Driver::open(path).map_err(|e| e.to_string())?; match cotton_store::meta::read_meta(&driver) { Ok(Some(_)) => {} _ => return Err("not a whole copy: it names no database".to_string()), } cotton_store::shape_move::move_step(&driver).map_err(|e| e.to_string())?; Ok(()) } #[cfg(test)] #[path = "dev_heal_tests.rs"] mod tests;