//! The DK's mint, open and hold, and the served row's open-or-park, without a //! transport. Synthetic keys only. use std::sync::Arc; use serde_json::{json, Map, Value}; use super::*; use cotton_core::seal::DataKey; use cotton_core::vault::Vmk; const DB: &str = "db-synthetic"; /// RULE (§2.1): the DK is minted under the VMK once, opens again with the /// VMK of the version its row names, and a VMK of another version is a /// refusal by name. #[test] fn the_data_key_mints_under_the_vault_key_and_opens_only_with_its_version() { let vmk = Vmk::from_bytes([3; 32]); let (dk, row) = mint_data_key(&vmk, 2, "2026-11-11T10:00:00.000Z").expect("a minted key"); assert!(row["dk_enc"].as_str().is_some_and(|text| !text.is_empty())); assert_eq!(row["vmk_version"], 2); assert_eq!(open_data_key(&vmk, 2, &row).expect("it opens").expose(), dk.expose()); assert_eq!(open_data_key(&vmk, 3, &row).expect_err("another version").code(), "seal_key_missing"); assert_eq!(open_data_key(&Vmk::from_bytes([4; 32]), 2, &row).expect_err("another key").code(), "seal_does_not_open"); } /// RULE: a held key is lent per database, forgotten on request, and its /// debug form names databases, never a key. #[test] fn held_keys_are_per_database_and_never_printed() { let keys = HeldDataKeys::new(); keys.hold(DB, &DataKey::from_bytes([5; 32])); assert!(keys.data_key("other").expect("a read").is_none()); assert_eq!(keys.data_key(DB).expect("a read").expect("held").expose(), &[5; 32]); assert!(!format!("{keys:?}").contains("5, 5"), "no key in the debug form"); assert!(keys.forget(DB)); assert!(keys.data_key(DB).expect("a read").is_none()); let sealer = Sealer::new(DB, keys as Arc); assert!(!sealer.has_key()); } /// RULE: a served row of a sealed table opens, or parks with its code; an /// open row reads as it stands and is noted for the sweep; a row of an open /// table is not the sealer's. #[test] fn a_served_row_opens_or_parks_by_name() { let spec = cotton_core::definitions::seal::SealSpec { clear: vec!["day".into()], blind: Vec::new(), blind_exact: Vec::new(), blind_bytes: Default::default() }; let keys = HeldDataKeys::new(); let dk = DataKey::from_bytes([6; 32]); let sealer = Sealer::new(DB, Arc::clone(&keys) as Arc); let mut plain = Map::new(); plain.insert("day".into(), json!("2026-11-11")); plain.insert("text".into(), json!("synthetic")); let stored = cotton_core::seal::seal_row(&dk, DB, "jot", "j-1", 1, &spec, &plain, None).expect("sealed"); let row = json!({"table": "jot", "id": "j-1", "version": 4, "data": stored}); let (folds, note) = unseal(Some(&sealer), Some(&spec), &row, "now").expect("the sealer's"); assert!(folds.is_none()); assert!(matches!(note, Note::Parked { ref code, .. } if code == "seal_key_missing")); keys.hold(DB, &dk); let (folds, note) = unseal(Some(&sealer), Some(&spec), &row, "now").expect("the sealer's"); assert_eq!(folds.expect("it folds")["data"], json!({"day": "2026-11-11", "text": "synthetic"})); assert!(matches!(note, Note::Sealed { seal_v: 1, version: 4, .. })); let open = json!({"table": "jot", "id": "j-2", "version": 5, "data": {"day": "2026-11-12", "text": "open"}}); let (folds, note) = unseal(Some(&sealer), Some(&spec), &open, "now").expect("the sealer's"); assert_eq!(folds, Some(open.clone())); assert_eq!(note, Note::Open { table: "jot".into(), id: "j-2".into(), version: 5 }); assert!(unseal(Some(&sealer), None, &open, "now").is_none(), "an open table's row is not the sealer's"); let gone = json!({"table": "jot", "id": "j-1", "version": 6, "deleted": true}); assert!(matches!(unseal(Some(&sealer), Some(&spec), &gone, "now"), Some((Some(_), Note::Gone { .. })))); } /// RULE: the notes land beside the copy, a later word of a row clears its /// park, and a version only moves forward. #[test] fn the_notes_land_beside_the_copy_and_a_later_word_clears_a_park() { let db = rusqlite::Connection::open_in_memory().expect("a file"); let parked_row = json!({"table": "jot", "id": "j-1"}); write_notes(&db, &[Note::Parked { table: "jot".into(), id: "j-1".into(), code: "seal_does_not_open".into(), reason: "r".into(), row: parked_row.clone(), at: "now".into() }]).expect("written"); assert_eq!(parked(&db).expect("read")[0].row, parked_row); write_notes(&db, &[Note::Sealed { table: "jot".into(), id: "j-1".into(), dek_enc: "d1:x".into(), seal_v: 2, version: 7 }]).expect("written"); assert!(parked(&db).expect("read").is_empty()); assert_eq!(held_wrap(&db, "jot", "j-1").expect("read"), Some(("d1:x".into(), 2))); write_notes(&db, &[Note::Key { id: "v:jot".into(), data: json!({"v": 2}).as_object().cloned().unwrap_or_default() }]).expect("written"); let sealer = Sealer::new(DB, HeldDataKeys::new() as Arc); for (id, data) in kept_keys(&db).expect("read") { sealer.learn(&id, &data); } assert_eq!(sealer.version("jot"), 2); sealer.learn("v:jot", json!({"v": 1}).as_object().expect("an object")); assert_eq!(sealer.version("jot"), 2, "never backwards"); assert_eq!(sealer.version("other"), 1); let _: Value = sealer.advance("jot"); assert_eq!(sealer.version("jot"), 3); // A table the object holds no version row of yet: the first advance // makes `v:`, every later one updates it. let first = sealer.advance("other"); assert_eq!(first, json!({"act": "create", "args": {"table": "seal_key", "id": "v:other", "data": {"v": 2}}})); assert_eq!(sealer.advance("other")["act"], "update"); assert_eq!(sealer.version("other"), 3); } /// RULE: a sealing refusal's code in words marks them as the core's own (never said on a screen); the /// seal_key table's name, a word that only contains `seal_`, and plain words do not. #[test] fn words_naming_a_sealing_refusal_are_told_apart() { for core in ["seal_key_missing: no key for the data key of db (this device holds none yet)", "this phone's copy could not be sent (seal_does_not_open)"] { assert!(names_a_seal_refusal(core), "{core}"); } for plain in ["seal_key: a call of 3 rows got no answer in 30 s (timeout)", "music_album, song: a call of 50 rows was refused", "unseal_this is not one", "Backing up… 0 of 3 rows"] { assert!(!names_a_seal_refusal(plain), "{plain}"); } } /// MEASURE (ignored; FIRST SYNC FAST): 5,000 parked notes of about 4 KB, as a first pull before the key writes them, /// kept the way write_notes keeps them, against the same statement parsed again each row. #[test] #[ignore] fn measure_parking_a_first_pull() { let rows: Vec = (0..5_000) .map(|i| Note::Parked { table: "email".into(), id: format!("m-{i:05}"), code: SEAL_KEY_MISSING.into(), reason: "no key yet".into(), row: serde_json::json!({ "data": { "sealed_enc": "x".repeat(4_000) } }), at: "2026-11-26T10:00:00Z".into() }) .collect(); let open = || { let db = rusqlite::Connection::open_in_memory().expect("a file"); db.execute_batch(STATE_DDL).expect("state"); write_notes(&db, &[]).expect("a new copy's parks' keys"); db }; let db = open(); let t = std::time::Instant::now(); write_notes(&db, &rows).expect("kept"); let cached = t.elapsed(); let db = open(); let t = std::time::Instant::now(); db.execute_batch("SAVEPOINT s").expect("savepoint"); for note in &rows { if let Note::Parked { table, id, code, reason, row, at } = note { db.execute( "INSERT INTO _seal_parked (tbl, row_id, code, reason, row, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT (tbl, row_id) DO UPDATE SET code = excluded.code, reason = excluded.reason, row = excluded.row, at = excluded.at", rusqlite::params![table, id, code, reason, row.to_string(), at], ) .expect("kept"); } } db.execute_batch("RELEASE s").expect("release"); let parsed = t.elapsed(); println!("PARKING 5,000 notes: cached {:.0} ms ({:.3} ms a row), parsed each row {:.0} ms ({:.3} ms a row)", cached.as_secs_f64() * 1e3, cached.as_secs_f64() * 1e3 / 5e3, parsed.as_secs_f64() * 1e3, parsed.as_secs_f64() * 1e3 / 5e3); } /// MEASURE (ignored; FIRST SYNC 5 REVIEW): one 2,000-row batch chosen from 280,000 parks, as at his size (210,000 /// mails and 70,000 conversations parked before the key, a fifth tried), off the indexes, against the old one-query /// order that looked each park's table up in the kit list. #[test] #[ignore] fn measure_choosing_a_batch_at_his_size() { let db = rusqlite::Connection::open_in_memory().expect("a file"); db.execute_batch(STATE_DDL).expect("state"); write_notes(&db, &[]).expect("the parks' keys"); db.execute_batch( "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 280000) INSERT INTO _seal_parked (tbl, row_id, code, reason, row, at) SELECT CASE WHEN i % 4 = 0 THEN 'email_thread' ELSE 'email' END, 'r-' || i, 'seal_key_missing', 'no key yet', '{\"data\":{\"sealed_enc\":\"' || hex(randomblob(1500)) || '\"}}', CASE WHEN i % 5 = 0 THEN printf('~%020d', i % 7 + 1) ELSE printf('2026-11-26T%02d:%02d:00Z', (i / 3600) % 24, (i / 60) % 60) END FROM n", ) .expect("280,000 parks"); let late = ["email_thread".to_string(), "email".to_string()]; let first = ["email_thread".to_string(), "email".to_string()]; let t = std::time::Instant::now(); let chosen = parked_next_in(&db, &late, &first, 2_000).expect("a batch"); let indexed = t.elapsed(); assert_eq!(chosen.len(), 2_000); assert!(chosen.iter().take(10).all(|r| r.table == "email_thread" && !r.tried()), "parents first among the untried"); let t = std::time::Instant::now(); let old: Vec<(String, String)> = db .prepare( "SELECT tbl, row_id FROM _seal_parked ORDER BY at >= '~', (at < '~' AND tbl IN (SELECT value FROM json_each(?1))), CASE WHEN at < '~' THEN coalesce((SELECT key FROM json_each(?3) WHERE value = tbl), 1000000) END, at, tbl, row_id LIMIT ?2", ) .expect("the old order") .query_map(rusqlite::params![serde_json::to_string(&late).unwrap(), 2_000, serde_json::to_string(&first).unwrap()], |row| Ok((row.get(0)?, row.get(1)?))) .expect("rows") .collect::>() .expect("rows"); let one_query = t.elapsed(); assert_eq!(old.len(), 2_000); println!("CHOOSING a batch of 2,000 from 280,000 parks: off the parks' keys {:.1} ms (keys and rows), the old one query {:.1} ms (keys alone)", indexed.as_secs_f64() * 1e3, one_query.as_secs_f64() * 1e3); } /// MEASURE (ignored; FIRST SYNC 6 REVIEW (1)): the indexes FIRST SYNC 5 and 6 add to `_seal_parked`, built by the /// first note write over 280,000 parks the old code made (about 5 KB a row, `at` stored after the row): each index's /// time on a file on this disk, and a build cut off half way (the index is not there, the file is whole). #[test] #[ignore] fn measure_the_new_park_indexes_over_old_parks() { let dir = tempfile::tempdir_in(std::env::var("COTTON_MEASURE_DIR").unwrap_or_else(|_| std::env::temp_dir().to_string_lossy().into())).expect("a folder"); let path = dir.path().join("replica.db"); { let db = rusqlite::Connection::open(&path).expect("a file"); db.execute_batch( "PRAGMA journal_mode = WAL; CREATE TABLE _seal (tbl TEXT NOT NULL, row_id TEXT NOT NULL, sealed INTEGER NOT NULL, dek_enc TEXT, seal_v INTEGER, version INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID; CREATE TABLE _seal_parked (tbl TEXT NOT NULL, row_id TEXT NOT NULL, code TEXT NOT NULL, reason TEXT NOT NULL, row TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID; BEGIN; WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 280000) INSERT INTO _seal_parked SELECT CASE WHEN i % 4 = 0 THEN 'email_thread' ELSE 'email' END, printf('r-%07d', i), 'seal_key_missing', 'no key yet', '{\"data\":{\"sealed_enc\":\"' || hex(randomblob(2500)) || '\"}}', printf('2026-11-26T%02d:%02d:%02dZ', (i / 3600) % 24, (i / 60) % 60, i % 60) FROM n; COMMIT;", ) .expect("280,000 old parks"); } let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) + std::fs::metadata(path.with_extension("db-wal")).map(|m| m.len()).unwrap_or(0); let mut db = rusqlite::Connection::open(&path).expect("the file"); // A build cut off a second in: nothing of the index stays, and the file reads whole. let began = std::time::Instant::now(); db.progress_handler(10_000, Some(move || began.elapsed() > std::time::Duration::from_secs(1))); let cut = db.execute_batch("CREATE INDEX IF NOT EXISTS _seal_parked_tbl_at ON _seal_parked (tbl, at)"); db.progress_handler(0, None:: bool>); let held: i64 = db.query_row("SELECT count(*) FROM sqlite_master WHERE name = '_seal_parked_tbl_at'", [], |row| row.get(0)).expect("a read"); let whole: String = db.query_row("PRAGMA quick_check(1)", [], |row| row.get(0)).expect("a check"); println!("PARK INDEXES over 280,000 old parks ({} MB): a build cut off at 1 s -> {:?}, index there: {held}, file: {whole}", bytes / 1_000_000, cut.err().map(|e| e.to_string())); for (name, sql) in [ ("_seal_parked_at (at)", "CREATE INDEX IF NOT EXISTS _seal_parked_at ON _seal_parked (at)"), ("_seal_parked_tbl_at (tbl, at)", "CREATE INDEX IF NOT EXISTS _seal_parked_tbl_at ON _seal_parked (tbl, at)"), ("_seal_parked_code (code)", "CREATE INDEX IF NOT EXISTS _seal_parked_code ON _seal_parked (code)"), ] { let t = std::time::Instant::now(); db.execute_batch(sql).expect("built"); println!("PARK INDEXES {name}: {:.1} s", t.elapsed().as_secs_f64()); } // FIRST SYNC 9: each drop's time on this copy (why they are dropped in the background, one per step). for name in OLD_PARK_INDEXES_FOR_TESTS { let t = std::time::Instant::now(); db.execute_batch(&format!("DROP INDEX {name}")).expect("dropped"); println!("PARK INDEXES DROP {name}: {:.0} ms", t.elapsed().as_secs_f64() * 1e3); } // FIRST SYNC 8: the parks' keys instead, made at a note write and filled in slices, each its own write, on a // connection as the store opens one (WAL, `synchronous = NORMAL`: a commit is not an fsync). db.pragma_update(None, "synchronous", "NORMAL").expect("as the store"); // The parks in the file itself, not the WAL (as a copy's checkpoints leave them): the whole 1.7 GB in the WAL made // every slice read through it (69 s in all, the longest slice 4.6 s on the busy box). if std::env::var("COTTON_MEASURE_IN_WAL").is_err() { db.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)").expect("checkpointed"); } let t = std::time::Instant::now(); write_notes(&db, &[]).expect("the keys made"); let made = t.elapsed(); let (mut slices, mut longest, t) = (0, std::time::Duration::ZERO, std::time::Instant::now()); let mut holds = Vec::new(); loop { let s = std::time::Instant::now(); let full = fill_park_keys(&db, std::time::Duration::ZERO).expect("a slice"); longest = longest.max(s.elapsed()); holds.push(s.elapsed()); if s.elapsed().as_millis() > 300 { let (work, commit) = LAST_SLICE.with(|last| last.get()); println!("PARKS' KEYS a hold of {:.0} ms: the slice's work {:.0} ms, its commit {:.0} ms", s.elapsed().as_secs_f64() * 1e3, work.as_secs_f64() * 1e3, commit.as_secs_f64() * 1e3); } slices += 1; if full { break; } } let filled = t.elapsed(); holds.sort(); println!( "PARKS' KEYS slice holds: median {:.0} ms, 99th {:.0} ms, over 300 ms {} of {}", holds[holds.len() / 2].as_secs_f64() * 1e3, holds[holds.len() * 99 / 100].as_secs_f64() * 1e3, holds.iter().filter(|hold| hold.as_millis() > 300).count(), holds.len() ); let keys_bytes: i64 = db.query_row("SELECT sum(pgsize) FROM dbstat WHERE name LIKE '_seal_park_keys%'", [], |row| row.get(0)).unwrap_or(-1); let t = std::time::Instant::now(); let chosen = parked_next_in(&db, &[], &["email_thread".to_string(), "email".to_string()], 2_000).expect("a batch"); let batch = t.elapsed(); let t = std::time::Instant::now(); let counts = parked_by_code(&db).expect("counted").expect("known"); let counted = t.elapsed(); println!( "PARKS' KEYS over 280,000 old parks: made at the note {:.0} ms; filled in {slices} slices, {:.1} s in all, the longest slice {:.0} ms; keys and their indexes {} MB; a batch of {} {:.1} ms; counts {:?} {:.1} ms", made.as_secs_f64() * 1e3, filled.as_secs_f64(), longest.as_secs_f64() * 1e3, keys_bytes / 1_000_000, chosen.len(), batch.as_secs_f64() * 1e3, counts, counted.as_secs_f64() * 1e3 ); } const OLD_PARK_INDEXES_FOR_TESTS: [&str; 3] = ["_seal_parked_at", "_seal_parked_tbl_at", "_seal_parked_code"]; fn index_held(db: &rusqlite::Connection, name: &str) -> bool { db.query_row("SELECT count(*) FROM sqlite_master WHERE name = ?1", [name], |row| row.get::<_, i64>(0)).expect("a read") > 0 } /// An older build's seal state at `path`: `n` parks, a fifth of them tried, and FIRST SYNC 7's index over `at` if /// `indexed`. fn old_parks(path: &std::path::Path, n: usize, indexed: bool) -> rusqlite::Connection { let db = rusqlite::Connection::open(path).expect("a file"); db.execute_batch( "CREATE TABLE _seal (tbl TEXT NOT NULL, row_id TEXT NOT NULL, sealed INTEGER NOT NULL, dek_enc TEXT, seal_v INTEGER, version INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID; CREATE TABLE _seal_parked (tbl TEXT NOT NULL, row_id TEXT NOT NULL, code TEXT NOT NULL, reason TEXT NOT NULL, row TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID;", ) .expect("an older build's state"); if n > 0 { db.execute_batch(&format!( "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < {n}) INSERT INTO _seal_parked SELECT CASE WHEN i % 4 = 0 THEN 'email_thread' ELSE 'email' END, printf('r-%06d', i), 'seal_key_missing', 'no key yet', '{{}}', CASE WHEN i % 5 = 0 THEN printf('~%020d', i % 7 + 1) ELSE printf('2026-11-26T10:%02d:%02dZ', (i / 60) % 60, i % 60) END FROM n" )) .expect("old parks"); } if indexed { db.execute_batch("CREATE INDEX _seal_parked_at ON _seal_parked (at)").expect("FIRST SYNC 7's index"); } db } /// The order FIRST SYNC 5's one query gave over the wide table, to hold the keys' order to. fn order_of_one_query(db: &rusqlite::Connection, late: &[String], first: &[String], limit: usize) -> Vec<(String, String)> { db.prepare( "SELECT tbl, row_id FROM _seal_parked WHERE at < char(127) ORDER BY at >= '~', (at < '~' AND tbl IN (SELECT value FROM json_each(?1))), CASE WHEN at < '~' THEN coalesce((SELECT key FROM json_each(?3) WHERE value = tbl), 1000000) END, at, tbl, row_id LIMIT ?2", ) .expect("the one query") .query_map(rusqlite::params![serde_json::to_string(late).unwrap(), limit as i64, serde_json::to_string(first).unwrap()], |row| Ok((row.get(0)?, row.get(1)?))) .expect("rows") .collect::>() .expect("rows") } /// RULE (FIRST SYNC 8, the coordinator's review of FIRST SYNC 7 (2)): a copy holding many parks an older build made /// gets the parks' keys at its first note write, never filled there (inside a pass): what parks from then on has its /// key at once, so the batches read the keys alone and never the wide table, the counts are unknown (never zero), and /// the old parks fill in slices, each its own short write. Once full, every park is counted, the batch is in FIRST /// SYNC 5's order, and FIRST SYNC 7's index over the wide table is gone. #[test] fn many_old_parks_fill_their_keys_in_slices_never_at_a_note_write() { let dir = tempfile::tempdir().expect("a folder"); let n = PARKS_INLINE + 5; let db = old_parks(&dir.path().join("replica.db"), n, true); write_notes(&db, &[Note::Parked { table: "email_thread".into(), id: "new-1".into(), code: SEAL_KEY_MISSING.into(), reason: "invented".into(), row: serde_json::json!({}), at: "2026-11-26T09:00:00Z".into() }]).expect("a note"); let keys: i64 = db.query_row("SELECT count(*) FROM _seal_park_keys", [], |row| row.get(0)).expect("keys"); assert_eq!(keys, 1, "only the park written now has its key: none filled at the note write"); assert!(!park_keys_full(&db).expect("asked")); assert_eq!(parked_by_code(&db).expect("asked"), None, "not counted until full: unknown, never zero"); let first = vec!["email_thread".to_string(), "email".to_string()]; let batch = parked_next_in(&db, &[], &first, 50).expect("a batch off the keys"); assert_eq!(batch.iter().map(|row| row.id.as_str()).collect::>(), ["new-1"], "the keys alone are read, never the wide table"); // A park the fill has not reached changes meanwhile: a try marks one, another goes. write_notes(&db, &[Note::Tried { table: (if (n - 1) % 4 == 0 { "email_thread" } else { "email" }).into(), id: format!("r-{:06}", n - 1), at: "~00000000000000000099".into() }, Note::Unparked { table: (if (n - 2) % 4 == 0 { "email_thread" } else { "email" }).into(), id: format!("r-{:06}", n - 2) }]).expect("notes"); let mut slices = 0; while !fill_park_keys(&db, std::time::Duration::ZERO).expect("a slice") { slices += 1; } assert!(slices >= n / FILL_SLICE, "filled a slice at a time: {slices}"); let counts = parked_by_code(&db).expect("asked").expect("known once full"); assert_eq!(counts, vec![(SEAL_KEY_MISSING.to_string(), n as u64)], "every park, the one written now in, the one gone out"); let marked: String = db.query_row("SELECT at FROM _seal_park_keys WHERE row_id = ?1", [format!("r-{:06}", n - 1)], |row| row.get(0)).expect("its key"); assert_eq!(marked, "~00000000000000000099", "the mark made before the fill reached it"); assert_eq!(old_park_index_left(&db).expect("asked"), Some("_seal_parked_at"), "FIRST SYNC 7's index: left for the background step, never dropped on a slice"); let late = vec!["email".to_string()]; let keyed: Vec<(String, String)> = parked_next_in(&db, &late, &first, 300).expect("a batch").into_iter().map(|row| (row.table, row.id)).collect(); assert_eq!(keyed, order_of_one_query(&db, &late, &first, 300), "the same order as the one query over the wide table"); } /// RULE (FIRST SYNC 8): a new copy has the parks' keys with its state and owes no fill; one an older build left with /// few parks ([`PARKS_INLINE`]) has them filled at once. #[test] fn a_new_copy_or_few_old_parks_have_their_keys_at_once() { let db = rusqlite::Connection::open_in_memory().expect("a file"); write_notes(&db, &[Note::Unparked { table: "email".into(), id: "none".into() }]).expect("a note"); assert!(park_keys_full(&db).expect("asked"), "a new copy owes no fill"); assert_eq!(parked_by_code(&db).expect("asked"), Some(Vec::new())); let dir = tempfile::tempdir().expect("a folder"); let db = old_parks(&dir.path().join("replica.db"), 300, true); write_notes(&db, &[]).expect("a note"); assert!(park_keys_full(&db).expect("asked"), "few old parks filled at once"); assert_eq!(parked_by_code(&db).expect("asked"), Some(vec![(SEAL_KEY_MISSING.to_string(), 300)])); // FIRST SYNC 9: never dropped at a note write or a slice; one per background step once full. assert!(index_held(&db, "_seal_parked_at"), "still held after the fill"); let mut dropped = Vec::new(); while let Some(name) = old_park_index_left(&db).expect("asked") { drop_old_park_index(&db, name).expect("dropped"); dropped.push(name); } assert_eq!(dropped, ["_seal_parked_at"], "the one this old copy held"); assert!(drop_old_park_index(&db, "_seal_park_keys_at").is_err(), "only the old indexes over the wide table"); } /// RULE (FIRST SYNC 7 REVIEW, low): the daily try at the end of a pull is due with none made, a day after the last, /// and when the last is stamped after now (a clock set forward, then back), never held off until that day comes round. #[test] fn the_daily_wake_is_due_after_a_clock_set_back() { let day = WAKE_AT_END_EVERY_MS; let now = 1_800_000_000_000; assert!(wake_at_end_due(None, now)); assert!(!wake_at_end_due(Some(now - day + 1), now), "within the day"); assert!(wake_at_end_due(Some(now - day), now), "a day on"); assert!(wake_at_end_due(Some(now + 30 * day), now), "stamped by a clock set forward a month"); } /// RULE (FIRST SYNC 9 (2)): the parks' keys are set up whole or not at all. A setup that fails after any of its /// statements (as a kill or a failed statement would) leaves none of them; the next note sets them up again and owes /// a whole fill, after which every park has its key and a new park gets one. A part an older setup left (a keys /// table without its triggers, no fill state) is not taken for a setup: it is made again. #[test] fn the_parks_keys_are_set_up_whole_or_not_at_all() { let objects = |db: &rusqlite::Connection| -> Vec<&'static str> { PARK_KEYS_OBJECTS.iter().copied().filter(|name| index_held(db, name)).collect() }; let n = PARKS_INLINE + 5; for fail_after in 1..=PARK_KEYS_STATEMENTS.len() + 1 { let dir = tempfile::tempdir().expect("a folder"); let db = old_parks(&dir.path().join("replica.db"), n, false); FAIL_SETUP_AFTER.with(|after| after.set(fail_after)); assert!(write_notes(&db, &[]).is_err(), "the setup failed after statement {fail_after}"); FAIL_SETUP_AFTER.with(|after| after.set(0)); assert!(objects(&db).is_empty(), "nothing of the keys stays after a failure at {fail_after}: {:?}", objects(&db)); write_notes(&db, &[Note::Parked { table: "email".into(), id: "new-1".into(), code: SEAL_KEY_MISSING.into(), reason: "invented".into(), row: serde_json::json!({}), at: "2026-11-26T09:00:00Z".into() }]).expect("set up"); assert_eq!(objects(&db).len(), PARK_KEYS_OBJECTS.len()); assert_eq!(parked_by_code(&db).expect("asked"), None, "a whole fill owed"); while !fill_park_keys(&db, std::time::Duration::from_secs(5)).expect("fill") {} assert_eq!(parked_by_code(&db).expect("asked"), Some(vec![(SEAL_KEY_MISSING.to_string(), n as u64 + 1)]), "after a failure at {fail_after}"); } // What a setup without the savepoint could have left: the keys table alone, with a key, no triggers, no state. let dir = tempfile::tempdir().expect("a folder"); let db = old_parks(&dir.path().join("replica.db"), 50, false); db.execute_batch(PARK_KEYS_STATEMENTS[0]).expect("the keys table alone"); db.execute_batch("INSERT INTO _seal_park_keys VALUES ('email', 'r-000001', 'seal_key_missing', 'x')").expect("one key"); write_notes(&db, &[]).expect("set up again"); assert_eq!(objects(&db).len(), PARK_KEYS_OBJECTS.len()); assert_eq!(parked_by_code(&db).expect("asked"), Some(vec![(SEAL_KEY_MISSING.to_string(), 50)]), "filled whole (few parks: at once)"); db.execute_batch("INSERT INTO _seal_parked VALUES ('email', 'later', 'seal_key_missing', 'x', '{}', 'y')").expect("a park"); assert_eq!(parked_count(&db).expect("asked"), Some(51), "its trigger keys a new park"); } /// RULE (FIRST SYNC 9 (1)): rows waiting for their conversation in parks an older build made are never left out of /// every batch by wakes that ran during the fill: those wakes keep the tables' marks (at the parent's mark now, so /// they do not wake the same rows every pass, 9b), and the fill's last slice marks every table holding waiting rows, /// so the next pass wakes them all. #[test] fn rows_waiting_in_old_parks_are_woken_after_the_fill() { let dir = tempfile::tempdir().expect("a folder"); let n = PARKS_INLINE + 5; let db = old_parks(&dir.path().join("replica.db"), n, false); // A fifth of the mails wait for their conversation, as FIRST SYNC 6 and 7 leave them, the table marked. db.execute_batch( "CREATE TABLE _seal_waiting (tbl TEXT PRIMARY KEY NOT NULL, mark INTEGER NOT NULL) WITHOUT ROWID; INSERT INTO _seal_waiting VALUES ('email', 5); UPDATE _seal_parked SET code = 'waiting_parent', at = char(127) || at WHERE tbl = 'email' AND CAST(substr(row_id, 3) AS INTEGER) % 5 = 1;", ) .expect("waiting rows"); let waiting: i64 = db.query_row("SELECT count(*) FROM _seal_parked WHERE at >= char(127)", [], |row| row.get(0)).expect("count"); assert!(waiting > 1_000); // The first pass after the upgrade: its wakes run before any slice is filled. write_notes(&db, &[Note::Wake { table: Some("email".into()), at_ms: 0, mark: 9 }, Note::Wake { table: None, at_ms: 1_800_000_000_000, mark: 0 }]).expect("the first pass's wakes"); // FIRST SYNC 9b: the mark stays, moved to the parent's mark now, so the next pass (no new conversation) does not // wake the same rows again; the daily wake is stamped, so a caught-up pass does not either. assert_eq!(waiting_marks(&db).expect("marks"), vec![("email".to_string(), 9)], "the mark stays while the fill is owed, at the parent's now"); assert_eq!(woken_at_end(&db).expect("stamp"), Some(1_800_000_000_000), "the daily wake stamped: not again every caught-up pass"); assert!(!wake_at_end_due(Some(1_800_000_000_000), 1_800_000_000_000 + 60_000), "the next pass's daily wake is not due"); while !fill_park_keys(&db, std::time::Duration::from_secs(5)).expect("fill") {} assert_eq!(waiting_marks(&db).expect("marks"), vec![("email".to_string(), -1)], "the last slice marks the table to be woken"); // The next pass: the parent mark is past -1, so the table's rows wake, every one. write_notes(&db, &[Note::Wake { table: Some("email".into()), at_ms: 0, mark: 12 }]).expect("woken"); let still: i64 = db.query_row("SELECT count(*) FROM _seal_park_keys WHERE at >= char(127)", [], |row| row.get(0)).expect("count"); assert_eq!(still, 0, "no row left waiting unwoken"); let batch = parked_next_in(&db, &[], &[], n + 10).expect("a batch"); let woken = batch.iter().filter(|row| row.code == WAITING_PARENT).count() as i64; assert_eq!(woken, waiting, "every waiting row is in the batches again"); } /// RULE (FIRST SYNC 9 (3)): full keys are checked against the parks once a launch; keys that disagree (a key lost, a /// code not the park's) owe a whole fill again, which mends them a slice at a time, never trusted for good. #[test] fn keys_that_disagree_with_the_parks_are_filled_again() { let dir = tempfile::tempdir().expect("a folder"); let db = old_parks(&dir.path().join("replica.db"), 3_000, false); write_notes(&db, &[]).expect("set up and filled at once"); assert!(check_park_keys(&db).expect("checked"), "keys made by the fill agree"); assert!(settle_full_keys(&db).expect("settled")); db.execute_batch("DELETE FROM _seal_park_keys WHERE row_id = (SELECT min(row_id) FROM _seal_park_keys WHERE tbl = 'email')").expect("a key lost"); assert!(!check_park_keys(&db).expect("checked"), "the first key of a table lost is seen"); assert!(!settle_full_keys(&db).expect("settled"), "disagreed"); assert!(!park_keys_full(&db).expect("asked"), "owes a whole fill again"); let held: i64 = db.query_row("SELECT count(*) FROM _seal_park_keys", [], |row| row.get(0)).expect("count"); assert_eq!(held, 2_999, "FIRST SYNC 9b: no DELETE of every key at the settle, inside a pass"); // Keys with no park (as a disagreement may leave), in the middle and past the last park: mended by the slices. db.execute_batch("INSERT INTO _seal_park_keys VALUES ('email', 'r-001500x', 'other', 'x'), ('zzz', 'gone', 'other', 'x')").expect("stale keys"); while !fill_park_keys(&db, std::time::Duration::from_secs(5)).expect("fill") {} assert!(check_park_keys(&db).expect("checked")); assert_eq!(parked_count(&db).expect("asked"), Some(3_000), "the lost key back, the keys with no park gone"); db.execute_batch("UPDATE _seal_park_keys SET code = 'other' WHERE tbl = 'email_thread' AND row_id = (SELECT min(row_id) FROM _seal_park_keys WHERE tbl = 'email_thread')").expect("a code changed"); assert!(!check_park_keys(&db).expect("checked"), "a key whose code is not its park's is seen"); } /// RULE (FIRST SYNC 9, low): an idle copy of an older build with no park counts none, never "unknown"; one not set up /// answers whether a code waits from its first parks only, never a scan of all. #[test] fn an_old_copy_with_no_parks_counts_none() { let dir = tempfile::tempdir().expect("a folder"); let db = old_parks(&dir.path().join("replica.db"), 0, false); assert_eq!(parked_by_code(&db).expect("asked"), Some(Vec::new())); assert_eq!(parked_count(&db).expect("asked"), Some(0)); let other = tempfile::tempdir().expect("a folder"); let db = old_parks(&other.path().join("replica.db"), 10, false); assert_eq!(parked_by_code(&db).expect("asked"), None, "parks not counted yet: unknown"); assert!(any_parked_with(&db, SEAL_KEY_MISSING).expect("asked")); assert!(any_parked_with(&db, "never").expect("asked"), "9c: not set up, a code not seen is unknown, and unknown counts as waiting"); // FIRST SYNC 9b: set up, the keys still empty of the old parks (more than are filled at once): the code is still // seen, off the first parks. let third = tempfile::tempdir().expect("a folder"); let db = old_parks(&third.path().join("replica.db"), PARKS_INLINE + 5, false); write_notes(&db, &[]).expect("set up, the fill owed"); assert!(!park_keys_full(&db).expect("asked")); assert!(any_parked_with(&db, SEAL_KEY_MISSING).expect("asked"), "not full and no key with it: the first parks say"); } /// RULE (FIRST SYNC 9, 9b): a slice ends once it has read and written for [`SLICE_TIME`], whatever the disk, and /// the fill goes on from the last key written: every park gets its key. #[test] fn a_slow_slice_ends_at_its_time_and_the_fill_goes_on() { let dir = tempfile::tempdir().expect("a folder"); let db = old_parks(&dir.path().join("replica.db"), 40, false); SLICE_TIME_FOR_TESTS.with(|time| time.set(Some(std::time::Duration::ZERO))); write_notes(&db, &[]).expect("a note"); let mut slices = 0; while !fill_park_keys(&db, std::time::Duration::ZERO).expect("a slice") { slices += 1; assert!(slices < 100, "the fill ends"); } SLICE_TIME_FOR_TESTS.with(|time| time.set(None)); assert_eq!(parked_by_code(&db).expect("asked"), Some(vec![(SEAL_KEY_MISSING.to_string(), 40)]), "every park, one a slice"); assert!(check_park_keys(&db).expect("checked")); } /// RULE (FIRST SYNC 9c): while the fill is owed, a park with the code placed after 10,000 others (the first rows the /// fill has already keyed) is never answered "none": unknown counts as waiting. Once full, the keys answer exactly. #[test] fn a_code_behind_ten_thousand_parks_is_never_answered_none_during_the_fill() { let dir = tempfile::tempdir().expect("a folder"); let n = PARKS_INLINE + 2_000; let db = old_parks(&dir.path().join("replica.db"), n, false); db.execute("UPDATE _seal_parked SET code = 'fold_refused' WHERE row_id < ?1", [format!("r-{:06}", PARKS_INLINE)]).expect("the first 10,000 another code"); write_notes(&db, &[]).expect("set up, the fill owed"); fill_park_keys(&db, std::time::Duration::ZERO).expect("one slice"); assert!(!park_keys_full(&db).expect("asked")); assert!(any_parked_with(&db, SEAL_KEY_MISSING).expect("asked"), "behind the slices filled: unknown, so waiting"); while !fill_park_keys(&db, std::time::Duration::from_secs(5)).expect("fill") {} assert!(any_parked_with(&db, SEAL_KEY_MISSING).expect("asked"), "full: the keys hold it"); assert!(!any_parked_with(&db, "never").expect("asked"), "full: exactly none"); } /// RULE (FIRST SYNC 9c): a slice cut in its write phase moves the cursor to the last key written, and the fill goes /// on from there: every park gets its key. #[test] fn a_slice_cut_while_writing_goes_on_from_the_last_key_written() { let dir = tempfile::tempdir().expect("a folder"); let db = old_parks(&dir.path().join("replica.db"), PARKS_INLINE + 1_500, false); write_notes(&db, &[]).expect("set up, the fill owed"); WRITE_CUT_FOR_TESTS.with(|after| after.set(Some(7))); fill_park_keys(&db, std::time::Duration::ZERO).expect("one slice, cut while writing"); let (row_id, keyed): (String, i64) = db .query_row("SELECT row_id, (SELECT count(*) FROM _seal_park_keys) FROM _seal_park_state WHERE k = 0", [], |row| Ok((row.get(0)?, row.get(1)?))) .expect("the cursor"); let seventh: String = db.query_row("SELECT row_id FROM _seal_parked ORDER BY tbl, row_id LIMIT 1 OFFSET 6", [], |row| row.get(0)).expect("the seventh park"); assert_eq!(row_id, seventh, "the cursor at the last key written"); assert_eq!(keyed, 7); while !fill_park_keys(&db, std::time::Duration::from_secs(5)).expect("fill") {} WRITE_CUT_FOR_TESTS.with(|after| after.set(None)); assert_eq!(parked_count(&db).expect("asked"), Some((PARKS_INLINE + 1_500) as u64)); assert!(check_park_keys(&db).expect("checked")); } /// RULE (FIRST SYNC 9c): a table's waiting rows wake once its parents gained a row; a table this build cannot name /// wakes once, then not again on every pass. #[test] fn a_wake_with_no_parent_table_comes_once() { assert_eq!(wake_mark(Some(9), 5), Some(9)); assert_eq!(wake_mark(Some(5), 5), None, "no new parent row: no wake"); assert_eq!(wake_mark(None, 5), Some(i64::MAX), "unnamed parents: woken once"); assert_eq!(wake_mark(None, i64::MAX), None, "and not again"); assert_eq!(wake_mark(None, -1), Some(i64::MAX), "the fill's last slice marks it to be woken once more"); }