use super::*; use cotton_store::meta::Meta; fn household(size: usize) -> (tempfile::TempDir, cotton_store::Driver, Counts) { let (dir, db, meta) = empty_household(); let media = dir.path().join("media"); let put = |key: &str, bytes: &[u8]| -> std::io::Result<()> { let path = media.join(key); std::fs::create_dir_all(path.parent().expect("a key has a folder"))?; std::fs::write(path, bytes) }; let counts = seed_household_with(&db, &meta.owner_id, &Plan::scaled(size), 7, fixed_now(), Some(&put)).expect("a household"); (dir, db, counts) } /// A founded, unseeded workspace file: the rows a birth writes and nothing else. fn empty_household() -> (tempfile::TempDir, cotton_store::Driver, Meta) { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("life.db"); let meta = Meta { workspace_id: "11111111-1111-4111-8111-111111111111".into(), owner_id: "22222222-2222-4222-8222-222222222222".into(), device_id: "device:test".into(), last_server_seq: 0, last_hlc: None, }; let db = cotton_store::test_template::create_workspace_for_test(&path, &meta).expect("a schema"); cotton_store::birth::seed_workspace_rows( &db, &fixed_now().to_rfc3339(), fixed_now().timestamp_millis(), &cotton_store::birth::WorkspaceSeed { workspace_id: &meta.workspace_id, owner_id: &meta.owner_id, name: Some("Dev"), kind: "personal", relay: None }, // A counter, not the system's randomness: two runs must mint the same ids. &mut cotton_store::protocol::ulid::Monotonic::new({ let mut next = 0u8; move |bytes: &mut [u8]| { for byte in bytes.iter_mut() { next = next.wrapping_add(1); *byte = next; } } }), cotton_store::mint::Held::Served, ) .expect("the workspace row and the calendar"); (dir, db, meta) } #[derive(Debug)] struct PlainRail; impl crate::rails::VaultRail for PlainRail { fn seal(&self, secret_id: &str, payload: &[u8]) -> Option { Some(crate::rails::SealedSecret { value_enc: format!("sealed:{secret_id}:{}", String::from_utf8_lossy(payload)), vmk_version: 1 }) } fn open(&self, secret_id: &str, vmk_version: u32, sealed: &str) -> Option> { (vmk_version == 1).then(|| sealed.strip_prefix(&format!("sealed:{secret_id}:")).map(|p| p.as_bytes().to_vec())).flatten() } } /// RULE: Seeded with a vault, every secret carries a sealed value at the vault's version and the hint the payload answers, so a seeded login opens with Show and Copy; seeded without one, the rows are bare. #[test] fn seeded_secrets_are_sealed_when_the_seeder_has_a_vault() { let (_dir, db, meta) = empty_household(); seed_household_sealed(&db, &meta.owner_id, &Plan::scaled(60), 7, fixed_now(), None, Some(std::sync::Arc::new(PlainRail))) .expect("a household"); let rows = db.all("SELECT id, kind, value_enc, vmk_version, hint FROM cotton_secrets", &[]).expect("secrets"); assert!(rows.len() >= 6); for row in &rows { let sealed = row.text("value_enc").expect("a sealed value"); assert_eq!(row.int("vmk_version"), Some(1)); let opened = crate::rails::VaultRail::open(&PlainRail, row.text("id").unwrap(), 1, sealed).expect("opens"); let payload: cotton_core::vault::SecretPayload = serde_json::from_slice(&opened).expect("a payload"); assert_eq!(row.text("hint"), Some(payload.hint().as_str()), "{}", row.text("kind").unwrap_or_default()); } } /// THE SHAPES REAL DATA HAS are in every household, whatever its size: the /// walk of each tool needs its case to look at (UX walk, 4 Oct 2026 — a list /// that opens empty, or holds only the plain case, cannot be checked). Each /// line is one shape and the least the file must hold of it. /// RULE: The synthetic household holds one of every shape real data has, whatever its size, so no tool's screens are walked on the plain case alone. #[test] fn a_household_holds_every_shape_a_walk_needs_to_see() { let (dir, db, _) = household(2_000); // Every picture a row says is there, is: the original and its thumbnail. let pictured = db .all("SELECT key FROM cotton_photos WHERE preview IS NOT NULL", &[]) .expect("the pictured photos"); assert!(!pictured.is_empty()); for row in &pictured { let key = row.text("key").expect("a key"); let thumb = cotton_core::media::keys::thumb_key_for(key).expect("a photo has a thumbnail key"); for key in [key, thumb.as_str()] { let bytes = std::fs::read(dir.path().join("media").join(key)).unwrap_or_default(); assert!(bytes.starts_with(&[0x89, b'P', b'N', b'G']), "{key} is not a picture on disk"); } } let mut short = Vec::new(); for (shape, sql, at_least) in [ ("a repeating todo", "SELECT count(*) AS n FROM cotton_todo_recurrences", 3), // One live copy per series until it is done or skipped (882e949a7): three series, three copies. ("a repeating todo's occurrences", "SELECT count(*) AS n FROM cotton_todos WHERE recurrence_id IS NOT NULL", 3), ("a snoozed todo", "SELECT count(*) AS n FROM cotton_todos WHERE snoozed_until IS NOT NULL", 3), ("a high-priority todo", "SELECT count(*) AS n FROM cotton_todos WHERE priority > 0", 4), ("a dropped todo", "SELECT count(*) AS n FROM cotton_todos WHERE status = 'dropped'", 4), ("a todo due within a day of now", "SELECT count(*) AS n FROM cotton_todos WHERE status = 'open' AND due_at BETWEEN '2026-09-30' AND '2026-10-03'", 5), ("a repeating event", "SELECT count(*) AS n FROM cotton_events WHERE rrule IS NOT NULL", 4), ("an invitation to answer", "SELECT count(*) AS n FROM cotton_events WHERE my_response = 'needs_action' AND organizer_is_self = 0", 2), ("an event with guests", "SELECT count(DISTINCT event_id) AS n FROM cotton_event_attendees", 6), ("a guest who declined", "SELECT count(*) AS n FROM cotton_event_attendees WHERE response = 'declined'", 2), ("an event on a second calendar", "SELECT count(*) AS n FROM cotton_events e JOIN cotton_collections c ON c.id = e.collection_id WHERE c.is_default = 0", 5), // Every such row on a v76 file names its Google account; one that did not would be pushed by no account. ("an event Google holds, naming its account", "SELECT count(*) AS n FROM cotton_events WHERE gcal_etag IS NOT NULL AND account IS NOT NULL", 9), ("no event Google holds that names no account", "SELECT 1 - count(*) AS n FROM cotton_events WHERE gcal_etag IS NOT NULL AND account IS NULL", 1), ("an event over several days", "SELECT count(*) AS n FROM cotton_events WHERE julianday(ends_at) - julianday(starts_at) > 1.5", 2), ("a note with a picture", "SELECT count(DISTINCT note_id) AS n FROM cotton_note_attachments", 2), ("an archived note", "SELECT count(*) AS n FROM cotton_notes WHERE archived_at IS NOT NULL", 3), ("a published note", "SELECT count(*) AS n FROM cotton_notes WHERE published_at IS NOT NULL", 2), ("a note an assistant keeps", "SELECT count(*) AS n FROM cotton_notes WHERE managed_by IS NOT NULL", 2), ("a group chat", "SELECT count(*) AS n FROM cotton_msg_threads WHERE kind = 'group'", 2), ("a group's members", "SELECT count(*) AS n FROM cotton_msg_thread_participants", 10), ("a member who left", "SELECT count(*) AS n FROM cotton_msg_thread_participants WHERE left_at IS NOT NULL", 1), ("an imported chat", "SELECT count(*) AS n FROM cotton_msg_messages WHERE origin = 'imported'", 30), ("a message with a picture, voice note or file", "SELECT count(*) AS n FROM cotton_msg_messages WHERE json_array_length(media) > 0", 8), ("a message with no words", "SELECT count(*) AS n FROM cotton_msg_messages WHERE body IS NULL", 4), ("a reply", "SELECT count(*) AS n FROM cotton_msg_messages WHERE reply_to_id IS NOT NULL", 2), ("a reaction", "SELECT count(*) AS n FROM cotton_msg_reactions", 8), ("a kept message", "SELECT count(*) AS n FROM cotton_msg_messages WHERE starred_at IS NOT NULL", 6), ("a pinned chat", "SELECT count(*) AS n FROM cotton_msg_threads WHERE pinned_at IS NOT NULL", 1), ("a muted chat", "SELECT count(*) AS n FROM cotton_msg_threads WHERE muted_until IS NOT NULL", 1), ("an archived chat", "SELECT count(*) AS n FROM cotton_msg_threads WHERE archived = 1", 1), ("a number with no name", "SELECT count(*) AS n FROM cotton_msg_contacts WHERE display_name IS NULL", 1), ("a chat with nothing in it", "SELECT count(*) AS n FROM cotton_msg_threads t WHERE NOT EXISTS (SELECT 1 FROM cotton_msg_messages m WHERE m.thread_id = t.id)", 1), ("a status someone posted", "SELECT count(*) AS n FROM cotton_stories", 4), ("a status kept after the app let it go", "SELECT count(*) AS n FROM cotton_stories WHERE kept = 1", 1), ("a meeting no worker would pick up", "SELECT 1 - count(*) AS n FROM cotton_meetings WHERE status NOT IN ('ready', 'failed')", 1), ("a note about a person", "SELECT count(*) AS n FROM cotton_person_notes", 8), ("a todo linked to a person", "SELECT count(*) AS n FROM cotton_links WHERE from_kind = 'todo' AND to_kind = 'person'", 8), ("a statement no worker would pick up", "SELECT 1 - count(*) AS n FROM cotton_money_statements WHERE read_status = 'pending'", 1), ("an edition no worker would pick up", "SELECT 1 - count(*) AS n FROM cotton_news_editions WHERE status NOT IN ('ready', 'failed')", 1), ("a photo that is a real picture", "SELECT count(*) AS n FROM cotton_photos WHERE content_type = 'image/png' AND preview IS NOT NULL AND summary IS NOT NULL", 40), ("a photo that is not on this device", "SELECT count(*) AS n FROM cotton_photos WHERE preview IS NULL", 1), ("a photo with a caption", "SELECT count(*) AS n FROM cotton_photos WHERE caption IS NOT NULL", 5), ("a kept album", "SELECT count(*) AS n FROM cotton_media_albums WHERE state = 'kept'", 2), ("a suggested album", "SELECT count(*) AS n FROM cotton_media_albums WHERE state = 'open'", 1), ("an album's pictures", "SELECT count(*) AS n FROM cotton_media_album_items", 21), ("a face asking who it is", "SELECT count(*) AS n FROM cotton_media_faces WHERE suggested_person_id IS NOT NULL AND person_id IS NULL AND suggestion_dismissed_at IS NULL", 4), ("a face somebody named", "SELECT count(*) AS n FROM cotton_media_faces WHERE person_id IS NOT NULL", 2), ("a duplicate to decide", "SELECT count(*) AS n FROM cotton_media_duplicates WHERE state = 'open'", 2), ("a film with its length", "SELECT count(*) AS n FROM cotton_videos WHERE duration_ms > 0", 7), ("a film with a poster", "SELECT count(*) AS n FROM cotton_videos WHERE poster_key IS NOT NULL", 7), ("a document no worker would pick up", "SELECT 1 - count(*) AS n FROM cotton_documents WHERE status IN ('processing', 'summarizing')", 1), ("a thought no worker would pick up", "SELECT 1 - count(*) AS n FROM cotton_inbox_items WHERE route_status = 'pending' AND route_reason IS NULL", 1), ("an email with attachments", "SELECT count(*) AS n FROM cotton_emails WHERE json_array_length(attachments) > 0", 2), ("a long email thread", "SELECT max(n) AS n FROM (SELECT count(*) AS n FROM cotton_emails GROUP BY thread_id)", 11), ("a starred email", "SELECT count(*) AS n FROM cotton_emails WHERE starred = 1", 2), ("an unread email", "SELECT count(*) AS n FROM cotton_emails WHERE unread = 1", 3), ("an archived email", "SELECT count(*) AS n FROM cotton_emails WHERE in_inbox = 0 AND trashed_at IS NULL", 1), ("a binned email", "SELECT count(*) AS n FROM cotton_emails WHERE trashed_at IS NOT NULL", 1), ("a blocked sender", "SELECT count(*) AS n FROM cotton_blocked_senders", 1), ("a thread in the People stack", "SELECT count(*) AS n FROM cotton_email_threads WHERE sender_kind = 'person'", 1), ("a thread in the Records stack", "SELECT count(*) AS n FROM cotton_email_threads WHERE sender_kind = 'service'", 1), ("a thread in the Junk stack", "SELECT count(*) AS n FROM cotton_email_threads WHERE sender_kind = 'junk'", 3), ("one of each kind the vault keeps", "SELECT count(DISTINCT kind) AS n FROM cotton_secrets", 6), ("a key placed on a Mac", "SELECT count(*) AS n FROM cotton_secret_placements", 2), ("a session no Mac would take up", "SELECT 1 - count(*) AS n FROM cotton_sessions WHERE state IN ('queued', 'starting')", 1), ] { let n = db.get(sql, &[]).expect(shape).and_then(|row| row.int("n")).unwrap_or_default(); if n < at_least { short.push(format!("{shape}: the household holds {n}, a walk needs {at_least}")); } } assert!(short.is_empty(), "{}", short.join("\n")); } /// The acceptance test for the generator: a small household on a fresh file /// through the real write paths, with every kind present and the file /// reading back the counts. It is also the schema guard — a column that moves /// breaks a handler here before it breaks the development server. #[test] fn a_small_household_is_written_whole_and_the_same_twice() { let make = || household(2_000); let (_a, db, counts) = make(); for table in [ "cotton_people", "cotton_todos", "cotton_notes", "cotton_events", "cotton_msg_messages", "cotton_emails", "cotton_photos", ] { assert!(counts.of(table) > 0, "{table} was not written"); let in_file = db .get(&format!("SELECT count(*) AS n FROM {table}"), &[]) .expect("a count") .and_then(|row| row.int("n")) .expect("a number"); assert_eq!(in_file as usize, counts.of(table), "{table}"); } assert!(counts.total() >= 1_500, "{}", counts.total()); let (_b, _, again) = make(); assert_eq!(counts.by_table(), again.by_table(), "the same seed gives the same household"); } /// The "one" size seeds through the same paths with every count at one, so a /// walk has a database where each tool's list holds a single row. #[test] fn a_household_of_one_of_everything_is_written_whole() { let (_dir, db, meta) = empty_household(); let counts = seed_household_with(&db, &meta.owner_id, &Plan::named("one").expect("the one plan"), 7, fixed_now(), None) .expect("a household of one"); for table in [ "cotton_people", "cotton_todos", "cotton_notes", "cotton_events", "cotton_emails", "cotton_photos", ] { assert!(counts.of(table) >= 1, "{table} was not written"); } assert!(counts.total() < 1_500, "one of everything stays small: {}", counts.total()); } /// The bytes under `key` in the household's media folder — where the sink put /// them, which is where the served object store keeps them. fn object(dir: &tempfile::TempDir, key: &str) -> Vec { std::fs::read(dir.path().join("media").join(key)).unwrap_or_default() } /// RULE: The first chat in the list ends with a film, a voice note, a file and a Markdown line, and each attachment's bytes are really there — content-addressed at its key, as long as the row says — so a walk can open and play each kind. #[test] fn the_first_chat_holds_a_film_a_voice_note_a_file_and_markdown_with_their_bytes() { use sha2::Digest; let (dir, db, _) = household(2_000); let first = db .get("SELECT id FROM cotton_msg_threads ORDER BY pinned_at IS NULL, last_message_at DESC LIMIT 1", &[]) .expect("threads") .expect("a chat"); let newest = db .get("SELECT max(last_message_at) AS at FROM cotton_msg_threads", &[]) .expect("threads") .and_then(|row| row.text("at").map(str::to_string)); let thread = first.text("id").expect("an id"); let rows = db .all( "SELECT body, media, sent_at FROM cotton_msg_messages WHERE thread_id = ? ORDER BY sent_at DESC LIMIT 4", &[rusqlite::types::Value::Text(thread.to_string())], ) .expect("its messages"); assert_eq!(rows[0].text("sent_at").map(str::to_string), newest, "the pinned chat is also the newest"); let mut kinds: Vec = Vec::new(); for row in &rows { let media: Vec = serde_json::from_str(row.text("media").unwrap_or("[]")).expect("media entries"); for entry in media { let bytes = object(&dir, &entry.key); assert!(!bytes.is_empty(), "{} is not on disk", entry.key); assert_eq!(entry.size_bytes, Some(bytes.len() as f64), "{} says its size", entry.key); let sha = hex::encode(sha2::Sha256::digest(&bytes)); assert!(entry.key.contains(&sha), "{} is addressed by its bytes", entry.key); let looks = match entry.content_type.as_str() { "video/mp4" => &bytes[4..8] == b"ftyp", "audio/wav" => super::sound::wav_duration_ms(&bytes) == entry.duration_ms.map(|ms| ms as i64), "application/pdf" => bytes.starts_with(b"%PDF-") && bytes.ends_with(b"%%EOF\n"), other => panic!("an unexpected {other}"), }; assert!(looks, "{} is not the {} it says", entry.key, entry.content_type); kinds.push(serde_json::to_value(entry.kind).expect("a kind").as_str().unwrap_or_default().to_string()); } } kinds.sort(); assert_eq!(kinds, ["file", "video", "voice"]); let markdown = rows.iter().filter_map(|row| row.text("body")).find(|body| body.contains("**")).expect("a Markdown line"); assert!(markdown.contains("\n- ") && markdown.contains("](https://example.com"), "{markdown}"); } /// RULE: Every seeded email attachment has a key in its file whose bytes are really there, addressed by them, as large as it says and of the type it says, so a walk can open each print. #[test] fn every_seeded_email_attachment_has_its_bytes() { use sha2::Digest; let (dir, db, _) = household(2_000); let rows = db .all("SELECT attachments, workspace_id FROM cotton_emails WHERE json_array_length(attachments) > 0", &[]) .expect("emails"); let mut seen = 0; for row in &rows { let entries: Vec = serde_json::from_str(row.text("attachments").unwrap_or("[]")).expect("attachments"); for entry in entries { let key = entry["key"].as_str().expect("a key"); assert!(cotton_core::media::keys::is_key_in_row_file(Some(key), row.text("workspace_id").unwrap_or_default()), "{key} is in its file"); let bytes = object(&dir, key); assert_eq!(entry["size"].as_u64(), Some(bytes.len() as u64), "{key} is on disk at its size"); assert!(key.contains(&hex::encode(sha2::Sha256::digest(&bytes))), "{key} is addressed by its bytes"); let looks = match entry["mime"].as_str().unwrap_or_default() { "image/png" => bytes.starts_with(b"\x89PNG") && entry["name"].as_str().is_some_and(|n| n.ends_with(".png")), "application/pdf" => bytes.starts_with(b"%PDF-") && entry["name"].as_str().is_some_and(|n| n.ends_with(".pdf")), other => panic!("an unexpected {other}"), }; assert!(looks, "{entry} is the type and name it says"); seen += 1; } } assert_eq!(seen, 4); } /// The development household's own size, which the small run above does not /// reach (thirty-six months of statements, every account). Minutes long, so /// it runs when asked: `cargo test -p cotton-tools --lib synthetic -- --ignored`. #[test] #[ignore = "minutes long; run before changing what scales with the plan"] fn a_large_household_is_written_whole() { let (_dir, _db, counts) = household(100_000); assert!(counts.total() >= 90_000, "{}", counts.total()); } /// RULE: A household is never stamped ahead of the wall clock it was seeded by — no receipt after its `now`, and a seed's now is nine UTC or the wall clock if earlier — or a joined phone's edits of seeded rows fold as stale. #[test] fn a_household_is_never_stamped_ahead_of_its_now() { use chrono::TimeZone; let early = chrono::Utc.with_ymd_and_hms(2026, 10, 5, 3, 4, 0).single().unwrap(); assert_eq!(super::seed_now(early), early); let late = chrono::Utc.with_ymd_and_hms(2026, 10, 5, 15, 0, 0).single().unwrap(); assert_eq!(super::seed_now(late), chrono::Utc.with_ymd_and_hms(2026, 10, 5, 9, 0, 0).single().unwrap()); let (_dir, db, _) = household(2_000); let newest = db .all("SELECT last_hlc FROM _meta", &[]) .expect("the clock") .first() .and_then(|row| row.text("last_hlc").map(str::to_string)) .expect("a stamp"); let ms: i64 = newest.split(':').next().unwrap().parse().unwrap(); assert!(ms <= fixed_now().timestamp_millis() + 1_000, "stamped at {newest}, after {}", fixed_now()); // And seeded an hour into the HOUSE's day, before its morning: the rows // dated this morning (the morning edition, at seven there) lie after // `now`, and their receipts must not. let zone = db .get("SELECT timezone FROM cotton_news_settings", &[]) .expect("the settings") .and_then(|row| row.text("timezone").map(str::to_string)) .expect("a house zone"); // The day after the birth's own stamps (`fixed_now`), in every zone. let day = crate::mcp::handlers::common::today_in(&zone, fixed_now().timestamp_millis() + 86_400_000).unwrap(); let start = crate::mcp::handlers::common::start_of_day_in(&day, &zone).unwrap(); let early = chrono::Utc.timestamp_millis_opt(start + 3_600_000).single().unwrap(); let (_dir, db, meta) = empty_household(); seed_household_at(&db, &meta.owner_id, &Plan::scaled(2_000), 7, early).expect("a household"); let ahead = db .get(&format!("SELECT tbl, hlc FROM _writes WHERE hlc > '{:013}' ORDER BY hlc LIMIT 1", early.timestamp_millis() + 1_000), &[]) .expect("the receipts"); assert!(ahead.is_none(), "seeded at {early} ({zone}), stamped after it: {ahead:?}"); } /// RULE: A seeded household's Todos list has a Late group and a Done group within its first page — open todos due in the last days and todos done today and yesterday — on the small seed and the large, so both can be walked on a fresh seed. #[test] fn the_todos_list_has_late_and_done_near_now() { let (_dir, db, _) = household(2_000); let now = fixed_now(); let week = (now - chrono::Duration::days(7)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let late = db .all( "SELECT id FROM cotton_todos WHERE status = 'open' AND due_at IS NOT NULL AND due_at < ? AND due_at >= ?", &[rusqlite::types::Value::Text(now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)), rusqlite::types::Value::Text(week.clone())], ) .expect("todos"); assert!(late.len() >= 3, "only {} open todos fell due in the last week", late.len()); let done = db .all("SELECT id FROM cotton_todos WHERE status = 'done' AND completed_at >= ?", &[rusqlite::types::Value::Text(week)]) .expect("todos"); assert!(done.len() >= 3, "only {} todos were done in the last week", done.len()); } /// RULE: The seed keeps one long note — about 1,500 words of Markdown with headings, a list and a quote — beside short ones, so a long page can be read and walked (Spec 8). #[test] fn the_seed_keeps_one_long_note_beside_short_ones() { let (_dir, db, _) = household(2_000); let long = db .get("SELECT body FROM cotton_notes WHERE title = 'Moving house: the whole plan'", &[]) .expect("notes") .expect("the long note"); let body = long.text("body").expect("a body"); let words = body.split_whitespace().count(); assert!((1_300..=1_800).contains(&words), "{words} words"); assert!(body.matches("\n## ").count() >= 4, "sections under headings"); assert!(body.contains("\n- ") && body.contains("\n> "), "a list and a quote"); let short = db .all("SELECT body FROM cotton_notes WHERE length(body) < 600 AND body IS NOT NULL", &[]) .expect("notes"); assert!(!short.is_empty(), "a short note beside it"); } /// RULE: Generated money rows retain their account's currency, so synthetic tests never conceal a currency conversion as an ordinary movement. #[test] fn generated_money_rows_keep_their_accounts_currency() { let (_dir, db, _) = household(2_000); let mismatch=db.get("SELECT count(*) AS n FROM cotton_money_transactions t JOIN cotton_money_accounts a ON a.id=t.account_id WHERE t.currency<>a.currency",&[]).unwrap().unwrap(); assert_eq!(mismatch.int("n"), Some(0)); } /// The open after an install whose shipped definitions moved (phone 296 over /// 295, 17 Oct 2026): `_computed` stamped by the older build, timed through /// the open's own step. COTTON_OPEN_SIZE sets the household's size. #[test] #[ignore = "minutes long; a timing, run by hand"] fn the_open_after_a_definition_change_is_timed() { let size = std::env::var("COTTON_OPEN_SIZE").ok().and_then(|size| size.parse().ok()).unwrap_or(100_000); let started = std::time::Instant::now(); let (_dir, db, counts) = household(size); eprintln!("TIMING seeded {} records in {:?}", counts.total(), started.elapsed()); let started = std::time::Instant::now(); crate::derive::ensure_current(&db).expect("current"); eprintln!("TIMING open, index current: {:?}", started.elapsed()); cotton_store::derived::mark_rebuilt(&db, "3:sha256:an-older-build").expect("stamped older"); let started = std::time::Instant::now(); crate::derive::ensure_current(&db).expect("rebuilt"); eprintln!("TIMING open after a definition change (rebuild): {:?}", started.elapsed()); } /// RULE: A seed defers every fold's computed work and rebuilds exactly once /// after its last row; a rebuild during import loses the bulk advantage. #[test] fn a_seed_rebuilds_only_after_its_last_fold() { let (_dir, db, meta) = empty_household(); db.watch_statements(); seed_household(&db, &meta.owner_id, &Plan::one(), 7).unwrap(); assert_eq!(db.statements_seen().iter().filter(|sql| sql.as_str() == "DELETE FROM main._computed").count(), 1); assert!(crate::derive::is_current(&db).unwrap()); assert_eq!(db.get("SELECT count(*) AS n FROM _computed WHERE key='pending'", &[]).unwrap().unwrap().int("n"), Some(0)); assert!(!db.indexes_beside(), "bulk deferral does not escape the seed"); }