//! The in-place trim of a copy made before schema 151 (TRIM, 21 Nov 2026)://! the object's receipts are kept as their identity while their rows say//! them (`cotton_store::receipts::implied`). Carried after each pass, a few//! bounded steps at a time, each its own transaction under the writer, the//! writer let go between steps so a pass or a write is never held long.//!//! When the walk is done and it freed a good part of the file, the file is//! compacted once (`VACUUM`, with `auto_vacuum = INCREMENTAL` from then on),//! so the space comes back to the phone; after that, free pages are handed//! back a bounded chunk at a time (`incremental_vacuum`).use std::sync::Arc;usecrate::shell::client::ClientController;/// Steps of [`cotton_store::receipts::implied::TRIM_PAGE`] receipts after one pass.pubconst STEPS_A_PASS: usize = 50;/// Free space worth a compaction: at least this much, and a fifth of the file.const COMPACT_AT_BYTES: i64 = 16 * 1024 * 1024;/// Free pages handed back after a pass once the file vacuums incrementally.const GIVE_BACK_PAGES: i64 = 2048;/// The shell line rows this copy wrote for itself that only repeat the kit's/// words: rows of `cotton_lines` whose words are the kit's, every receipt/// of them its own shell's (`device-job:shell`: the object's are/// `job:object-sync`, a rewording another actor's), none held, none waiting to be/// sent. A copy made before 21 Nov wrote all 6,116 of them; it says the kit's/// words without them (`shell_lines::resolved`).pub(crate) fn default_lines(db: &cotton_store::Driver) -> Result<Vec<(String, String)>, String> {let held = db.get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = 'cotton_lines'", &[]).map_err(|e| e.to_string())?;if held.is_none() {returnOk(Vec::new()); }let shipped: std::collections::HashMap<(String, String), &str> = cotton_core::rules::shell_lines::shipped_lines() .iter() .map(|row| ((row.set.clone(), row.line.clone()), row.words.as_str())) .collect();let rows = db .all("SELECT l.id, l.\"set\" AS set_name, l.line, l.words FROM cotton_lines l \ WHERE NOT EXISTS (SELECT 1 FROM _writes w WHERE w.tbl = 'cotton_lines' AND w.row_id = l.id \ AND (w.held <> 0 OR w.actor IS NOT 'device-job:shell' \ OR EXISTS (SELECT 1 FROM _outbox o WHERE o.op_id = w.op_id))) \ AND NOT EXISTS (SELECT 1 FROM _tombstones t WHERE t.tbl = 'cotton_lines' AND t.row_id = l.id)", &[], ) .map_err(|e| e.to_string())?;Ok(rows .iter() .filter(|row| {let key = (row.text("set_name").unwrap_or_default().to_string(), row.text("line").unwrap_or_default().to_string()); shipped.get(&key).is_some_and(|words| Some(*words) == row.text("words")) }) .filter_map(|row| row.text("id").map(|id| ("cotton_lines".to_string(), id.to_string()))) .collect())}/// How long a binned row stays in a phone's copy (TRIM 3, coordinator, 21 Nov 2026). The Bin lists/// what is older from the object (`seal.bin`), and a restore of it goes there (`seal.restoreBinned`).pub(crate) const BIN_KEPT_DAYS: i64 = 7;/// The rows of this copy binned more than [`BIN_KEPT_DAYS`] ago (a `trashed_at` before then): rows of/// a synced table, with nothing of this phone's waiting to be sent or held back, that no row of the/// copy hangs off (a binned conversation keeps its messages, so a restore never brings back a row/// without what hangs off it). At most `most`.pub(crate) fn binned_long_ago(db: &cotton_store::Driver, now: chrono::DateTime<chrono::Utc>, most: usize) -> Result<Vec<(String, String)>, String> {let before = (now - chrono::Duration::days(BIN_KEPT_DAYS)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);let tables: Vec<String> = db .all("SELECT m.name AS tbl FROM sqlite_master m WHERE m.type = 'table' AND m.name NOT LIKE '\\_%' ESCAPE '\\' \ AND EXISTS (SELECT 1 FROM pragma_table_info(m.name) WHERE name = 'trashed_at') \ AND EXISTS (SELECT 1 FROM pragma_table_info(m.name) WHERE name = 'id') \ AND EXISTS (SELECT 1 FROM _writes w WHERE w.tbl = m.name) ORDER BY m.name", &[], ) .map_err(|e| e.to_string())? .iter() .filter_map(|row| row.text("tbl").map(str::to_string)) .collect();letmut found = Vec::new();for table in tables {if found.len() >= most {break; }let quoted = table.replace('"', "\"\"");// A message the disappearing timer binned stays until he restores it or erases it for good (ABSENCE 6): the// timer never erases, and an "off" line arriving later restores it.// Nor a timer line, binned or not, for as long as its chat stands: a binned "off" still ends the span before it// (ABSENCE 5, item 1).let timer = if table == "cotton_msg_messages" { " AND json_extract(t.meta, '$.cotton.timer_binned') IS NULL AND json_extract(t.meta, '$.cotton.timer') IS NULL" } else { "" };let rows = db .all( &format!("SELECT t.id FROM \"{quoted}\" t WHERE t.trashed_at IS NOT NULL AND t.trashed_at <> '' AND t.trashed_at < ?1 \ AND NOT EXISTS (SELECT 1 FROM _outbox o WHERE o.tbl = ?2 AND o.row_id = t.id) \ AND NOT EXISTS (SELECT 1 FROM _writes w WHERE w.tbl = ?2 AND w.row_id = t.id AND w.held <> 0) \ AND NOT EXISTS (SELECT 1 FROM _writes_owners k WHERE k.tbl = ?2 AND k.owner = t.id){timer} \ LIMIT ?3" ), &[rusqlite::types::Value::Text(before.clone()), rusqlite::types::Value::Text(table.clone()), rusqlite::types::Value::Integer((most - found.len()) as i64)], ) .map_err(|e| e.to_string())?; found.extend(rows.iter().filter_map(|row| row.text("id").map(|id| (table.clone(), id.to_string())))); }Ok(found)}/// How many default line rows one pass drops.const LINES_A_PASS: usize = 2_000;/// Carry the trim on after a pass. Quiet on success; a failure is logged and/// asked again on the next pass.pub(crate) fn carry(client: &Arc<ClientController>) {let lines = client.with_writer(|file| {let found = default_lines(&file.driver)?;let some: Vec<(String, String)> = found.into_iter().take(LINES_A_PASS).collect(); cotton_store::keep::drop_here(&file.driver, &some).map_err(|e| e.to_string())?;Ok(some.len()) });ifletErr(why) = lines { tracing::warn!("trim: the default lines were not dropped — {why}; asked again after the next pass"); }let binned = client.with_writer(|file| {let some = binned_long_ago(&file.driver, chrono::Utc::now(), LINES_A_PASS)?; cotton_store::keep::drop_here(&file.driver, &some).map_err(|e| e.to_string())?;Ok(some.len()) });ifletErr(why) = binned { tracing::warn!("trim: rows binned long ago were not dropped — {why}; asked again after the next pass"); }for _ in0..STEPS_A_PASS {let step = client.with_writer(|file| cotton_store::receipts::implied::carry(&file.driver, 1).map_err(|error| error.to_string()));match step {Ok((_, true)) => {// Only the bounded hand-back here, while the app may be in use; the one whole// compaction waits for the app to be in the back (`went_back`).ifletErr(why) = client.with_writer(|file| give_back(&file.driver).map(|_| ())) { tracing::warn!("trim: free pages were not handed back — {why}; asked again after the next pass"); }return; }Ok((_, false)) => {}Err(why) => { tracing::warn!("trim: a step did not finish — {why}; asked again after the next pass");return; } } }}/// Compact once when the trim freed enough; hand back a bounded chunk after.fn pragma(db: &cotton_store::Driver, name: &str) -> Result<i64, String> {Ok(db.get(&format!("PRAGMA {name}"), &[]).map_err(|e| e.to_string())?.and_then(|row| row.int(name)).unwrap_or(0))}/// A file that vacuums incrementally hands back at most [`GIVE_BACK_PAGES`] free pages (a few/// MB, well under a second): answers whether it vacuums incrementally.pub(crate) fn give_back(db: &cotton_store::Driver) -> Result<bool, String> {if pragma(db, "auto_vacuum")? != 2 {returnOk(false); }let free = pragma(db, "freelist_count")?;if free > 0 {// It frees pages as its rows are stepped: every row read, not the first alone. db.all(&format!("PRAGMA incremental_vacuum({})", free.min(GIVE_BACK_PAGES)), &[]).map_err(|e| e.to_string())?; }Ok(true)}/// The whole compaction a file owes, in bytes of the file, or `None`, for a file that does not/// vacuum incrementally yet and is at least [`COMPACT_AT_BYTES`]: once the in-place trim has walked/// it, or once it holds that much free and a fifth of the file.////// The walk frees almost no pages: a receipt made implied shrinks inside its page, and the pages/// stay, each part empty (a 550 MB copy of 202,000 messages, trimmed whole on an emulator, kept 30/// free pages of 134,314, 22 Nov 2026). Only the compaction gives that space back, so a walked copy/// owes it whatever its free list says.pub(crate) fn compaction_owed(db: &cotton_store::Driver) -> Result<Option<i64>, String> {if pragma(db, "auto_vacuum")? == 2 {returnOk(None); }let (page, pages, free) = (pragma(db, "page_size")?, pragma(db, "page_count")?, pragma(db, "freelist_count")?);if pages * page < COMPACT_AT_BYTES {returnOk(None); }Ok((walked(db)? || free * page >= COMPACT_AT_BYTES && free * 5 >= pages).then_some(pages * page))}/// Whether the in-place trim has walked this copy to its end.fn walked(db: &cotton_store::Driver) -> Result<bool, String> {if db.get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = '_trim'", &[]).map_err(|e| e.to_string())?.is_none() {returnOk(false); }Ok(db.get("SELECT done FROM _trim WHERE only_one = 1", &[]).map_err(|e| e.to_string())?.and_then(|row| row.int("done")) == Some(1))}/// How long a whole compaction takes, judged from the file's size: 120 ms a MB (the big-account/// run gave 46 and 113 on a loaded Linux box, 21 Nov 2026), twice over.pub(crate) fn compaction_needs(bytes: i64) -> std::time::Duration { std::time::Duration::from_millis((bytes.max(0) as u64 / 1_000_000).saturating_mul(240))}/// `sync.compact { budgetMs? , stop? }` — for an iPhone `BGProcessingTask` (minutes, on power),/// where a 300 to 550 MB copy's one whole compaction fits and a trip to the back does not:////// - `{}`: whether the copy owes it, and how long it needs: `{owed, needsMs}`. The app submits a/// processing request while `owed` is true./// - `{budgetMs}`: run it now, if owed and `needsMs` fits the budget: `{owed, needsMs, ran, tookMs?}`./// The call blocks until it is done (a minute or two); `ran: false` with `owed: true` is too little/// time, or it was stopped./// - `{stop: true}`: the task's `expirationHandler`: a compaction running stops at once, the file as/// it was (`{stopped}`). `sync.foreground` stops it too.////// THE INDEXES A MOVE LEFT ride the same job (INDEX LATER 2, SCHEMA 155): `owed` is true while one is/// missing too (`indexes` names them), and `{budgetMs}` makes each that fits what is left after the/// compaction (`mail_index::build_in_task`). A trip to the back is often shorter than one index takes;/// the job, on the charger, is minutes. `{stop}` takes an index being made back, the file as it was.pubfn compact_call(handle: &crate::handle::CottonHandle, request: &serde_json::Value) -> Result<serde_json::Value, crate::methods::MethodError> {usecrate::methods::MethodError;let path = handle.client().attached_database().map(|database| handle.client().layout().replica(&database));if request.get("stop").and_then(serde_json::Value::as_bool) == Some(true) {let running = RUNNING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();letmut stopped = running.is_some();ifletSome(running) = running { running.interrupt(); }// An index being made of this copy is taken back, and the stop sticks for the job: an index not begun yet// when it came is not begun (INDEX LATER 3 REVIEW).ifletSome(path) = &path { stopped |= crate::phone::mail_index::came_forward_at(path); stopped |= stop_jobs(Some(path)); }returnOk(serde_json::json!({ "stopped": stopped })); }let budget = match request.get("budgetMs") {None | Some(serde_json::Value::Null) => None,Some(ms) => Some(ms.as_u64().filter(|ms| (1_000..=1_800_000).contains(ms)).map(std::time::Duration::from_millis).ok_or_else(|| MethodError::new("bad_request", "budgetMs is the milliseconds the task has, 1000 to 1800000"))?), };let client = handle.client();let owed = client.with_file(|file| compaction_owed(&file.driver)).map_err(|why| MethodError::new("could_not_read", why))?;let indexes = ifcrate::phone::mail_index::later_owed(&client) { client.with_file(|file| cotton_store::index_later::missing(&file.driver).map_err(|error| error.to_string())).unwrap_or_default() } else {Vec::new() };let index_needs = if indexes.is_empty() { std::time::Duration::ZERO } else {let mail = client.with_file(|file| cotton_store::index_later::mail_count(&file.driver).map_err(|error| error.to_string())).unwrap_or(0); cotton_store::index_later::time_needed(mail) * indexes.len() as u32 };let needs = owed.map(compaction_needs).unwrap_or_default() + index_needs;let owes = owed.is_some() || !indexes.is_empty();letmut answer = serde_json::json!({ "owed": owes, "needsMs": owes.then(|| needs.as_millis() as u64), "indexes": indexes });letSome(budget) = budget.filter(|_| owes) else { returnOk(answer) };let started = std::time::Instant::now();let job = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));ifletSome(path) = &path { JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).entry(path.clone()).or_default().push(std::sync::Arc::clone(&job)); }// Each job on a copy keeps its own flag (two may run at once); only its own goes as it ends.structJob(Option<std::path::PathBuf>, std::sync::Arc<std::sync::atomic::AtomicBool>);implDropforJob {fn drop(&mutself) {ifletSome(path) = &self.0 {letmut jobs = JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);ifletSome(held) = jobs.get_mut(path) { held.retain(|held| !std::sync::Arc::ptr_eq(held, &self.1));if held.is_empty() { jobs.remove(path); } } } } }let _job = Job(path.clone(), std::sync::Arc::clone(&job));let in_task = client.clone();let ran = handle .block_on(asyncmove { tokio::task::spawn_blocking(move || {let compacted = if owed.is_some() { in_task.with_writer(|file| compact_in(&file.driver, Some(budget), false))? } else { None };let left = budget.saturating_sub(started.elapsed());let (made, still) = crate::phone::mail_index::build_in_task(&in_task, left, &|| job.load(std::sync::atomic::Ordering::SeqCst))?;// And the copy's own check, when due: the job is the app away.crate::phone::file_check::carry_when(&in_task, true);Ok::<_, String>((compacted, made, still)) }) .await }) .map_err(|error| MethodError::new("compact_failed", error.to_string()))? .map_err(|why| MethodError::new("compact_failed", why))?;let (compacted, made, still) = ran;let compaction_left = owed.is_some() && compacted.is_none(); answer["ran"] = serde_json::json!(compacted.is_some() || !made.is_empty()); answer["owed"] = serde_json::json!(compaction_left || still); answer["made"] = serde_json::json!(made);ifletSome(took) = compacted { tracing::info!("trim: the copy compacted in a processing task, in {took:?}"); }if compacted.is_some() || !made.is_empty() { answer["tookMs"] = serde_json::json!(started.elapsed().as_millis() as u64); }Ok(answer)}/// Whether the app is in the back: set by `sync.background`, cleared by `sync.foreground`.static AWAY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);/// The processing jobs running, by copy, each with the flag its `{stop}` (or the app coming forward) sets: it does/// nothing more once set, an index not begun yet included (INDEX LATER 3 REVIEW).static JOBS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, Vec<std::sync::Arc<std::sync::atomic::AtomicBool>>>>> = std::sync::LazyLock::new(Default::default);/// How many processing jobs run on the copy at `path` (the tests: two at once each keep their own stop).#[cfg(test)]pub(crate) fn jobs_at(path: &std::path::Path) -> usize { JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(path).map_or(0, Vec::len)}fn stop_jobs(only: Option<&std::path::Path>) -> bool {let jobs = JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);letmut any = false;for (path, stopped) in jobs.iter() {if only.is_none_or(|only| only == path) {for stopped in stopped { stopped.store(true, std::sync::atomic::Ordering::SeqCst); any = true; } } } any}/// Whether the app is in the back now.pub(crate) fn is_away() -> bool { AWAY.load(std::sync::atomic::Ordering::SeqCst)}/// The compaction running now, to be stopped the moment the app comes to the front.static RUNNING: std::sync::Mutex<Option<rusqlite::InterruptHandle>> = std::sync::Mutex::new(None);/// The app came to the front: a compaction running stops at once. SQLite takes the whole/// rewrite back (the file is as it was), and it runs again the next time the app is away.pub(crate) fn came_forward() { AWAY.store(false, std::sync::atomic::Ordering::SeqCst); stop_jobs(None);// And an index a move left, being made: taken back whole, made again the next time the app is away.crate::phone::mail_index::came_forward();ifletSome(running) = RUNNING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() { running.interrupt(); tracing::info!("trim: the app came to the front; the compaction stops and waits for the next time it is away"); }}/// The app went to the back with `left` of the time it is given (`None`: no limit said, Android):/// the copy's one whole compaction, if it owes one and it fits in that time, runs on its own thread/// (TRIM, coordinator, 21 Nov 2026: it held the writer 25 to 48 s in one go, so never while the app/// is in use or a person is typing).pub(crate) fn went_back(client: &Arc<ClientController>, left: Option<std::time::Duration>) { AWAY.store(true, std::sync::atomic::Ordering::SeqCst);let client = Arc::downgrade(client);let _ = std::thread::Builder::new().name("cotton-compact".to_string()).spawn(move || {letSome(client) = client.upgrade() else { return };match client.with_writer(|file| compact_away(&file.driver, left)) {Ok(Some(took)) => tracing::info!("trim: the copy compacted while the app was away, in {took:?}"),Ok(None) => {}Err(why) => tracing::warn!("trim: the copy was not compacted — {why}; asked again the next time the app is away"), }// The indexes a move left (SCHEMA 155), while the app is still away.ifletErr(why) = crate::phone::mail_index::build_later(&client) { tracing::warn!("index later: {why}; asked again the next time the app is away"); } });}/// The whole compaction, while the app is away and only if it fits in `left`: answers how long it/// took, `None` when it did not run (nothing owed, not away, not time enough, or the app came to/// the front and it stopped).pub(crate) fn compact_away(db: &cotton_store::Driver, left: Option<std::time::Duration>) -> Result<Option<std::time::Duration>, String> { compact_in(db, left, true)}/// [`compact_away`], with `away` false for a caller that is itself the app away (an iPhone/// `BGProcessingTask`: the app may have been launched into the back, with no `sync.background`).fn compact_in(db: &cotton_store::Driver, left: Option<std::time::Duration>, away: bool) -> Result<Option<std::time::Duration>, String> {letSome(bytes) = compaction_owed(db)? else { returnOk(None) };if left.is_some_and(|left| left < compaction_needs(bytes)) { tracing::info!("trim: the compaction needs about {:?} and the app is away for {left:?}; it waits for a longer time", compaction_needs(bytes));returnOk(None); } *RUNNING.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(db.connection().get_interrupt_handle());let stop = |db: &cotton_store::Driver| { RUNNING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();let _ = db.exec("PRAGMA auto_vacuum = NONE"); };if away && !AWAY.load(std::sync::atomic::Ordering::SeqCst) { stop(db);returnOk(None); }let started = std::time::Instant::now();let ran = db.exec("PRAGMA auto_vacuum = INCREMENTAL; VACUUM");let interrupted = RUNNING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take().is_none();match ran {Ok(()) => Ok(Some(started.elapsed())),// Stopped by `came_forward`: the file is as it was, and the mode is put back with it.Err(_) if interrupted => { stop(db);Ok(None) }Err(error) => { stop(db);Err(error.to_string()) } }}#[cfg(test)]mod tests {usesuper::*;/// RULE: `sync.compact` says whether a copy owes its compaction and how long it needs, refuses a budget out of range by name, and a stop with nothing running says so. #[test]fn sync_compact_answers_what_is_owed_and_stops() {let (_dir, handle) = crate::fixture::synthetic_phone();let asked = crate::methods::dispatch(&handle, "sync.compact", &serde_json::json!({})).expect("an answer"); assert_eq!(asked["owed"], false, "a fresh copy owes nothing: {asked}");let ran = crate::methods::dispatch(&handle, "sync.compact", &serde_json::json!({ "budgetMs": 600_000 })).expect("an answer"); assert!(ran.get("ran").is_none(), "nothing owed, nothing run: {ran}"); assert_eq!(crate::methods::dispatch(&handle, "sync.compact", &serde_json::json!({ "budgetMs": 5 })).expect_err("too small").code, "bad_request"); assert_eq!(crate::methods::dispatch(&handle, "sync.compact", &serde_json::json!({ "stop": true })).expect("an answer")["stopped"], false); }/// RULE (TRIM 3, coordinator, 21 Nov 2026): a row binned more than 7 days ago leaves the copy, here alone (no retract, nothing sent); one binned this week, a live one, one with a write of this phone's still to send, and one another row hangs off stay. #[test]fn a_row_binned_more_than_a_week_ago_leaves_the_copy() {let dir = tempfile::tempdir().unwrap();let db = crate::fixture::seeded(&dir.path().join("copy.db"));let now = chrono::DateTime::parse_from_rfc3339("2026-11-21T10:00:00Z").unwrap().with_timezone(&chrono::Utc);let note = |id: &str, trashed: Option<&str>| {let sql = format!("INSERT INTO cotton_notes (id, workspace_id, title, body, created_at, updated_at, trashed_at) VALUES ('{id}', (SELECT workspace_id FROM _meta), 'Invented', 'Invented words', '2026-10-01T00:00:00.000Z', '2026-10-01T00:00:00.000Z', {})", trashed.map_or("NULL".to_string(), |at| format!("'{at}'")) ); db.exec(&sql).unwrap();crate::fixture::receipted(&db, &sql); }; note("n-old", Some("2026-11-10T09:00:00.000Z")); note("n-week", Some("2026-11-16T09:00:00.000Z")); note("n-live", None); note("n-unsent", Some("2026-11-01T09:00:00.000Z")); note("n-owner", Some("2026-11-01T09:00:00.000Z"));let count = |sql: &str| db.get(sql, &[]).unwrap().and_then(|row| row.int("n")).unwrap_or(-1);let op = db.get("SELECT op_id FROM _writes WHERE row_id = 'n-unsent'", &[]).unwrap().unwrap().text("op_id").unwrap().to_string(); db.exec(&format!("INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes) VALUES ('{op}', 'change', 'device:x', 'cotton_notes', 'n-unsent', '0', 151, '2026-11-21', x'00')")).unwrap();let receipt = db.get("SELECT op_id FROM _writes WHERE row_id = 'n-live'", &[]).unwrap().unwrap().text("op_id").unwrap().to_string(); db.exec(&format!("INSERT INTO _writes_owners (receipt, tbl, owner) VALUES ('{receipt}', 'cotton_notes', 'n-owner')")).unwrap();let found: Vec<(String, String)> = binned_long_ago(&db, now, 100).unwrap().into_iter().filter(|(table, _)| table == "cotton_notes").collect(); assert_eq!(found, vec![("cotton_notes".to_string(), "n-old".to_string())]);let outbox = count("SELECT COUNT(*) AS n FROM _outbox"); cotton_store::keep::drop_here(&db, &found).unwrap(); assert_eq!(count("SELECT COUNT(*) AS n FROM cotton_notes WHERE id = 'n-old'"), 0); assert_eq!(count("SELECT COUNT(*) AS n FROM _writes WHERE row_id = 'n-old'"), 0, "its receipts go with it"); assert_eq!(count("SELECT COUNT(*) AS n FROM _tombstones WHERE row_id = 'n-old'"), 0, "no retract: the object keeps it binned"); assert_eq!(count("SELECT COUNT(*) AS n FROM _outbox"), outbox, "nothing to send"); assert_eq!(count("SELECT COUNT(*) AS n FROM cotton_notes WHERE id IN ('n-week', 'n-live', 'n-unsent', 'n-owner')"), 4, "the week's, the live, the unsent and the owner stay"); assert!(binned_long_ago(&db, now, 100).unwrap().iter().all(|(table, _)| table != "cotton_notes")); }/// RULE (TRIM, 21 Nov 2026): a copy made before drops, here alone, the shell line rows it wrote that only repeat the kit's words — no retract minted, nothing sent — and keeps every rewording; a new copy writes none. #[test]fn a_copys_default_lines_go_and_a_rewording_stays() {let dir = tempfile::tempdir().unwrap();let db = crate::fixture::seeded(&dir.path().join("copy.db"));let now = chrono::DateTime::parse_from_rfc3339("2026-09-01T00:00:00Z").unwrap().with_timezone(&chrono::Utc); cotton_tools::presentation::write_shell(&db, now, std::sync::Arc::new(cotton_tools::random::SystemRandom), cotton_store::mint::Held::Served).unwrap();let count = |sql: &str| db.get(sql, &[]).unwrap().and_then(|row| row.int("n")).unwrap_or(-1);let written = count("SELECT COUNT(*) AS n FROM cotton_lines"); assert!(written > 6_000, "an earlier build's copy: {written} line rows");let reworded = db.get("SELECT id FROM cotton_lines ORDER BY id LIMIT 1", &[]).unwrap().unwrap().text("id").unwrap().to_string();let rewording = format!("UPDATE cotton_lines SET words = 'My own words' WHERE id = '{reworded}'"); db.exec(&rewording).unwrap();crate::fixture::receipted(&db, &rewording);let found = default_lines(&db).unwrap(); assert_eq!(found.len() as i64, written - 1, "every default but the rewording");let outbox = count("SELECT COUNT(*) AS n FROM _outbox"); cotton_store::keep::drop_here(&db, &found).unwrap(); assert_eq!(count("SELECT COUNT(*) AS n FROM cotton_lines"), 1); assert_eq!(count("SELECT COUNT(*) AS n FROM _writes WHERE tbl = 'cotton_lines' AND row_id <> (SELECT id FROM cotton_lines)"), 0, "their receipts go with them"); assert_eq!(count("SELECT COUNT(*) AS n FROM _tombstones WHERE tbl = 'cotton_lines'"), 0, "no retract minted"); assert_eq!(count("SELECT COUNT(*) AS n FROM _outbox"), outbox, "nothing to send"); assert!(default_lines(&db).unwrap().is_empty());let bare = crate::fixture::bare();let fresh = crate::fixture::seeded(&dir.path().join("fresh.db")); drop(bare); cotton_tools::presentation::write_shell_for_a_copy(&fresh, now, std::sync::Arc::new(cotton_tools::random::SystemRandom), cotton_store::mint::Held::Served).unwrap();let lines = fresh.get("SELECT COUNT(*) AS n FROM cotton_lines", &[]).ok().flatten().and_then(|row| row.int("n")).unwrap_or(0); assert_eq!(lines, 0, "a new copy writes no default line"); }fn int(db: &cotton_store::Driver, name: &str) -> i64 { db.get(&format!("PRAGMA {name}"), &[]).unwrap().and_then(|row| row.int(name)).unwrap_or(0) }/// RULE (TRIM, coordinator, 21 Nov 2026): the one whole compaction of a copy the trim freed (25 to 48 s under the writer on the big-account run) runs only while the app is away, only when the time it is given is enough, and stops the moment the app comes to the front, the file as it was; once done the file vacuums incrementally, a bounded chunk after each pass. A copy with little free is left alone. #[test]fn a_copy_is_compacted_only_while_the_app_is_away_and_stops_when_it_comes_back() {let dir = tempfile::tempdir().unwrap();let freed = |name: &str, rows: i64, keep_every: i64| {let db = cotton_store::Driver::open(&dir.path().join(name)).unwrap(); db.exec(&format!("CREATE TABLE t (x BLOB); WITH RECURSIVE n(i) AS (VALUES(0) UNION ALL SELECT i+1 FROM n WHERE i < {rows}) INSERT INTO t SELECT randomblob(4000) FROM n")).unwrap(); db.exec(&format!("DELETE FROM t WHERE rowid % {keep_every} <> 0")).unwrap(); db };// A copy the trim walked: its pages part empty, almost none free, and it owes the compaction all the same.let walked = freed("walked.db", 9_999, 1); assert!(int(&walked, "freelist_count") * 5 < int(&walked, "page_count")); walked.exec("CREATE TABLE _trim (only_one INTEGER PRIMARY KEY, after INTEGER NOT NULL, done INTEGER NOT NULL); INSERT INTO _trim VALUES (1, 9999, 0)").unwrap(); assert_eq!(compaction_owed(&walked).unwrap(), None, "not while the walk is still going"); walked.exec("UPDATE _trim SET done = 1").unwrap(); assert!(compaction_owed(&walked).unwrap().is_some(), "walked to its end, it owes it");let db = freed("copy.db", 9_999, 100);let free = int(&db, "freelist_count"); assert!(free * int(&db, "page_size") >= COMPACT_AT_BYTES); assert!(!give_back(&db).unwrap(), "after a pass, in use: nothing but the bounded hand-back, and this file has none yet"); assert!(compaction_owed(&db).unwrap().is_some()); came_forward(); assert_eq!(compact_away(&db, None).unwrap(), None, "in use: never"); AWAY.store(true, std::sync::atomic::Ordering::SeqCst); assert_eq!(compact_away(&db, Some(std::time::Duration::from_millis(5))).unwrap(), None, "too little time away: it waits"); assert_eq!((int(&db, "freelist_count"), int(&db, "auto_vacuum")), (free, 0), "untouched");// Comes to the front part way: stopped, the file as it was, and it runs again the next time away.let big = freed("big.db", 39_999, 2);let big_free = int(&big, "freelist_count");let path = dir.path().join("big.db");let running = std::thread::spawn(move || compact_away(&cotton_store::Driver::open(&path).unwrap(), None));while RUNNING.lock().unwrap().is_none() && !running.is_finished() { std::thread::yield_now(); } std::thread::sleep(std::time::Duration::from_millis(20)); came_forward(); assert_eq!(running.join().unwrap().unwrap(), None, "stopped by the app coming back"); assert_eq!((int(&big, "freelist_count"), int(&big, "auto_vacuum")), (big_free, 0), "the file as it was"); AWAY.store(true, std::sync::atomic::Ordering::SeqCst); assert!(compact_away(&db, None).unwrap().is_some(), "away, with the time: compacted"); assert_eq!((int(&db, "auto_vacuum"), int(&db, "freelist_count")), (2, 0), "vacuums incrementally from now on"); assert_eq!(compaction_owed(&db).unwrap(), None); db.exec("WITH RECURSIVE n(i) AS (VALUES(0) UNION ALL SELECT i+1 FROM n WHERE i < 2999) INSERT INTO t SELECT randomblob(4000) FROM n; DELETE FROM t WHERE rowid > 100").unwrap();let free = int(&db, "freelist_count"); assert!(free > GIVE_BACK_PAGES); assert!(give_back(&db).unwrap()); assert_eq!(int(&db, "freelist_count"), free - GIVE_BACK_PAGES, "a bounded chunk handed back"); came_forward();// An iPhone processing task (the app launched into the back, no `sync.background`): compacted in its own time.let task = freed("task.db", 9_999, 100); assert_eq!(compact_in(&task, Some(std::time::Duration::from_millis(5)), false).unwrap(), None, "too little time"); assert!(compact_in(&task, None, false).unwrap().is_some()); assert_eq!(int(&task, "auto_vacuum"), 2);let small = cotton_store::Driver::open(&dir.path().join("small.db")).unwrap(); small.exec("CREATE TABLE t (x BLOB); INSERT INTO t VALUES (randomblob(100000)); DELETE FROM t").unwrap(); assert_eq!(compaction_owed(&small).unwrap(), None, "little free: left alone"); assert!(compaction_needs(546_000_000) >= std::time::Duration::from_secs(60), "the big-account file needs a long time away"); }}