//! A search index filled in the BACKGROUND, newest rows first — never a//! rebuild while a file opens.//!//! The mailsearch brief (12 Oct 2026): the owner keeps twelve years of mail on//! the phone, so a new or wider index over `cotton_emails` is tens of thousands//! of bodies to read. A shape move that rebuilt it in its one transaction would//! hold the phone's first screen for minutes. Instead the move creates the//! index EMPTY and writes a row here; a budgeted job ([`step`]) fills it a//! slice at a time, and the coordinator's steer (20:46Z) keeps the index it//! replaces answering until the fill is done — the engine reads the new one//! only once its row is gone ([`filling`]).//!//! THE FLOOR. A filling index holds exactly the source rows whose rowid is at//! or above `floor`. Its triggers act only on those rows (each is declared//! `WHEN … >= coalesce((SELECT floor FROM _fts_fill WHERE fts = '<index>'), 0)`),//! so a write below the floor never touches an entry that is not there — for//! an external-content index, a `'delete'` of an entry never inserted is//! corruption, not a no-op. [`step`] lowers the floor by one slice, inserting//! that slice. New mail lands above the floor and is indexed by its trigger at//! once; the walk goes DOWN from the newest row, so the mail a person searches//! for first is the mail found first. When nothing is left below the floor the//! row is deleted, and with no row the floor reads 0: the index is whole.//!//! The row is DEVICE-LOCAL and never synced: how far this file's index is//! filled is a fact about this file. A phone that joins from a whole copy of//! a Mac mid-fill takes the Mac's index AND this row with it, so the two agree.use rusqlite::types::ValueasSqlValue;usecrate::driver::Driver;usecrate::error::{Result, StoreError};usecrate::schema::decl::FtsSource;usecrate::schema::fts::fts_source_named;/// The table's own name.pubconst TABLE: &str = "_fts_fill";/// The file's own clock for the row's stamps: this crate keeps no clock of/// its own, and the row is a fact about this file.const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";/// Where a filling index stands.#[derive(Debug, Clone, PartialEq, Eq)]pubstructProgress {pub fts: String,/// The rows the fill has put in so far.pub filled: i64,/// The rows it had to put in when it began.pub total: i64,/// Whether this step finished it.pub done: bool,}fn source(fts: &str) -> Result<&'staticFtsSource> { fts_source_named(fts).ok_or_else(|| StoreError::refused(format!("{fts} is not a declared search index")))}/// Start filling `fts` from the rows its source holds NOW: the floor is one/// above the newest row, so every existing row is the fill's and every row/// written from here on is the trigger's. A source with no rows needs no fill/// and writes nothing. Called by the shape move in the transaction that/// creates the index, before anything else can write.pubfn begin(db: &Driver, fts: &str) -> Result<()> {let source = source(fts)?;let row = db .get(&format!("SELECT max(rowid) AS top, count(*) AS n FROM \"{}\"", source.source), &[])? .ok_or_else(|| StoreError::refused(format!("{} answered nothing", source.source)))?;let (Some(top), n) = (row.int("top"), row.int("n").unwrap_or(0)) else {returnOk(()); }; db.run( &format!("INSERT INTO {TABLE} (fts, floor, filled, total, started_at, updated_at) VALUES (?, ?, 0, ?, {NOW}, {NOW}) \ ON CONFLICT (fts) DO UPDATE SET floor = excluded.floor, filled = 0, total = excluded.total, \ started_at = excluded.started_at, updated_at = excluded.updated_at" ), &[SqlValue::Text(fts.to_string()),SqlValue::Integer(top + 1),SqlValue::Integer(n), ], )?;Ok(())}/// Where `fts` stands, or `None` when it is whole (no fill is running).pubfn filling(db: &Driver, fts: &str) -> Result<Option<Progress>> {Ok(db .get(&format!("SELECT filled, total FROM {TABLE} WHERE fts = ?"), &[SqlValue::Text(fts.to_string())])? .map(|row| Progress { fts: fts.to_string(), filled: row.int("filled").unwrap_or(0), total: row.int("total").unwrap_or(0), done: false, }))}/// Every index still filling, for a progress line.pubfn all_filling(db: &Driver) -> Result<Vec<Progress>> {Ok(db .all(&format!("SELECT fts, filled, total FROM {TABLE} ORDER BY fts"), &[])? .iter() .map(|row| Progress { fts: row.text("fts").unwrap_or_default().to_string(), filled: row.int("filled").unwrap_or(0), total: row.int("total").unwrap_or(0), done: false, }) .collect())}/// Fill at most `rows` more rows of `fts`, the newest below the floor first,/// in ONE transaction — the caller's budget is the slice size, and the file is/// released between slices. `None` when the index is not filling.pubfn step(db: &Driver, fts: &str, rows: i64) -> Result<Option<Progress>> {let source = source(fts)?; db.transaction(|db| {letSome(row) = db.get( &format!("SELECT floor, filled, total FROM {TABLE} WHERE fts = ?"), &[SqlValue::Text(fts.to_string())], )?else {returnOk(None); };let floor = row.int("floor").unwrap_or(0);let filled = row.int("filled").unwrap_or(0);let total = row.int("total").unwrap_or(0);let columns = source.columns.join(", ");let slice = format!("SELECT rowid FROM \"{src}\" WHERE rowid < ?1 ORDER BY rowid DESC LIMIT ?2", src = source.source );let low = db .get(&format!("SELECT min(rowid) AS low, count(*) AS n FROM ({slice})"), &[SqlValue::Integer(floor), SqlValue::Integer(rows.max(1))])? .and_then(|row| row.int("low").map(|low| (low, row.int("n").unwrap_or(0))));letSome((low, n)) = low else { db.run(&format!("DELETE FROM {TABLE} WHERE fts = ?"), &[SqlValue::Text(fts.to_string())])?;returnOk(Some(Progress { fts: fts.to_string(), filled, total: total.max(filled), done: true })); }; db.run( &format!("INSERT INTO \"{fts}\" (rowid, {columns}) SELECT rowid, {columns} FROM \"{src}\" \ WHERE rowid >= ?1 AND rowid < ?2", src = source.source ), &[SqlValue::Integer(low), SqlValue::Integer(floor)], )?;let filled = filled + n;// Rows written below the floor while it walked can push the count past// the total it began with; the line never says more than all of them.let total = total.max(filled); db.run( &format!("UPDATE {TABLE} SET floor = ?, filled = ?, total = ?, updated_at = {NOW} WHERE fts = ?"), &[SqlValue::Integer(low),SqlValue::Integer(filled),SqlValue::Integer(total),SqlValue::Text(fts.to_string()), ], )?;Ok(Some(Progress { fts: fts.to_string(), filled, total, done: false })) })}