Cotton code
261 lines · 10.0 KB · RustRaw
//! Bounded current-row reads for the media index. A caller holding a writer//! releases it between `next` calls; each page is read and inserted together.use super::*;pub const PAGE_SIZE: i64 = 64;pub const RECEIPTS_PAGE: &str = "SELECT row_id, hlc, bytes FROM _writes WHERE tbl = ?1 AND (row_id, hlc) > (?2, ?3) ORDER BY row_id, hlc LIMIT ?4";const FIRST_RECEIPTS_PAGE: &str =    "SELECT row_id, hlc, bytes FROM _writes WHERE tbl = ?1 ORDER BY row_id, hlc LIMIT ?2";#[derive(Default)]pub struct NameSweep {    tables: Vec<&'static str>,    table: usize,    receipts: bool,    cursor: Option<(String, String)>,    started: bool,}impl NameSweep {    /// One page of names from current rows or receipts, with no retained lock    /// or transaction. Concurrent writes name their own keys through the hook.    fn next(&mut self, db: &Driver) -> Result<Option<BTreeSet<Name>>> {        self.next_matching(db, None, &|_| true)    }    /// Read and insert one current page in a transaction. The caller releases    /// its writer lock after this returns, before asking for the next page.    pub fn rebuild_next(&mut self, db: &Driver) -> Result<Option<usize>> {        db.transaction(|db| {            self.next(db)?                .map(|names| insert_names(db, &names))                .transpose()        })    }    pub(super) fn next_matching(        &mut self,        db: &Driver,        needle: Option<&str>,        wanted: &dyn Fn(&str) -> bool,    ) -> Result<Option<BTreeSet<Name>>> {        if !self.started {            self.tables = MEDIA_KEY_HOLDERS                .iter()                .map(|(table, _, _)| *table)                .chain(DERIVED_MEDIA_KEYS.iter().map(|(table, _, _)| *table))                .collect();            self.tables.sort_unstable();            self.tables.dedup();            self.started = true;        }        let Some(&table) = self.tables.get(self.table) else {            return Ok(None);        };        let Some(spec) = spec_for(table) else {            self.table += 1;            return Ok(Some(BTreeSet::new()));        };        let file = file_id(db)?;        let mut names = BTreeSet::new();        let rows = if self.receipts {            if let Some((row, hlc)) = &self.cursor {                db.all(                    RECEIPTS_PAGE,                    &[                        table.to_string().into(),                        row.clone().into(),                        hlc.clone().into(),                        PAGE_SIZE.into(),                    ],                )?            } else {                db.all(                    FIRST_RECEIPTS_PAGE,                    &[table.to_string().into(), PAGE_SIZE.into()],                )?            }        } else {            let columns: Vec<String> = key_columns(table)                .iter()                .map(|column| format!("\"{column}\""))                .collect();            let filter = if self.cursor.is_some() {                format!(" WHERE \"{}\" > ?1", spec.pk)            } else {                String::new()            };            let sql = format!("SELECT \"{}\" AS row_id, {} FROM {table}{filter} ORDER BY \"{}\" LIMIT {PAGE_SIZE}", spec.pk, columns.join(", "), spec.pk);            let params = self                .cursor                .as_ref()                .map(|(row, _)| vec![row.clone().into()])                .unwrap_or_default();            db.all(&sql, &params)?        };        for row in &rows {            let id = row.text("row_id").unwrap_or_default();            if self.receipts {                // Advance on every fetched receipt, including NULL bytes and                // non-matching needles. Filtering SQL before LIMIT could scan                // millions of receipts to produce an empty page.                self.cursor = Some((                    id.to_string(),                    row.text("hlc").unwrap_or_default().to_string(),                ));                let bytes = match row.get("bytes") {                    Some(SqlValue::Blob(bytes)) => bytes.as_slice(),                    Some(SqlValue::Text(text)) => text.as_bytes(),                    _ => continue,                };                if let Some(needle) =                    needle.filter(|needle| !needle.is_empty() && survives_json_text(needle))                {                    let in_id = DERIVED_MEDIA_KEYS.iter().any(|(t, _, _)| *t == table)                        && needle.contains(id);                    if !in_id                        && !bytes                            .windows(needle.len().max(1))                            .any(|part| part == needle.as_bytes())                    {                        continue;                    }                }                let receipt = crate::canonical::decode(bytes)?;                if receipt.kind == Kind::Retract {                    continue;                }                if release_column(table).is_some() {                    let fields = match present_fields(db, table, id)? {                        Some(fields) => fields,                        None => crate::receipts::dormant_fields(db, table, id)?,                    };                    if is_released(table, |column| fields.get(column)) {                        continue;                    }                }                for key in keys_of_row(file.as_ref(), table, id, |column| {                    receipt.fields.get(column)                }) {                    if wanted(&key) {                        names.insert((key, table.to_string(), id.to_string()));                    }                }            } else {                self.cursor = Some((id.to_string(), String::new()));                let fields: BTreeMap<String, JsonValue> = key_columns(table)                    .iter()                    .filter_map(|column| {                        row.text(column)                            .map(|text| (column.to_string(), JsonValue::String(text.to_string())))                    })                    .collect();                for key in keys_of_row(file.as_ref(), table, id, |column| fields.get(column)) {                    if wanted(&key) {                        names.insert((key, table.to_string(), id.to_string()));                    }                }            }        }        if rows.len() < PAGE_SIZE as usize {            if self.receipts {                self.table += 1;            }            self.receipts = !self.receipts;            self.cursor = None;        }        Ok(Some(names))    }}#[cfg(test)]mod tests {    use super::*;    /// RULE: A media rebuild pages the receipt primary-key index without sorting the archive; its row-and-stamp cursor keeps every receipt across page boundaries, regardless of scheduler timing.    #[test]    fn million_receipts_rebuild_in_indexed_writer_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);        crate::meta::seed_meta(            &db,            &crate::meta::Meta {                workspace_id: crate::fixtures::WORKSPACE.into(),                owner_id: "synthetic-owner".into(),                device_id: "synthetic-device".into(),                last_server_seq: 0,                last_hlc: None,            },            crate::migrate::SCHEMA_VERSION,        )        .unwrap();        let receipt = Receipt {            table: "cotton_photos".into(),            row_id: "synthetic-row".into(),            kind: Kind::Change,            stamp: "0001759480000000:000:synthetic".into(),            author: "synthetic".into(),            actor: "synthetic".into(),            schema: crate::migrate::SCHEMA_VERSION,            fields: BTreeMap::from([(                "key".into(),                JsonValue::String(format!(                    "{}/photos/synthetic-row-synthetic-stamp.jpg",                    crate::fixtures::WORKSPACE                )),            )]),            restamps: None,            erase: None,            undo: None,        };        let bytes = String::from_utf8(crate::canonical::encode(&receipt).unwrap()).unwrap();        db.run("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 'cotton_photos',printf('%08d',x/3),printf('%08d',x), \            CAST(replace(replace(?1,'synthetic-row',printf('%08d',x/3)),'synthetic-stamp',printf('%08d',x)) AS BLOB) FROM n", &[bytes.into()]).unwrap();        for (sql, params) in [            (                FIRST_RECEIPTS_PAGE,                vec!["cotton_photos".to_string().into(), PAGE_SIZE.into()],            ),            (                RECEIPTS_PAGE,                vec![                    "cotton_photos".to_string().into(),                    "00000100".to_string().into(),                    "00000300".to_string().into(),                    PAGE_SIZE.into(),                ],            ),        ] {            let plan = db                .all(&format!("EXPLAIN QUERY PLAN {sql}"), &params)                .unwrap();            assert!(                plan.iter()                    .any(|row| row.text("detail").is_some_and(|text| text                        .contains("SEARCH _writes USING INDEX sqlite_autoindex__writes_2"))),                "{plan:?}"            );            assert!(                !plan.iter().any(|row| row                    .text("detail")                    .is_some_and(|text| text.contains("TEMP B-TREE"))),                "{plan:?}"            );        }        let mut sweep = NameSweep::default();        let mut added = 0;        loop {            let page = sweep.rebuild_next(&db).unwrap();            match page {                Some(count) => added += count,                None => break,            }        }        assert_eq!(            added, 1000000,            "no row was skipped across receipt page boundaries"        );    }}