Cotton code
281 lines · 10.6 KB · RustRaw
//! List counts must not repeatedly walk the owner's mail and messages while//! holding the served file. Everything here is synthetic, including bodies.mod support;use cotton_store::held::{Asked, Work};use cotton_tools::clock::Clock;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::tables::list_records;use rusqlite::types::Value as Sql;use serde_json::{json, Value};use std::time::{Duration, Instant};use support::harness::Harness;fn list(h: &Harness, args: Value) -> Value {    let audit = |_: &str, _: &str| {};    let scopes = vec!["read".to_string()];    let mut ctx = Ctx::new(        &h.db,        &h.file,        &h.owner_id,        "Synthetic reader",        "synthetic",        &scopes,        h.clock.now(),        std::sync::Arc::clone(&h.random),        None,        &h.services.services,        &audit,    );    h.db.read_transaction(|_| {        list_records(&mut ctx, args.as_object().unwrap()).map_err(cotton_store::StoreError::refused)    })    .unwrap()}fn held<T>(h: &Harness, read: impl FnOnce() -> T) -> (T, Asked) {    let _hold = cotton_store::held::holding("synthetic list file");    let before = Asked::so_far(&h.db);    let began = Instant::now();    let result = read();    let asked = Asked::since(&h.db, &before);    let line = cotton_store::held::slow_hold_line(        "synthetic",        began.elapsed(),        Duration::ZERO,        &Work::default(),        &asked,        std::panic::Location::caller(),    )    .unwrap();    println!("{line}");    assert!(        asked            .slowest            .as_ref()            .is_none_or(|(took, _)| *took < Duration::from_secs(1)),        "{line}"    );    (result, asked)}/// RULE: A page draw shares Email facet totals and reuses unchanged list counts; an unrelated one-row list reads no mail, and a write invalidates the totals so no stale count is drawn.#[test]fn list_counts_share_one_mail_pass_and_reuse_unchanged_totals() {    let h = Harness::new();    let params = [Sql::Text(h.workspace_id.clone())];    h.db.run(        "WITH RECURSIVE n(i) AS (VALUES(0) UNION ALL SELECT i+1 FROM n WHERE i<999)        INSERT INTO cotton_email_threads (id,workspace_id,external_key,created_at,updated_at)        SELECT 'synthetic:thread:'||i,?1,'synthetic:thread:'||i,'2026-10-01','2026-10-01' FROM n",        &params,    )    .unwrap();    h.db.run("WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i<60000)        INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,sent_at,created_at,body,trashed_at)        SELECT 'synthetic:mail:'||i,?1,'synthetic:thread:'||CASE WHEN i<=54000 THEN 0 ELSE i%1000 END,            'synthetic:mail:'||i,CASE WHEN i%32=0 THEN 'SÉNDER@example.test' ELSE 'sender'||(i%32)||'@example.test' END,            '2026-10-01','2026-10-01',replace(hex(zeroblob(2048)),'0','x'),            CASE WHEN i=60000 THEN '2026-10-02' END FROM n", &params).unwrap();    h.db.run(        "INSERT INTO cotton_blocked_senders (id,workspace_id,address,created_at)        VALUES ('synthetic:block',?1,'blocked@example.test','2026-10-01')",        &params,    )    .unwrap();    // Measure the former two per-facet reads on the identical skewed fixture.    let before = Asked::so_far(&h.db);    for column in ["thread_id", "from_email"] {        h.db.all(            &format!(                "SELECT {column} FROM cotton_emails WHERE workspace_id=?1 AND trashed_at IS NULL"            ),            &params,        )        .unwrap();    }    let old = Asked::since(&h.db, &before);    println!(        "former mail facets: {} steps, {:?} inside SQLite",        old.steps, old.inside    );    h.db.watch_statements();    let (_, cold) = held(&h, || {        for (table, total) in [            ("email", 59999),            ("email_thread", 1000),            ("email_sender", 33),        ] {            assert_eq!(                list(&h, json!({"table":table,"count_only":true}))["total"],                total            );        }    });    let mail_reads: Vec<_> =        h.db.statements_seen()            .into_iter()            .filter(|sql| sql.contains("FROM cotton_emails"))            .collect();    assert_eq!(        mail_reads.len(),        1,        "all mail facets share their visibility pass: {mail_reads:?}"    );    println!(        "shared mail facets: {} steps, {:?} inside SQLite",        cold.steps, cold.inside    );    h.db.watch_statements();    let (_, warm) = held(&h, || {        for table in [            "email",            "email_thread",            "email_sender",            "email",            "email_sender",        ] {            list(&h, json!({"table":table,"count_only":true}));        }        assert_eq!(list(&h, json!({"table":"note","limit":1}))["total"], 0);    });    assert!(        !h.db            .statements_seen()            .iter()            .any(|sql| sql.contains("FROM cotton_emails")),        "warm facets and other tables must not walk Email"    );    assert!(        warm.steps < 10000,        "a page draw must do bounded metadata work: {warm:?}"    );    println!(        "reused mail facets and unrelated row: {} steps, {:?} inside SQLite",        warm.steps, warm.inside    );    h.db.run(        "UPDATE cotton_emails SET trashed_at='2026-10-02' WHERE id='synthetic:mail:1'",        &[],    )    .unwrap();    assert_eq!(        list(&h, json!({"table":"email","count_only":true}))["total"],        59998    );    h.db.run(        "INSERT INTO cotton_blocked_senders (id,workspace_id,address,created_at)        VALUES ('synthetic:block:two',?1,'second@example.test','2026-10-01')",        &params,    )    .unwrap();    assert_eq!(        list(&h, json!({"table":"email_sender","count_only":true}))["total"],        34    );}/// RULE: A paged Messages count is reused only for the same workspace and filters, and clearing a thread invalidates it; NOT EXISTS must not scan messages again for each page.#[test]fn filtered_message_counts_follow_their_query_and_writes() {    use cotton_tools::mcp::read_db::{Filter, Query, ReadDb};    let h = Harness::new();    h.db.run(        "INSERT INTO cotton_msg_threads (id,workspace_id,kind,title,created_at,updated_at)        VALUES ('synthetic:chat',?1,'group','Synthetic chat','2026-10-01','2026-10-01')",        &[Sql::Text(h.workspace_id.clone())],    )    .unwrap();    h.db.run("WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i<60000)        INSERT INTO cotton_msg_messages (id,workspace_id,thread_id,direction,channel,origin,body,sent_at,created_at)        SELECT 'synthetic:message:'||i,?1,'synthetic:chat','in','cotton','imported','Synthetic words','2026-10-01','2026-10-01' FROM n",        &[Sql::Text(h.workspace_id.clone())]).unwrap();    let read = ReadDb::new(&h.db, &h.workspace_id);    let query = Query::on("cotton_msg_messages").filter(Filter::Static(        "NOT EXISTS (SELECT 1 FROM cotton_msg_threads t WHERE t.id=cotton_msg_messages.thread_id AND t.cleared_before >= cotton_msg_messages.sent_at)"));    held(&h, || assert_eq!(read.count(&query).unwrap(), 60000));    h.db.watch_statements();    held(&h, || assert_eq!(read.count(&query).unwrap(), 60000));    assert!(!h        .db        .statements_seen()        .iter()        .any(|sql| sql.contains("FROM cotton_msg_messages")));    assert_eq!(        read.count(&query.clone().eq("direction", "out".to_string()))            .unwrap(),        0,        "filters have distinct cache keys"    );    held(&h, || {        assert_eq!(            list(&h, json!({"table":"message","limit":1}))["total"],            60000        )    });    h.db.watch_statements();    held(&h, || {        assert_eq!(            list(&h, json!({"table":"message","limit":1,"page":1}))["total"],            60000        )    });    assert!(!h        .db        .statements_seen()        .iter()        .any(|sql| sql.starts_with("SELECT COUNT(*)") && sql.contains("cotton_msg_messages")));    h.db.run(        "UPDATE cotton_msg_threads SET cleared_before='2026-10-02' WHERE id='synthetic:chat'",        &[],    )    .unwrap();    assert_eq!(read.count(&query).unwrap(), 0);    assert_eq!(list(&h, json!({"table":"message","limit":1}))["total"], 0);}/// A mailbox the size of the owner's: 100,000 threads, 300,000 emails, every thread starred, half in the inbox.fn wide_mailbox(h: &Harness) {    let params = [Sql::Text(h.workspace_id.clone())];    h.db.run(        "WITH RECURSIVE n(i) AS (VALUES(0) UNION ALL SELECT i+1 FROM n WHERE i<99999)        INSERT INTO cotton_email_threads (id,workspace_id,external_key,last_at,created_at,updated_at)        SELECT 'synthetic:thread:'||i,?1,'synthetic:thread:'||i,printf('2026-10-01T00:%02d:%02d.000Z',(i/60)%60,i%60),'2026-10-01','2026-10-01' FROM n",        &params,    )    .unwrap();    h.db.run(        "WITH RECURSIVE n(i) AS (VALUES(0) UNION ALL SELECT i+1 FROM n WHERE i<299999)        INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,sent_at,created_at,starred,in_inbox)        SELECT 'synthetic:mail:'||i,?1,'synthetic:thread:'||(i%100000),'synthetic:mail:'||i,'sender@example.test',            '2026-10-01','2026-10-01',i%3=0,i%2 FROM n",        &params,    )    .unwrap();}/// RULE: The mail list knows whether another page follows without its count, and counts once per snapshot — the next page of the same list reuses the total, and a write lets the next read see the new one.#[test]fn the_mail_lists_pages_share_one_count_per_snapshot() {    let h = Harness::new();    wide_mailbox(&h);    h.db.watch_statements();    let first = list(&h, json!({"table":"email_thread","where":{"starred":true},"limit":20}));    let second = list(&h, json!({"table":"email_thread","where":{"starred":true},"limit":20,"page":20}));    let counts = h.db.statements_seen().iter().filter(|sql| sql.contains("count(*)") && sql.contains("cotton_email_threads")).count();    assert_eq!(counts, 1, "each page recounted the mailbox");    assert_eq!(first["total"], 100000);    assert_eq!(second["total"], 100000);    assert_eq!(first["next_page"], 20);    assert_eq!(second["next_page"], 40);    let last = list(&h, json!({"table":"email_thread","where":{"starred":true},"limit":20,"page":99980}));    assert_eq!(last["records"].as_array().unwrap().len(), 20);    assert_eq!(last["next_page"], Value::Null, "the last page offered another");    h.db.run("UPDATE cotton_emails SET trashed_at='2026-10-02' WHERE thread_id='synthetic:thread:0'", &[]).unwrap();    assert_eq!(list(&h, json!({"table":"email_thread","where":{"starred":true},"limit":20}))["total"], 99999);}