//! PHASE 2 PHONE 2, item 5 (the coordinator, 27 Nov 2026): what the landing fill costs on a full-size copy. A//! synthetic file of `LANDED_COST_MAILS` mails (default 300,000) with bodies of 1 to 12 KB (about 5 KB each, as a//! real mailbox's text parts run) is built once in `LANDED_COST_DIR`, then the fill is applied in slices of 1,000 the//! way the phone applies it, two ways: the landing time written onto the wide mail row, and written into a narrow//! side table keyed by id. For each it prints the bytes this process wrote (`/proc/self/io`), the longest slice (the//! longest the writer is held) and the WAL's peak. Invented rows only. Run by hand://!//! LANDED_COST_DIR=/path/to/cost cargo test -p cotton-store --test landed_fill_cost -- --ignored --nocaptureuse cotton_store::{create::apply_schema, Driver};use rusqlite::types::Value;fn written() -> u64 {let io = std::fs::read_to_string("/proc/self/io").unwrap_or_default(); io.lines().find_map(|l| l.strip_prefix("write_bytes: ")).and_then(|n| n.trim().parse().ok()).unwrap_or(0)}fn size(path: &std::path::Path) -> u64 { std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)}/// A deterministic body of 1 to 12 KB of plain words.fn body(n: u64) -> String {const WORDS: &[&str] = &["the", "invented", "order", "receipt", "meeting", "tomorrow", "please", "find", "attached", "regards", "lake", "garden", "project", "update", "thanks", "offer", "week", "plan"];letmut x = n.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);let target = 1024 + (x % 11264) as usize;letmut out = String::with_capacity(target + 16);while out.len() < target { x ^= x << 13; x ^= x >> 7; x ^= x << 17; out.push_str(WORDS[(x % WORDS.len() as u64) as usize]); out.push(' '); } out}fn build(path: &std::path::Path, mails: u64) {let db = Driver::open(path).unwrap(); apply_schema(&db).unwrap(); db.exec("INSERT INTO cotton_workspaces(id,name,owner_user_id,created_at) VALUES ('synthetic','Synthetic','person','2026-01-01T00:00:00.000Z')").unwrap(); db.exec("BEGIN").unwrap();for i in0..mails {if i % 3 == 0 { db.run("INSERT INTO cotton_email_threads(id,workspace_id,external_key,subject,last_at,created_at,updated_at) VALUES (?,'synthetic',?,'Invented','2026-11-01T00:00:00.000Z','2026-11-01T00:00:00.000Z','2026-11-01T00:00:00.000Z')", &[Value::Text(format!("t-{:07}", i / 3)), Value::Text(format!("k-{i}"))], ) .unwrap(); }let at = format!("2026-{:02}-{:02}T{:02}:{:02}:00.000Z", 1 + (i % 11), 1 + (i % 28), i % 24, i % 60); db.run("INSERT INTO cotton_emails(id,workspace_id,thread_id,external_id,from_email,from_name,subject,body,snippet,sent_at,created_at,attachments,in_inbox,unread) VALUES (?,'synthetic',?,?,?,'Invented Sender','Invented subject',?,'Invented snippet',?,?,'[]',1,0)", &[Value::Text(format!("e-{i:08}")), Value::Text(format!("t-{:07}", i / 3)), Value::Text(format!("<{i}@invented.example>")), Value::Text(format!("sender{}@domain{}.example", i % 4000, i % 900)), Value::Text(body(i)), Value::Text(at.clone()), Value::Text(at)], ) .unwrap();if i % 10_000 == 9_999 { db.exec("COMMIT").unwrap(); db.exec("BEGIN").unwrap(); } } db.exec("COMMIT").unwrap(); db.exec("PRAGMA wal_checkpoint(TRUNCATE)").unwrap();}fn measure(path: &std::path::Path, mails: u64, how: &str, slice_sql: &str, setup: &str) { measure_then(path, mails, how, slice_sql, setup, "");}fn measure_then(path: &std::path::Path, mails: u64, how: &str, slice_sql: &str, setup: &str, after: &str) {let db = Driver::open(path).unwrap(); db.exec(setup).unwrap(); db.exec("PRAGMA wal_checkpoint(TRUNCATE)").unwrap();// Every frame counted: no automatic checkpoint, one after each slice, as many as that slice wrote. db.exec("PRAGMA wal_autocheckpoint = 0").unwrap();let page = db.get("PRAGMA page_size", &[]).unwrap().and_then(|r| r.int("page_size")).unwrap() as u64;let (before, began) = (written(), std::time::Instant::now());let (mut longest, mut peak, mut frames) = (std::time::Duration::ZERO, 0u64, 0u64);letmut i = 0;while i < mails {let start = std::time::Instant::now(); db.exec("BEGIN IMMEDIATE").unwrap();for j in i..(i + 1000).min(mails) { db.run(slice_sql, &[Value::Text(format!("e-{j:08}")), Value::Text("2026-11-27T09:00:00.000Z".into()), Value::Text(format!("sender{}@domain{}.example", j % 4000, j % 900))]).unwrap(); } db.exec("COMMIT").unwrap(); longest = longest.max(start.elapsed());// PASSIVE answers the frames the WAL holds (this slice's) and copies them; TRUNCATE then empties it.let row = db.get("PRAGMA wal_checkpoint(PASSIVE)", &[]).unwrap().unwrap();let log = row.int("log").unwrap_or(0).max(0) as u64; db.exec("PRAGMA wal_checkpoint(TRUNCATE)").unwrap(); frames += log; peak = peak.max(log * (page + 24)); i += 1000; }if !after.is_empty() {let start = std::time::Instant::now(); db.exec(after).unwrap();let row = db.get("PRAGMA wal_checkpoint(PASSIVE)", &[]).unwrap().unwrap();let log = row.int("log").unwrap_or(0).max(0) as u64; db.exec("PRAGMA wal_checkpoint(TRUNCATE)").unwrap(); frames += log; peak = peak.max(log * (page + 24)); println!("{how}: the indexes made at the end in {} ms ({log} frames)", start.elapsed().as_millis()); longest = longest.max(start.elapsed()); }let total = written() - before;// Each frame is written to the WAL, then its page to the file by the checkpoint.let exact = frames * (page + 24) + frames * page; println!("{how}: {mails} mails, {frames} WAL frames of {page} B = {:.1} MB written (WAL and checkpoint), {:.1} MB by /proc/self/io, longest slice {} ms, WAL peak {:.1} MB, {:.1} s in all, file {:.0} MB", exact as f64 / 1e6, total as f64 / 1e6, longest.as_millis(), peak as f64 / 1e6, began.elapsed().as_secs_f64(), size(path) as f64 / 1e6 );}#[test]#[ignore = "builds a full-size copy (about 2 GB); run by hand with LANDED_COST_DIR"]fn what_the_landing_fill_costs_at_full_size() {let dir = std::path::PathBuf::from(std::env::var("LANDED_COST_DIR").expect("LANDED_COST_DIR"));let mails: u64 = std::env::var("LANDED_COST_MAILS").ok().and_then(|n| n.parse().ok()).unwrap_or(300_000); std::fs::create_dir_all(&dir).unwrap();let base = dir.join("base.db");if !base.exists() {let t = std::time::Instant::now(); build(&base, mails); println!("built {mails} mails in {:.0} s: {:.0} MB", t.elapsed().as_secs_f64(), size(&base) as f64 / 1e6); }let copy = |name: &str| {let to = dir.join(name);for suffix in ["", "-wal", "-shm"] {let _ = std::fs::remove_file(format!("{}{suffix}", to.display())); } std::fs::copy(&base, &to).unwrap(); to };let only = std::env::var("LANDED_COST_ONLY").unwrap_or_default();if only == "late" {let side = copy("late.db"); measure_then( &side, mails,"in a side table, its indexes made after","INSERT INTO _mail_landed (id, landed_at, \"key\", domain) VALUES (?1, ?2, ?3, substr(?3, instr(?3, '@'))) ON CONFLICT (id) DO NOTHING","CREATE TABLE IF NOT EXISTS _mail_landed (id TEXT PRIMARY KEY, landed_at TEXT NOT NULL, \"key\" TEXT NOT NULL, domain TEXT NOT NULL) WITHOUT ROWID","CREATE INDEX IF NOT EXISTS _mail_landed_key ON _mail_landed (\"key\", landed_at); CREATE INDEX IF NOT EXISTS _mail_landed_domain ON _mail_landed (domain, landed_at); CREATE INDEX IF NOT EXISTS _mail_landed_at ON _mail_landed (landed_at)", ); std::fs::remove_file(&side).unwrap();return; }let wide = copy("wide.db"); measure(&wide, mails, "on the mail row", "UPDATE cotton_emails SET landed_at = ?2 WHERE id = ?1 AND landed_at IS NULL AND ?3 IS NOT NULL", "SELECT 1"); std::fs::remove_file(&wide).unwrap();let side = copy("side.db"); measure( &side, mails,"in a side table","INSERT INTO _mail_landed (id, landed_at, \"key\", domain) VALUES (?1, ?2, ?3, substr(?3, instr(?3, '@'))) ON CONFLICT (id) DO NOTHING","CREATE TABLE IF NOT EXISTS _mail_landed (id TEXT PRIMARY KEY, landed_at TEXT NOT NULL, \"key\" TEXT NOT NULL, domain TEXT NOT NULL) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS _mail_landed_key ON _mail_landed (\"key\", landed_at); CREATE INDEX IF NOT EXISTS _mail_landed_domain ON _mail_landed (domain)", ); std::fs::remove_file(&side).unwrap();}