//! Indexes a copy builds after its move, off the open path (SCHEMA 155, POST AT SIZE, 26 Nov 2026). //! //! An index over a table that already holds rows reads every one of them to be made: on his phone, 110,000 mails, //! mostly bodies, about 1.7 GB. A move runs at the open, before the first screen, so the indexes named here are //! never made by a move (`shape_move` leaves them out and does not miss them). A fresh file has them from its first //! statement (`SCHEMA_DDL`, over no rows). A moved copy makes each in the background, one per step, on the thread //! that fills the search indexes (`cotton-ffi` `mail_index::build_later`). Until then, each read they serve answers //! as before, from the table, only slower. The file itself is the state: an index is made once //! `sqlite_master` names it. use crate::schema::ddl::SCHEMA_DDL; use crate::{Driver, Result, StoreError}; /// The indexes of [`SCHEMA_DDL`] a move leaves to the background. pub const LATER: &[&str] = &["idx_cotton_emails_inbox", "idx_cotton_emails_archived", "idx_cotton_emails_files", "idx_cotton_emails_sender_id", "_mail_landed_key", "_mail_landed_domain", "_mail_landed_at"]; /// The indexes of `_mail_landed` (schema 157, PHASE 2 PHONE 2 item 5): made only once the phone's landing fill is /// done (`_landed_fill.done`), never while it runs. Filled into the bare table in id order, then indexed once, the /// fill of 300,000 mails wrote 182 MB; into the indexed table, 4.1 GB (every slice touched ~1,600 random index pages). pub const AFTER_THE_FILL: &[&str] = &["_mail_landed_key", "_mail_landed_domain", "_mail_landed_at"]; /// Indexes an older build made that one of [`LATER`] replaces (schema 157, MAIL PREDICATE phase 2: the sender index /// with `id`, which a cut's cover reads). Each is dropped once its replacement is held, so a read never loses its /// index while the new one is being made. pub const RETIRED: &[(&str, &str)] = &[("idx_cotton_emails_sender", "idx_cotton_emails_sender_id")]; /// This build's statement for the index `name`. fn statement(name: &str) -> Result<&'static str> { SCHEMA_DDL .iter() .copied() .find(|sql| sql.split_whitespace().take(7).any(|word| word == name)) .ok_or_else(|| StoreError::refused(format!("index_later: no statement makes {name}"))) } /// The indexes of [`LATER`] this file does not hold yet, in order. pub fn missing(db: &Driver) -> Result> { let mut out = Vec::new(); for name in LATER { let held = db.get("SELECT 1 AS held FROM sqlite_master WHERE type = 'index' AND name = ?", &[rusqlite::types::Value::Text(name.to_string())])?; if held.is_none() { out.push(*name); } } Ok(out) } /// Bytes an index of [`LATER`] may need on disk to be made over this file's mail: each mail an entry of at most /// [`ENTRY_BYTES`], three times over (SQLite's sorter spills its runs to temporary files first, then the entries /// are written to the log and to the file, INDEX LATER 2 REVIEW), and [`ROOM_MARGIN`] beside them. A phone short of /// that is not asked (SQLITE_FULL half way through is a 7 s stall for nothing, SCHEMA 155 REVIEW). pub fn room_needed(db: &Driver) -> Result { Ok(mail_count(db)? * ENTRY_BYTES * 3 + ROOM_MARGIN) } /// The mail an index of [`LATER`] reads to be made. pub fn mail_count(db: &Driver) -> Result { Ok(db.get("SELECT count(*) AS n FROM cotton_emails", &[])?.and_then(|row| row.int("n")).unwrap_or(0).max(0) as u64) } /// How long one index of [`LATER`] may take over `mail` mails, at the slowest seen: 204 s over 110,000 on this /// box's cold, loaded disk (26 Nov 2026), rounded up to 2 ms a mail. Warm it was 7.1 s. pub fn time_needed(mail: u64) -> std::time::Duration { std::time::Duration::from_millis(mail.saturating_mul(2)) } /// The most one entry of the widest index of [`LATER`] holds (`idx_cotton_emails_inbox`: two ids, an address, three /// times and three flags, with SQLite's own record and page overhead). pub const ENTRY_BYTES: u64 = 320; /// What is left free beside an index's own bytes: the phone's other writes go on. pub const ROOM_MARGIN: u64 = 64 * 1024 * 1024; /// Make the next index this file lacks, in one statement: the name it made, or `None` when every one is held. An /// index of [`RETIRED`] whose replacement is held is dropped first, one a step (its name answered). pub fn step(db: &Driver) -> Result> { for (old, new) in RETIRED { let held = |name: &str| db.get("SELECT 1 AS held FROM sqlite_master WHERE type = 'index' AND name = ?", &[rusqlite::types::Value::Text(name.to_string())]).map(|r| r.is_some()); if held(old)? && held(new)? { db.exec(&format!("DROP INDEX {old}"))?; return Ok(Some(old)); } } let filling = db.get("SELECT 1 AS filling FROM sqlite_master WHERE type = 'table' AND name = '_landed_fill'", &[])?.is_some() && db.get("SELECT 1 AS filling FROM _landed_fill WHERE done = 0", &[])?.is_some(); let Some(name) = missing(db)?.into_iter().find(|name| !(filling && AFTER_THE_FILL.contains(name))) else { return Ok(None) }; db.exec(statement(name)?)?; Ok(Some(name)) } #[cfg(test)] mod tests { use super::*; /// RULE: every index named LATER is one of this build's statements, made with IF NOT EXISTS, so a step that /// races a fresh file's own statement makes nothing twice. #[test] fn every_later_index_is_a_statement_of_this_build() { for name in LATER { let sql = statement(name).unwrap(); assert!(sql.starts_with("CREATE INDEX IF NOT EXISTS"), "{sql}"); } } /// RULE: a file without them makes them one per step, then answers None; a fresh file already holds them. #[test] fn a_file_without_them_makes_each_once() { let db = Driver::open_in_memory().unwrap(); crate::create::apply_schema(&db).unwrap(); assert!(missing(&db).unwrap().is_empty(), "a fresh file holds them"); for name in LATER { db.exec(&format!("DROP INDEX {name}")).unwrap(); } let mut made = Vec::new(); while let Some(name) = step(&db).unwrap() { made.push(name); } assert_eq!(made, LATER); assert!(missing(&db).unwrap().is_empty()); } /// RULE (schema 157): a moved copy keeps the old sender and Inbox indexes until it holds their replacements, then /// drops each, so a read never goes without an index meanwhile. #[test] fn an_old_index_goes_only_once_its_replacement_is_held() { let db = Driver::open_in_memory().unwrap(); crate::create::apply_schema(&db).unwrap(); let held = |name: &str| db.get("SELECT 1 AS held FROM sqlite_master WHERE name = ?", &[rusqlite::types::Value::Text(name.into())]).unwrap().is_some(); for (old, new) in RETIRED { db.exec(&format!("DROP INDEX {new}")).unwrap(); db.exec(&format!("CREATE INDEX {old} ON cotton_emails (workspace_id, from_email)")).unwrap(); } let mut steps = Vec::new(); while let Some(name) = step(&db).unwrap() { for (old, new) in RETIRED { assert!(held(old) || held(new), "{old} went before {new} was made"); } steps.push(name); } assert_eq!(steps, ["idx_cotton_emails_sender_id", "idx_cotton_emails_sender"]); assert!(RETIRED.iter().all(|(old, new)| !held(old) && held(new))); } /// RULE (PHASE 2 PHONE 2, item 5): `_mail_landed`'s indexes wait while the landing fill runs, and are made one a /// step once it is done; the mail indexes do not wait for it. #[test] fn the_landing_indexes_wait_for_the_fill() { let db = Driver::open_in_memory().unwrap(); crate::create::apply_schema(&db).unwrap(); for name in LATER { db.exec(&format!("DROP INDEX {name}")).unwrap(); } db.exec("CREATE TABLE _landed_fill (one INTEGER PRIMARY KEY CHECK (one = 1), after TEXT, done INTEGER NOT NULL DEFAULT 0, asked_at TEXT, rounds INTEGER NOT NULL DEFAULT 0); INSERT INTO _landed_fill (one, done) VALUES (1, 0)").unwrap(); let mut made = Vec::new(); while let Some(name) = step(&db).unwrap() { made.push(name); } assert!(made.iter().all(|n| !AFTER_THE_FILL.contains(n)), "{made:?}"); assert_eq!(missing(&db).unwrap(), AFTER_THE_FILL); db.exec("UPDATE _landed_fill SET done = 1").unwrap(); let mut after = Vec::new(); while let Some(name) = step(&db).unwrap() { after.push(name); } assert_eq!(after, AFTER_THE_FILL); } }