//! Conformance, lane 3b: SEARCH — the Rust twin of `harness/search.test.ts`//! (spec R9).//!//! Search is the one part of the store a person watches happen. A store that//! folds identically but ranks differently would put a different row at the top//! of the same list, and nothing in a dump would ever say so — so this lane asks//! the question a dump cannot: given the same file and the same typed string,//! does the Rust answer with the recorded rows, in the same ORDER?//!//! The queries are fixed rather than generated, because what has to be covered//! is not volume but the awkward halves of `to_match_query`: the operators FTS5//! would otherwise read as syntax (`*`, `-`, `:`, `^`, quotes, parentheses), the//! words FTS5 reads as operators (OR, AND, NEAR), the query that strips to//! nothing, and a token that only ever matches a TITLE — which is the one that//! exercises the ×2 boost, the single place the ranking is the store's own//! arithmetic rather than SQLite's.//!//! The corpus is carried by the vectors AS OPS, so the file this lane searches//! is built by folding the very batch the record was taken from — not by a second//! fixture builder that could drift from it.use cotton_store::driver::Driver;use cotton_store::fold::fold_ops;use cotton_store::actor::{Actor, JobName};use cotton_store::mint::changes_of;use cotton_store::outbox::LocalChange;use cotton_store::protocol::types::{CottonOp, OpKind};use cotton_store::wire::op_of_change;use cotton_store::search::search_all;use cotton_conformance::{baseline, vectors, HitVector, Vectors};/// f64s printed by one language and parsed by another: bm25 is the same/// arithmetic on both sides, and the ORDER is the claim, so the ranks are/// compared to a tolerance far tighter than any reordering could hide inside.const RANK_TOLERANCE: f64 = 1e-9;/// What a person sees: which row, from which table, under which title.fn visible(hit: &HitVector) -> String { format!("{}/{} — {}", hit.table, hit.row_id, hit.title)}/// What the recorded answer and this one disagree about, as sentences.////// A function rather than a run of `assert_eq!`s because the last test in this/// file feeds it PERTURBED vectors and asserts it notices — a comparison only/// ever driven from the happy side is a comparison nobody has watched fail.fn search_differences(expected: &[HitVector], actual: &[HitVector]) -> Vec<String> {letmut out = Vec::new();if expected.len() != actual.len() { out.push(format!("{} hits recorded, {} in Rust", expected.len(), actual.len() ));return out; }for (at, ours) in actual.iter().enumerate() {let theirs = &expected[at];if visible(ours) != visible(theirs) { out.push(format!("hit {at}:\n recorded {}\n Rust {}", visible(theirs), visible(ours) ));continue; }// The snippet: it is what the row looks like in the list, and it comes// from SQLite's own `snippet()` with arguments the two stores must pass// identically — a different ellipsis or token count shows here.if ours.snippet != theirs.snippet { out.push(format!("hit {at} snippet:\n recorded {:?}\n Rust {:?}", theirs.snippet, ours.snippet ));continue; }// And the rank, which decided the order above.if (ours.rank - theirs.rank).abs() >= RANK_TOLERANCE { out.push(format!("hit {at} rank: recorded {} against Rust {}", theirs.rank, ours.rank )); } } out}fn corpus_file(vectors: &Vectors) -> Driver {let db = baseline(&vectors.baseline);// The corpus was recorded as the ops the TypeScript era wrote; each is// read as the write it describes and handed over as the receipt a device// makes of it today — the lane is about ranking, not the op's shape.let described = vectors.search.ops.as_array().expect("the corpus is a list of ops");let text = |op: &serde_json::Value, key: &str| { op[key].as_str().unwrap_or_else(|| panic!("a corpus op names no {key}: {op}")).to_string() };let local: Vec<LocalChange> = described .iter() .map(|op| LocalChange {// A delete names its kind to `mint`; a corpus delete is a Retract. delete: (op["kind"] == "delete").then_some(cotton_store::mint::Delete::Retract), kind: if op["kind"] == "delete" { OpKind::Delete } else { OpKind::Upsert }, table: text(op, "table"), row_id: text(op, "rowId"), patch: op["patch"].as_object().cloned(), }) .collect();let actor = Actor::DeviceJob(JobName::named("conformance").expect("a job name"));let ops: Vec<CottonOp> = described .iter() .zip(changes_of(&db, &local)) .map(|(op, change)| { op_of_change(&db, &change, &text(op, "hlc"), &text(op, "deviceId"), &actor, text(op, "opId")) .expect("a corpus op has a receipt") }) .collect();let folded = fold_ops(&db, &ops).expect("the corpus folds"); assert!( folded.rejected.is_empty() && folded.applied.len() == ops.len(),"the corpus did not land: {} of {} applied, {:?}", folded.applied.len(), ops.len(), folded.rejected ); db}fn ask(db: &Driver, query: &str, limit: Option<i64>) -> Vec<HitVector> { search_all(db, query, None, limit) .expect("the search answers") .into_iter() .map(|hit| HitVector { table: hit.table, row_id: hit.row_id, title: hit.title, snippet: hit.snippet, rank: hit.rank, }) .collect()}/// RULE: Search returns the same results on the server and on the phone, checked against hand-written vectors.#[test]fn answers_the_same_rows_in_the_same_order() {let vectors: Vectors = vectors();let db = corpus_file(&vectors);for case in &vectors.search.queries {let ours = ask(&db, &case.query, case.limit);let what = match case.limit {Some(limit) => format!("{:?} limited to {limit}", case.query),None => format!("{:?}", case.query), };let found = search_differences(&case.hits, &ours); assert!( found.is_empty(),"{what}: the Rust search answered differently from the recorded answer\n\n{}\n\n\ The vectors are this crate's `vectors/conformance.json`, an ordinary committed \ fixture that nothing regenerates — a legitimate change is edited into it BY HAND \ in the SAME PR, with the reason in the PR body.", found.join("\n") );ifletSome(limit) = case.limit { assert!( ours.len() as i64 <= limit,"{what}: the limit was not honoured" ); } }}#[test]fn the_lane_is_comparing_work() {// Twenty-four empty answers compare equal too. This is what says the// twenty-four above are worth running.let vectors: Vectors = vectors();let db = corpus_file(&vectors); assert!( ask(&db, "lorem", None).len() > 10,"the busy query returned nothing" ); assert!( !ask(&db, "marlo", None).is_empty(),"the title-only query returned nothing" ); assert!( ask(&db, ":::", None).is_empty(),"a query that strips to nothing returned rows" ); assert!(ask(&db, "", None).is_empty(), "the empty box returned rows"); assert!( ask(&db, "zzzznotawordinthecorpus", None).is_empty(),"a word nothing holds returned rows" );// The operator words are stripped to plain tokens, and the corpus holds a// line carrying them AS words — so these two really compare rows. A store// that honoured FTS5's `OR` would answer with the whole corpus instead, and// two empty lists would have hidden either behaviour. assert!( !ask(&db, "culpa OR lorem", None).is_empty(),"the stripped OR returned nothing" ); assert!( ask(&db, "culpa OR lorem", None).len() < ask(&db, "lorem", None).len(),"the OR was honoured rather than stripped" );// And the limits really cut: the corpus is bigger than the smallest of them.let limited: Vec<i64> = vectors .search .queries .iter() .filter_map(|case| case.limit) .collect(); assert!(limited.len() >= 4, "the limits were not recorded"); assert!( limited.contains(&1) && limited.contains(&5),"no limit smaller than the corpus" );}#[test]fn a_title_hit_outranks_a_body_hit() {// The ×2 boost is the store's own arithmetic — the only part of the ranking// SQLite does not decide — so it gets its own assertion rather than living// inside a list comparison.let vectors: Vectors = vectors();let db = corpus_file(&vectors);let ours = ask(&db, "marlo", None);let theirs = &vectors .search .queries .iter() .find(|case| case.query == "marlo" && case.limit.is_none()) .expect("the recorded `marlo` query") .hits; assert_eq!(ours[0].row_id, theirs[0].row_id); assert!(ours[0].title.to_lowercase().contains("marlo")); assert!( ours[0].rank < 0.0,"bm25 ranks are negative and smaller is better" );}#[test]fn the_comparison_catches_a_ranking_that_drifted() {// The seeded defect, permanent and negative rather than a breaking commit:// the recorded answer is perturbed the three ways a real search regression// perturbs it — a row lost, two rows reordered, a rank moved — and each// perturbation is fed to the very comparison the lane above uses. If any of// these goes quiet the lane above is no longer capable of going red.let vectors: Vectors = vectors();let db = corpus_file(&vectors);let ours = ask(&db, "lorem", None); assert!( ours.len() > 2,"the busy query is what the perturbations need" );// (a) a row the search stopped returning.letmut shortened = ours.clone(); shortened.pop();let found = search_differences(&shortened, &ours); assert!( found.iter().any(|line| line.contains("hits recorded")),"a lost row went unnoticed: {found:?}" );// (b) two rows the ranking swapped — the defect a dump can never see.letmut swapped = ours.clone(); swapped.swap(0, 1);let found = search_differences(&swapped, &ours); assert!( found.iter().any(|line| line.starts_with("hit 0:")),"a reordering went unnoticed: {found:?}" );// (c) a rank that moved by a hair, with the rows still in the same order —// which is the shape a scoring change takes before it is big enough to// reorder anything, and the one a row-list comparison alone would miss.letmut nudged = ours.clone(); nudged[0].rank += 1e-6;let found = search_differences(&nudged, &ours); assert!( found.iter().any(|line| line.starts_with("hit 0 rank:")),"a moved rank went unnoticed: {found:?}" );// (d) a snippet that changed while the row and the rank did not.letmut resnipped = ours.clone(); resnipped[0].snippet = format!("{}…", resnipped[0].snippet);let found = search_differences(&resnipped, &ours); assert!( found.iter().any(|line| line.starts_with("hit 0 snippet:")),"a changed snippet went unnoticed: {found:?}" );}