Cotton code
226 lines · 12.2 KB · RustRaw
//! Searching a sealed table beyond the copy, against a fake object that//! answers `/v1/blind` as the Worker does (rows holding every token, newest//! first, as stored). Synthetic keys and rows only.use std::collections::{BTreeSet, HashMap};use std::sync::Arc;use serde_json::{json, Map, Value};use super::*;use crate::seal::{DataKeyStore, HeldDataKeys};use cotton_core::seal::{blind, DataKey};const DB: &str = "db-synthetic";const TABLE: &str = "sealed_journal";fn spec() -> SealSpec {    SealSpec { clear: vec!["written_at".into()], blind: vec!["heading".into(), "body".into()], blind_exact: vec!["reference".into()], blind_bytes: Default::default() }}/// The object's side: each row as stored (sealed) and its token set, as the/// phone that sealed it sent them.struct FakeObject {    rows: Vec<(String, Map<String, Value>, BTreeSet<i64>)>,    asked: Vec<String>,}impl FakeObject {    fn get(&mut self, path: &str) -> Result<Value, String> {        self.asked.push(path.to_string());        let query: HashMap<&str, &str> = path.split_once('?').ok_or("no query")?.1.split('&').filter_map(|pair| pair.split_once('=')).collect();        assert_eq!(query.get("rows"), Some(&"1"));        assert_eq!(query.get("table"), Some(&TABLE));        let tokens: Vec<i64> = query["tok"].split(',').map(|t| t.parse().map_err(|_| format!("{t} is no token"))).collect::<Result<_, _>>()?;        let mut hits: Vec<&(String, Map<String, Value>, BTreeSet<i64>)> = self.rows.iter().filter(|(_, _, held)| tokens.iter().all(|t| held.contains(t))).collect();        hits.sort_by(|a, b| b.1["written_at"].as_str().cmp(&a.1["written_at"].as_str()));        let rows: Vec<Value> = hits.iter().map(|(id, data, _)| json!({"table": TABLE, "id": id, "data": data, "version": 1})).collect();        Ok(json!({"table": TABLE, "ids": hits.iter().map(|(id, _, _)| id.clone()).collect::<Vec<_>>(), "rows": rows}))    }}fn sealer(dk: Option<[u8; 32]>) -> Arc<Sealer> {    let keys = HeldDataKeys::new();    if let Some(bytes) = dk {        keys.hold(DB, &DataKey::from_bytes(bytes));    }    let sealer = Sealer::new(DB, keys as Arc<dyn DataKeyStore>);    // As a phone's sealer after its first pull read the object's seal keys (5d3709fae3).    sealer.learned_all();    sealer}fn row(heading: &str, body: &str, at: usize) -> Map<String, Value> {    json!({"written_at": format!("2026-10-{:02}T00:00:00.000Z", 1 + at % 28), "heading": heading, "body": body, "reference": format!("ref-{at}")}).as_object().unwrap().clone()}const VOCABULARY: [&str; 22] = [    "conference", "conferred", "conferring", "con", "cone", "market", "marketing", "Market", "go", "ox", "the", "and", "café", "cafe",    "बाज़ार", "किताब", "किताबें", "2026", "40", "pelican", "pen", "quokka",];/// A synthetic corpus, sealed by `sealer` as a phone seals it.fn corpus(sealer: &Sealer) -> (Vec<(String, Map<String, Value>)>, FakeObject) {    let mut seed = 11u64;    let mut next = || {        seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);        (seed >> 33) as usize    };    let mut words = |n: usize| (0..n).map(|_| VOCABULARY[next() % VOCABULARY.len()]).collect::<Vec<_>>().join(" ");    let mut clear = Vec::new();    let mut object = FakeObject { rows: Vec::new(), asked: Vec::new() };    for at in 0..50 {        let id = format!("row-{at:02}");        let plain = row(&words(1 + at % 3), &words(3 + at % 6), at);        let sealed = sealer.seal(TABLE, &id, &spec(), &plain, None).expect("sealed");        let tokens = sealed.blind.iter().map(|t| t.parse::<i64>().unwrap()).collect();        object.rows.push((id.clone(), sealed.data, tokens));        clear.push((id, plain));    }    (clear, object)}/// RULE (plan §4, L7): beyond the copy, a search by blind tokens answers/// exactly the rows the same search finds over the clear rows, newest first,/// and the object is asked by tokens alone: no word of the query or of a row/// is in any request.#[test]fn a_search_beyond_the_copy_equals_the_clear_search_and_asks_by_tokens_alone() {    let sealer = sealer(Some([9; 32]));    let (clear, mut object) = corpus(&sealer);    let queries = ["conference", "confer", "conf", "con", "market", "marketing", "MARK", "go", "the", "cafe", "Café", "किताब", "किता", "बाज़ार", "40", "pen", "pelican", "quokka market", "the market", "conference conferred", "x", "zebra"];    let mut some = 0;    for query in queries {        let found = search_beyond(&sealer, TABLE, &spec(), Some("written_at"), query, 1000, &|_| false, &mut |path| object.get(path)).expect("a search");        let mut want: Vec<(String, String)> = clear            .iter()            .filter(|(_, row)| blind::row_match(&spec(), row, query).is_some())            .map(|(id, row)| (row["written_at"].as_str().unwrap().to_string(), id.clone()))            .collect();        want.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));        let got: Vec<String> = found.hits.iter().map(|hit| hit.id.clone()).collect();        assert_eq!(got, want.iter().map(|(_, id)| id.clone()).collect::<Vec<_>>(), "{query:?}");        assert!(found.unopened.is_empty());        for hit in &found.hits {            let (_, plain) = clear.iter().find(|(id, _)| id == &hit.id).unwrap();            assert_eq!(&hit.row, plain, "a hit is the row opened whole");        }        some += got.len();    }    assert!(some > 0);    for path in &object.asked {        let tok = path.split("tok=").nth(1).unwrap().split('&').next().unwrap();        assert!(tok.chars().all(|c| c.is_ascii_digit() || c == ',' || c == '-'), "only tokens: {path}");        for word in VOCABULARY.iter().filter(|w| w.chars().count() > 2).chain(["ref-1"].iter()) {            assert!(!path.to_lowercase().contains(&word.to_lowercase()), "{word} in {path}");        }    }}/// RULE: a row the copy holds is its own search's; a row that does not open/// is answered by name, never dropped or blank; no key asks nothing and is a/// refusal by name.#[test]fn held_rows_are_skipped_unopened_ones_named_and_no_key_refused() {    let sealer_a = sealer(Some([9; 32]));    let (clear, mut object) = corpus(&sealer_a);    // A row sealed under another database's key: its tokens match, its blob does not open here.    let stranger = sealer(Some([1; 32]));    let plain = row("quokka", "quokka at dawn", 3);    let sealed = stranger.seal(TABLE, "stranger", &spec(), &plain, None).expect("sealed");    let mut tokens: BTreeSet<i64> = sealed.blind.iter().map(|t| t.parse().unwrap()).collect();    tokens.extend(sealer_a.query_tokens(TABLE, &spec(), "quokka").unwrap().into_iter().flat_map(|(_, toks)| toks).map(|t| t.parse::<i64>().unwrap()));    object.rows.push(("stranger".into(), sealed.data, tokens));    let quokkas: Vec<&String> = clear.iter().filter(|(_, row)| blind::row_match(&spec(), row, "quokka").is_some()).map(|(id, _)| id).collect();    assert!(quokkas.len() >= 2, "the corpus holds quokkas");    let held = quokkas[0].clone();    let found = search_beyond(&sealer_a, TABLE, &spec(), Some("written_at"), "quokka", 1000, &|id| id == held, &mut |path| object.get(path)).expect("a search");    assert!(!found.hits.iter().any(|hit| hit.id == held), "the copy's own row is its own search's");    assert_eq!(found.hits.len(), quokkas.len() - 1);    assert_eq!(found.unopened, vec![("stranger".to_string(), "seal_does_not_open".to_string())]);    let asked = object.asked.len();    let refused = search_beyond(&sealer(None), TABLE, &spec(), None, "quokka", 10, &|_| false, &mut |path| object.get(path)).expect_err("no key");    assert!(refused.starts_with("seal_key_missing"), "{refused}");    assert_eq!(object.asked.len(), asked, "nothing is asked without a key");    // A query with no word asks nothing and finds nothing.    assert_eq!(search_beyond(&sealer_a, TABLE, &spec(), None, "the a", 10, &|_| false, &mut |path| object.get(path)).expect("a search"), BlindFound::default());    assert_eq!(object.asked.len(), asked);}/// The blind index's size on 100k synthetic messages (plan §4 "Cost", L7's/// benchmark), in the Worker's own schema (`store.ts`: `blind_row`, `blind`/// WITHOUT ROWID, `blind_rid`). Ignored in the gate; run with/// `cargo test -p cotton-client --lib -- seal::search::tests::blind_index_size --ignored --nocapture`./// Words are synthetic: a 30k-word vocabulary drawn Zipf-wise (s = 1), a/// third of every message's words English stopwords, 1–24 words a message/// (mean about 12), one in ten messages with a Hindi word.#[test]#[ignore]fn blind_index_size_on_100k_synthetic_messages() {    const MESSAGES: usize = 100_000;    let dk = DataKey::from_bytes([7; 32]);    let bk = cotton_core::seal::blind_key(&dk, DB, "message").unwrap();    let mut seed = 5u64;    let mut next = move || {        seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);        seed >> 11    };    let letters: Vec<char> = "etaoinshrdlucmfwypvbgkqjxz".chars().collect();    let vocabulary: Vec<String> = (0..30_000)        .map(|_| {            let len = 2 + (next() % 5 + next() % 6) as usize;            (0..len).map(|_| letters[((next() % 26) * (next() % 26) / 26) as usize]).collect()        })        .collect();    let hindi = ["बाज़ार", "किताब", "दिल्ली", "मिलते", "कल", "नमस्ते"];    let stop = ["the", "a", "to", "and", "of", "in", "is", "it", "you", "that", "for", "on", "i", "we", "at"];    // Zipf by inverse CDF over ranks 1..=N.    let harmonic: Vec<f64> = (1..=vocabulary.len()).scan(0.0, |sum, r| { *sum += 1.0 / r as f64; Some(*sum) }).collect();    let total = *harmonic.last().unwrap();    let mut zipf = |u: f64| vocabulary[harmonic.partition_point(|h| *h < u * total).min(vocabulary.len() - 1)].as_str();    let dir = tempfile::tempdir().unwrap();    let sizes: Vec<(&str, u64, u64)> = [("words and prefixes 3-6", true), ("whole words only", false)]        .into_iter()        .map(|(name, prefixes)| {            let path = dir.path().join(format!("{prefixes}.db"));            let db = rusqlite::Connection::open(&path).unwrap();            db.execute_batch("PRAGMA page_size=4096; PRAGMA journal_mode=OFF; CREATE TABLE blind_row (rid INTEGER PRIMARY KEY, table_id TEXT NOT NULL, id TEXT NOT NULL, UNIQUE (table_id, id)); CREATE TABLE blind (tok INTEGER NOT NULL, rid INTEGER NOT NULL, PRIMARY KEY (tok, rid)) WITHOUT ROWID; CREATE INDEX blind_rid ON blind (rid); BEGIN;").unwrap();            let mut entries = 0u64;            for m in 0..MESSAGES {                let n = 1 + (next() % 12 + next() % 13) as usize;                let mut words: Vec<&str> = (0..n).map(|_| if next() % 3 == 0 { stop[(next() % stop.len() as u64) as usize] } else { zipf((next() % 1_000_000) as f64 / 1_000_000.0) }).collect();                if m % 10 == 0 {                    words.push(hindi[m / 10 % hindi.len()]);                }                let text = words.join(" ");                let tokens: BTreeSet<blind::Token> = if prefixes {                    blind::text_tokens(&bk, "body", &text)                } else {                    blind::words(&text).iter().map(|w| blind::word_token(&bk, "body", w)).collect()                };                db.execute("INSERT INTO blind_row (rid, table_id, id) VALUES (?1, 'message', ?2)", rusqlite::params![m as i64 + 1, format!("{:08x}-0000-4000-8000-{:012x}", m, m)]).unwrap();                let mut insert = db.prepare_cached("INSERT INTO blind (tok, rid) VALUES (?1, ?2)").unwrap();                for t in &tokens {                    insert.execute(rusqlite::params![t.0, m as i64 + 1]).unwrap();                }                entries += tokens.len() as u64;            }            db.execute_batch("COMMIT; VACUUM;").unwrap();            drop(db);            (name, std::fs::metadata(&path).unwrap().len(), entries)        })        .collect();    for (name, bytes, entries) in &sizes {        println!(            "{name}: {entries} entries, {:.1} tokens a message, {bytes} bytes ({:.1} MB), {:.0} B a message, {:.1} B an entry",            *entries as f64 / MESSAGES as f64,            *bytes as f64 / 1e6,            *bytes as f64 / MESSAGES as f64,            *bytes as f64 / *entries as f64        );    }    assert!(sizes[0].1 > sizes[1].1);}