//! Every table definition is resolved once per file, database, shape and set //! of stored rows, and every later read takes that answer //! (`cotton_tools::definitions::table_definitions_from_driver`): with every //! built-in seeded as a row, a resolution costs milliseconds, and a record //! page reads the list several times. //! //! Every row is synthetic and every value invented //! ([nothing-real-ever-goes-in-cotton-s-public-tree]). mod support; use std::sync::Arc; use cotton_core::definitions::{builtin_table_definitions, TableDefinition}; use cotton_tools::definitions::{shared_table_definitions_from_driver, table_definitions_from_driver, take_definition_diagnostics, Definitions, SEED_JOB, SEED_LABEL, TABLE_DEFINITIONS}; use cotton_tools::mcp::dispatch::{Ctx, ToolServices}; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::harness::Harness; /// A seeded file ON DISK, read again through a second handle on its path โ€” /// the answer a file on disk keeps is every handle's on it, where a file in /// memory keeps its own by its handle (`Driver::file_key`). fn seeded_on_disk(dir: &tempfile::TempDir) -> Harness { let h = Harness::new(); let services = ToolServices::none(); let audit = |_tool: &str, _summary: &str| {}; h.with(|db| { let mut ctx = Ctx::for_worker( db, &h.file, &h.owner_id, cotton_tools::mcp::writer::job(SEED_JOB), SEED_LABEL, cotton_tools::clock::Clock::now(&h.clock), Arc::clone(&h.random), &services, &audit, ); cotton_tools::kit::import_kit_tools(&mut ctx).expect("seeds"); ctx.commit().expect("commits"); }); let path = dir.path().join("seeded.cotton"); h.run("VACUUM INTO ?", &[SqlValue::Text(path.to_string_lossy().into_owned())]); Harness::open_copy(&path.to_string_lossy()) } fn listed(h: &Harness) -> Definitions { h.with(|db| table_definitions_from_driver(db, &h.workspace_id).expect("lists")) } fn drawn(h: &Harness, id: &str) -> TableDefinition { listed(h).definitions.into_iter().find(|d| d.id == id).expect("listed") } fn compiled(id: &str) -> TableDefinition { builtin_table_definitions().iter().cloned().find(|d| d.id == id).expect("ships") } fn stored(h: &Harness, id: &str) -> Value { let text = h .one(&format!("SELECT definition FROM {TABLE_DEFINITIONS} WHERE id = ?"), &[SqlValue::Text(id.into())]) .and_then(|row| row["definition"].as_str().map(str::to_string)) .expect("a stored row"); serde_json::from_str(&text).unwrap() } fn store(h: &Harness, id: &str, definition: &Value) { h.run( &format!("UPDATE {TABLE_DEFINITIONS} SET definition = ? WHERE id = ?"), &[SqlValue::Text(definition.to_string()), SqlValue::Text(id.into())], ); } /// RULE: a file in memory keeps its answer as a file on disk does, by its own handle (`Driver::file_key`), and no other file in memory is given it: every fold's derive pass reads the definitions, and a test's in-memory file that resolved them afresh on every read spent forty minutes folding a mail fixture (run 6347). #[test] fn a_file_in_memory_keeps_its_answer_by_its_own_handle() { let h = Harness::new(); let first = shared_table_definitions_from_driver(&h.db, &h.workspace_id).expect("lists"); let again = shared_table_definitions_from_driver(&h.db, &h.workspace_id).expect("lists"); assert!(Arc::ptr_eq(&first, &again), "a second read of the same file in memory takes the kept answer"); let other = Harness::new(); let theirs = shared_table_definitions_from_driver(&other.db, &other.workspace_id).expect("lists"); assert!(!Arc::ptr_eq(&first, &theirs), "another file in memory resolves its own"); assert_ne!(h.db.file_key(), other.db.file_key(), "two files in memory are never one key"); } /// RULE: an unreadable stored row is reported by every read, kept or not โ€” Debug drains the diagnostics after each read, and a kept answer that dropped them would hide a broken definition. #[test] fn a_kept_answer_still_reports_an_unreadable_row() { let dir = tempfile::tempdir().unwrap(); let h = seeded_on_disk(&dir); store(&h, "person", &json!({"id": "person", "page": "not a page"})); h.run( &format!("UPDATE {TABLE_DEFINITIONS} SET builtin_stamp = ? WHERE id = 'device'"), &[SqlValue::Integer(cotton_core::definitions::BUILTIN_DEFINITIONS_STAMP + 1)], ); let _ = take_definition_diagnostics(); for read in ["first", "kept"] { let answer = listed(&h); assert!(answer.definitions.iter().any(|d| d.id == "person"), "{read}: the built-in still draws"); let diagnostics = take_definition_diagnostics(); assert_eq!(diagnostics.len(), 1, "{read}: {diagnostics:?}"); assert_eq!(diagnostics[0].id, "person"); } } /// What one read of the list costs with every built-in seeded as a row, first /// and kept โ€” not a guard, a measurement: /// `cargo +1.98.1 test --release -p cotton-tools --test definitions_resolved_once -- --ignored --nocapture`. #[test] #[ignore = "a timing, run by hand"] fn timing() { let dir = tempfile::tempdir().unwrap(); let h = seeded_on_disk(&dir); // A connection of its own: the harness reconciles every table after each // read, which would be most of what this measures. let db = cotton_store::driver::Driver::open(dir.path().join("seeded.cotton")).expect("opens"); // The shipped file is parsed once per process; keep that out of the first read. std::hint::black_box(builtin_table_definitions()); let time = |runs: u32, read: &dyn Fn()| { let began = std::time::Instant::now(); for _ in 0..runs { read(); } began.elapsed().as_secs_f64() * 1000.0 / f64::from(runs) }; let list = || { std::hint::black_box(table_definitions_from_driver(&db, &h.workspace_id).expect("lists")); }; let first = time(1, &list); let kept = time(50, &list); let rows = time(50, &|| { std::hint::black_box(cotton_tools::definitions::definition_rows_from_driver(&db, &h.workspace_id, None).expect("rows")); }); println!("[definitions] first read {first:.2} ms ยท kept read {kept:.2} ms (of which reading the rows {rows:.2} ms)"); }