//! The real files cross from the schema the last real install wrote to this//! build's, IN PLACE, from the flat DDL itself.//!//! After the 4 Oct move every real file is a fresh file of its day: exactly the//! flat DDL of the schema it is stamped with, plus the server-local `_` tables//! workers make at run time. So the way across is the difference between the//! file and a fresh file of this build, worked out at move time rather than//! written down rung by rung://!//! - an object the fresh file has and this one lacks is created;//! - a table whose fresh statement only APPENDS columns, written where//! SQLite's own `ADD COLUMN` writes them, gains them by `ADD COLUMN`: no row,//! rowid, receipt or index moves ([`Crossing::add_columns`]);//! - a table whose statement differs otherwise is REBUILT under the fresh//! statement, its rows copied with their rowids (every FTS5 index is keyed//! on its source's rowid), then its fresh indexes and triggers created;//! - an index or trigger whose statement differs is dropped and created again;//! - a table a rise declares dropped (`schema::move_intents`, a plain//! `Loss::DropTable`) goes with every row, and with what it leaves on other//! tables: the search index over its words and the `_writes` index of its//! receipts;//! - any other object absent from the fresh file is left exactly as it is.//!//! A column a rebuild would lose, a new `NOT NULL` column with no default, or//! a rise that declares any loss but a plain table drop refuses the move//! before a statement runs. The move is one transaction, and before it commits//! the file must hold every object of the fresh file in the same bytes, every//! row it held, no new dangling reference, and whole search indexes — or//! nothing happened.//!//! Which stamps it moves from is [`MOVES_FROM`]: every stamp from//! [`LEDGER_BASE`] up to this build's. A file at one of them is exactly its//! fresh DDL, so the difference IS the shape ledger's way up.use std::collections::{BTreeMap, BTreeSet};use std::time::Instant;usecrate::create::{apply_schema, schema_objects, SchemaObject};usecrate::driver::Driver;usecrate::error::{Result, StoreError};usecrate::meta::file_schema_version;usecrate::schema::ddl::SCHEMA_VERSION;usecrate::schema::move_intents::{losses_between, Loss, INTENTS};/// The oldest stamp this build moves: 141, the schema of the oldest file any/// shipped build wrote and kept on a device (Rigby's first builds, 22 Oct/// 2026, local-only). Every file from it up is exactly its fresh DDL, so the/// diff is the ledger's way up; a file below it is refused, and its copy is/// kept unchanged (`cotton_client::replica`).pubconst LEDGER_BASE: u32 = 141;// The loss declarations begin at the first rise a move from the floor// crosses: none is kept for a crossing this build never makes, and none is// missing for one it does.const _: () = assert!(INTENTS[0].version == LEDGER_BASE + 1, "move_intents declares exactly the rises above LEDGER_BASE");/// The stamps this move starts from, derived rather than listed: a file/// stamped anywhere from [`LEDGER_BASE`] up to this build was written fresh at/// its stamp or by this move, which verifies the fresh DDL before it commits./// So the difference is the shape ledger's way up, and a SHAPE line the diff/// cannot carry (a lost column, a NOT NULL with no default) refuses at/// plan time. A list here needed a hand patch at every cut (72 → 73, 6 Oct).pubconst MOVES_FROM: std::ops::Range<u32> = LEDGER_BASE..SCHEMA_VERSION;/// What the move did, in schema words only: no row of the file is named.#[derive(Debug, Clone, Default)]pubstructShapeMoveReport {pub from: u32,pub to: u32,/// Objects created, `kind name`.pub created: Vec<String>,/// Tables rebuilt under their fresh statement.pub rebuilt: Vec<String>,/// Indexes and triggers dropped and created again, and search indexes/// made again and filled from their source (`search index <name>`).pub replaced: Vec<String>,/// Objects the fresh file does not have, left as they were.pub kept: Vec<String>,/// Rows of each rebuilt table, before and after.pub rows: Vec<(String, i64, i64)>,/// Tables a rise declared dropped, with their dependent objects removed.pub dropped: Vec<String>,pub took_ms: u128,/// Whether the move ran the whole-file checks (`PRAGMA integrity_check` and the foreign-key scans): every move but/// one that only made objects (`made_only`, SCHEMA 155).pub whole_file_checked: bool,}impl std::fmt::DisplayforShapeMoveReport {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!(f, "Shape move: v{} → v{}", self.from, self.to)?; writeln!(f, "Created ({}): {}", self.created.len(), self.created.join(", "))?; writeln!(f, "Rebuilt ({}): {}", self.rebuilt.len(), self.rebuilt.join(", "))?; writeln!(f, "Replaced ({}): {}", self.replaced.len(), self.replaced.join(", "))?; writeln!(f, "Left as they were, not in this build's schema: {}", self.kept.len())?; writeln!(f, "Retired tables: {}", self.dropped.len())?;let unchanged = self.rows.iter().all(|(_, before, after)| before == after); writeln!( f,"Rows of the rebuilt tables: {}",if unchanged { "every count unchanged" } else { "COUNTS CHANGED" } )?; writeln!(f, "Schema: every object of a fresh v{} file, in the same bytes", self.to)?; writeln!(f, "Integrity, foreign keys and search: ok")?; write!(f, "Time: {} ms", self.took_ms) }}/// The objects of a fresh file of this build.fn fresh_objects() -> Result<Vec<SchemaObject>> {let fresh = Driver::open_in_memory()?; apply_schema(&fresh)?; schema_objects(&fresh)}fn by_name(objects: Vec<SchemaObject>) -> BTreeMap<String, SchemaObject> { objects.into_iter().map(|o| (o.name.clone(), o)).collect()}structColumn { name: String, not_null: bool, has_default: bool,}fn columns(db: &Driver, schema: &str, table: &str) -> Result<Vec<Column>> {Ok(db .all( &format!("SELECT name, \"notnull\" AS nn, dflt_value FROM pragma_table_info('{table}', '{schema}') ORDER BY cid"), &[], )? .iter() .map(|row| Column { name: row.text("name").unwrap_or_default().to_string(), not_null: row.int("nn") == Some(1), has_default: row.get("dflt_value").is_some_and(|v| !matches!(v, rusqlite::types::Value::Null)), }) .collect())}/// Is this search index an external-content one — `content = '<a table>'` —/// so that every word in it can be read again from that table?fn reads_a_source(sql: &str) -> bool {let sql = sql.to_ascii_lowercase(); sql.split("content").skip(1).any(|rest| {let rest = rest.trim_start(); rest.strip_prefix('=').is_some_and(|named| {let named = named.trim_start(); named.starts_with('\'') && !named.starts_with("''") }) })}/// The table an external-content search index reads its words from:/// `content = 'cotton_products'` → `cotton_products`.fn content_source(sql: &str) -> Option<String> {let lower = sql.to_ascii_lowercase(); lower.match_indices("content").find_map(|(at, word)| {let rest = sql[at + word.len()..].trim_start().strip_prefix('=')?.trim_start();let rest = rest.strip_prefix('\'')?;let name = &rest[..rest.find('\'')?]; (!name.is_empty()).then(|| name.to_string()) })}fn count(db: &Driver, table: &str) -> Result<i64> {Ok(db .get(&format!("SELECT count(*) AS n FROM \"{table}\""), &[])? .and_then(|row| row.int("n")) .unwrap_or(0))}fn dangling(db: &Driver) -> Result<i64> {Ok(db .get("SELECT count(*) AS n FROM pragma_foreign_key_check", &[])? .and_then(|row| row.int("n")) .unwrap_or(0))}/// A run of column definitions split at its top-level commas: a comma inside/// parentheses or a quoted word belongs to its definition.fn definitions(run: &str) -> Vec<String> {let (mut depth, mut quote, mut start, mut found) = (0usize, None::<char>, 0, vec![]);for (at, c) in run.char_indices() {match (quote, c) { (Some(open), c) if c == open => quote = None, (Some(_), _) => {} (None, '\'' | '"' | '`') => quote = Some(c), (None, '(') => depth += 1, (None, ')') => depth = depth.saturating_sub(1), (None, ',') if depth == 0 => { found.push(run[start..at].trim().to_string()); start = at + 1; } _ => {} } } found.push(run[start..].trim().to_string()); found}/// Does SQLite's own `ADD COLUMN`, given these definitions in order, turn the/// file's statement into the fresh one to the byte? Asked of an empty scratch/// table rather than worked out, so what SQLite cannot add in place — a `NOT/// NULL` column with no constant default, a key, a stored generated column —/// is refused by SQLite itself.fn add_column_writes(table: &str, had: &str, definitions: &[String], fresh: &str) -> bool {letOk(scratch) = Driver::open_in_memory() else { returnfalse }; scratch.exec(had).is_ok() && definitions.iter().all(|definition| scratch.exec(&format!("ALTER TABLE \"{table}\" ADD COLUMN {definition}")).is_ok()) && scratch .get("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", &[rusqlite::types::Value::Text(table.to_string())]) .ok() .flatten() .is_some_and(|row| row.text("sql") == Some(fresh))}/// The column definitions the fresh statement appends to the file's, when/// appending them is their ONLY difference: read off the two statements, so no/// list names a table or a column (the hand list this replaces needed a line/// at every rise, 133 to 135). `ADD COLUMN` writes `, <definition>` after the/// last column and before the table's constraints, so the fresh statement must/// be the file's with one such run let in, and the run is then proven by/// [`add_column_writes`] rather than trusted.fn appended_columns(table: &str, had: &str, fresh: &str) -> Option<Vec<String>> {let grown = fresh.len().checked_sub(had.len()).filter(|grown| *grown > 2)?;let prefix = had.bytes().zip(fresh.bytes()).take_while(|(a, b)| a == b).count();let suffix = had.bytes().rev().zip(fresh.bytes().rev()).take_while(|(a, b)| a == b).count();// Every place the file's statement can be cut so that its head opens the// fresh statement and its tail closes it. (had.len().saturating_sub(suffix)..=prefix) .filter(|at| fresh.is_char_boundary(*at) && fresh.is_char_boundary(at + grown)) .find_map(|at| {let added = definitions(fresh[at..at + grown].strip_prefix(", ")?); add_column_writes(table, had, &added, fresh).then_some(added) })}/// A LOCAL table: one a file keeps for itself and no peer is ever sent a row/// of — the parked rows, the outbox, the receipts' own bookkeeping, a device's/// media and fetch state. Every one is named with a leading underscore, and/// no synced table is (`tests/shape_additive.rs` holds `TABLE_SPECS` to it).pubfn is_local(table: &str) -> bool { table.starts_with('_')}/// What crossing from one shape to another takes, read off the two shapes/// alone. [`move_to_current`] runs exactly this and a rise is classified from/// it (`schema::move_intents`, [`Crossing::not_additive`]), so the move and/// the classification cannot disagree about what a crossing does.#[derive(Debug, Clone, Default)]pubstructCrossing {/// Tables and search indexes the older shape lacks.pub create_tables: Vec<SchemaObject>,/// `(table, column definition)`, in the order `ADD COLUMN` runs them: all/// rows, rowids, receipts and indexes stay where they were.pub add_columns: Vec<(String, String)>,/// Tables whose statement differs by more than appended columns: made/// again under the fresh statement and their rows copied.pub rebuild: Vec<String>,/// Search indexes whose statement changed: made again and filled from/// their source table, which holds every word they index.pub reindex: Vec<SchemaObject>,/// Indexes and triggers whose statement changed: dropped and created.pub replace: Vec<SchemaObject>,/// Indexes and triggers the older shape lacks.pub create_rest: Vec<SchemaObject>,/// Objects of the older shape the newer one does not have.pub absent: Vec<SchemaObject>, not_additive: Vec<String>,}implCrossing {/// Why this crossing changes the EXCHANGE shape by more than adding to/// it, one line per cause; empty when it is additive.////// The exchange shape is what one build sends another: the rows of the/// synced tables. A crossing is additive when, on those tables, it only/// creates tables and appends columns by `ADD COLUMN` — none is rebuilt/// (a dropped or folded column, a changed CHECK, a filled NOT NULL) or/// gone, and no rule over rows a peer may send (a UNIQUE index, a trigger/// that is not a search index's own) is made, changed or removed on a/// table that already holds rows. What it does to a LOCAL table/// ([`is_local`]), a search index or a plain index never counts: no peer/// is served a row of those, so a rebuild of `_parked` leaves a peer/// exactly as served as before.pubfn not_additive(&self) -> &[String] { &self.not_additive }}/// The way from `had` to `fresh`, before a statement runs: refuses what no/// rule carries across.pubfn crossing(had: &[SchemaObject], fresh: &[SchemaObject]) -> Result<Crossing> {let live = by_name(had.to_vec());let fresh = by_name(fresh.to_vec());letmut plan = Crossing::default();for (name, object) in &fresh {match live.get(name) {Noneif object.kind == "table" => plan.create_tables.push(object.clone()),None => plan.create_rest.push(object.clone()),Some(had) if had.kind != object.kind => {returnErr(StoreError::refused(format!("shape move: {name} is a {} here and a {} in this build", had.kind, object.kind ))) }// The columns added to a shipped table in place — a person's, and// those a copy keeps for the object's definition — are carried,// never a difference (`package_shape::without_added`).Some(had) ifcrate::schema::package_shape::without_added(&had.sql).0 == object.sql => {}// An index over another table's words holds nothing of its own:// it is dropped, made under its fresh statement and filled again// from that table. One that keeps its own words would lose them.Some(had) if object.kind == "table" && object.is_fts5_virtual() => {if !(reads_a_source(&had.sql) && reads_a_source(&object.sql)) {returnErr(StoreError::refused(format!("shape move: search index {name} changed and keeps its own words; no rule rebuilds one" ))); } plan.reindex.push(object.clone()); }Some(had) if object.kind == "table" => match appended_columns(name, &crate::schema::package_shape::without_added(&had.sql).0, &object.sql) {Some(added) => plan.add_columns.extend(added.into_iter().map(|definition| (name.clone(), definition))),None => plan.rebuild.push(name.clone()), },Some(_) => plan.replace.push(object.clone()), } } plan.absent = live.values().filter(|object| !fresh.contains_key(&object.name)).cloned().collect();// An index or trigger of a rebuilt table is made again with it.let rebuilt: BTreeSet<&String> = plan.rebuild.iter().collect(); plan.replace.retain(|o| !rebuilt.contains(&o.tbl_name)); plan.create_rest.retain(|o| !rebuilt.contains(&o.tbl_name));let search: BTreeSet<&str> = live.values().chain(fresh.values()).filter(|o| o.is_fts5_virtual()).map(|o| o.name.as_str()).collect();let exchanged = |table: &str| !is_local(table) && !search.contains(table);// A rule over the rows of an exchanged table, which a peer's rows meet.let rule = |o: &SchemaObject| { exchanged(&o.tbl_name) && match o.kind.as_str() {"index" => o.sql.to_ascii_uppercase().starts_with("CREATE UNIQUE"),// A trigger that keeps a search index, or only writes this device's own tables (never refusing a// row: no RAISE), judges no peer's row (schema 157: `_mail_landed` kept beside the mail)."trigger" => !search.iter().any(|index| o.sql.contains(index)) && !writes_only_local(&o.sql), _ => false, } };letmut why: Vec<String> = plan.rebuild.iter().filter(|table| exchanged(table)).map(|table| format!("table {table} is rebuilt")).collect(); why.extend(plan.absent.iter().filter(|o| (o.kind == "table" && exchanged(&o.name)) || rule(o)).map(|o| format!("{} {} is gone", o.kind, o.name))); why.extend(plan.replace.iter().filter(|o| rule(o)).map(|o| format!("{} {} is replaced", o.kind, o.name))); why.extend( plan.create_rest .iter() .filter(|o| rule(o) && live.contains_key(&o.tbl_name)) .map(|o| format!("{} {} is a new rule over {}, which already holds rows", o.kind, o.name, o.tbl_name)), ); plan.not_additive = why;Ok(plan)}/// Whether a trigger's body only writes device-local tables and never refuses the row it fires on.fn writes_only_local(sql: &str) -> bool {let upper = sql.to_ascii_uppercase();letSome(body) = upper.find(" BEGIN ").map(|at| &sql[at..]) else { returnfalse };if upper.contains("RAISE(") || upper.contains("RAISE (") {returnfalse; }let words: Vec<&str> = body.split_whitespace().collect();letmut targets = Vec::new();for (i, w) in words.iter().enumerate() {let w = w.to_ascii_uppercase();let target = match w.as_str() {"INTO"if i > 0 && words[i - 1].eq_ignore_ascii_case("INSERT") => words.get(i + 1),"FROM"if i > 0 && words[i - 1].eq_ignore_ascii_case("DELETE") => words.get(i + 1),// An upsert's `DO UPDATE SET` writes the row it inserted."UPDATE"if !words.get(i + 1).is_some_and(|n| n.eq_ignore_ascii_case("SET")) => words.get(i + 1), _ => None, };ifletSome(t) = target { targets.push(t.trim_matches(|c| matches!(c, '"' | '`' | '(' | ')' | ',')).to_string()); } } !targets.is_empty() && targets.iter().all(|t| is_local(t))}/// The fresh table's columns against the file's: what the copy selects./// `added` declares the columns the file added to the table in place/// (`package_shape::without_added`), which the rebuild carries.fn copy_list(db: &Driver, fresh_db: &Driver, table: &str, without_rowid: bool, added: &[String]) -> Result<(Vec<String>, Vec<String>)> {let old = columns(db, "main", table)?;let new = columns(fresh_db, "main", table)?;let new_names: BTreeSet<&str> = new.iter().map(|c| c.name.as_str()).collect();let added: BTreeSet<String> = added.iter().filter_map(|declared| crate::schema::package_shape::added_name(declared)).collect();let added = |name: &str| added.contains(name);ifletSome(lost) = old.iter().find(|c| !new_names.contains(c.name.as_str()) && !added(&c.name)) {returnErr(StoreError::refused(format!("shape move: rebuilding {table} would lose its column {}; no rule says where it goes", lost.name ))); }let old_names: BTreeSet<&str> = old.iter().map(|c| c.name.as_str()).collect();// The rowid is carried: every FTS5 index is keyed on its source's rowid.let (mut into, mut select) = if without_rowid { (vec![], vec![]) } else { (vec!["rowid".to_string()], vec!["old.rowid".to_string()]) };for column in &new {if old_names.contains(column.name.as_str()) { into.push(format!("\"{}\"", column.name)); select.push(format!("old.\"{}\"", column.name)); } elseif column.not_null && !column.has_default {returnErr(StoreError::refused(format!("shape move: {table}.{} is new, NOT NULL and has no default, and nothing fills it", column.name ))); } }// The columns added in place go into the rebuilt table with their values.for column in old.iter().filter(|c| added(&c.name) && !new_names.contains(c.name.as_str())) { into.push(format!("\"{}\"", column.name)); select.push(format!("old.\"{}\"", column.name)); }Ok((into, select))}/// How far a move has got: `done` of `total` steps finished. One step is the/// new tables, columns and retirements together (with the file's own `_`/// tables rebuilt); then one per other table/// rebuilt and one per search index made again; and one for the indexes,/// triggers, the stamp and the check. `done == 0` is the plan made and nothing/// written yet.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructShapeStep {pub done: usize,pub total: usize,}/// The device-local record of a move under way: one row per step still to/// run, written in the move's first transaction and taken away by each step's/// own. A STAMP N SAYS NO TABLE IS BELOW N (architect's ruling, 18 Oct 2026):/// the stamp is written only by the last step, so a copy cut off part way/// stays stamped below this build, and its next open finishes the steps left/// here — the tables not yet moved — and only then stamps. The table is gone/// when the move is done; a fresh file never has it.pubconst MOVE_TABLE: &str = "_shape_move";/// Whether `table` is rebuilt in the first step rather than one of its own:/// the file's own `_` tables — its identity, cursors, outbox and receipts —/// which the open itself and every sync pass read, so a copy whose move is/// under way is never opened over an old one.fn moves_first(table: &str) -> bool { table.starts_with('_')}/// One step of a move after the first, written down whole so the next open/// can run it without planning again: the plan reads columns the first step/// has already changed.#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]#[serde(tag = "kind", rename_all = "snake_case")]enumStep {/// Rebuild `table` under `sql`, its rows copied with their rowids.Rebuild { table: String, sql: String, own: Vec<String>, into: Vec<String>, select: Vec<String>, rest: Vec<String> },/// Drop the search index and make it again from its source.Reindex { name: String, sql: String },/// Indexes, triggers, the stamp and the check.Finish { replace: Vec<(String, String, String)>, rest: Vec<(String, String, String)>, receipt_owners: bool, fills: Vec<String>, kept: Vec<String>, dangling_before: i64, },}implStep {fn kind(&self) -> &'static str {matchself {Step::Rebuild { .. } => "rebuild",Step::Reindex { .. } => "reindex",Step::Finish { .. } => "finish", } }fn name(&self) -> &str {matchself {Step::Rebuild { table, .. } => table,Step::Reindex { name, .. } => name,Step::Finish { .. } => "", } }}/// What a file's move has left, read without writing.#[derive(Debug, Clone, PartialEq, Eq)]pubstructMoveLeft {/// The stamp the file is moving from.pub from: u32,pub done: usize,/// Every step of the move; 0 before the first step has run, when the/// plan has not been made.pub total: usize,/// Whether the first step has run. Before it, every table of the file is/// in its old shape.pub begun: bool,/// The tables and search indexes still in their old shape once the/// first step has run: a read of one waits for its step.pub tables: Vec<String>,}implMoveLeft {/// Whether a read of `table` must wait for the move.pubfn holds(&self, table: &str) -> bool { !self.begun || self.tables.iter().any(|t| t == table) }}/// One step a move ran.#[derive(Debug, Clone, PartialEq, Eq)]pubstructStepped {/// The tables (and search indexes) this step moved.pub tables: Vec<String>,pub done: usize,pub total: usize,/// The step was the last: the file is stamped with this build's schema.pub finished: bool,}/// Whether `db` has a move to run or finish, and how far it has got. `None`/// for a file stamped with this build's schema and no move under way.pubfn left(db: &Driver) -> Result<Option<MoveLeft>> {if has_move_table(db)? {let (from, total) = header(db)?;let rows = db.all(&format!("SELECT kind, name FROM \"{MOVE_TABLE}\" WHERE step > 0 ORDER BY step"), &[])?;let tables = rows.iter() .filter(|row| row.text("kind") != Some("finish")) .filter_map(|row| row.text("name").map(str::to_string)) .collect();returnOk(Some(MoveLeft { from, done: total.saturating_sub(rows.len()), total, begun: true, tables })); }let from = file_schema_version(db)?;Ok(MOVES_FROM.contains(&from).then(|| MoveLeft { from, done: 0, total: 0, begun: false, tables: vec![] }))}/// Run the NEXT step of `db`'s move in its own transaction — the first (which/// plans the move and writes its steps down) or the next one written — and/// say what it moved. `None` when there is nothing to move. A step that fails/// rolls back alone; the steps before it stay, and the file stays stamped/// below this build until the last one runs.pubfn move_step(db: &Driver) -> Result<Option<Stepped>> {letmut report = ShapeMoveReport::default(); with_move_pragmas(db, || db.transaction(|db| next_step(db, &mut report)))}/// Whether `db`'s move to this build only ADDS, so it runs in moments over a/// file of any size and every row stays where it is: tables and search/// indexes made (a new search index starts empty and fills in the/// background), columns appended by `ADD COLUMN`, indexes and triggers made/// or made again, a retired table dropped. False for a file a move would/// rebuild a table of or refill a search index of (each copies every row),/// one whose move is already under way, and one this build does not move/// (`MOVES_FROM`). A served copy that only adds is moved in place on the/// phone (`cotton_client::unsent::move_copy_if_it_only_adds`), where any/// other is made again from its object.pubfn only_adds(db: &Driver) -> Result<bool> {if has_move_table(db)? || !MOVES_FROM.contains(&file_schema_version(db)?) {returnOk(false); }let plan = crossing(&schema_objects(db)?, &fresh_objects()?)?;Ok(plan.rebuild.is_empty() && plan.reindex.is_empty())}/// Move an OPEN file from a stamp in [`MOVES_FROM`] to [`SCHEMA_VERSION`], in/// place, as one transaction. The caller holds the file alone.pubfn move_to_current(db: &Driver) -> Result<ShapeMoveReport> { move_to_current_reporting(db, &mut |_| {})}/// [`move_to_current`], saying each step as it finishes — a phone's 4.6 GB/// copy moves for minutes, and a page that can only say "opening" for that/// long offers the wrong doors (build 264, 13 Oct 2026). Every step runs in/// the one transaction, so a failure anywhere leaves the file as it was; a/// file part way through a step-by-step move ([`move_step`]) is finished.pubfn move_to_current_reporting(db: &Driver, on_step: &mutdynFnMut(ShapeStep)) -> Result<ShapeMoveReport> {let started = Instant::now();let from = file_schema_version(db)?;if !MOVES_FROM.contains(&from) && !has_move_table(db)? {returnErr(StoreError::refused(format!("shape move: this file is stamped {from}; this build moves files from {MOVES_FROM:?} to {SCHEMA_VERSION}" ))); }letmut report = ShapeMoveReport { from, to: SCHEMA_VERSION, ..Default::default() }; with_move_pragmas(db, || { db.transaction(|db| {letmut said_start = false;whileletSome(stepped) = next_step(db, &mut report)? {if !said_start { on_step(ShapeStep { done: stepped.done - 1, total: stepped.total }); said_start = true; } on_step(ShapeStep { done: stepped.done, total: stepped.total });if stepped.finished {break; } }Ok(()) }) })?; report.took_ms = started.elapsed().as_millis();Ok(report)}/// A rebuild renames a table away and drops it: references in other tables/// and in triggers must stay spelled as they are, and the copy must not be/// judged half way. Both pragmas are no-ops inside a transaction, so they are/// set around the outermost one.fn with_move_pragmas<T>(db: &Driver, f: implFnOnce() -> Result<T>) -> Result<T> {if db.transaction_depth() > 0 {return f(); }let conn = db.connection(); conn.execute_batch("PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = ON;")?;let outcome = f(); conn.execute_batch("PRAGMA legacy_alter_table = OFF; PRAGMA foreign_keys = ON;")?; outcome}fn has_move_table(db: &Driver) -> Result<bool> {Ok(db.get("SELECT 1 AS n FROM sqlite_master WHERE type = 'table' AND name = ?", &[rusqlite::types::Value::Text(MOVE_TABLE.into())])?.is_some())}/// Whether the move under way only makes objects, as its plan wrote down.fn made_only_of(db: &Driver) -> Result<bool> {let body = db.get(&format!("SELECT body FROM \"{MOVE_TABLE}\" WHERE step = 0"), &[])?.and_then(|row| row.text("body").map(str::to_string)).unwrap_or_default();Ok(serde_json::from_str::<serde_json::Value>(&body).ok().and_then(|h| h["made_only"].as_bool()).unwrap_or(false))}fn header(db: &Driver) -> Result<(u32, usize)> {let body = db.get(&format!("SELECT body FROM \"{MOVE_TABLE}\" WHERE step = 0"), &[])? .and_then(|row| row.text("body").map(str::to_string)) .ok_or_else(|| StoreError::refused("shape move: the move under way has no header"))?;let header: serde_json::Value = serde_json::from_str(&body).map_err(|e| StoreError::refused(format!("shape move: header: {e}")))?;let from = header["from"].as_u64().unwrap_or(0) as u32;let total = header["total"].as_u64().unwrap_or(0) as usize;Ok((from, total))}/// The next step, inside the caller's transaction.fn next_step(db: &Driver, report: &mutShapeMoveReport) -> Result<Option<Stepped>> {if !has_move_table(db)? {let from = file_schema_version(db)?;if !MOVES_FROM.contains(&from) {returnOk(None); }return begin(db, from, report).map(Some); }let (from, total) = header(db)?;if file_schema_version(db)? != from {returnErr(StoreError::refused("shape move: the file's stamp is not the one its move began from")); }letSome(row) = db.get(&format!("SELECT step, body FROM \"{MOVE_TABLE}\" WHERE step > 0 ORDER BY step LIMIT 1"), &[])? else {returnErr(StoreError::refused("shape move: the move under way has no step left and no stamp")); };let at = row.int("step").unwrap_or(0);let step: Step = serde_json::from_str(row.text("body").unwrap_or_default()) .map_err(|e| StoreError::refused(format!("shape move: step {at}: {e}")))?;let tables = match &step {Step::Finish { .. } => vec![], other => vec![other.name().to_string()], }; run(db, &step, report)?;let finished = matches!(step, Step::Finish { .. });if finished {// The file is at this build's shape now: what its old constraints// refused is due again (`rejected::shape_changed`), and what an// owning reference this move ended held out of its table comes in// (`fold::settle_released`).crate::rejected::shape_changed(db)?;crate::fold::settle_released(db, from)?; } else { db.run(&format!("DELETE FROM \"{MOVE_TABLE}\" WHERE step = ?"), &[rusqlite::types::Value::Integer(at)])?; }let left = if finished { 0 } else { db.get(&format!("SELECT count(*) AS n FROM \"{MOVE_TABLE}\" WHERE step > 0"), &[])?.and_then(|r| r.int("n")).unwrap_or(0) as usize };Ok(Some(Stepped { tables, done: total - left, total, finished }))}/// The tables the rises above `from` drop, of those this file holds — each a/// plain [`Loss::DropTable`], its rows kept nowhere. A rise that declares/// anything else (a column folded into another table) refuses the move: no/// converter for one is written in this build. The folds of the rises up to/// 139 left with the moves from below 141 (29 Oct 2026), and none may come/// back silently.fn retired(db: &Driver, from: u32) -> Result<BTreeSet<String>> {if INTENTS.last().map(|intent| intent.version) != Some(SCHEMA_VERSION) {returnErr(StoreError::refused("shape move: this schema has no explicit loss declaration")); }let tables: BTreeSet<String> = schema_objects(db)?.into_iter().filter(|o| o.kind == "table").map(|o| o.name).collect();letmut retired = BTreeSet::new();for loss in losses_between(from, SCHEMA_VERSION) {match *loss {Loss::DropTable { table } => {if tables.contains(table) { retired.insert(table.to_owned()); } }Loss::FoldColumn { table, column, into } => {returnErr(StoreError::refused(format!("shape move: a rise folds {table}.{column} into {into}, and no converter carries it" ))) } } }Ok(retired)}/// The first step: plan the move from the file as it stands, write the rest/// of it down, and make the additive part — new tables and columns,/// retirements, and the file's own `_` tables.fn begin(db: &Driver, from: u32, report: &mutShapeMoveReport) -> Result<Stepped> {let fresh_list = fresh_objects()?;let fresh = by_name(fresh_list.clone());let fresh_db = Driver::open_in_memory()?; apply_schema(&fresh_db)?;let old_objects = schema_objects(db)?;let plan = crossing(&old_objects, &fresh_list)?;// The columns added to shipped tables in place, carried through a rebuild.let own_of: BTreeMap<String, Vec<String>> = old_objects .iter() .filter(|o| o.kind == "table") .map(|o| (o.name.clone(), crate::schema::package_shape::without_added(&o.sql).1)) .filter(|(_, own)| !own.is_empty()) .collect();let retired = retired(db, from)?;// A dropped table's receipts leave the owner projection with it.let fill_receipt_owners = plan.rebuild.iter().any(|table| table == "_writes") || !retired.is_empty();// What a retired table leaves on OTHER tables goes with it: a search// index over its words (`content = '<table>'`, which holds none of its// own) and the `_writes` index of its receipts (`WHERE tbl = '<table>'`).let retired_dependents: Vec<SchemaObject> = old_objects.iter().filter(|object| { !retired.contains(&object.tbl_name) && retired.iter().any(|table| { (object.is_fts5_virtual() && content_source(&object.sql).as_deref() == Some(table.as_str())) || (object.kind == "index" && object.sql.contains(&format!("WHERE tbl = '{table}'"))) }) }).cloned().collect();let retired_objects: BTreeSet<_> = old_objects.into_iter() .filter(|object| retired.contains(&object.tbl_name)) .map(|object| object.name) .chain(retired_dependents.iter().map(|object| object.name.clone())) .collect();let kept: Vec<String> = plan.absent.iter().map(|object| &object.name).filter(|name| !retired_objects.contains(*name)).cloned().collect();// Refuse a lost column or an unfillable one before anything is written.letmut rebuilds = Vec::new();for table in &plan.rebuild {let without_rowid = fresh[table].sql.to_ascii_uppercase().contains("WITHOUT ROWID");let (into, select) = copy_list(db, &fresh_db, table, without_rowid, own_of.get(table).map(Vec::as_slice).unwrap_or_default())?; rebuilds.push(Step::Rebuild { table: table.clone(), sql: fresh[table].sql.clone(), own: own_of.get(table).cloned().unwrap_or_default(), into, select, rest: fresh_list.iter().filter(|o| &o.tbl_name == table && o.kind != "table").map(|o| o.sql.clone()).collect(), }); }let (first, rebuilds): (Vec<Step>, Vec<Step>) = rebuilds.into_iter().partition(|step| moves_first(step.name()));// Indexes before triggers, the flat DDL's own order.letmut rest = plan.create_rest.clone();// An index over rows the file already holds reads every one: those named in `index_later::LATER` are made// in the background after the move, never at the open (SCHEMA 155). rest.retain(|o| !(o.kind == "index" && crate::index_later::LATER.contains(&o.name.as_str()))); rest.sort_by_key(|o| (o.kind != "index", o.name.clone()));// A move that only MAKES objects: no table copied (first or later), no search index refilled, no object made// again, nothing dropped. It moves no row, so the whole-file checks are not run for it (`verify`).// Nor a column taken over (`take_over`): it sets every row's value and drops the column set aside, which rewrites// every row of the table (SCHEMA 155 REVIEW, 26 Nov 2026: a 151 copy served 152's mail columns moved as made_only).letmut takes_over = false;for (table, column) in &plan.add_columns { takes_over |= holds_column(db, table, column.split_whitespace().next().unwrap_or(column).trim_matches('"'))?; }let made_only = rebuilds.is_empty() && first.is_empty() && plan.reindex.is_empty() && plan.replace.is_empty() && retired.is_empty() && retired_dependents.is_empty() && !takes_over;// Read over every child row; a move that only makes objects never compares it.let dangling_before = if made_only { 0 } else { dangling(db)? };let later: Vec<Step> = rebuilds.into_iter()// After the rebuilds: the fill reads the source's fresh columns. .chain(plan.reindex.iter().map(|index| Step::Reindex { name: index.name.clone(), sql: index.sql.clone() })) .chain(std::iter::once(Step::Finish { replace: plan.replace.iter().map(|o| (o.kind.clone(), o.name.clone(), o.sql.clone())).collect(), rest: rest.iter().map(|o| (o.kind.clone(), o.name.clone(), o.sql.clone())).collect(), receipt_owners: fill_receipt_owners,// A search index this move CREATED over rows the file already// holds is filled in the background, newest first, never here:// a rebuild of twelve years of mail in one transaction would hold// a phone's first screen for minutes (mailsearch brief, 12 Oct// 2026). It starts empty with its floor above every row. fills: plan.create_tables.iter().filter(|o| o.is_fts5_virtual() && reads_a_source(&o.sql)).map(|o| o.name.clone()).collect(), kept: kept.clone(), dangling_before, })) .collect();let total = 1 + later.len(); report.from = from; report.to = SCHEMA_VERSION; report.kept = kept; db.exec(&format!("CREATE TABLE \"{MOVE_TABLE}\" (step INTEGER PRIMARY KEY, kind TEXT NOT NULL, name TEXT NOT NULL, body TEXT NOT NULL)" ))?; db.run( &format!("INSERT INTO \"{MOVE_TABLE}\" (step, kind, name, body) VALUES (0, 'move', '', ?)"), &[rusqlite::types::Value::Text(serde_json::json!({ "from": from, "total": total, "made_only": made_only }).to_string())], )?;for (at, step) in later.iter().enumerate() {let body = serde_json::to_string(step).map_err(|e| StoreError::refused(format!("shape move: {e}")))?; db.run( &format!("INSERT INTO \"{MOVE_TABLE}\" (step, kind, name, body) VALUES (?, ?, ?, ?)"), &[ rusqlite::types::Value::Integer(at as i64 + 1), rusqlite::types::Value::Text(step.kind().into()), rusqlite::types::Value::Text(step.name().into()), rusqlite::types::Value::Text(body), ], )?; }letmut moved: Vec<String> = Vec::new();for object in &plan.create_tables { db.exec(&object.sql)?; report.created.push(format!("table {}", object.name)); moved.push(object.name.clone()); }for (table, column) in &plan.add_columns {let name = column.split_whitespace().next().unwrap_or(column).trim_matches('"');if holds_column(db, table, name)? { take_over(db, table, name, column)?; } else { db.exec(&format!("ALTER TABLE \"{table}\" ADD COLUMN {column}"))?; } report.created.push(format!("column {table}.{name}")); moved.push(table.clone()); }for object in &retired_dependents {let kind = if object.kind == "index" { "INDEX" } else { "TABLE" }; db.exec(&format!("DROP {kind} \"{}\"", object.name))?; }for table in &retired { db.exec(&format!("DROP TABLE \"{table}\""))?; report.dropped.push(table.clone()); }for step in &first { run(db, step, report)?; moved.push(step.name().to_string()); } moved.sort(); moved.dedup();Ok(Stepped { tables: moved, done: 1, total, finished: total == 1 })}/// Whether the file's `table` already holds a column `name` (one the object's definition served, or a person's own).fn holds_column(db: &Driver, table: &str, name: &str) -> Result<bool> {Ok(db .get("SELECT 1 AS held FROM pragma_table_info(?) WHERE name = ?", &[rusqlite::types::Value::Text(table.to_string()), rusqlite::types::Value::Text(name.to_string())])? .is_some())}/// A column this build adds that the file already holds, served by the object's definition before the build knew/// it (`package_shape::add_served`, `CONSTRAINT served NULL`): ADD COLUMN would be refused as a duplicate and the copy/// would stay unmoved, and unopenable, for good (24 Nov 2026: a copy at 151 served `to_line` and the rest of 152's/// mail columns; the 152 move stopped on "duplicate column name: to_line"). The served column is set aside, the/// build's own added in its place, its values carried, and the one set aside dropped: the table ends as the build/// declares it, and no value is lost.fn take_over(db: &Driver, table: &str, name: &str, column: &str) -> Result<()> {let aside = format!("_shape_move_aside_{name}"); db.exec(&format!("ALTER TABLE \"{table}\" RENAME COLUMN \"{name}\" TO \"{aside}\""))?; db.exec(&format!("ALTER TABLE \"{table}\" ADD COLUMN {column}"))?; db.exec(&format!("UPDATE \"{table}\" SET \"{name}\" = \"{aside}\" WHERE \"{aside}\" IS NOT NULL"))?; db.exec(&format!("ALTER TABLE \"{table}\" DROP COLUMN \"{aside}\""))?;Ok(())}/// Run one written step inside the caller's transaction.fn run(db: &Driver, step: &Step, report: &mutShapeMoveReport) -> Result<()> {match step {Step::Rebuild { table, sql, own, into, select, rest } => {let before = count(db, table)?;let parked = format!("_shape_move_old_{table}"); db.exec(&format!("ALTER TABLE \"{table}\" RENAME TO \"{parked}\""))?; db.exec(sql)?;for column in own { db.exec(&format!("ALTER TABLE \"{table}\" ADD COLUMN {column}"))?; } db.exec(&format!("INSERT INTO \"{table}\" ({}) SELECT {} FROM \"{parked}\" AS old", into.join(", "), select.join(", ") ))?; db.exec(&format!("DROP TABLE \"{parked}\""))?;for object in rest { db.exec(object)?; }let after = count(db, table)?;// Each rebuild is its own step: its rows are judged before it commits.if before != after {returnErr(StoreError::refused(format!("shape move: {table} held {before} rows and holds {after}"))); } report.rows.push((table.clone(), before, after)); report.rebuilt.push(table.clone()); }Step::Reindex { name, sql } => { db.exec(&format!("DROP TABLE \"{name}\""))?; db.exec(sql)?; db.exec(&format!("INSERT INTO \"{name}\" (\"{name}\") VALUES ('rebuild')"))?; report.replaced.push(format!("search index {name}")); }Step::Finish { replace, rest, receipt_owners, fills, kept, dangling_before } => {// Said by the plan (a move under way from an earlier build says nothing: false).let made_only = made_only_of(db)?;for (kind, name, sql) in replace { db.exec(&format!("DROP {} \"{name}\"", kind.to_ascii_uppercase()))?; db.exec(sql)?; report.replaced.push(format!("{kind} {name}")); }for (kind, name, sql) in rest { db.exec(sql)?; report.created.push(format!("{kind} {name}")); }if *receipt_owners {crate::receipts::rebuild_owners(db)?; }for name in fills {crate::fts_fill::begin(db, name)?; report.created.push(format!("search index {name} (filling)")); } db.exec(&format!("DROP TABLE \"{MOVE_TABLE}\""))?; db.exec(&format!("PRAGMA user_version = {SCHEMA_VERSION}"))?; db.exec(&format!("UPDATE _meta SET schema_version = {SCHEMA_VERSION}"))?;let fresh = by_name(fresh_objects()?);// What the file made at run time while its move went on — a// worker's own `_` table, made by the open between two steps — is// left as it is, as everything the fresh file lacks is; what the// move itself parked never is.letmut kept = kept.clone(); kept.extend(schema_objects(db)?.into_iter() .map(|object| object.name) .filter(|name| !fresh.contains_key(name) && !name.starts_with("_shape_move")));let judged = ShapeMoveReport { kept, ..Default::default() }; verify(db, &fresh, &judged, *dangling_before, made_only)?; report.whole_file_checked = !made_only; } }Ok(())}/// Inside the move's transaction: the file is a fresh file of this build plus/// what it kept, or the move rolls back.fn verify( db: &Driver, fresh: &BTreeMap<String, SchemaObject>, report: &ShapeMoveReport, dangling_before: i64, made_only: bool,) -> Result<()> {let live = by_name(schema_objects(db)?);for (name, object) in fresh {match live.get(name) {Some(had) ifcrate::schema::package_shape::without_added(&had.sql).0 == object.sql && had.kind == object.kind => {}Some(_) => returnErr(StoreError::refused(format!("shape move: {name} does not match this build's statement"))),Noneif object.kind == "index" && crate::index_later::LATER.contains(&name.as_str()) => {}None => returnErr(StoreError::refused(format!("shape move: {name} is missing after the move"))), } }let extra: Vec<&String> = live.keys().filter(|n| !fresh.contains_key(*n) && !report.kept.contains(n)).collect();if !extra.is_empty() {returnErr(StoreError::refused(format!("shape move: left behind {extra:?}"))); }ifletSome((table, before, after)) = report.rows.iter().find(|(_, b, a)| b != a) {returnErr(StoreError::refused(format!("shape move: {table} held {before} rows and holds {after}"))); }// A move that only made objects (tables, columns, indexes, triggers) copied no row and rewrote no page of one:// the whole-file checks below read every page, 7 s at his size (110,000 mails, 1.7 GB) at the open, for a// move that cannot have touched what they check (SCHEMA 155). Every statement above still stands.if made_only {returnOk(()); }let check = db .get("PRAGMA integrity_check", &[])? .and_then(|row| row.text("integrity_check").map(str::to_string)) .unwrap_or_default();if check != "ok" {returnErr(StoreError::refused(format!("shape move: integrity check: {check}"))); }let after = dangling(db)?;if after > dangling_before {returnErr(StoreError::refused(format!("shape move: dangling references rose from {dangling_before} to {after}" ))); }// An index still filling holds its rows at or above its floor and no// others, by design; it is whole once its row is gone (`fts_fill`).let filling: BTreeSet<String> = crate::fts_fill::all_filling(db)?.into_iter().map(|p| p.fts).collect();for object in fresh.values().filter(|o| o.is_fts5_virtual() && !filling.contains(&o.name)) { db.exec(&format!("INSERT INTO \"{0}\" (\"{0}\", rank) VALUES ('integrity-check', 1)", object.name)) .map_err(|e| StoreError::refused(format!("shape move: search index {} is not whole: {e}", object.name)))?; }Ok(())}