//! 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, 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). The typed payload // carries the parser's own classification. set("XAPIAN_DB_PATH", ""); set("SEARCH_ENGINE", "native"); let result = Native.search("alcohol AND", "phenotype", 5, 1).await; assert_eq!(variant_name(&result), "InvalidQuery"); let Err(SearchError::InvalidQuery { message, xapian_error_type, }) = result else { unreachable!(); }; assert_eq!(message, "Syntax: AND "); assert_eq!(xapian_error_type.as_deref(), Some("QueryParserError")); // 2. The same query through the seam dispatch proves the config // switch selects the native engine. let result = seam::search("alcohol AND", "phenotype", 5, 1).await; assert_eq!(variant_name(&result), "InvalidQuery"); // 3. An unset index path is a local misconfiguration: Internal. let result = Native.search("alcohol", "phenotype", 5, 1).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, 1).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, 1).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, 1).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, 1) .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, 1) .await .expect("dev-index insulin/gene search"); eprintln!( "dev-index reference counts: alcohol/phenotype={}, insulin/gene={}", small.len(), genes.len() ); // 8. The page window (origin/main's pagination through the seam): // `page` shifts retrieval by (page - 1) * limit ranks, exactly // as gn3's per_page/page pair does. The second page must be // everything from rank 11 onward (the limit-ignored remainder // shifted by one window), a page past the match set must be // empty, and the two pages' keys must be disjoint. Pinned at // the engine seam so the native engine keeps serving the // route's pagination contract after the C4 flip. let hit_key = |h: &SearchHit| { ( h.dataset.clone().unwrap_or_default(), h.name.clone().unwrap_or_default(), ) }; let page2 = Native .search("alcohol", "phenotype", 10, 2) .await .expect("dev-index page-2 search"); assert_eq!( page2.len() + 10, small.len(), "page 2 with limit=10 must return the match set from rank 11 onward" ); let expected_keys: Vec<_> = small[10..].iter().map(|h| hit_key(h)).collect(); let got_keys: Vec<_> = page2.iter().map(|h| hit_key(h)).collect(); assert_eq!( got_keys, expected_keys, "page 2 must start exactly at rank 11 — the window offset is (page-1)*limit" ); let head: std::collections::HashSet<_> = small[..10].iter().map(|h| hit_key(h)).collect(); assert!( page2.iter().all(|h| !head.contains(&hit_key(h))), "page 1 and page 2 must be disjoint" ); let far = Native .search("alcohol", "phenotype", 10, 100_000) .await .expect("dev-index far-page search"); assert!( far.is_empty(), "a page past the match set must be empty, got {} hits", far.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") }, } }