//! Mail's wide search index, filled on THIS device in the background//! (mailsearch brief, 12 Oct 2026).//!//! Version 122 creates `fts_mail` empty beside `fts_emails` in a file that//! already held mail (`cotton_store::fts_fill`). A phone holding twelve years//! fills it here: after an idle sync pass, on the after-pass thread — never the//! thread that draws the screen — one slice of rows per hold of the replica,//! the replica released and a breath taken between slices so a read or a//! write waiting on it goes first, and the pass stops at its budget; the next//! idle pass goes on. Search reads `fts_emails` until the fill is done.//!//! A serving Mac fills its file in its own worker (`cotton-server`//! `mail_index`); this runs only where nothing is served.use std::time::{Duration, Instant};use cotton_store::fts_fill::{self, Progress};usecrate::shell::client::ClientController;/// The index this fills.pubconst INDEX: &str = "fts_mail";/// The tables a filled index moves, as the done signal names them.pubconst MOVED_TABLES: &[&str] = &["cotton_emails", "cotton_email_threads"];/// Rows one hold of the replica indexes — a few tens of milliseconds of a/// phone's time, the longest a screen's read waits behind it.pubconst SLICE: i64 = 200;/// How long one idle pass fills before it gives the device back.pubconst PASS_BUDGET: Duration = Duration::from_secs(15);/// The pause between slices, so the replica is free between them.const BREATH: Duration = Duration::from_millis(25);/// Chat's search index (v149, chat-search): message text by any three/// characters in a row, filled the same way after mail's.pubconst CHAT_INDEX: &str = "fts_chat";/// The table a filled chat index moves.pubconst CHAT_MOVED_TABLES: &[&str] = &["cotton_msg_messages"];/// Fill for at most `budget`. `None` when nothing was filling; a refusal of/// a slice ends the pass and the next pass asks again.pubfn fill(client: &ClientController, budget: Duration) -> Result<Option<Progress>, String> { fill_index(client, INDEX, MOVED_TABLES, budget)}/// Chat's index, for at most `budget`, as [`fill`] fills mail's.pubfn fill_chat(client: &ClientController, budget: Duration) -> Result<Option<Progress>, String> { fill_index(client, CHAT_INDEX, CHAT_MOVED_TABLES, budget)}fn fill_index(client: &ClientController, index: &str, moved: &[&str], budget: Duration) -> Result<Option<Progress>, String> {let started = Instant::now();let filled = fill_index_for(client, index, moved, budget, started);// PHONE MEASURES: the fill's time, part of what the copy's first sync cost, until no search index is filling.iflet (Some(database), true) = (client.attached_database(), filled.is_ok()) {let whole = client.with_file(|replica| fts_fill::all_filling(&replica.driver).map_err(|error| error.to_string())).is_ok_and(|filling| filling.is_empty()); cotton_client::first_sync::add_indexing(&client.layout().replica(&database), started.elapsed().as_millis() as u64, whole); } filled}fn fill_index_for(client: &ClientController, index: &str, moved: &[&str], budget: Duration, started: Instant) -> Result<Option<Progress>, String> {letmut last = None;loop {let progress = client.with_writer(|replica| { fts_fill::step(replica.driver, index, SLICE).map_err(|error| error.to_string()) })?;match progress {None => returnOk(last),// Done: the search that read the narrower index meanwhile is// read again by itself on the done signal (passivemove rule 3).Some(progress) if progress.done => { client.say_moves_done(moved.iter().map(|table| table.to_string()).collect());returnOk(Some(progress)); }Some(progress) => last = Some(progress), }if started.elapsed() >= budget {returnOk(last); } std::thread::sleep(BREATH); }}/// Pages one hold of the replica merges while an erase's words leave a search index: a few tens of milliseconds/// of a phone's time, like a fill's slice.pubconst PURGE_PAGES: u32 = 64;/// Merge the search indexes an erase left words in (`cotton_store::fts_purge`, DELETE FAST) for at most `budget`,/// a few pages per hold of the replica and a breath between, as [`fill`] does. Answers how many were finished; the/// next pass goes on with the rest.pubfn purge(client: &ClientController, budget: Duration) -> Result<usize, String> {// Each purge merges a whole index, hundreds of MB of mail on his phone: a run of deletes shares one. A purge// waits until the oldest erase it covers is `PURGE_AFTER` old, except at this launch's first pass (DELETE FAST:// "within the hour or at next launch").let first = !PURGED_THIS_LAUNCH.swap(true, std::sync::atomic::Ordering::SeqCst);let oldest = client.with_writer(|replica| cotton_store::fts_purge::oldest(replica.driver).map_err(|error| error.to_string()))?;letSome(oldest) = oldest else { returnOk(0) };let age = chrono::Utc::now().timestamp_millis() - crate::phone::chat_app::ms(&oldest);if !first && age < PURGE_AFTER.as_millis() as i64 {returnOk(0); } purge_now(client, budget)}/// How long one pass purges once a purge is due: until it is whole, the replica freed between steps. A fill's 15 s/// a pass left his mail index merging for hours on the walk's emulator (SENDERS TRUE), past "within the hour".pubconst PURGE_BUDGET: Duration = Duration::from_secs(30 * 60);/// How long the oldest erase waits for its purge while Comms stays open.pubconst PURGE_AFTER: Duration = Duration::from_secs(15 * 60);static PURGED_THIS_LAUNCH: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);/// The indexes a moved copy makes after its move (`cotton_store::index_later`, SCHEMA 155): each reads every mail/// once, so never at the open, and holds the writer while it does (7.1 s for the widest at his size, 110,000 mails,/// and 204 s once on this box's cold, busy disk, a draft saved meanwhile waiting 65 s). So one is made only while/// nobody is waiting on the copy:/// - in the phone's processing job, minutes on the charger ([`build_in_task`], from `sync.compact { budgetMs }`:/// iOS's `BGProcessingTask`, Android's `CompactWorker`), where `sync.compact` says it is owed while one is missing;/// - on a trip to the back (`trim::is_away`, [`build_later`]), at most [`TRIES_AWAY`] times a launch, since a trip/// shorter than the build takes it back each time;/// - on a Mac, once no call but sync's has come for [`MAC_IDLE`] (a Mac is rarely "in the back");////// and taken back whole the moment anyone is (the app comes forward, the job's time is up, a call comes on the/// Mac): a progress handler on the writer watches for it, set before the away is asked again inside the writer, so/// no moment falls between them (INDEX LATER 2 REVIEW). Besides, an index is made only/// - once the copy has had no write for [`BUILD_QUIET`] (a trip to the back; the job is on the charger),/// - when the disk has the room it needs (`index_later::room_needed`), and/// - never again this launch once one was refused (SQLITE_FULL half way is a 7 s stall each pass, SCHEMA 155 REVIEW).////// A CREATE INDEX is one statement and cannot be cut into steps; the waits are what keep it out of a person's way./// Answers the names made this pass.pubfn build_later(client: &ClientController) -> Result<Vec<&'static str>, String> {let away = || crate::phone::trim::is_away() || mac_idle();let path = match client.attached_database() {Some(database) => client.layout().replica(&database),None => returnOk(Vec::new()), };// A trip to the back too short for the build takes it back each time: past TRIES_AWAY, the job's.if !mac_idle() && state_of(&path, |held| held.taken_back) >= TRIES_AWAY {returnOk(Vec::new()); } build_later_after(client, BUILD_QUIET, &away)}/// The processing job's turn (`sync.compact { budgetMs }`), with `left` of its time: every index that fits it, the/// job itself being the app away, until `stopped` (the job's `{stop}`, which sticks for the job: a stop that came/// during the compaction, before any index began, still stops them, INDEX LATER 3 REVIEW). The build's own progress/// handler watches the deadline too, so no index runs past the job's time. Answers the names made and whether any is/// still owed.pubfn build_in_task(client: &ClientController, left: Duration, stopped: &(dynFn() -> bool + Sync)) -> Result<(Vec<&'static str>, bool), String> {let until = Instant::now() + left;if stopped() {returnOk((Vec::new(), later_owed(client))); }let fits = || {// On the read connection: a second job, or a job while a trip to the back builds, never waits on the writer. client.with_file(|replica| cotton_store::index_later::mail_count(&replica.driver).map_err(|error| error.to_string())).map(|mail| Instant::now() + cotton_store::index_later::time_needed(mail) <= until) };if !fits()? { tracing::info!("index later: the job's time is shorter than an index may take; the next job");returnOk((Vec::new(), later_owed(client))); }let made = build_with(client, Duration::ZERO, &|| Instant::now() < until && !stopped(), Some(until))?;Ok((made, later_owed(client)))}/// Whether this copy still lacks an index a move left, and may make it this launch: what `sync.compact {}` says/// is owed, so the phone asks for its processing job./// It takes the LATER lock only to read one field (no build holds it, INDEX LATER 3 REVIEW) and reads the copy on/// the read connection, never the writer's: iOS asks it from the processing task's Swift `Task` (the core's call/// queue), Android from `CompactWorker`/`PassWorker` on WorkManager's coroutine thread, and neither waits on a build.pubfn later_owed(client: &ClientController) -> bool {letSome(database) = client.attached_database() else { returnfalse };if state_of(&client.layout().replica(&database), |held| held.refused.is_some()) {returnfalse; } client.with_file(|replica| cotton_store::index_later::missing(replica.driver).map_err(|error| error.to_string())).is_ok_and(|missing| !missing.is_empty()) || old_park_index_left(client).is_ok_and(|left| left.is_some())}/// The first old index over the wide park table this copy may drop now (FIRST SYNC 9), read on the read connection.fn old_park_index_left(client: &ClientController) -> Result<Option<&'static str>, String> { client.with_file(|replica| cotton_client::seal::old_park_index_left(replica.driver.connection()).map_err(|error| error.to_string()))}/// The app came to the front, the job's time is up, or a call came on the Mac: an index being made stops at once/// (the file as it was) and is made again the next time. Answers whether one was being made.pub(crate) fn came_forward() -> bool {let building = BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);for watch in building.values() { watch.stop.store(true, std::sync::atomic::Ordering::SeqCst); }if !building.is_empty() { tracing::info!("index later: someone is waiting on the copy; the index is taken back and made the next time"); } !building.is_empty()}/// [`came_forward`] for one copy alone (its processing job's `{stop}`; the tests, whose copies build side by side).pub(crate) fn came_forward_at(path: &std::path::Path) -> bool { BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(path).inspect(|watch| watch.stop.store(true, std::sync::atomic::Ordering::SeqCst)).is_some()}/// How many times the build of the copy at `path` has looked at its flag (the tests: it is under way).#[cfg(test)]pub(crate) fn watched_at(path: &std::path::Path) -> u64 { BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(path).map_or(0, |watch| watch.watched.load(std::sync::atomic::Ordering::SeqCst))}/// An index being made: the flag its progress handler watches, and how often it has looked.#[derive(Default)]structWatch { stop: std::sync::atomic::AtomicBool, watched: std::sync::atomic::AtomicU64,}/// The indexes being made now, by copy.static BUILDING: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, std::sync::Arc<Watch>>>> = std::sync::LazyLock::new(Default::default);/// How often (in SQLite's virtual-machine steps) the build looks at its flag: about a millisecond of work.const WATCH_STEPS: i32 = 1_000;/// How long the copy must have had no write before an index is made on a trip to the back.pubconst BUILD_QUIET: Duration = Duration::from_secs(30);/// How many trips to the back a launch tries an index on before it waits for the processing job.pubconst TRIES_AWAY: u32 = 3;/// How long a Mac has had no call but sync's before an index is made there.pubconst MAC_IDLE: Duration = Duration::from_secs(5 * 60);/// When a call last came that a person makes (any method but `sync.*`), for [`mac_idle`].static LAST_CALL: std::sync::Mutex<Option<Instant>> = std::sync::Mutex::new(None);/// A call came (`methods::dispatch`): on a Mac a person is at it, so an index being made stops.pub(crate) fn called(method: &str) {if method.starts_with("sync.") {return; } *LAST_CALL.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Instant::now());if cfg!(target_os = "macos") && !cfg!(test) { came_forward(); }}/// On a Mac: no call but sync's for [`MAC_IDLE`], counted from the launch before the first (a Mac just opened is/// in use, INDEX LATER 3 REVIEW). Never on a phone, whose away is `trim::is_away`.fn mac_idle() -> bool { cfg!(target_os = "macos") && !cfg!(test) && idle_since(*LAUNCHED, *LAST_CALL.lock().unwrap_or_else(std::sync::PoisonError::into_inner), Instant::now())}/// Whether [`MAC_IDLE`] has passed since the later of the launch and the last call.fn idle_since(launched: Instant, last_call: Option<Instant>, now: Instant) -> bool { now.saturating_duration_since(last_call.map_or(launched, |at| at.max(launched))) >= MAC_IDLE}static LAUNCHED: std::sync::LazyLock<Instant> = std::sync::LazyLock::new(Instant::now);fn state_of<T>(path: &std::path::Path, read: implFnOnce(&Later) -> T) -> T {letmut state = LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); read(state.entry(path.to_path_buf()).or_default())}/// [`build_later`] with the quiet it waits for and what says nobody waits on the copy.pubfn build_later_after(client: &ClientController, quiet: Duration, away: &dynFn() -> bool) -> Result<Vec<&'static str>, String> { build_with(client, quiet, away, None)}/// The LATER state is read and written in short holds only, never across a build or a wait for the writer, so/// `sync.compact {}` (`later_owed`) never waits on one (INDEX LATER 3 REVIEW).fn build_with(client: &ClientController, quiet: Duration, away: &dynFn() -> bool, until: Option<Instant>) -> Result<Vec<&'static str>, String> {if !away() {returnOk(Vec::new()); }letSome(database) = client.attached_database() else { returnOk(Vec::new()) };let path = client.layout().replica(&database);let held = |update: &mutdynFnMut(&mutLater)| {letmut state = LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); update(state.entry(path.clone()).or_default()); };// One build of a copy at a time (the pass after a sync and a trip to the back may both ask): the other answers// at once, and the claim goes however this one ends.let claimed = {letmut state = LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner);let later = state.entry(path.clone()).or_default();if later.refused.is_some() || later.running {false } else { later.running = true;true } };if !claimed {returnOk(Vec::new()); }structClaim<'a>(&'a std::path::Path);implDropforClaim<'_> {fn drop(&mutself) {ifletSome(later) = LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_mut(self.0) { later.running = false; } } }let _claim = Claim(&path);let missing = client.with_file(|replica| cotton_store::index_later::missing(&replica.driver).map_err(|error| error.to_string()))?;let old_park_index = old_park_index_left(client)?;if missing.is_empty() && old_park_index.is_none() {returnOk(Vec::new()); }// Quiet since when: the file's write count as this pass found it, kept from the pass that first saw it.let moved = client.moved();let quiet_since = state_of(&path, |later| later.quiet_since);match quiet_since {Some((at, since)) if at == moved && since.elapsed() >= quiet => {}Some((at, _)) if at == moved => returnOk(Vec::new()), _ => { held(&mut |later| later.quiet_since = Some((moved, Instant::now())));if !quiet.is_zero() {returnOk(Vec::new()); } } }// FIRST SYNC 9: an old index over the wide park table, read nowhere once the parks' keys are full, goes first,// one per step: a DROP INDEX frees every page in one statement (up to 4.4 s over 280,000 parks), so never on a pass.ifletSome(name) = old_park_index {let started = Instant::now();let dropped = client.with_writer(|replica| {let connection = replica.driver.connection();if !connection.is_autocommit() {returnErr(IN_A_TRANSACTION.to_string()); }if !away() {returnErr(TAKEN_BACK.to_string()); } cotton_client::seal::drop_old_park_index(connection, name).map_err(|error| error.to_string()) });match dropped {Ok(()) => tracing::info!("index later: the old park index {name} dropped in {} ms", started.elapsed().as_millis()),Err(why) => { tracing::info!("index later: the old park index {name} waits for the next time ({why})");returnOk(Vec::new()); } }if !missing.is_empty() && !quiet.is_zero() {// The drop was a write: the indexes a move left wait for the quiet again. held(&mut |later| later.quiet_since = None);returnOk(Vec::new()); } }letmut made = Vec::new();for name in missing {let need = client.with_file(|replica| cotton_store::index_later::room_needed(&replica.driver).map_err(|error| error.to_string()))?;// The platform's reading when the app gave one, else the volume's own (statvfs: on an iPhone below the// room iOS would make by clearing caches, so it errs low). Unread, the refusal below is the guard.let free = client.disk().free_bytes(&path).or_else(|| cotton_client::media::hydrate::free_bytes_at(path.parent().unwrap_or(&path)));if free.is_some_and(|free| free < need) {let why = format!("{} MB free, {name} may need {} MB", free.unwrap_or(0) / (1024 * 1024), need / (1024 * 1024)); tracing::warn!("index later: not made this launch — {why}"); held(&mut |later| later.refused = Some(why.clone()));returnOk(made); }let started = Instant::now();let stop = std::sync::Arc::new(Watch::default()); BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(path.clone(), std::sync::Arc::clone(&stop));let step = client.with_writer_driver(|driver| {// Never inside a transaction someone left open on the writer: the index would commit with it, or wait// with it (INDEX LATER 3 REVIEW). The writer is lent between statements; this says so, or makes nothing.if !driver.connection().is_autocommit() {returnErr(IN_A_TRANSACTION.to_string()); }let watch = std::sync::Arc::clone(&stop); driver .connection_mut() .progress_handler( WATCH_STEPS,Some(move || { watch.watched.fetch_add(1, std::sync::atomic::Ordering::SeqCst); watch.stop.load(std::sync::atomic::Ordering::SeqCst) || until.is_some_and(|until| Instant::now() >= until) }), ) .map_err(|error| error.to_string())?;// Asked again with the writer held and the handler set: the wait for the writer (a pass holding it) may// have outlasted the away, and anyone who comes after this sets the flag the handler reads.let made = if !away() || stop.stop.load(std::sync::atomic::Ordering::SeqCst) {Err(TAKEN_BACK.to_string()) } else { cotton_store::index_later::step(driver).map_err(|error| error.to_string()) };let _ = driver.connection_mut().progress_handler(0, None::<fn() -> bool>); made }); BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&path);match step {Err(why) if why == IN_A_TRANSACTION => { tracing::warn!("index later: the writer was inside a transaction; {name} waits for the next time");returnOk(made); }// Someone came, or the job's time is up: not a refusal; the next time.Err(why) if why == TAKEN_BACK || why.contains("interrupt") => {// Only a trip to the back taken back counts toward TRIES_AWAY: the job's stop or deadline says// nothing of how long a trip lasts (INDEX LATER 3 REVIEW).letmut times = 0; held(&mut |later| {if until.is_none() { later.taken_back += 1; } times = later.taken_back; }); tracing::info!("index later: {name} taken back after {} ms ({times} this launch)", started.elapsed().as_millis());returnOk(made); }Ok(Some(name)) => { tracing::info!("index later: {name} made in {} ms", started.elapsed().as_millis()); made.push(name); }Ok(None) => break,Err(refusal) => {// Full, locked or anything else: asked again at the next launch, never every pass. tracing::warn!("index later: {name} was refused ({refusal}); asked again at the next launch"); held(&mut |later| later.refused = Some(refusal.clone()));returnOk(made); } }// A write that came while it was made starts the quiet again.if !quiet.is_zero() && client.moved() != moved { held(&mut |later| later.quiet_since = None);returnOk(made); }let now = client.moved(); held(&mut |later| later.quiet_since = Some((now, Instant::now())));if !quiet.is_zero() { std::thread::sleep(BREATH); } }Ok(made)}const IN_A_TRANSACTION: &str = "the writer is inside a transaction";const TAKEN_BACK: &str = "taken back: someone came before it began";/// Why this launch makes no more of the indexes a move left, for a copy at `path` (`None` while it may).pubfn later_refused(path: &std::path::Path) -> Option<String> { LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(path).and_then(|held| held.refused.clone())}/// How many times this launch an index of the copy at `path` was taken back.pubfn later_taken_back(path: &std::path::Path) -> u32 { LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(path).map_or(0, |held| held.taken_back)}#[derive(Default)]structLater {/// The file's write count and when a pass first saw it at that count. quiet_since: Option<((u64, u64), Instant)>,/// Why this launch makes no more. refused: Option<String>,/// How many times this launch an index was taken back. taken_back: u32,/// A build of this copy is under way. running: bool,}static LATER: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, Later>>> = std::sync::LazyLock::new(Default::default);/// [`purge`] without the wait: what is due, now (the tests, and a pass that found it due).pubfn purge_now(client: &ClientController, budget: Duration) -> Result<usize, String> {let started = Instant::now();letmut finished = 0;let due = client.with_writer(|replica| cotton_store::fts_purge::due(replica.driver).map_err(|error| error.to_string()))?;for fts in due {loop {let step = client.with_writer(|replica| cotton_store::fts_purge::step(replica.driver, &fts, PURGE_PAGES).map_err(|error| error.to_string()))?;if step != Some(false) {if step == Some(true) { finished += 1; tracing::info!("search purge: {fts} merged whole, no erased words left ({} ms this pass)", started.elapsed().as_millis()); }break; }if started.elapsed() >= budget {returnOk(finished); } std::thread::sleep(BREATH); } }Ok(finished)}/// Where this device's index stands, for the Sync section's line: `None`/// when it is whole.pubfn progress(client: &ClientController) -> Option<Progress> { client .with_writer(|replica| fts_fill::filling(replica.driver, INDEX).map_err(|error| error.to_string())) .ok() .flatten()}#[cfg(test)]mod idle_tests {usesuper::*;/// RULE (INDEX LATER 3 REVIEW): a Mac just launched is in use: idle only MAC_IDLE after the launch, or after the/// last call when one came. #[test]fn a_mac_is_idle_only_five_minutes_after_its_launch_or_last_call() {let launched = Instant::now();let later = |d: Duration| launched + d; assert!(!idle_since(launched, None, later(Duration::from_secs(30))), "30 s after the launch"); assert!(idle_since(launched, None, later(MAC_IDLE))); assert!(!idle_since(launched, Some(later(Duration::from_secs(240))), later(MAC_IDLE)), "a call 4 min in"); assert!(idle_since(launched, Some(later(Duration::from_secs(240))), later(MAC_IDLE + Duration::from_secs(240)))); }}