Cotton code
114 lines · 5.2 KB · RustRaw
//! `channels_by_thread` reads a thread's channels by skipping through//! `cotton_msg_messages (thread_id, channel)`. Synthetic data only.use super::*;use std::sync::Arc;use chrono::{DateTime, Utc};use cotton_store::driver::Driver;use crate::mcp::dispatch::ToolServices;const OWNER: &str = "00000000-0000-4000-8000-0000000000bb";const WORKSPACE: &str = "00000000-0000-4000-8000-0000000000a1";const NOW: &str = "2026-10-04T10:00:00.000Z";const THREADS: usize = 20;fn t(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// `THREADS` conversations of `per_thread` messages each, all on WhatsApp but/// the last, which came by iMessage. Answers the thread ids.fn database(per_thread: usize) -> (Driver, Vec<String>) {    let db = cotton_store::test_template::create_workspace_in_memory_for_test(&cotton_store::meta::Meta {        workspace_id: WORKSPACE.to_string(),        owner_id: OWNER.to_string(),        device_id: "device:channels".to_string(),        last_server_seq: 0,        last_hlc: None,    })    .expect("a fresh file");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, _hlc) VALUES (?, 'Invented', ?, ?, '')",        &[t(WORKSPACE), t(OWNER), t(NOW)],    )    .expect("the workspace row");    let mut threads = Vec::new();    for n in 0..THREADS {        let thread = format!("thread-{n:03}");        db.run(            "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) VALUES (?, ?, 'group', ?, ?, ?)",            &[t(&thread), t(WORKSPACE), t(&format!("Invented {n}")), t(NOW), t(NOW)],        )        .expect("a thread");        db.run(            "WITH RECURSIVE k(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM k WHERE i < ?) \             INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, seq) \             SELECT ? || '-' || i, ?, ?, 'in', CASE WHEN i = ? THEN 'imessage' ELSE 'whatsapp' END, 'imported', 'invented words', ?, ?, i FROM k",            &[                SqlValue::Integer(per_thread as i64),                t(&thread),                t(&thread),                t(WORKSPACE),                SqlValue::Integer(per_thread as i64),                t(NOW),                t(NOW),            ],        )        .expect("its messages");        threads.push(thread);    }    (db, threads)}/// The steps one call reads, and what it answered.fn channels(db: &Driver, threads: &[String]) -> (u64, HashMap<String, Vec<String>>) {    let services = ToolServices::none();    let scopes = vec!["read".to_string()];    let log = |_: &str, _: &str| {};    let now = NOW.parse::<DateTime<Utc>>().expect("a fixed instant");    let identity = cotton_store::file_identity::read_file_identity(db).expect("the file reads").expect("seeded");    let ctx = Ctx::new(db, &identity, OWNER, "channels-test", "token-channels", &scopes, now, Arc::new(crate::random::SystemRandom), None, &services, &log);    let before = db.steps();    let answer = channels_by_thread(&ctx, threads).expect("the channels read");    (db.steps() - before, answer)}/// RULE: A page of conversations reads each thread's channels by skipping through cotton_msg_messages (thread_id, channel) — one seek per channel a thread holds — so it costs the same among 5,000 messages a thread as among 50, never a walk of every listed thread's messages./// On the owner's serving Mac (11 Oct 2026, after the 0.29.26 restart) the DISTINCT this replaced held the personal file 8.2 s: 7.8 s and 1,681,586 steps for one page, and the hold sent that Mac's own git fetch through the relay.#[test]fn a_page_reads_its_threads_channels_without_reading_their_messages() {    let (db, threads) = database(50);    let (small, answer) = channels(&db, &threads);    assert_eq!(answer.len(), THREADS);    for thread in &threads {        assert_eq!(answer[thread], vec!["whatsapp".to_string(), "imessage".to_string()], "{answer:?}");    }    let (db, threads) = database(5_000);    let (large, answer) = channels(&db, &threads);    assert_eq!(answer.len(), THREADS);    assert!(large <= small + small / 2, "the page read {large} steps among 5,000 messages a thread and {small} among 50");    // And the measure sees the walk it guards against.    db.exec("DROP INDEX idx_cotton_msg_messages_thread_channel").expect("the index is there to drop");    let (walked, _) = channels(&db, &threads);    assert!(walked > large * 10, "without the index the page read {walked} steps, with it {large}");}/// RULE: A thread of another workspace, and a thread with no messages, answer no channels.#[test]fn a_thread_outside_the_workspace_or_without_messages_answers_nothing() {    let (db, mut threads) = database(3);    db.run(        "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) VALUES ('thread-empty', ?, 'group', 'Quiet', ?, ?)",        &[t(WORKSPACE), t(NOW), t(NOW)],    )    .expect("an empty thread");    threads.push("thread-empty".to_string());    threads.push("thread-elsewhere".to_string());    let (_, answer) = channels(&db, &threads);    assert_eq!(answer.len(), THREADS);    assert!(!answer.contains_key("thread-empty") && !answer.contains_key("thread-elsewhere"));}