Cotton code
240 lines · 8.9 KB · RustRaw
//! Receipt payload predicates run only after an indexed, bounded page is read.//! The caller keeps its transaction: a safety judgement must not mix snapshots.use crate::{    driver::{Driver, Row},    error::Result,};use rusqlite::types::Value;pub(crate) const PAGE_SIZE: usize = 64;#[derive(Clone, Copy)]pub(crate) enum Side {    Writes,    Tombstones,}pub(crate) struct Pages {    side: Side,    cursor: Option<Vec<Value>>,    done: bool,    row: Option<(String, String)>,}impl Pages {    pub(crate) fn new(side: Side) -> Self {        Self {            side,            cursor: None,            done: false,            row: None,        }    }    pub(crate) fn of_row(table: &str, id: &str) -> Self {        let mut pages = Self::new(Side::Writes);        pages.row = Some((table.to_string(), id.to_string()));        pages    }    fn params(&self) -> Vec<Value> {        if let Some((table, id)) = &self.row {            let mut args = vec![Value::Text(table.clone()), Value::Text(id.clone())];            if let Some(cursor) = &self.cursor {                args.push(cursor[2].clone());            }            args        } else {            self.cursor                .clone()                .unwrap_or_else(|| vec![Value::Text(String::new())])        }    }    pub(crate) fn sql(&self, predicate: &str) -> String {        let (table, key, bound) = match self.side {            Side::Writes => ("_writes", "tbl,row_id,hlc", "(tbl,row_id,hlc) > (?,?,?)"),            Side::Tombstones => ("_tombstones", "tbl,row_id", "(tbl,row_id) > (?,?)"),        };        let bound = if self.row.is_some() {            if self.cursor.is_some() {                "tbl = ? AND row_id = ? AND hlc > ?"            } else {                "tbl = ? AND row_id = ?"            }        } else if self.cursor.is_some() {            bound        } else {            "tbl >= ?"        };        // MATERIALIZED is essential: moving a payload predicate before LIMIT        // would inspect the whole file when there are no matching receipts.        format!("WITH page AS MATERIALIZED (SELECT * FROM {table} WHERE {bound} ORDER BY {key} LIMIT {PAGE_SIZE}) SELECT *, COALESCE(({predicate}),0) AS matches FROM page")    }    pub(crate) fn next(        &mut self,        db: &Driver,        predicate: &str,        args: &[Value],    ) -> Result<Option<Vec<Row>>> {        if self.done {            return Ok(None);        }        let mut params = self.params();        params.extend_from_slice(args);        let rows = db.all(&self.sql(predicate), &params)?;        if let Some(last) = rows.last() {            let mut cursor = vec![                last.get("tbl").unwrap().clone(),                last.get("row_id").unwrap().clone(),            ];            if matches!(self.side, Side::Writes) {                cursor.push(last.get("hlc").unwrap().clone());            }            self.cursor = Some(cursor);        }        self.done = rows.len() < PAGE_SIZE;        Ok(Some(rows))    }}#[cfg(test)]mod tests {    use super::*;    /// RULE: A take-back checks every receipt at its own row before naming receipts elsewhere; the stamp cursor must retain an empty first stamp and never cross into a neighbouring row.    #[test]    fn own_row_pages_keep_all_stamps_and_exclude_neighbours() {        let db = Driver::open_in_memory().unwrap();        db.exec(crate::schema::ddl::WRITES_TABLE).unwrap();        db.exec("WITH RECURSIVE n(x) AS (VALUES(0) UNION ALL SELECT x+1 FROM n WHERE x<129) INSERT INTO _writes(tbl,row_id,hlc) SELECT 'a','row',printf('%08d',x) FROM n; INSERT INTO _writes(tbl,row_id,hlc) VALUES ('a','row',''),('a','before',''),('a','zafter',''),('b','row','')").unwrap();        let mut pages = Pages::of_row("a", "row");        let mut stamps = Vec::new();        while let Some(rows) = pages.next(&db, "1", &[]).unwrap() {            for row in rows {                assert_eq!(row.text("tbl"), Some("a"));                assert_eq!(row.text("row_id"), Some("row"));                stamps.push(row.text("hlc").unwrap().to_string());            }        }        let expected: Vec<String> = std::iter::once(String::new())            .chain((0..130).map(|x| format!("{x:08}")))            .collect();        assert_eq!(stamps, expected);    }    /// RULE: Take-back and undo payload checks read bounded indexed pages before filtering, retaining every receipt; filtering before LIMIT can search the whole file while holding its writer.    #[test]    fn million_receipts_payload_checks_seek_bounded_pages() {        let dir = tempfile::tempdir().unwrap();        let db = Driver::open(dir.path().join("synthetic.db")).unwrap();        crate::fixtures::build_at_version(&db, crate::migrate::SCHEMA_VERSION);        db.exec("WITH RECURSIVE n(x) AS (VALUES(0) UNION ALL SELECT x+1 FROM n WHERE x<999999) INSERT INTO _writes(tbl,row_id,hlc,bytes) SELECT CASE WHEN x<500000 THEN 'a' ELSE 'b' END,printf('%08d',x/3),printf('%08d',x),CASE WHEN x%997=0 THEN NULL ELSE CAST('{\"undo\":\"synthetic-fact\",\"target\":\"synthetic-target\"}' AS BLOB) END FROM n").unwrap();        db.exec(            "INSERT INTO _tombstones(tbl,row_id,hlc,op_id,author,actor,bytes) SELECT tbl,hlc,hlc,hlc,'synthetic','synthetic',COALESCE(bytes,CAST('{}' AS BLOB)) FROM _writes",        )        .unwrap();        for (side, predicate, args, index) in [            (                Side::Writes,                crate::take_back::RELATED,                vec![                    "".into(),                    "absent".into(),                    "synthetic-target".into(),                    "synthetic-target".into(),                ],                "sqlite_autoindex__writes_2",            ),            (                Side::Writes,                crate::fact_hooks::UNDO_RECEIPT,                vec!["synthetic-fact".into()],                "sqlite_autoindex__writes_2",            ),            (                Side::Tombstones,                crate::fact_hooks::UNDO_RECEIPT,                vec!["synthetic-fact".into()],                "sqlite_autoindex__tombstones_1",            ),            (                Side::Writes,                crate::take_back::RELATED,                vec![                    "".into(),                    "absent".into(),                    "missing".into(),                    "missing".into(),                ],                "sqlite_autoindex__writes_2",            ),            (                Side::Writes,                crate::fact_hooks::UNDO_RECEIPT,                vec!["missing".into()],                "sqlite_autoindex__writes_2",            ),            (                Side::Tombstones,                crate::fact_hooks::UNDO_RECEIPT,                vec!["missing".into()],                "sqlite_autoindex__tombstones_1",            ),        ] {            let expected = if args.last().is_some_and(|arg| arg == "missing") {                0            } else {                1_000_000 - (999_999 / 997 + 1)            };            let args: Vec<Value> = args.into_iter().map(Value::Text).collect();            let mut pages = Pages::new(side);            let mut read = 0;            let mut matched = 0;            loop {                // Prove both the first-page seek and the cursor-page seek.                if read <= PAGE_SIZE {                    let mut params = pages                        .cursor                        .clone()                        .unwrap_or_else(|| vec![Value::Text(String::new())]);                    params.extend_from_slice(&args);                    let plan = db                        .all(                            &format!("EXPLAIN QUERY PLAN {}", pages.sql(predicate)),                            &params,                        )                        .unwrap();                    assert!(                        plan.iter()                            .any(|row| row.text("detail").is_some_and(|detail| detail                                .contains("SEARCH")                                && detail.contains(index))),                        "{plan:?}"                    );                    assert!(                        !plan.iter().any(|row| row                            .text("detail")                            .is_some_and(|detail| detail.contains("TEMP B-TREE"))),                        "{plan:?}"                    );                }                let Some(rows) = pages.next(&db, predicate, &args).unwrap() else {                    break;                };                assert!(rows.len() <= PAGE_SIZE);                read += rows.len();                matched += rows                    .iter()                    .filter(|row| row.int("matches") == Some(1))                    .count();            }            assert_eq!(                read, 1_000_000,                "NULL payloads and repeated row ids must not break the cursor"            );            assert_eq!(matched, expected);        }    }}