//! The recorded fixtures for the search and write-local lanes, and the//! comparison the two share.//!//! The fresh-schema fixtures include nullable `_born`, key-rotation and receipt//! envelope columns. Legacy input ops leave those NULL; the local-write fixture//! explicitly takes its recorded device as `_meta.author_id`.//!//! `vectors/conformance.json` is an ORDINARY committed fixture: for each lane,//! the INPUTS (the baseline, the search corpus and its queries, the local//! changes) and the ANSWERS a store gave to them. The two integration tests in//! `tests/` replay every recorded answer against `cotton-store`.//!//! **Nothing regenerates this file.** A recorder that replays Rust to write//! down what Rust said, so that Rust can be diffed against it, compares//! nothing: it is a snapshot test wearing a conformance test's clothes, and it//! turns any behaviour change into a green diff nobody reads. So the answers//! are edited BY HAND, like any other fixture, and a search or outbox change//! that moves one lands with the edit and its reason in the same PR.//! The answers were first recorded against the second engine the recorder was//! written for; that recorder is gone and is never to be rebuilt.//!//! Nothing here reads a clock or a random source: the baseline is built from//! the crate's own schema, the ids in the vectors are the generator's, and the//! one place randomness is needed — a ULID's sixteen characters — takes it from//! a seeded xorshift the caller passes in.use std::collections::{BTreeMap, BTreeSet};use cotton_store::create::create_workspace;use cotton_store::driver::Driver;use cotton_store::meta::Meta;use rusqlite::types::ValueasSqlValue;use serde::{Deserialize, Serialize};use serde_json::{Map, ValueasJsonValue};/// The committed vectors, read once per test target.pubfn vectors() -> Vectors {let text = include_str!("../vectors/conformance.json"); serde_json::from_str(text).expect("vectors/conformance.json parses")}#[derive(Debug, Deserialize, Serialize)]pubstructVectors {pub baseline: Baseline, #[serde(rename = "triggerMinted")]pub trigger_minted: BTreeMap<String, Vec<String>>,pub search: SearchVectors, #[serde(rename = "writeLocal")]pub write_local: WriteLocalVector,}#[derive(Debug, Deserialize, Serialize, Clone)]pubstructBaseline { #[serde(rename = "workspaceId")]pub workspace_id: String, #[serde(rename = "ownerId")]pub owner_id: String, #[serde(rename = "deviceId")]pub device_id: String, #[serde(rename = "workspaceName")]pub workspace_name: String, #[serde(rename = "workspaceCreatedAt")]pub workspace_created_at: String,}#[derive(Debug, Deserialize, Serialize)]pubstructSearchVectors {/// The corpus, as ops — the Rust side builds the very same file by folding/// the very same batch rather than by re-implementing a fixture.pub ops: JsonValue,pub queries: Vec<SearchVector>,}#[derive(Debug, Deserialize, Serialize)]pubstructSearchVector {pub query: String,pub limit: Option<i64>,pub hits: Vec<HitVector>,}#[derive(Debug, Deserialize, Serialize, Clone)]pubstructHitVector {pub table: String, #[serde(rename = "rowId")]pub row_id: String,pub title: String,pub snippet: String, #[serde(serialize_with = "serialize_rank")]pub rank: f64,}#[derive(Debug, Deserialize, Serialize)]pubstructWriteLocalVector {pub device: String, #[serde(rename = "nowMs")]pub now_ms: i64,pub changes: JsonValue,/// Each op with `opId` and `schemaVersion` already dropped — see the/// emitter's own words for why neither can be compared.pub ops: Vec<JsonValue>,pub state: StateVector,}/// The comparable half of a canonical dump: every NON-EMPTY table and every/// FTS index. `schema` and `user_version` are the schema-snapshot lane's/// question, not this one's.#[derive(Debug, Deserialize, Serialize)]pubstructStateVector {pub tables: BTreeMap<String, Vec<Map<String, JsonValue>>>,pub fts: BTreeMap<String, JsonValue>,}// ---------------------------------------------------------------------------// The baseline both stores build// ---------------------------------------------------------------------------/// A fresh Rust file with the one row every domain row's foreign key points at.////// The TypeScript side built its baseline with `migrateStore` +/// `createWorkspaceFile` + this same INSERT; the shape lane is what says the/// two are the same database. In memory, because every lane wants a fresh one/// and none of them is asking a question about a path.pubfn baseline(ids: &Baseline) -> Driver {let db = Driver::open_in_memory().expect("an in-memory file opens"); create_workspace( &db, &Meta { workspace_id: ids.workspace_id.clone(), owner_id: ids.owner_id.clone(), device_id: ids.device_id.clone(), last_server_seq: 0, last_hlc: None, }, ) .expect("the baseline is created"); db.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)", &[SqlValue::Text(ids.workspace_id.clone()),SqlValue::Text(ids.workspace_name.clone()),SqlValue::Text(ids.owner_id.clone()),SqlValue::Text(ids.workspace_created_at.clone()), ], ) .expect("the workspace row"); db}/// A seeded xorshift64*, so a lane run twice mints the same ULIDs.////// Deliberately NOT a dependency and deliberately NOT cryptographic: op ids are/// dedupe keys inside one person's workspace, and what a lane needs from them is/// REPRODUCIBILITY. The CLI in `src/main.rs` carries its own, drawing a/// different byte out of the same word — the two are not interchangeable and/// neither is a source of ids for anything but a fixture.pubstructXorshift64(u64);implXorshift64 {pubfn seeded(seed: u64) -> Xorshift64 {// A zero state is a fixed point of xorshift — every draw would be 0.Xorshift64(if seed == 0 {0x9E37_79B9_7F4A_7C15 } else { seed }) }pubfn fill(&mutself, bytes: &mut [u8]) {for byte in bytes.iter_mut() {self.0 ^= self.0 << 13;self.0 ^= self.0 >> 7;self.0 ^= self.0 << 17; *byte = (self.0 >> 24) as u8; } }}// ---------------------------------------------------------------------------// The comparison// ---------------------------------------------------------------------------/// JSON with the keys in a fixed order, so two values compare as strings.////// The workspace turns on serde_json's `preserve_order`, so an object's key/// order is its insertion order on both sides — which is a property of two/// dumps that happen to agree today, not a guarantee. Sorting makes the/// comparison about the CONTENT.pubfn canonical(value: &JsonValue) -> String { serde_json::to_string(&sorted(value)).expect("a dump value serialises")}fn sorted(value: &JsonValue) -> JsonValue {match value {JsonValue::Array(items) => JsonValue::Array(items.iter().map(sorted).collect()),JsonValue::Object(fields) => {let ordered: BTreeMap<&String, &JsonValue> = fields.iter().collect();letmut out = Map::new();for (key, nested) in ordered { out.insert(key.clone(), sorted(nested)); }JsonValue::Object(out) } other => other.clone(), }}fn without(row: &Map<String, JsonValue>, dropped: &[String]) -> JsonValue {letmut out = Map::new();for (column, value) in row {if !dropped.iter().any(|name| name == column) { out.insert(column.clone(), value.clone()); } }JsonValue::Object(out)}/// The file the lane just built, as the vectors record one: non-empty tables/// and every FTS index, out of `cotton_store::dump::dump`.pubfn state_of(db: &Driver) -> StateVector {let whole = cotton_store::dump::dump(db).expect("the file dumps");let tables = whole .get("tables") .and_then(JsonValue::as_object) .expect("the dump has tables");letmut kept = BTreeMap::new();for (name, rows) in tables {let rows = rows.as_array().expect("a table's rows are an array");if rows.is_empty() {continue; } kept.insert( name.clone(), rows.iter() .map(|row| row.as_object().expect("a row is an object").clone()) .collect(), ); }let fts = whole .get("fts") .and_then(JsonValue::as_object) .expect("the dump has fts") .iter() .map(|(name, entry)| (name.clone(), entry.clone())) .collect();StateVector { tables: kept, fts }}/// What the two states disagree about, as sentences a human can act on.////// Returned rather than asserted so one `assert!` names the table first — a/// `assert_eq!` over a twenty-thousand-row dump prints a diff nobody can read.////// Two kinds of column are excluded, and the vector file names both in its own/// words (`triggerMinted`): the ones SQLite's own triggers mint (none since/// schema 89 dropped the history triggers) and `_meta.schema_version`, which was the first engine's number/// against this one's by design. No two runs agree on them, so the recorded/// state never carried them./// A table with excluded columns is compared as a sorted MULTISET of what/// remains, because dropping the first column changes the row order too.pubfn differences( expected: &StateVector, actual: &StateVector, minted: &BTreeMap<String, Vec<String>>,) -> Vec<String> {letmut out = Vec::new();let names: BTreeSet<&String> = expected.tables.keys().chain(actual.tables.keys()).collect();for name in names {let theirs = expected.tables.get(name);let ours = actual.tables.get(name);let (theirs, ours) = match (theirs, ours) { (Some(theirs), Some(ours)) => (theirs, ours), (Some(theirs), None) => { out.push(format!("{name}: the record has {} rows, the Rust file none", theirs.len() ));continue; } (None, Some(ours)) => { out.push(format!("{name}: the Rust file has {} rows, the record none", ours.len() ));continue; } (None, None) => continue, };if theirs.len() != ours.len() { out.push(format!("{name}: {} rows recorded, {} in Rust", theirs.len(), ours.len() ));continue; }match minted.get(name) {Some(dropped) => {let strip = |rows: &Vec<Map<String, JsonValue>>| {letmut lines: Vec<String> = rows .iter() .map(|row| canonical(&without(row, dropped))) .collect(); lines.sort(); lines };let theirs = strip(theirs);let ours = strip(ours);for at in0..theirs.len() {if theirs[at] != ours[at] { out.push(format!("{name} row {at} ({} excluded — SQLite's own trigger writes them and \ no run agrees with another):\n recorded {}\n Rust {}", dropped.join(", "), theirs[at], ours[at] ));break; } } }None => {for at in0..theirs.len() {let a = canonical(&JsonValue::Object(theirs[at].clone()));let b = canonical(&JsonValue::Object(ours[at].clone()));if a != b { out.push(format!("{name} row {at}:\n recorded {a}\n Rust {b}" ));break; } } } } }let indexes: BTreeSet<&String> = expected.fts.keys().chain(actual.fts.keys()).collect();for index in indexes {let theirs = expected.fts.get(index).map(canonical);let ours = actual.fts.get(index).map(canonical);if theirs != ours { out.push(format!("fts {index}:\n recorded {}\n Rust {}", theirs.unwrap_or_else(|| "(absent)".to_string()), ours.unwrap_or_else(|| "(absent)".to_string()) )); } } out}// ---------------------------------------------------------------------------// What the lanes share with the fixture// ---------------------------------------------------------------------------/// The seed the write-local lane's ULIDs are drawn from.////// A constant rather than a flag because the recorded state carries/// `_outbox.op_id`: a second seed would put a different id there on every run./// The crate itself holds no RNG (spec R7) — this is the caller's seed,/// spelled once.pubconst WRITE_LOCAL_SEED: u64 = 20_260_822;/// The `_outbox` columns the write-local comparison leaves out: `op_id` is a/// ULID and `schema_version` is the era's number. Merged with the vector file's/// own `triggerMinted` list by the lane.pubconst OUTBOX_EXCLUSIONS: &[&str] = &["op_id", "schema_version"];// FTS5 bm25 uses libm log(), whose last digits can differ across platforms.// Scientific notation with eleven fractional digits keeps twelve significant// digits without another libm operation; the lane compares within 1e-9.fn serialize_rank<S: serde::Serializer>(rank: &f64, serializer: S) -> Result<S::Ok, S::Error> {let rounded: f64 = format!("{rank:.11e}").parse().map_err(serde::ser::Error::custom)?; serializer.serialize_f64(rounded)}#[cfg(test)]mod tests {usesuper::*; #[test]fn ranks_keep_twelve_significant_digits() {for (rank, expected) in [ (-1.234567890123456, -1.23456789012), (-0.000001234567890123456, -0.00000123456789012), (9.999999999999, 10.0), (0.0, 0.0), ] {let rounded = serialize_rank(&rank, serde_json::value::Serializer).unwrap(); assert_eq!(rounded, serde_json::json!(expected)); } }}