Cotton code
91 lines · 5.5 KB · RustRaw
//! Schema 155 (POST AT SIZE, 26 Nov 2026): three partial indexes on cotton_emails, the Inbox by sender, mail//! archived by its own flag, and mail with attachments, so Post's first open after new mail or a start never reads//! every mail's body at his size. A fresh file has them from its first statement. A copy stamped 154 moves without//! them: an index over rows it holds reads every one, 30 s or more over 110,000 mails on a busy disk, and the move//! runs at the open. `index_later` makes them afterwards, one a step, in the background. The move only makes//! objects, so its whole-file checks are left out. Invented rows only.use cotton_store::{    create::{apply_schema, SchemaObject},    index_later::{missing, step, LATER},    shape_move::{left, move_to_current},    Driver,};fn at_154() -> Driver {    let had: Vec<SchemaObject> = serde_json::from_str(include_str!("fixtures/schema-v154.json")).unwrap();    assert!(!had.iter().any(|o| LATER.contains(&o.name.as_str())), "154 has none of the three");    let db = Driver::open_in_memory().unwrap();    apply_schema(&db).unwrap();    for index in LATER {        db.exec(&format!("DROP INDEX {index}")).unwrap();    }    db.exec("PRAGMA user_version=154").unwrap();    db.exec("UPDATE _meta SET schema_version = 154").unwrap();    db}const SEED: &str = "INSERT INTO cotton_workspaces(id,name,owner_user_id,created_at) VALUES ('synthetic','Synthetic','person','now');INSERT INTO cotton_email_threads(id,workspace_id,external_key,subject,last_at,created_at,updated_at) VALUES ('t-1','synthetic','k-1','Invented receipt','2026-11-21T10:00:00Z','now','now'),('t-2','synthetic','k-2','Invented plan','2026-11-21T11:00:00Z','now','now');INSERT INTO cotton_emails(id,workspace_id,thread_id,external_id,from_email,subject,body,sent_at,created_at,attachments,in_inbox)  VALUES ('e-1','synthetic','t-1','x-1','shop@invented.example','Invented receipt','Thanks','2026-11-21T10:00:00Z','2026-11-21T10:00:01Z','[{\"name\":\"receipt.pdf\"}]',1),         ('e-2','synthetic','t-2','x-2','ada@invented.example','Invented plan','Saturday?','2026-11-21T11:00:00Z','2026-11-21T11:00:01Z','[]',0);";fn plan(db: &Driver, sql: &str) -> Vec<String> {    db.all(&format!("EXPLAIN QUERY PLAN {sql}"), &[]).unwrap().iter().filter_map(|row| row.text("detail").map(str::to_string)).collect()}/// RULE: a copy stamped 154 moves to 155 without the three indexes, every mail and rowid as it was; the background/// makes each once afterwards, and the reads Post asks then read them.#[test]fn a_154_copy_moves_without_the_indexes_and_makes_them_after() {    let db = at_154();    db.exec(SEED).unwrap();    let before = db.all("SELECT rowid, * FROM cotton_emails ORDER BY rowid", &[]).unwrap();    assert!(left(&db).unwrap().is_some(), "a 154 copy has a move to run");    let report = move_to_current(&db).unwrap();    assert!(left(&db).unwrap().is_none(), "moved to 155: {report:?}");    assert_eq!(db.all("SELECT rowid, * FROM cotton_emails ORDER BY rowid", &[]).unwrap(), before);    assert_eq!(missing(&db).unwrap(), LATER, "the move made none of them");    assert!(!report.whole_file_checked, "154 to 155 only makes objects, so the whole-file checks are left out: {report}");    let mut made = Vec::new();    while let Some(name) = step(&db).unwrap() {        made.push(name);    }    assert_eq!(made, LATER);    let inbox = plan(&db, "SELECT lower(trim(from_email)) AS a, count(*) FROM cotton_emails WHERE workspace_id = 'synthetic' AND trashed_at IS NULL AND archived_at IS NULL AND coalesce(in_inbox, 1) <> 0 GROUP BY lower(trim(from_email))");    assert!(inbox.iter().any(|d| d.contains("COVERING INDEX idx_cotton_emails_inbox")), "{inbox:?}");    let archived = plan(&db, "SELECT thread_id FROM cotton_emails e WHERE e.trashed_at IS NULL AND (e.archived_at IS NOT NULL OR e.in_inbox = 0)");    assert!(archived.iter().any(|d| d.contains("idx_cotton_emails_archived")), "{archived:?}");    let files = plan(&db, "SELECT id FROM cotton_emails WHERE workspace_id = 'synthetic' AND trashed_at IS NULL AND attachments IS NOT NULL AND attachments <> '' AND attachments <> '[]' ORDER BY sent_at DESC, id DESC LIMIT 200");    assert!(files.iter().any(|d| d.contains("idx_cotton_emails_files")), "{files:?}");    let found: Vec<String> = db.all("SELECT thread_id FROM cotton_emails e WHERE e.trashed_at IS NULL AND (e.archived_at IS NOT NULL OR e.in_inbox = 0)", &[]).unwrap().iter().filter_map(|r| r.text("thread_id").map(str::to_string)).collect();    assert_eq!(found, ["t-2"]);}/// RULE: a fresh file holds the three from its first statement; nothing is left for the background.#[test]fn a_fresh_file_holds_them() {    let db = Driver::open_in_memory().unwrap();    apply_schema(&db).unwrap();    assert!(missing(&db).unwrap().is_empty());}/// MEASURE (ignored): the move of a real-size copy, `COTTON_MOVE_FILE` (a copy stamped 154; moved in place), timed/// whole and then each index the background makes after it.#[test]#[ignore]fn measure_the_move_of_a_copy_at_size() {    let Ok(path) = std::env::var("COTTON_MOVE_FILE") else { return };    let db = Driver::open(std::path::Path::new(&path)).unwrap();    let started = std::time::Instant::now();    let report = move_to_current(&db).unwrap();    println!("MOVE from {} to {} in {} ms (opened and moved), created {:?}", report.from, report.to, started.elapsed().as_millis(), report.created);    loop {        let t = std::time::Instant::now();        let Some(name) = step(&db).unwrap() else { break };        println!("MOVE then {name} in {} ms", t.elapsed().as_millis());    }}