276 lines · 10.3 KB · RustRaw
//! The normalized lookup is a projection of immutable canonical receipts.use super::*;use serde_json::json;fn put(db: &Driver, table: &str, id: &str, fields: JsonValue, ms: i64) -> CottonOp { let receipt = Receipt { table: table.into(), row_id: id.into(), kind: Kind::Create, stamp: format!("{ms:013}:0000:device:owner-test"), author: "device:owner-test".into(), actor: crate::fixtures::fixture_actor().to_wire(), schema: crate::schema::ddl::SCHEMA_VERSION, restamps: None, erase: None, undo: None, fields: fields .as_object() .unwrap() .iter() .map(|(k, v)| (k.clone(), v.clone())) .collect(), }; let op = crate::wire::from_receipt(format!("owner-test-{table}-{id}-{ms}"), &receipt).unwrap(); store(db, &op, &receipt, false).unwrap(); op}pub(super) fn no_orphans(db: &Driver) { assert!(db.get("SELECT 1 FROM _writes_owners o LEFT JOIN _writes w ON w.op_id = o.receipt WHERE w.op_id IS NULL LIMIT 1", &[]).unwrap().is_none());}/// RULE: Normalized receipt owners find exactly the canonical field's rows, including simultaneous and coincident parents, so dormant reassembly and erasure never lose or misidentify a child.#[test]fn owner_lookups_match_canonical_expressions_for_every_reference() { let db = crate::test_support::seeded_file("device:owner-test"); let mut by_table = BTreeMap::<&str, BTreeSet<&str>>::new(); for (child, column, _) in crate::schema::table_specs::OWNING_REFS .iter() .chain(crate::erase::OWNED_BY.iter()) { by_table.entry(child).or_default().insert(column); } for (table, columns) in by_table { let fields: serde_json::Map<_, _> = columns .iter() .map(|column| (column.to_string(), json!(format!("owner-{column}")))) .collect(); put(&db, table, "distinct", JsonValue::Object(fields), 100); let fields: serde_json::Map<_, _> = columns .iter() .map(|column| (column.to_string(), json!("shared-owner"))) .collect(); put(&db, table, "coincident", JsonValue::Object(fields), 101); for (n, column) in columns.iter().enumerate() { put( &db, table, &format!("only-{column}"), json!({*column:"single-parent"}), 200 + n as i64, ); } put(&db, table, "absent", json!({}), 300); for column in columns { for owner in [ format!("owner-{column}"), "shared-owner".into(), "single-parent".into(), "missing".into(), ] { let old = format!("SELECT row_id FROM _writes WHERE tbl = '{table}' AND json_extract(CAST(bytes AS TEXT), '$.fields.\"{column}\"') = ? ORDER BY row_id"); let new = format!( "{} ORDER BY w.row_id", owners_naming_sql(table, column, "= ?") ); let key = [SqlValue::Text(owner)]; let ids = |sql: &str| { db.all(sql, &key) .unwrap() .iter() .map(|r| r.text("row_id").unwrap().to_string()) .collect::<Vec<_>>() }; assert_eq!(ids(&new), ids(&old), "{table}.{column}"); let plan = db .all(&format!("EXPLAIN QUERY PLAN {new}"), &key) .unwrap() .iter() .filter_map(|r| r.text("detail")) .collect::<Vec<_>>() .join(" | "); assert!( plan.contains("idx_writes_owners"), "{table}.{column}: {plan}" ); assert!( !plan.contains("SCAN o") && !plan.contains("SCAN w"), "{plan}" ); } } } no_orphans(&db);}/// RULE: Owner references are receipt-local and disappear atomically with every deleted receipt, so keep, erase, restamp and snapshot deletions cannot leave a false owning relationship behind.#[test]fn references_cascade_with_receipt_deletion_and_keep_only() { let db = crate::test_support::seeded_file("device:owner-test"); let old = put( &db, "cotton_msg_reactions", "row", json!({"message_id":"message","thread_id":"thread"}), 100, ); let kept = put( &db, "cotton_msg_reactions", "row", json!({"message_id":"message-2","thread_id":"thread-2"}), 101, ); assert_eq!( db.get( "SELECT COUNT(*) AS n FROM _writes_owners WHERE receipt = ?", &[old.op_id.clone().into()] ) .unwrap() .unwrap() .int("n"), Some(2) ); keep_only( &db, "cotton_msg_reactions", "row", &[kept.op_id.clone()].into_iter().collect(), ) .unwrap(); assert!(db .get( "SELECT 1 FROM _writes_owners WHERE receipt = ?", &[old.op_id.into()] ) .unwrap() .is_none()); assert!(db .get( "SELECT 1 FROM _writes_owners WHERE receipt = ?", &[kept.op_id.clone().into()] ) .unwrap() .is_some()); db.run( "DELETE FROM _writes WHERE tbl = 'cotton_msg_reactions' AND row_id = 'row'", &[], ) .unwrap(); assert!(db .get( "SELECT 1 FROM _writes_owners WHERE receipt = ?", &[kept.op_id.into()] ) .unwrap() .is_none()); assert!(db.run("INSERT INTO _writes_owners (receipt,tbl,owner) VALUES ('absent','cotton_msg_reactions','thread')",&[]).is_err()); no_orphans(&db);}/// RULE: Erasing an owner removes dormant descendants' receipt projections too, so deleted records cannot leave owning relationships that later resurrect a child.#[test]fn erase_removes_a_dormant_childs_owner_references() { let db = crate::test_support::seeded_file("device:owner-test"); let child = put( &db, "cotton_msg_reactions", "reaction", json!({"message_id":"message","thread_id":"thread"}), 100, ); let mut receipt = canonical::decode(child.receipt.as_bytes()).unwrap(); receipt.table = "cotton_msg_threads".into(); receipt.row_id = "thread".into(); receipt.kind = Kind::Retract; receipt.stamp = "0000000000200:0000:device:owner-test".into(); receipt.fields.clear(); receipt.erase = Some("invented erase".into()); let op = crate::wire::from_receipt("erase-owner-test".into(), &receipt).unwrap(); crate::erase::apply(&db, &op, &receipt, &crate::erase::Owned::default()).unwrap(); assert!(db .get( "SELECT 1 FROM _writes WHERE op_id=?", &[child.op_id.clone().into()] ) .unwrap() .is_none()); assert!(db .get( "SELECT 1 FROM _writes_owners WHERE receipt=?", &[child.op_id.into()] ) .unwrap() .is_none()); no_orphans(&db);}/// RULE: Receipt owner projections are device-local protocol state and never enter an author's sync stream, because peers build their own projection from canonical receipts.#[test]fn owner_projection_is_not_a_synced_table() { let db = crate::test_support::seeded_file("device:owner-test"); assert!(!crate::changes::known_tables_clause(&db) .unwrap() .contains("'_writes_owners'")); assert!(crate::meta::SYSTEM_TABLE_NAMES.contains(&"_writes_owners"));}/// RULE: Storing a receipt and its owner projection is atomic, so a failed owner insert cannot leave a receipt that owning-parent lookups silently miss.#[test]fn a_failed_owner_insert_rolls_back_the_receipt_and_partial_projection() { let db = crate::test_support::seeded_file("device:owner-test"); db.exec("CREATE TRIGGER refuse_second_owner BEFORE INSERT ON _writes_owners WHEN NEW.owner = 'thread' BEGIN SELECT RAISE(ABORT, 'synthetic refusal'); END").unwrap(); let receipt = Receipt { table: "cotton_msg_reactions".into(), row_id: "failed".into(), kind: Kind::Create, stamp: "0000000000300:0000:device:owner-test".into(), author: "device:owner-test".into(), actor: crate::fixtures::fixture_actor().to_wire(), schema: crate::schema::ddl::SCHEMA_VERSION, restamps: None, erase: None, undo: None, fields: [ ("message_id".into(), json!("message")), ("thread_id".into(), json!("thread")), ] .into_iter() .collect(), }; let op = crate::wire::from_receipt("failed-owner-op".into(), &receipt).unwrap(); assert!(store(&db, &op, &receipt, false).is_err()); assert!(db .get("SELECT 1 FROM _writes WHERE op_id='failed-owner-op'", &[]) .unwrap() .is_none()); assert!(db .get( "SELECT 1 FROM _writes_owners WHERE receipt='failed-owner-op'", &[] ) .unwrap() .is_none()); no_orphans(&db);}/// RULE: The owner projection rebuild is atomic so no ownership query sees a partial projection; its receipt reads must cost only the owning tables' rows, never unrelated receipts.#[test]fn atomic_owner_rebuild_seeks_only_owning_tables() { let db = crate::test_support::seeded_file("device:owner-test"); for n in 0..130 { put(&db, "cotton_emails", "repeated", json!({"thread_id":"parent"}), n); } let before = db.steps(); rebuild_owners(&db).unwrap(); let small = db.steps() - before; let expected = db.all("SELECT * FROM _writes_owners ORDER BY receipt,tbl,owner", &[]).unwrap(); 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) SELECT 'synthetic_unowned',printf('%08d',x),'' FROM n").unwrap(); let before = db.steps(); rebuild_owners(&db).unwrap(); let large = db.steps() - before; assert!(large <= small + small/4, "unrelated receipts grew the rebuild from {small} to {large} steps"); assert_eq!(db.all("SELECT * FROM _writes_owners ORDER BY receipt,tbl,owner", &[]).unwrap(), expected); assert_eq!(expected.len(), 130);}