diff options
| author | Alexander_Kabui <alexanderkabua@gmail.com> | 2026-10-07 06:34:51 +0300 |
|---|---|---|
| committer | Alexander_Kabui <alexanderkabua@gmail.com> | 2026-10-07 06:34:51 +0300 |
| commit | a5c40fc78f6b3cb32fba3daeb9f2a8e95558ba09 (patch) | |
| tree | 51dba2ecba0e7371e220b6c6d7eaa99a13b0adf5 /tests | |
| parent | f7423aaaf71194a169ded303baa3cb7bda8f0b53 (diff) | |
| download | genenetwork4-a5c40fc78f6b3cb32fba3daeb9f2a8e95558ba09.tar.gz | |
src/search/native.rs (native engine): port the xapian query path behind the Engine seam (C3.1).
New native engine, a Rust port of gn3 search path (gn3/api/search.py),
opt-in via SEARCH_ENGINE=native (the gn3 forwarder stays the default;
src/search/mod.rs now dispatches on config, routes/search.rs delegates):
- startup-cached QueryParser behind a mutex: custom-prefix registration
is Box::leak-based inside the binding, so a per-request parser would
leak; built once per process (binding-report §5 item 3, R2 pattern).
Minimal configuration this commit per PORT-DESIGN C3.1: Stem("en") +
STEM_ALL_Z only.
- checked parse via the fork's parse_query_checked: malformed queries
are typed errors, not panics; Err maps to SearchError::InvalidQuery
(422 invalid_query, the owner-blessed contract), carrying the
parser diagnostic. Parse happens before the index is opened, as in
gn3 (search.py:291 vs :296), so a bad query reports InvalidQuery
even when the index is misconfigured.
- XT{type} document filter: OP_FILTER(parsed, "XT"+type)
(search.py:298-300).
- FULL-match-set retrieval ignoring the forwarded limit (per-page
invariant, PORT-DESIGN §5): mset bound is a deliberately huge fixed
constant; the route keeps its validation and limit logic unchanged.
- per-hit mapping: doc data JSON -> SearchHit via serde
(search.py:302 equivalent); unknown fields flow through extra.
Decode failure maps to SearchError::Misbehaving.
- index open behind an app-level guard (the binding aborts on open
failure; see the module doc): unset XAPIAN_DB_PATH -> Internal,
unopenable path -> Unreachable.
tests/search_native.rs: error-contract scenarios (hermetic) + the
per-page invariant + dispatch pinning, one sequential test fn per the
process-global env rule; the dev-index part skips loudly when
XAPIAN_DB_PATH is unset. tests/search_native_shapes.rs: the shape-CLASS
gate (this lane s AMENDMENT-B translation of the C3.1 stage gate) --
16 shapes (Q01,Q03-Q13,Q47,Q50,Q51,Q54), each expected class cited to
its tests/search_parity.rs shape! line; dev-index counts are printed
as reference data only, never compared to production.
Evidence: logs/c3-1.log (build EXIT=0, native tests green, lib 14/14),
logs/c3-1-full.log (FULL suite EXIT=0, parity floor green),
logs/shape-class-c3-1.log (SHAPE-CLASS GATE 16/16 PASS vs the dev
index; Q51 byte-identical diagnostic; per-page invariant: limit=10
forwarded, 2330-hit full set returned).
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/search_native.rs | 161 | ||||
| -rw-r--r-- | tests/search_native_shapes.rs | 127 |
2 files changed, 288 insertions, 0 deletions
diff --git a/tests/search_native.rs b/tests/search_native.rs new file mode 100644 index 0000000..f34dc55 --- /dev/null +++ b/tests/search_native.rs @@ -0,0 +1,161 @@ +//! Native-engine contract tests: the `SearchError` mapping and the +//! per-page invariant, directly against the engine (no route, no +//! auth), in the process-global-environment style of +//! `tests/search_engine.rs` (one sequential test function, since +//! `XAPIAN_DB_PATH` / `SEARCH_ENGINE` are process-global and mutating +//! them from parallel test threads would race). +//! +//! Hermetic parts run everywhere (a malformed query needs no index; +//! misconfigurations are the point). The dev-index part — the per-page +//! invariant, which needs a real index — runs only when +//! `XAPIAN_DB_PATH` points at one (the lane's shape-gate runs set it +//! to the development index at +//! `~/spikes/index-self-build/xapian-index`, 47 040 docs; a +//! development index is never a recorded-count source, per +//! AMENDMENT B — counts are printed as reference data only). + +use genenetwork4::search::{self as seam, Engine, SearchError, SearchHit, native::Native}; + +/// The name of a result's variant, so a failed assertion can name what +/// it got without requiring `SearchHit: Debug`. +fn variant_name(result: &Result<Vec<SearchHit>, SearchError>) -> &'static str { + match result { + Ok(_) => "Ok", + Err(SearchError::InvalidQuery(_)) => "InvalidQuery", + Err(SearchError::Unreachable(_)) => "Unreachable", + Err(SearchError::Misbehaving(_)) => "Misbehaving", + Err(SearchError::Backend(_)) => "Backend", + Err(SearchError::Internal(_)) => "Internal", + } +} + +fn set(key: &str, value: &str) { + // SAFETY: this test binary has a single test function and no other + // thread reads these keys concurrently (see the module doc). + unsafe { std::env::set_var(key, value) }; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn native_engine_error_contract_and_per_page_invariant() { + let prior_path = std::env::var("XAPIAN_DB_PATH").ok(); + let prior_engine = std::env::var("SEARCH_ENGINE").ok(); + let prior_gn3_url = std::env::var("GN3_URL").ok(); + + // 1. A malformed query is a typed InvalidQuery, not a panic, and it + // is reported before any index is needed (gn3 parses before it + // opens the index, search.py:291 vs :296). + set("XAPIAN_DB_PATH", ""); + set("SEARCH_ENGINE", "native"); + let result = Native.search("alcohol AND", "phenotype", 5).await; + assert_eq!(variant_name(&result), "InvalidQuery"); + let Err(SearchError::InvalidQuery(message)) = result else { + unreachable!(); + }; + assert_eq!(message, "Syntax: <expression> AND <expression>"); + + // 2. The same query through the seam dispatch proves the config + // switch selects the native engine. + let result = seam::search("alcohol AND", "phenotype", 5).await; + assert_eq!(variant_name(&result), "InvalidQuery"); + + // 3. An unset index path is a local misconfiguration: Internal. + let result = Native.search("alcohol", "phenotype", 5).await; + assert_eq!(variant_name(&result), "Internal"); + + // 4. An index path that cannot be opened: Unreachable. + set("XAPIAN_DB_PATH", "/nonexistent/gn4-native-test-index"); + let result = Native.search("alcohol", "phenotype", 5).await; + assert_eq!(variant_name(&result), "Unreachable"); + + // 5. The default engine stays the gn3 forwarder: with + // SEARCH_ENGINE unset, a broken GN3_URL surfaces as the + // forwarder's Internal misconfiguration, never as a native + // engine call. + set("SEARCH_ENGINE", ""); + unsafe { std::env::remove_var("SEARCH_ENGINE") }; + set("GN3_URL", ":::not a url"); + let result = seam::search("alcohol", "phenotype", 5).await; + assert_eq!(variant_name(&result), "Internal"); + match prior_gn3_url { + Some(value) => set("GN3_URL", &value), + None => unsafe { std::env::remove_var("GN3_URL") }, + } + + // 6. Per-page invariant against the dev index (skips loudly when + // no index is configured, keeping hermetic runs green). + let dev_index = prior_path + .clone() + .or_else(|| std::env::var("XAPIAN_DB_PATH").ok().filter(|v| !v.is_empty())); + let dev_index = match dev_index.filter(|path| { + !path.is_empty() && std::fs::metadata(path).map(|m| m.is_dir()).unwrap_or(false) + }) { + Some(path) => path, + None => { + eprintln!("skipping per-page invariant: no XAPIAN_DB_PATH index configured"); + return; + } + }; + set("SEARCH_ENGINE", "native"); + set("XAPIAN_DB_PATH", &dev_index); + eprintln!("per-page invariant against dev index: {dev_index}"); + + // Forward limit=10: the engine must ignore it and return the FULL + // match set (PORT-DESIGN §5 — the recording compared complete + // match sets; Q02's is 57 632 hits). + let small = Native.search("alcohol", "phenotype", 10).await; + let small = match small { + Ok(hits) => hits, + Err(e) => panic!("dev-index search failed: {e:?}"), + }; + // ... and the same query at a different limit returns the same set. + let large = Native + .search("alcohol", "phenotype", 100) + .await + .expect("dev-index search with limit=100"); + assert_eq!( + small.len(), + large.len(), + "the forwarded limit must not change the returned set size" + ); + // The witness is only meaningful if the match set exceeds the + // forwarded limit; `alcohol` over the dev index matches far more + // than 10 phenotypes. + assert!( + small.len() > 10, + "dev-index alcohol/phenotype match set is {} — the per-page \ + invariant test needs a shape exceeding the forwarded limit", + small.len() + ); + eprintln!( + "per-page invariant: limit=10 forwarded, full set returned: {} hits", + small.len() + ); + + // Doc-data mapping: the first hit must carry the identifier fields + // the parity comparison reads ((dataset, name); parity-metric §1a). + if let Some(first) = small.first() { + assert!( + first.name.is_some() || first.dataset.is_some(), + "dev-index hits carry no identifier fields" + ); + } + + // 7. The typed search hits decode through the doc-data mapping: + // a typed query through a type the index documents (gene) must + // also come back Ok (the XT filter maps to real XT terms). + let genes = Native + .search("insulin", "gene", 20) + .await + .expect("dev-index insulin/gene search"); + eprintln!("dev-index reference counts: alcohol/phenotype={}, insulin/gene={}", small.len(), genes.len()); + + // Restore the environment we found. + match prior_path { + Some(value) => set("XAPIAN_DB_PATH", &value), + None => unsafe { std::env::remove_var("XAPIAN_DB_PATH") }, + } + match prior_engine { + Some(value) => set("SEARCH_ENGINE", &value), + None => unsafe { std::env::remove_var("SEARCH_ENGINE") }, + } +} diff --git a/tests/search_native_shapes.rs b/tests/search_native_shapes.rs new file mode 100644 index 0000000..b8f2632 --- /dev/null +++ b/tests/search_native_shapes.rs @@ -0,0 +1,127 @@ +//! Shape-CLASS gate for the native engine (this lane's translation of +//! the PORT-DESIGN stage gates, per AMENDMENT B: a DEVELOPMENT index, +//! class-level assertions, counts recorded as reference data only — +//! NEVER compared to production fixtures). +//! +//! Per shape, the expected class is derived from the parity harness +//! table `tests/search_parity.rs` (each entry below cites its +//! `shape!` line) plus the fixture's `recorded_status`: +//! +//! - `Match200` (recorded 200): the engine must return `Ok` with a hit +//! set — the DEV-INDEX COUNT IS PRINTED as reference data and never +//! compared to the production count (dev and production indexes +//! differ by design). +//! - `Error4xx` (recorded 4xx): the engine must return the typed parse +//! error `SearchError::InvalidQuery` (the blessed 422 contract). +//! - `Surface400` (Q48/Q49): route-level, zero engine calls — NOT run +//! here (pinned by the route tests). +//! +//! The lists are cumulative per stage, matching the parser +//! configuration at each commit: +//! - stage C3.1 (this file's first commit): free text, operators, +//! phrase, wildcard, case, unknown-prefix-as-text, the && shapes +//! and the one parser-error shape — Stem("en") + STEM_ALL_Z only. +//! +//! Env: `XAPIAN_DB_PATH` must point at the dev index (the gate runs +//! set it to ~/spikes/index-self-build/xapian-index); the test skips +//! loudly when unset so the hermetic suites stay green. + +use genenetwork4::search::{Engine, SearchError, SearchHit, native::Native}; + +/// The recorded behavior class this gate asserts (see module doc). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Class { + /// Recorded 200: parse + execute Ok, a hit set (any dev-index size). + Match200, + /// Recorded 4xx: typed parse rejection → InvalidQuery. + InvalidQuery, +} + +fn variant_name(result: &Result<Vec<SearchHit>, SearchError>) -> &'static str { + match result { + Ok(_) => "Ok", + Err(SearchError::InvalidQuery(_)) => "InvalidQuery", + Err(SearchError::Unreachable(_)) => "Unreachable", + Err(SearchError::Misbehaving(_)) => "Misbehaving", + Err(SearchError::Backend(_)) => "Backend", + Err(SearchError::Internal(_)) => "Internal", + } +} + +/// (id, raw query, forwarded type, expected class, citation into +/// tests/search_parity.rs). +const SHAPES: &[(&str, &str, &str, Class)] = &[ + // ---- stage C3.1: free text, operators, phrase, unknown prefixes ---- + ("Q01", "alcohol", "phenotype", Class::Match200), // parity.rs:112 + ("Q03", "alcohol dependence", "phenotype", Class::Match200), // parity.rs:121 + ("Q04", "\"alcohol dependence\"", "phenotype", Class::Match200), // parity.rs:129 + ("Q05", "alcohol*", "phenotype", Class::Match200), // parity.rs:137 + ("Q06", "Alcohol", "phenotype", Class::Match200), // parity.rs:145 + ("Q07", "alcohol AND dependence", "phenotype", Class::Match200), // parity.rs:153 + ("Q08", "alcohol OR dependence", "phenotype", Class::Match200), // parity.rs:161 + ("Q09", "alcohol NOT dependence", "phenotype", Class::Match200), // parity.rs:169 + ("Q10", "alcohol XOR dependence", "phenotype", Class::Match200), // parity.rs:177 + ("Q11", "alcohol NEAR dependence", "phenotype", Class::Match200), // parity.rs:185 + ("Q12", "alcohol ADJ dependence", "phenotype", Class::Match200), // parity.rs:193 + ("Q13", "alcohol and dependence", "phenotype", Class::Match200), // parity.rs:201 + // The && shapes are recorded 200s under libxapian 1.4.29 and live + // production (harness-report §4 F2/F4; binding-report R1)… + ("Q47", "a&&b", "phenotype", Class::Match200), // parity.rs:459 + // …while the truncated AND is the recorded 4xx (Q51.json). + ("Q51", "alcohol AND", "phenotype", Class::InvalidQuery), // parity.rs:477 + // An unregistered prefix parses as free text. + ("Q50", "foo:bar", "phenotype", Class::Match200), // parity.rs:469 + ("Q54", "alcohol &&", "phenotype", Class::Match200), // parity.rs:501 +]; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn native_engine_shape_class_gate() { + let dev_index = std::env::var("XAPIAN_DB_PATH").unwrap_or_default(); + if dev_index.is_empty() || !std::fs::metadata(&dev_index).map(|m| m.is_dir()).unwrap_or(false) { + eprintln!( + "SKIPPED: XAPIAN_DB_PATH is not set to an index directory \ + (set it to the dev index for the shape-class gate)" + ); + return; + } + eprintln!("shape-class gate against dev index: {dev_index}"); + + let mut passed = 0usize; + let mut failed = Vec::new(); + for (id, query, type_, expected) in SHAPES { + let result = Native.search(query, type_, 100).await; + match (expected, &result) { + (Class::Match200, Ok(hits)) => { + // Dev-index counts are REFERENCE DATA ONLY (AMENDMENT B): + // printed, never compared to production counts. + eprintln!(" {id} q={query:?} type={type_} class=Match200 dev_hits={}", hits.len()); + passed += 1; + } + (Class::InvalidQuery, Err(SearchError::InvalidQuery(detail))) => { + eprintln!(" {id} q={query:?} type={type_} class=InvalidQuery detail={detail:?}"); + passed += 1; + } + _ => { + eprintln!( + " {id} q={query:?} type={type_} UNEXPECTED outcome={}", + variant_name(&result) + ); + failed.push(*id); + } + } + } + + let summary = if failed.is_empty() { + "stage C3.1".to_string() + } else { + format!("FAILED: {failed:?}") + }; + eprintln!( + "SHAPE-CLASS GATE: {passed}/{} PASS ({summary})", + SHAPES.len() + ); + assert!( + failed.is_empty(), + "shape-class gate failures: {failed:?} (expected classes per tests/search_parity.rs)" + ); +} |
