about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabua@gmail.com>2026-10-07 22:44:18 +0300
committerAlexander_Kabui <alexanderkabua@gmail.com>2026-10-07 22:52:27 +0300
commit8568928775e82a65942e191f957789848f61569d (patch)
tree719da1c548db592d537e81b0f07b194025747034 /src
parente8279e59992c74e2d1d131b56c7bbb4741934494 (diff)
downloadgenenetwork4-8568928775e82a65942e191f957789848f61569d.tar.gz
src/search/native.rs (native engine): register the numeric range processors (C3.4)
NumberRangeProcessor on mean (slot 0), peak (1), peakmb (3), additive
(4), year (5) per search.py:234-243 (slots verified literal at
index-genenetwork:293-299); the markers carry the colon exactly like
gn3's `NumberRangeProcessor(i, prefix + ":")`.

The fork's processor parses bounds as f64 (commit 2673115, Amendment A:
the C3.4 "apply the f64 fix" workload is done at the library level) and
its bridge maps empty sides onto gn3's one-sided VALUE_LE / VALUE_GE
semantics natively — measured on the pinned toolchain before coding
(probe/, logs): `mean:10..20` -> VALUE_RANGE 0, `mean:..15` ->
VALUE_LE 0, `mean:10..` -> VALUE_GE 0. The skeleton-era 0.0/1e18
substitution is therefore superseded for these registrations by the
strictly more faithful one-sided forms.

AMENDMENT A nuance measured and handled: the fork's decline->MatchNothing
bridge (aa915af) also swallows NON-NUMERIC range bounds at the parser
level (`mean:abc..def` parses Ok to MatchNothing — probe evidence), so
the recorded production 400 "Unknown range operation" (Q52, graded 422
invalid_query) can no longer come from the parser. The engine therefore
re-checks the C++ NumberRangeProcessor contract itself (guard_numeric_
ranges): unquoted `<prefix>:` runs containing ".." must have f64-parse-
able non-empty sides, else SearchError::InvalidQuery("Unknown range
operation") before the index is opened. Residuals documented in the
guard's doc comment (inf/nan forms, the degenerate both-empty range —
binding-report R3's ("","") divergence, no production shape).

Gate evidence (~/spikes/port-execution-r2/logs/c34-*): hermetic lib pins
green incl. per-slot VALUE_RANGE/VALUE_LE/VALUE_GE parse forms (a
wrong-slot registration goes red) and the guard accept/reject matrix;
shape-CLASS gate 44/44 vs the dev index (Q28-Q31,Q35-Q39,Q44 parse Ok
with dev counts printed as REFERENCE ONLY per AMENDMENT B: mean:10..20
=1741, mean:..15=23132, peak:5..15=21857, year:2010..2020=22081, Q44
=332; Q52 -> InvalidQuery "Unknown range operation"); wide-range probe
proves slots 0/3/4/5 live on the dev index so the 0-hit shapes are
data-truth; new route-level native scenarios (tests/search_native_
route.rs) pin Q52's STATUS CLASS at the route: 422 invalid_query, with
a valid range serving 200. rustfmt --edition 2024 clean on every file
this commit touches.
Diffstat (limited to 'src')
-rw-r--r--src/search/native.rs210
1 files changed, 205 insertions, 5 deletions
diff --git a/src/search/native.rs b/src/search/native.rs
index 5e5e254..6d093ad 100644
--- a/src/search/native.rs
+++ b/src/search/native.rs
@@ -45,9 +45,24 @@
 use super::{Engine, SearchError, SearchHit};
 use std::sync::{Mutex, OnceLock};
 use xapian_rs::{
-    Database, Enquire, FieldProcessor, Operator, Query, QueryParser, Stem, StemStrategy,
+    Database, Enquire, FieldProcessor, NumberRangeProcessor, Operator, Query, QueryParser, Stem,
+    StemStrategy,
 };
 
+/// The numeric range prefixes and their value slots (search.py:234-243,
+/// the loop's `enumerate` with `position` carved out for slot 2):
+/// mean→0, peak→1, peakmb→3, additive→4, year→5. The slots are
+/// verified literal on the indexer side (index-genenetwork:293-299).
+/// The markers carry the colon, exactly like gn3's
+/// `NumberRangeProcessor(i, prefix + ":")`.
+const NUMERIC_RANGE_PREFIXES: [(&str, u32); 5] = [
+    ("mean:", 0),
+    ("peak:", 1),
+    ("peakmb:", 3),
+    ("additive:", 4),
+    ("year:", 5),
+];
+
 /// MSet bound for full-match-set retrieval: deliberately large so the
 /// whole match set comes back regardless of the forwarded `limit`
 /// (PORT-DESIGN §5; the recorded Q02 set alone is 57 632 hits, above
@@ -100,6 +115,15 @@ fn build_query_parser() -> QueryParser {
     qp.add_prefix::<&str>("wiki", Some("XWK"));
     qp.add_prefix::<&str>("RIF", Some("XRF"));
     qp.add_prefix::<&str>("WIKI", Some("XWK"));
+    // Numeric range processors (search.py:234-243; C3.4). The fork's
+    // NumberRangeProcessor parses bounds as f64 (the 2673115 fix) and
+    // its bridge maps empty sides onto gn3's one-sided VALUE_LE /
+    // VALUE_GE (measured: `mean:..15` → VALUE_LE 0, `mean:10..` →
+    // VALUE_GE 0), superseding the skeleton's 0.0/1e18 substitution
+    // for these registrations.
+    for (marker, slot) in NUMERIC_RANGE_PREFIXES {
+        qp.add_rangeprocessor(marker, slot, NumberRangeProcessor, false, false, None);
+    }
     qp
 }
 
@@ -121,6 +145,71 @@ impl FieldProcessor for LowercaseGroupProcessor {
     }
 }
 
+/// Guard the gn3 numeric-range contract at the app level (C3.4).
+///
+/// Xapian's C++ `NumberRangeProcessor` rejects a range whose non-empty
+/// sides are not valid floating-point numbers, and the query parser then
+/// throws `QueryParserError("Unknown range operation")` — the recorded
+/// production diagnostic for `mean:abc..def` (Q52, a 400 at gn3, graded
+/// 422 `invalid_query` here). The fork's decline→MatchNothing bridge
+/// (commit aa915af, AMENDMENT A) turns those declines into accepted
+/// empty-match queries instead (measured: `mean:abc..def` parses Ok to
+/// MatchNothing), so the engine re-checks the contract itself — the same
+/// app-level-guard pattern the port pins for the Hs/Mm invalid leaf
+/// (PORT-DESIGN C3.6, evidence-backed option (b); no shim extension).
+///
+/// The scan is deliberately conservative: it only looks at unquoted
+/// `<prefix>:` token runs that contain `..` (xapian consults range
+/// processors only for range syntax; a quoted range is phrase content
+/// and is skipped, matching the parser). Markers are case-sensitive, as
+/// xapian's are. Known residuals, neither graded: exotic forms accepted
+/// by Rust's `f64` parser but not C++ (`inf`/`nan`) pass this guard, and
+/// the both-empty degenerate range (`mean:..`) stays accepted (the
+/// fork's MatchNothing — binding-report R3's documented `("","")`
+/// divergence; no production shape uses it).
+fn guard_numeric_ranges(q: &str) -> Result<(), SearchError> {
+    let invalid_range = || SearchError::InvalidQuery("Unknown range operation".to_string());
+    let bytes = q.as_bytes();
+    let mut in_quotes = false;
+    let mut i = 0;
+    while i < bytes.len() {
+        if bytes[i] == b'"' {
+            in_quotes = !in_quotes;
+            i += 1;
+            continue;
+        }
+        if !in_quotes {
+            if let Some(&(marker, _slot)) = NUMERIC_RANGE_PREFIXES
+                .iter()
+                .find(|&&(marker, _)| q[i..].starts_with(marker))
+            {
+                // A marker only starts a field at a token boundary:
+                // `xmean:` never reaches the range processor either.
+                let token_start =
+                    i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
+                if token_start {
+                    // The value runs to whitespace, a parenthesis or a
+                    // quote — the same characters that end a field value
+                    // for the parser.
+                    let value = q[i + marker.len()..]
+                        .split(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | '"'))
+                        .next()
+                        .unwrap_or("");
+                    if let Some((begin, end)) = value.split_once("..") {
+                        for side in [begin, end] {
+                            if !side.is_empty() && side.parse::<f64>().is_err() {
+                                return Err(invalid_range());
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        i += 1;
+    }
+    Ok(())
+}
+
 /// The native xapian search engine. Configure the index directory with
 /// `XAPIAN_DB_PATH` and select it with `SEARCH_ENGINE=native`; the
 /// default remains the gn3 forwarder (see [`crate::search::search`]).
@@ -157,11 +246,19 @@ fn search_blocking(q: &str, type_: &str, limit: u64) -> Result<Vec<SearchHit>, S
             .map_err(|e| SearchError::InvalidQuery(e.message))?
     };
 
-    // 2. Open the index.
+    // 2. Guard the numeric-range contract the fork's decline bridge no
+    //    longer enforces at the parser level (C3.4; see
+    //    [`guard_numeric_ranges`]). Parser syntax errors keep
+    //    precedence, as in gn3; the guard runs before the index is
+    //    opened so `mean:abc..def` reports as a query fault (Q52) even
+    //    on a misconfigured deployment.
+    guard_numeric_ranges(q)?;
+
+    // 3. Open the index.
     let db_path = crate::config::Config::load().xapian_db_path;
     let db = open_database(&db_path)?;
 
-    // 3. Filter to the document type: OP_FILTER(parsed, "XT" + type)
+    // 4. Filter to the document type: OP_FILTER(parsed, "XT" + type)
     //    (search.py:298-300; XT terms are written at index time by the
     //    production indexer).
     let filtered = Query::combine(
@@ -170,14 +267,14 @@ fn search_blocking(q: &str, type_: &str, limit: u64) -> Result<Vec<SearchHit>, S
         Query::term(format!("XT{type_}"), None, None),
     );
 
-    // 4. Retrieve the full match set — the forwarded `limit` is
+    // 5. Retrieve the full match set — the forwarded `limit` is
     //    deliberately not applied here (per-page invariant, §5).
     let _ = limit;
     let mut enquire = Enquire::new(&db);
     enquire.set_query(&filtered, None);
     let mset = enquire.mset(0, FULL_MATCH_SET_MAX_ITEMS, None, None);
 
-    // 5. Map each hit's stored doc data (the indexer's JSON, the
+    // 6. Map each hit's stored doc data (the indexer's JSON, the
     //    schema gn3 serves verbatim: json.loads(document.get_data()),
     //    search.py:302) onto SearchHit; unknown fields flow through
     //    `extra`.
@@ -331,6 +428,109 @@ mod tests {
         assert!(prefixed("WIKI:diabetes", "ZXWK"));
     }
 
+    /// The numeric-range registrations (C3.4): each prefix must produce a
+    /// value leaf on its OWN slot (search.py:234-243; slots verified
+    /// literal at index-genenetwork:293-299), with one-sided ranges on
+    /// gn3's C++ NumberRangeProcessor semantics (VALUE_LE / VALUE_GE —
+    /// the fork's bridge, measured in the lane's probe). The slot in the
+    /// query description is the pin: a registration wired to the wrong
+    /// slot goes red here.
+    #[test]
+    fn numeric_ranges_parse_to_value_leaves_on_their_slots() {
+        let mut qp = build_query_parser();
+        let description = |qp: &mut QueryParser, q: &str| {
+            qp.parse_query_checked::<&str>(q, None, None)
+                .unwrap_or_else(|e| panic!("{q} must parse: {e:?}"))
+                .to_string()
+        };
+
+        for (marker, slot) in NUMERIC_RANGE_PREFIXES {
+            let query = format!("{marker}1..2");
+            let expected = format!("VALUE_RANGE {slot} ");
+            let got = description(&mut qp, &query);
+            assert!(
+                got.contains(&expected),
+                "{query} must parse to `{expected}…` on slot {slot}, got {got:?}"
+            );
+        }
+
+        // One-sided and open forms keep gn3's one-sided C++ semantics
+        // (probe: VALUE_LE 0 / VALUE_GE 0), not a 0.0/1e18 pair.
+        assert!(description(&mut qp, "mean:..15").contains("VALUE_LE 0 "));
+        assert!(description(&mut qp, "mean:10..").contains("VALUE_GE 0 "));
+        assert!(description(&mut qp, "year:..2020").contains("VALUE_LE 5 "));
+
+        // A non-range use of the prefix is plain text (gn3 measures the
+        // same: `mean:5` is a `mean 5` phrase, never a range).
+        let mean5 = description(&mut qp, "mean:5");
+        assert!(!mean5.contains("VALUE"), "mean:5 is text, got {mean5:?}");
+
+        // The fork's decline→MatchNothing bridge: an unparseable range
+        // PARSES (the bridge prevents the OP_INVALID abort); the typed
+        // rejection is the engine-level guard's job (next test).
+        let declined = description(&mut qp, "mean:abc..def");
+        assert!(
+            !declined.contains("VALUE"),
+            "declined range must be MatchNothing"
+        );
+    }
+
+    /// The C3.4 app-level guard: `mean:abc..def` must surface as
+    /// InvalidQuery with gn3's recorded production diagnostic
+    /// ("Unknown range operation", Q52), while every valid form —
+    /// closed, one-sided, exponent, mixed boolean queries — passes.
+    #[test]
+    fn numeric_range_guard_rejects_unparseable_bounds() {
+        for query in [
+            "mean:abc..def",
+            "(mean:abc..def)",
+            "year:twenty..thirty",
+            "peak:abc..",
+            "additive:..def",
+            "peakmb:1.5..x",
+            "mean:10..20..30",
+        ] {
+            match guard_numeric_ranges(query) {
+                Err(SearchError::InvalidQuery(message)) => {
+                    assert_eq!(message, "Unknown range operation", "for {query:?}");
+                }
+                other => panic!("{query:?} must be rejected, got {other:?}"),
+            }
+        }
+        // Q52's exact recorded shape, once more on its own.
+        assert!(matches!(
+            guard_numeric_ranges("mean:abc..def"),
+            Err(SearchError::InvalidQuery(ref message))
+                if message == "Unknown range operation"
+        ));
+
+        for query in [
+            "mean:10..20",
+            "mean:..15",
+            "mean:10..",
+            "mean:..",
+            "mean:1e3..2e3",
+            "mean:99999..100000",
+            "author:mulligan AND year:2010..2015",
+            "year:2010..2020 AND peak:5..15",
+            // Not range syntax: no "..", so xapian treats it as text.
+            "mean:abc",
+            // Case-sensitive markers, as in xapian.
+            "Mean:abc..def",
+            // Mid-token occurrences never reach the processor.
+            "xmean:abc..def",
+            // Quoted content is phrase text, never a range.
+            "\"mean:abc..def\"",
+            // Unregistered prefixes are free text (Q50).
+            "foo:abc..def",
+        ] {
+            assert!(
+                guard_numeric_ranges(query).is_ok(),
+                "{query:?} must pass the range guard"
+            );
+        }
+    }
+
     /// The index-open guards, without touching a real index.
     #[test]
     fn open_database_maps_failures_onto_the_seam_vocabulary() {