diff options
| author | Alexander_Kabui <alexanderkabua@gmail.com> | 2026-10-07 22:59:17 +0300 |
|---|---|---|
| committer | Alexander_Kabui <alexanderkabua@gmail.com> | 2026-10-07 22:59:17 +0300 |
| commit | 9a76f1c7b855ace11de51d1e625fe4205f0096af (patch) | |
| tree | 6844a11696c3328686f08f0c26519de0bd1dc9bf /src | |
| parent | 8568928775e82a65942e191f957789848f61569d (diff) | |
| download | genenetwork4-9a76f1c7b855ace11de51d1e625fe4205f0096af.tar.gz | |
src/search/native.rs (native engine): register the position/pos processor (C3.5)
The gn3 SI-suffix FieldProcessor on slot 2 (search.py:237-241), for both
the `position` prefix and its `pos` alias, sharing one processor type
(each registration Box::leaks its own instance inside the binding; the
one-per-process parser absorbs that).
Ported faithfully from search.py:136-165:
- apply_si_suffix (136-142): trailing k/m/g (case-insensitive) multiply
by 10^3/6/9; an UNSUFFIXED value must be an integer (`int(location)`)
— `position:1.5` declines exactly where gn3 raises ValueError.
- parse_position (145-155): a `..` spec is a range with either side
optionally empty; a point expands to +/-50 000 bases clamped at 0.
- the slot-2 query (158-165): sides convert bases->megabases and keep
gn3's one-sided C++ NumberRangeProcessor semantics (VALUE_GE /
VALUE_LE for an empty side, measured identical to the bridge forms);
the degenerate both-empty range is MatchNothing (binding-report R3's
documented ("","") divergence, no production shape).
AMENDMENT A verified end-to-end: the fork's decline->MatchNothing bridge
(aa915af) is IN the dependency and behaves as documented — an
unparseable spec (`position:abc`) parses to an empty-match query and
serves 200 with 0 hits (POSABC gate row, dev index), never an <INVALID>
leaf, never a process abort; `position:abc OR alcohol` keeps its real
OR arm (xapian documents MatchNothing as boolean false). The
registration-only job was the lane's plan; no re-fixing of the library.
Q53 `position:` never reaches the processor (empty value -> free text,
recorded production 200 with 576 hits; dev reference count printed).
Gate evidence (~/spikes/port-execution-r2/logs/c35-*): hermetic pins
green (21 lib tests — slot-2 VALUE_RANGE/VALUE_GE/VALUE_LE forms, SI
case-insensitivity, point clamp, decline matrix incl. MatchNothing OR
semantics); shape-CLASS gate 49/49 cumulative vs the dev index
(Q32=1, Q33=2, Q34=1 dev gene hits at 1.05-1.06Mb/7.45-7.55Mb, Q53=1017
free-text hits, POSABC=0 — dev counts REFERENCE ONLY per AMENDMENT B).
rustfmt --edition 2024 clean on the touched files.
Diffstat (limited to 'src')
| -rw-r--r-- | src/search/native.rs | 185 |
1 files changed, 184 insertions, 1 deletions
diff --git a/src/search/native.rs b/src/search/native.rs index 6d093ad..a7b02cf 100644 --- a/src/search/native.rs +++ b/src/search/native.rs @@ -46,7 +46,7 @@ use super::{Engine, SearchError, SearchHit}; use std::sync::{Mutex, OnceLock}; use xapian_rs::{ Database, Enquire, FieldProcessor, NumberRangeProcessor, Operator, Query, QueryParser, Stem, - StemStrategy, + StemStrategy, ToValue, }; /// The numeric range prefixes and their value slots (search.py:234-243, @@ -63,6 +63,15 @@ const NUMERIC_RANGE_PREFIXES: [(&str, u32); 5] = [ ("year:", 5), ]; +/// The value slot holding gene positions, in MEGABASES (slot 2 — +/// `range_prefixes.index("position")`, search.py:234-235; the indexer's +/// `add_mb` writes slot 2, index-genenetwork:295). +const POSITION_SLOT: u32 = 2; +/// A point location expands to ± 50 000 bases (search.py:151-155). +const HALF_WINDOW_BASES: f64 = 50_000.0; +/// Bases per megabase (search.py:162-165: `Decimal(val)/10**6`). +const BASES_PER_MB: f64 = 1_000_000.0; + /// 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 @@ -124,6 +133,12 @@ fn build_query_parser() -> QueryParser { for (marker, slot) in NUMERIC_RANGE_PREFIXES { qp.add_rangeprocessor(marker, slot, NumberRangeProcessor, false, false, None); } + // `position` + its `pos` alias (search.py:237-241; C3.5): the custom + // SI-suffix FieldProcessor on slot 2. Both registrations share one + // processor type; each registration Box::leaks its own instance + // inside the binding (the one-per-process parser absorbs that). + qp.add_custom_boolean_prefix::<_, &str>("position", PositionProcessor, None); + qp.add_custom_boolean_prefix::<_, &str>("pos", PositionProcessor, None); qp } @@ -145,6 +160,86 @@ impl FieldProcessor for LowercaseGroupProcessor { } } +/// gn3's `apply_si_suffix` (search.py:136-142): an optional trailing +/// k/m/g multiplies by 10^3/6/9 (case-insensitive — gn3 lowercases the +/// last character before the lookup); an unsuffixed value must be an +/// INTEGER (`int(location)`, search.py:142 — so `1.5` without a +/// suffix is a gn3 ValueError, not a base-pair coordinate). Returns +/// `None` exactly where gn3 raises `ValueError` — the caller decides +/// what that means (position: MatchNothing per the parity-metric +/// amendment; Hs/Mm: the invalid-location sentinel). +fn apply_si_suffix(value: &str) -> Option<f64> { + let (digits, multiplier) = match value.chars().last()?.to_ascii_lowercase() { + 'k' => (&value[..value.len() - 1], 1e3), + 'm' => (&value[..value.len() - 1], 1e6), + 'g' => (&value[..value.len() - 1], 1e9), + _ => return value.parse::<i64>().ok().map(|n| n as f64), + }; + digits.parse::<f64>().ok().map(|n| n * multiplier) +} + +/// gn3's `parse_position` (search.py:145-155): a `..` spec is a range +/// with either side optionally empty; a point expands to ±50 kb clamped +/// at 0. Sides are in BASES. +fn parse_position(spec: &str) -> Option<(Option<f64>, Option<f64>)> { + if let Some((begin, end)) = spec.split_once("..") { + let begin = if begin.is_empty() { + None + } else { + Some(apply_si_suffix(begin)?) + }; + let end = if end.is_empty() { + None + } else { + Some(apply_si_suffix(end)?) + }; + Some((begin, end)) + } else { + let point = apply_si_suffix(spec)?; + Some(( + Some((point - HALF_WINDOW_BASES).max(0.0)), + Some(point + HALF_WINDOW_BASES), + )) + } +} + +/// The slot-2 value query for already-parsed position sides (gn3's +/// `parse_position_field`, search.py:158-165, minus the NumberRange- +/// Processor indirection): each side converts bases→megabases; an +/// empty side keeps gn3's one-sided C++ NumberRangeProcessor semantics +/// (VALUE_GE / VALUE_LE — the same forms the fork's bridge produces for +/// the registered numeric ranges); both empty is MatchNothing, the +/// degenerate form binding-report R3 documents as diverging (no +/// production shape uses it). +fn position_value_query(begin: Option<f64>, end: Option<f64>) -> Query { + let megabases = |bases: f64| (bases / BASES_PER_MB).serialize(); + match (begin, end) { + (Some(b), Some(e)) => Query::value_range(POSITION_SLOT, megabases(b), megabases(e)), + (Some(b), None) => Query::value_ge(POSITION_SLOT, megabases(b)), + (None, Some(e)) => Query::value_le(POSITION_SLOT, megabases(e)), + (None, None) => Query::match_nothing(), + } +} + +/// gn3's `position` / `pos` FieldProcessor (search.py:237-241; C3.5): +/// SI-suffixed base-pair coordinates become a slot-2 megabase value +/// query, points expanding to ±50 kb clamped at 0. An unparseable spec +/// declines (`None`), which the fork's bridge maps to MatchNothing +/// (commit aa915af, Amendment A) — the parity-metric amendment's +/// blessed 200-empty default. gn3's own behavior for that class is an +/// escaping `ValueError` (a latent 500 crash, curl-verified live), +/// explicitly NOT a contract; no recorded fixture pins it (Q53 +/// `position:` is an empty value and never reaches the processor). +#[derive(Clone)] +struct PositionProcessor; + +impl FieldProcessor for PositionProcessor { + fn process(&self, term: &str) -> Option<Query> { + let (begin, end) = parse_position(term)?; + Some(position_value_query(begin, end)) + } +} + /// Guard the gn3 numeric-range contract at the app level (C3.4). /// /// Xapian's C++ `NumberRangeProcessor` rejects a range whose non-empty @@ -531,6 +626,94 @@ mod tests { } } + /// The position/pos registrations (C3.5): SI-suffixed base-pair + /// coordinates parse to slot-2 MEGABASE value queries, points expand + /// to ±50 kb clamped at 0, and unparseable specs decline to the + /// bridge's MatchNothing (verified end-to-end in the dev-index gate: + /// `position:abc` serves 200 with 0 hits, never a process abort). + #[test] + fn position_prefixes_parse_si_suffixed_slot_two_queries() { + let mut qp = build_query_parser(); + let parse = |qp: &mut QueryParser, q: &str| { + qp.parse_query_checked::<&str>(q, None, None) + .unwrap_or_else(|e| panic!("{q} must parse: {e:?}")) + }; + + // Q32/Q34's shape: 1.05M..1.06M bases -> 1.05..1.06 Mb on slot 2. + for q in ["position:1.05M..1.06M", "pos:1.05M..1.06M"] { + let query = parse(&mut qp, q); + assert!( + query.to_string().contains("VALUE_RANGE 2 "), + "{q} must be a slot-2 value range, got {query}" + ); + } + + // Q33's shape: a point expands to ±50 kb (7 500 000 bases -> + // 7.45..7.55 Mb). + assert!( + parse(&mut qp, "position:7500000") + .to_string() + .contains("VALUE_RANGE 2 ") + ); + + // SI suffixes are case-insensitive (search.py:136-142 lowercases + // the last character). + assert!( + parse(&mut qp, "position:1.05m..1.06m") + .to_string() + .contains("VALUE_RANGE 2 ") + ); + assert!( + parse(&mut qp, "position:250k..500k") + .to_string() + .contains("VALUE_RANGE 2 ") + ); + + // One-sided position ranges keep gn3's one-sided semantics. + assert!( + parse(&mut qp, "position:1M..") + .to_string() + .contains("VALUE_GE 2 ") + ); + assert!( + parse(&mut qp, "position:..1M") + .to_string() + .contains("VALUE_LE 2 ") + ); + + // The clamp: a point below 50 kb clamps its lower bound at 0 + // (search.py:151-155) — pinned by the formula's parse form, the + // same slot-2 range. + assert!( + parse(&mut qp, "position:25000") + .to_string() + .contains("VALUE_RANGE 2 ") + ); + + // The MatchNothing bridge (C3.5's verification requirement): an + // unparseable spec parses to an empty-match query — never an + // <INVALID> leaf, never a process abort (fork commit aa915af, + // tested end-to-end against the dev index in the shape gate and + // the route scenarios). `position:1.5` declines too: gn3's + // unsuffixed values must be integers (int(location), + // search.py:142). + for q in ["position:abc", "pos:abc", "position:1.5", "position:1e3"] { + let query = parse(&mut qp, q); + assert!( + !query.to_string().contains("VALUE"), + "{q} must decline to MatchNothing, got {query}" + ); + } + // Xapian documents MatchNothing as boolean false in OR trees: + // `position:abc OR alcohol` still parses and keeps its real arm. + let combined = parse(&mut qp, "position:abc OR alcohol"); + let terms: Vec<String> = combined.unique_terms().map(|t| t.to_string()).collect(); + assert!( + terms.iter().any(|t| t.starts_with("Zalcohol")), + "the real OR arm must survive, got {terms:?}" + ); + } + /// The index-open guards, without touching a real index. #[test] fn open_database_maps_failures_onto_the_seam_vocabulary() { |
