//! Deleting a row does not cost the whole search index. //! //! The indexes were STANDALONE until version 3: each stored its own copy of the //! text beside an `UNINDEXED` `row_id` holding the source row's TEXT id. An //! FTS5 table has no index but its own rowid, so the only thing a delete //! trigger could say was `DELETE FROM fts_x WHERE row_id = old.id` — a read of //! the whole index, for every row deleted. Measured on this crate's own SQLite //! that is linear in the index: //! //! | rows | standalone | external-content | //! |--------|-----------:|-----------------:| //! | 5,000 | 6.82 ms | 0.13 ms | //! | 20,000 | 20.62 ms | 0.28 ms | //! | 80,000 | 73.84 ms | 0.51 ms | //! //! Version 3 made every index external-content, so a delete is a rowid seek. //! //! This guard is a CLASS detector, not a benchmark. A wall-clock ceiling on a //! shared machine would be flaky, and a flaky guard is a guard people learn to //! ignore — so what is asserted is the SHAPE of the curve: the per-row cost of //! deleting from a large index is not proportional to the index. A regression //! to the old shape makes the ratio grow with the row count; holding it under a //! generous ceiling catches that while leaving room for a machine under load. //! //! The sizes are the smallest pair that still separates the two classes. The //! cost of this test is SEEDING, not deleting — a 50,000-row fixture took //! twenty minutes in a debug build — and a guard slow enough that somebody //! skips it is not a guard. use std::time::Instant; use cotton_store::create::create_workspace; use cotton_store::meta::Meta; use cotton_store::search::search_all; use cotton_store::Driver; use rusqlite::types::Value; const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111"; const SMALL: usize = 1_000; const LARGE: usize = 20_000; const DELETES: usize = 100; /// Linear cost would put this at 20x (`LARGE / SMALL`). A rowid seek puts it at /// about 1. The ceiling is deliberately far from both: it has to separate two /// classes, not measure one. const CEILING: f64 = 6.0; const WORDS: [&str; 8] = [ "lorem", "ipsum", "dolor", "veniam", "culpa", "irure", "cillum", "proident", ]; fn meta() -> Meta { Meta { workspace_id: WORKSPACE.to_string(), owner_id: "owner-1".to_string(), device_id: "device:01J0000000000000000000000A".to_string(), last_server_seq: 0, last_hlc: None, } } /// A file with `rows` indexed notes in it. Synthetic, seeded, nothing real. fn seeded(rows: usize) -> Driver { let db = Driver::open_in_memory().expect("opens"); create_workspace(&db, &meta()).expect("creates"); db.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)", &[ Value::Text(WORKSPACE.to_string()), Value::Text("A workspace".to_string()), Value::Text("owner-1".to_string()), Value::Text("2026-09-11T09:00:00.000Z".to_string()), ], ) .expect("the workspace row"); let mut seed = 7u64; db.transaction(|db| { for i in 0..rows { let mut body = String::new(); for _ in 0..10 { seed = seed .wrapping_mul(6364136223846793005) .wrapping_add(1442695040888963407); body.push_str(WORDS[(seed >> 33) as usize % WORDS.len()]); body.push(' '); } body.push_str(&format!("tok{i}")); db.run( "INSERT INTO cotton_notes (id, workspace_id, title, body, created_at, updated_at) \ VALUES (?,?,?,?,?,?)", &[ Value::Text(format!("note-{i}")), Value::Text(WORKSPACE.to_string()), Value::Text(format!("Note {i}")), Value::Text(body), Value::Text("2026-09-11T09:00:00.000Z".to_string()), Value::Text("2026-09-11T09:00:00.000Z".to_string()), ], )?; } Ok(()) }) .expect("seeded"); db } /// Milliseconds per deleted row, at this index size. fn cost_per_delete(rows: usize) -> f64 { let db = seeded(rows); // Spread across the index rather than clustered, so a run cannot be fast // for having touched one page. let victims: Vec = (0..DELETES) .map(|k| format!("note-{}", (k * 7919) % rows)) .collect(); let started = Instant::now(); db.transaction(|db| { for victim in &victims { db.run( "DELETE FROM cotton_notes WHERE id = ?", &[Value::Text(victim.clone())], )?; } Ok(()) }) .expect("deleted"); started.elapsed().as_secs_f64() * 1000.0 / DELETES as f64 } /// RULE: Deleting a row costs a single seek in the search index, not a scan of all of it. #[test] fn deleting_a_row_does_not_cost_the_whole_index() { let small = cost_per_delete(SMALL); let large = cost_per_delete(LARGE); let growth = large / small.max(f64::MIN_POSITIVE); println!( "COST delete: {SMALL} rows {small:.3}ms, {LARGE} rows {large:.3}ms, \ growth {growth:.1}x over a {}x bigger index", LARGE / SMALL ); assert!( growth < CEILING, "a delete costs {growth:.1}x more on a {}x bigger index, which is the shape of a scan of \ the whole index per row — the indexes are external-content so a delete should be a rowid \ seek. Check that no trigger says `DELETE FROM fts_…` (see tests/fts_declared.rs).", LARGE / SMALL ); } /// RULE: Search still answers correctly after rows are deleted. #[test] fn the_index_still_answers_after_the_deletes() { // The other half, and the reason speed alone is not the assertion: an index // that answered nothing would be very fast. let db = seeded(SMALL); let hit = search_all(&db, "tok234", None, Some(10)).expect("searches"); assert_eq!( hit.iter().map(|h| h.row_id.as_str()).collect::>(), vec!["note-234"], "the index does not find a row that is there" ); db.run( "DELETE FROM cotton_notes WHERE id = ?", &[Value::Text("note-234".to_string())], ) .expect("deletes"); assert!( search_all(&db, "tok234", None, Some(10)) .expect("searches") .is_empty(), "the index still finds a row that was deleted — the delete trigger did not retract it" ); // And a neighbour is untouched: a retract that took the wrong rowid, or too // many, would show up here rather than in the count. assert_eq!( search_all(&db, "tok235", None, Some(10)) .expect("searches") .iter() .map(|h| h.row_id.as_str()) .collect::>(), vec!["note-235"], "deleting one row disturbed another row's index entry" ); }