AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(search): apply filters around hybrid queries (#943) — bool{must:hybrid,filter} pushed into every leg, post_filter+hybrid rejected 400
xerj-orgb311d66975e5
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 712da8dc3..2288c9e73 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -3453,6 +3453,14 @@ pub struct EsSearchBody {/// word would return lexical order to a caller who asked for something else.#[serde(default)]pub rerank: Option<Value>,+ /// `post_filter` — accepted-and-ignored for ordinary queries (it never+ /// reaches the engine; implementing it generally is #204), but captured+ /// here because beside a `hybrid` query it must be REJECTED (#943): the+ /// fused hits came back unfiltered with a 200, the exact+ /// accepted-and-wrong class. `build_search_request` refuses that one+ /// combination with a 400 naming the supported spellings.+ #[serde(default)]+ pub post_filter: Option<Value>,}impl Default for EsSearchBody {@@ -3489,6 +3497,7 @@ impl Default for EsSearchBody {pit: None,timeout: None,rerank: None,+ post_filter: None,}}}@@ -3504,8 +3513,10 @@ impl Default for EsSearchBody {/// Full set of top-level keys ES 8.13.4 accepts on the `_search` request/// source (live-probed against the reference cluster), NOT merely the subset/// `EsSearchBody` models. Keys ES accepts but xerj does not act on-/// (`terminate_after`, `post_filter`, `stats`, `ext`) stay accepted-and-ignored-/// exactly as before — only genuinely-unknown keys are rejected.+/// (`terminate_after`, `stats`, `ext`) stay accepted-and-ignored exactly as+/// before — only genuinely-unknown keys are rejected. `post_filter` is+/// accepted-and-ignored too, EXCEPT beside a hybrid query, where it is+/// rejected (#943): the fused hits used to come back unfiltered with a 200.const ES_SEARCH_TOP_LEVEL_KEYS: &[&str] = &["query","from",@@ -6132,6 +6143,21 @@ fn build_search_request(let mut req = parse_request(&query_body).map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))?;+ // #943: `post_filter` never reaches the engine (accepted-and-ignored for+ // ordinary queries — implementing it generally is #204), but beside a+ // hybrid query it answered 200 with the UNFILTERED fused hits, which is+ // the accepted-and-wrong class. Reject that one combination with the+ // same 400 style the engine already uses for aggs-beside-hybrid,+ // naming the supported spellings (the filter inside each leg, or the+ // bool{must, filter} wrapper the engine now pushes into every leg).+ if body.post_filter.is_some() && req.query.contains_hybrid() {+ return Err(xerj_common::XerjError::invalid_query(+ "post_filter is not supported with hybrid/fusion queries; put the \+ filter inside each leg (hybrid.queries[].query) or beside the hybrid \+ as bool{must: [hybrid], filter: […]} so it is applied to every leg",+ ));+ }+// Make sure size is respected exactly (parse_request uses default_size).req.size = body.size;req.from = body.from;@@ -21066,6 +21092,9 @@ pub async fn search_with_scroll(pit: body.pit.clone(),timeout: body.timeout.clone(),rerank: None,+ // #943: forward so the post_filter-beside-hybrid rejection in+ // `build_search_request` covers scroll requests too.+ post_filter: body.post_filter.clone(),};// page_size: what the caller requested (or default 10)let page_size = body.size;diff --git a/engine/crates/xerj-api/tests/hybrid_bool_filter_applied.rs b/engine/crates/xerj-api/tests/hybrid_bool_filter_applied.rsnew file mode 100644index 000000000..faf04c9ff--- /dev/null+++ b/engine/crates/xerj-api/tests/hybrid_bool_filter_applied.rs@@ -0,0 +1,272 @@+//! Issue #943: filters wrapped AROUND a `hybrid` query were accepted and+//! wrong over the ES wire.+//!+//! * `bool { must: { hybrid … }, filter: […] }` → 200 with **0 hits** (the+//! engine's generic doc matcher has no Hybrid arm, so the must clause+//! matched nothing).+//! * top-level `post_filter` beside `hybrid` → 200 with the **unfiltered**+//! hits (`post_filter` never reaches any executor — accepted-and-ignored,+//! the #204 class).+//!+//! The fix: the engine peels `bool{must: hybrid, filter}` and pushes the+//! filter into every leg (exactly the "filter inside each leg" spelling the+//! issue verified as correct), and the API layer rejects `post_filter` beside+//! a hybrid query with a 400 naming the supported spellings — mirroring the+//! `aggs`-beside-hybrid 400 that already existed.+//!+//! Elasticsearch is referenced for wire semantics only; no ES code is here.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++async fn app() -> (axum::Router, tempfile::TempDir) {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ (xerj_api::router::build_es_compat_router(state), dir)+}++async fn json_req(+ app: &axum::Router,+ method: &str,+ path: &str,+ body: Value,+) -> (StatusCode, Value) {+ let response = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request"),+ )+ .await+ .expect("response");+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .expect("body");+ (+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ )+}++async fn hyb943_app_with_docs() -> (axum::Router, tempfile::TempDir) {+ let (app, dir) = app().await;+ let (st, b) = json_req(+ &app,+ "PUT",+ "/hy943",+ json!({ "mappings": { "properties": {+ "title": { "type": "text" },+ "body": { "type": "text" },+ "ax_format": { "type": "keyword" }+ } } }),+ )+ .await;+ assert!(st.is_success(), "create index: {st} {b}");+ for (id, title, body, ax_format) in [+ ("d1", "alpha beta", "gamma delta", "eml"),+ ("d2", "gamma delta", "alpha beta", "pdf"),+ ("d3", "epsilon zeta", "eta theta", "txt"),+ ("d4", "alpha zeta", "alpha theta", "eml"),+ ] {+ let (st, b) = json_req(+ &app,+ "POST",+ &format!("/hy943/_doc/{id}"),+ json!({ "title": title, "body": body, "ax_format": ax_format }),+ )+ .await;+ assert!(st.is_success(), "index {id}: {st} {b}");+ }+ let (_s, _b) = json_req(&app, "POST", "/hy943/_refresh", json!({})).await;+ (app, dir)+}++fn hyb943_legs() -> Value {+ json!([+ { "query": { "match": { "title": { "query": "alpha beta", "operator": "and" } } },+ "weight": 1.0 },+ { "query": { "match": { "body": { "query": "alpha beta", "operator": "and" } } },+ "weight": 0.8 }+ ])+}++fn hit_ids_and_scores(body: &Value) -> Vec<(String, f64)> {+ body.pointer("/hits/hits")+ .and_then(Value::as_array)+ .map(|hits| {+ hits.iter()+ .filter_map(|h| {+ h.get("_id")+ .and_then(Value::as_str)+ .map(String::from)+ .zip(h.get("_score").and_then(Value::as_f64))+ })+ .collect()+ })+ .unwrap_or_default()+}++/// #943 shape A over HTTP: `bool{must: hybrid, filter}` must return the+/// filtered hits (pre-fix: 200 with `hits.total.value == 0`), and must equal+/// the verified-correct "filter inside each leg" spelling on ids AND fused+/// scores.+#[tokio::test]+async fn bool_must_hybrid_with_filter_applies_the_filter() {+ let (app, _dir) = hyb943_app_with_docs().await;++ let hybrid = json!({+ "hybrid": { "queries": hyb943_legs(), "fusion": { "type": "rrf", "k": 60 } }+ });++ let (status, body) = json_req(+ &app,+ "POST",+ "/hy943/_search",+ json!({ "size": 10, "query": {+ "bool": {+ "must": hybrid,+ "filter": [ { "term": { "ax_format": "eml" } } ]+ }+ } }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "_search status: {status} {body}");+ let total = body+ .pointer("/hits/total/value")+ .and_then(Value::as_u64)+ .expect("hits.total.value");+ assert!(+ total > 0,+ "#943: bool{{must: hybrid, filter}} returned 0 hits over HTTP: {body}"+ );+ let shape_a = hit_ids_and_scores(&body);+ assert!(+ shape_a.iter().all(|(id, _)| id == "d1"),+ "only the eml doc that matches a leg may survive: {shape_a:?}"+ );++ // Spelling B: the same filter inside each leg — same ids, same scores.+ let legs_eml: Vec<Value> = hyb943_legs()+ .as_array()+ .unwrap()+ .iter()+ .map(|leg| {+ json!({ "query": {+ "bool": {+ "must": [leg["query"].clone()],+ "filter": [ { "term": { "ax_format": "eml" } } ]+ }+ }, "weight": leg["weight"] })+ })+ .collect();+ let (status_b, body_b) = json_req(+ &app,+ "POST",+ "/hy943/_search",+ json!({ "size": 10, "query": {+ "hybrid": { "queries": legs_eml, "fusion": { "type": "rrf", "k": 60 } }+ } }),+ )+ .await;+ assert_eq!(+ status_b,+ StatusCode::OK,+ "spelling B status: {status_b} {body_b}"+ );+ assert_eq!(+ shape_a,+ hit_ids_and_scores(&body_b),+ "#943: shape A must equal the filter-inside-each-leg spelling"+ );+}++/// #943 shape C: `post_filter` beside a `hybrid` query was silently ignored+/// (the unfiltered hits came back). It must now be a 400 naming the supported+/// spellings, mirroring the existing aggs-beside-hybrid rejection.+#[tokio::test]+async fn post_filter_beside_hybrid_is_a_400_naming_the_spellings() {+ let (app, _dir) = hyb943_app_with_docs().await;++ let (status, body) = json_req(+ &app,+ "POST",+ "/hy943/_search",+ json!({+ "size": 4,+ "post_filter": { "term": { "ax_format": "eml" } },+ "query": { "hybrid": {+ "queries": hyb943_legs(),+ "fusion": { "type": "rrf", "k": 60 }+ } }+ }),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "#943: post_filter beside hybrid must fail loud (400), not answer with \+ the unfiltered hits: {status} {body}"+ );+ let reason = body+ .pointer("/error/reason")+ .or_else(|| body.pointer("/error/root_cause/0/reason"))+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ reason.contains("post_filter") && reason.contains("hybrid"),+ "#943: the 400 must name the key and the supported spellings: {body}"+ );+}++/// Guard against over-rejecting: `post_filter` beside a PLAIN query keeps its+/// documented accepted-and-ignored behaviour (#204 tracks implementing it) —+/// the 400 fires only when the query contains a hybrid.+#[tokio::test]+async fn post_filter_beside_a_plain_match_stays_accepted_and_ignored() {+ let (app, _dir) = hyb943_app_with_docs().await;++ let (status, body) = json_req(+ &app,+ "POST",+ "/hy943/_search",+ json!({+ "size": 10,+ "post_filter": { "term": { "ax_format": "eml" } },+ "query": { "match_all": {} }+ }),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::OK,+ "post_filter beside a plain query must stay 200 (accepted-and-ignored): {body}"+ );+ let ids: Vec<String> = body+ .pointer("/hits/hits")+ .and_then(Value::as_array)+ .map(|hits| {+ hits.iter()+ .filter_map(|h| h.get("_id").and_then(Value::as_str).map(String::from))+ .collect()+ })+ .unwrap_or_default();+ assert_eq!(+ ids.len(),+ 4,+ "the plain query must return its UNfiltered hit set (all four docs, not \+ just the two eml ones — post_filter is not applied to plain queries yet, \+ see #204): {ids:?}"+ );+}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 0910053a2..f8f7a1970 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -17482,6 +17482,29 @@ impl Index {.await;}+ // ── #943: a `hybrid` the ladder above declined is about to be+ // silently dropped ──────────────────────────────────────────────────+ // Every hybrid-aware peel has passed by now, so a Hybrid node still+ // in the tree is heading for the generic path, where the doc+ // matcher's catch-all (`_ => false`) makes the clause match nothing:+ // `bool{must:[hybrid, …]}`, a hybrid beside a must_not, dis_max over+ // a hybrid … all answered 200 with 0 hits (or with the non-hybrid+ // clauses' hits and the hybrid silently dropped). Fail loud with a+ // 400 naming the supported spellings, mirroring the `_passage` guard+ // above and the aggs-beside-hybrid rejection in+ // `run_hybrid_with_deadline`. `unwrap_single_clause_bool` has already+ // erased the harmless one-clause wrappers, so this only fires on+ // shapes that genuinely cannot execute.+ if query.contains_hybrid() {+ return Err(EngineError::Common(xerj_common::XerjError::invalid_query(+ "hybrid queries are supported at the top level or as \+ bool{must: [hybrid], filter: […]} (the filter clauses are pushed \+ into every leg); this query nests a hybrid where it cannot be \+ executed and would silently match nothing — put the filter inside \+ each leg of hybrid.queries, or move the hybrid to the top level",+ )));+ }+// ── #825: `knn` clause inside a compound `bool` ────────────────────────// Every vector-aware short-circuit above has declined by now, so a// `Knn` node still in the tree is about to hit the generic path,@@ -36056,6 +36079,60 @@ fn peel_hybrid_query(QueryNode::Constant { query, .. }| QueryNode::Boosted { query, .. }| QueryNode::Named { query, .. } => peel_hybrid_query(query),+ QueryNode::Bool {+ must,+ should,+ filter,+ must_not,+ minimum_should_match,+ } => {+ // #943: mirror peel_knn_query / peel_semantic_query — dispatch the+ // simple case of a bool with exactly one must/should clause+ // holding a `hybrid`. The Hybrid AST has no filter field, so the+ // wrapper's `filter` clauses are pushed into EVERY leg as+ // `Bool{must:[leg], filter:[…]}` — mechanically identical to the+ // spelling the issue verified as correct (filter inside each+ // leg), where each wrapped leg re-enters search_inner and the+ // semantic/knn/bool paths all apply filters. Without this arm the+ // wrapper fell through to the generic path, whose doc matcher has+ // no `QueryNode::Hybrid` arm (catch-all `_ => false`), so the+ // must clause matched NOTHING — a 200 with 0 hits. Multi-clause+ // bools (a hybrid clause beside a lexical one) still fall through+ // to the contains-hybrid guard below.+ if !must_not.is_empty() {+ return None;+ }+ let candidates: Vec<&QueryNode> = must.iter().chain(should.iter()).collect();+ if candidates.len() != 1 {+ return None;+ }+ // A lone `should` clause with an explicit minimum_should_match+ // changes the wrapper's own semantics (0 = optional, ≥2 with one+ // clause = matches nothing, Field/Script resolve per doc) — those+ // are not equivalent to `must`, so decline instead of silently+ // re-reading them.+ if !should.is_empty() && minimum_should_match.is_some() {+ return None;+ }+ let (sub_queries, fusion) = peel_hybrid_query(candidates[0])?;+ if filter.is_empty() {+ return Some((sub_queries, fusion));+ }+ let wrapped = sub_queries+ .into_iter()+ .map(|wq| xerj_query::ast::WeightedQuery {+ query: QueryNode::Bool {+ must: vec![wq.query],+ should: Vec::new(),+ must_not: Vec::new(),+ filter: filter.clone(),+ minimum_should_match: None,+ },+ weight: wq.weight,+ })+ .collect();+ Some((wrapped, fusion))+ }_ => None,}}diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rsindex 2bda8a24b..ce15e2a11 100644--- a/engine/crates/xerj-engine/tests/integration.rs+++ b/engine/crates/xerj-engine/tests/integration.rs@@ -1794,6 +1794,316 @@ async fn passage_provenance_rejects_ambiguous_multi_vector_composition_in_any_or}}+// ── #943: filters around a hybrid query ──────────────────────────────────────+//+// Two shapes were accepted and wrong: `bool{must: hybrid, filter: […]}` matched+// NOTHING (the generic doc matcher has no Hybrid arm, so the must clause failed+// every doc → 200 with 0 hits), and a top-level `post_filter` beside `hybrid`+// was silently ignored. The fix gives `peel_hybrid_query` the same Bool arm its+// siblings `peel_knn_query` / `peel_semantic_query` already have: the wrapper's+// filter clauses are pushed into EVERY leg, which is exactly the+// "filter inside each leg" spelling the issue verified as correct.++/// Docs shared by the #943 tests: two legs (`match` on `title`, `match` on+/// `body`, both operator AND) whose match sets are singletons, so the fused+/// union, the per-leg ranks, and therefore the RRF scores are fully+/// deterministic.+async fn hyb943_index() -> std::sync::Arc<xerj_engine::Index> {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("hyb943", Schema::empty()).unwrap();+ let idx = engine.get_index("hyb943").unwrap();+ for (id, title, body, ax_format) in [+ ("d1", "alpha beta", "gamma delta", "eml"),+ ("d2", "gamma delta", "alpha beta", "pdf"),+ ("d3", "epsilon zeta", "eta theta", "txt"),+ ("d4", "alpha zeta", "alpha theta", "eml"),+ ] {+ idx.index_document(+ Some(id.into()),+ json!({ "title": title, "body": body, "ax_format": ax_format }),+ )+ .await+ .unwrap();+ }+ idx.refresh().await.unwrap();+ idx+}++/// Legs shared by the #943 tests: title match hits only d1, body match hits+/// only d2, weights 1.0 / 0.8 like the issue's reproduce.+fn hyb943_legs() -> Value {+ json!([+ { "query": { "match": { "title": { "query": "alpha beta", "operator": "and" } } },+ "weight": 1.0 },+ { "query": { "match": { "body": { "query": "alpha beta", "operator": "and" } } },+ "weight": 0.8 }+ ])+}++/// #943 shape A: `bool{must: hybrid, filter: […]}` must apply the filter —+/// same hit set AND same fused scores as the verified-correct "filter inside+/// each leg" spelling (the fix builds exactly that), instead of the pre-fix+/// 200-with-0-hits.+#[tokio::test]+async fn bool_must_hybrid_with_filter_applies_the_filter() {+ let idx = hyb943_index().await;++ let hybrid = json!({+ "hybrid": { "queries": hyb943_legs(), "fusion": { "type": "rrf", "k": 60 } }+ });++ // Baseline: the root hybrid is untouched by the fix — d1 (title leg) and+ // d2 (body leg) in some RRF order, d3/d4 nowhere.+ let root = idx.search(&make_search(hybrid.clone())).await.unwrap();+ let root_ids: Vec<&str> = root.hits.iter().map(|h| h.id.as_str()).collect();+ assert_eq!(root.total.value, 2, "root hybrid baseline: {root_ids:?}");+ assert!(+ root_ids.contains(&"d1") && root_ids.contains(&"d2"),+ "root hybrid baseline hits: {root_ids:?}"+ );++ // Shape A (pre-fix: 0 hits).+ let shape_a = idx+ .search(&make_search(json!({+ "bool": {+ "must": hybrid,+ "filter": [ { "term": { "ax_format": "eml" } } ]+ }+ })))+ .await+ .unwrap();+ assert!(+ shape_a.total.value > 0,+ "#943: bool{{must: hybrid, filter}} returned 0 hits (the hybrid clause \+ matched nothing on the generic path)"+ );+ let a_hits: Vec<(String, f32)> = shape_a+ .hits+ .iter()+ .map(|h| (h.id.clone(), h.score))+ .collect();+ assert!(+ a_hits.iter().all(|(id, _)| id == "d1"),+ "shape A must keep only the eml docs that match the legs: {a_hits:?}"+ );++ // The verified-correct spelling B: the filter inside each leg.+ let legs_eml: Vec<Value> = hyb943_legs()+ .as_array()+ .unwrap()+ .iter()+ .map(|leg| {+ json!({ "query": {+ "bool": {+ "must": [leg["query"].clone()],+ "filter": [ { "term": { "ax_format": "eml" } } ]+ }+ }, "weight": leg["weight"] })+ })+ .collect();+ let shape_b = idx+ .search(&make_search(json!({+ "hybrid": { "queries": legs_eml, "fusion": { "type": "rrf", "k": 60 } }+ })))+ .await+ .unwrap();+ let b_hits: Vec<(String, f32)> = shape_b+ .hits+ .iter()+ .map(|h| (h.id.clone(), h.score))+ .collect();+ assert_eq!(+ a_hits, b_hits,+ "#943: shape A (filter pushed into every leg) must equal spelling B \+ (filter written inside every leg) — ids AND fused scores"+ );+}++/// #943 regression: plain `bool{must: hybrid}` with NO filter also used to+/// fall through to the generic path (0 hits). It must now be bit-identical to+/// the root hybrid.+#[tokio::test]+async fn bool_must_hybrid_without_filter_matches_the_root_hybrid() {+ let idx = hyb943_index().await;++ let hybrid = json!({+ "hybrid": { "queries": hyb943_legs(), "fusion": { "type": "rrf", "k": 60 } }+ });+ let root = idx.search(&make_search(hybrid.clone())).await.unwrap();+ let wrapped = idx+ .search(&make_search(json!({ "bool": { "must": hybrid } })))+ .await+ .unwrap();++ assert_eq!(+ wrapped.total.value, root.total.value,+ "#943: bool{{must: hybrid}} used to return 0 hits"+ );+ let root_hits: Vec<(String, f32)> = root.hits.iter().map(|h| (h.id.clone(), h.score)).collect();+ let wrapped_hits: Vec<(String, f32)> = wrapped+ .hits+ .iter()+ .map(|h| (h.id.clone(), h.score))+ .collect();+ assert_eq!(+ wrapped_hits, root_hits,+ "#943: bool{{must: hybrid}} must be bit-identical to the root hybrid"+ );+}++/// #943 with a semantic leg (the issue's exact leg types): the wrapper filter+/// is pushed into the semantic leg too, where `peel_semantic_query`'s own Bool+/// arm merges it into the kNN filter.+#[tokio::test]+async fn bool_must_hybrid_with_filter_covers_the_semantic_leg() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ // The schema shape es_compat produces for `"type": "semantic_text"`+ // (see `test_semantic_text_match_survives_flush`): lexical side = Text,+ // plus the built-in lexical embedder for the companion vector.+ let mut schema = Schema::empty();+ let mut fc = FieldConfig::new("body", FieldType::Text);+ fc.options.dimensions = Some(16);+ fc.options.similarity = Some("cosine".to_string());+ fc.embedding = Some(xerj_common::types::EmbeddingConfig {+ endpoint: None,+ model: None,+ target_field: Some("body_vector".to_string()),+ });+ schema.fields.push(fc);+ engine.create_index("hyb943-sem", schema).unwrap();+ let idx = engine.get_index("hyb943-sem").unwrap();+ for (id, body, ax_format) in [+ ("s1", "retention policy backup deletion", "eml"),+ ("s2", "retention policy archive", "pdf"),+ ("s3", "retention policy backup deletion", "txt"),+ ("s4", "quarterly unrelated prose", "eml"),+ ] {+ idx.index_document(+ Some(id.into()),+ json!({ "body": body, "ax_format": ax_format }),+ )+ .await+ .unwrap();+ }+ idx.refresh().await.unwrap();++ let legs = json!([+ { "query": { "match": { "body": "retention backup" } }, "weight": 1.0 },+ { "query": { "semantic": { "field": "body", "query": "retention policy backup", "k": 10 } },+ "weight": 0.8 }+ ]);+ let run = |query: Value| {+ let idx = idx.clone();+ async move { idx.search(&make_search(query)).await.unwrap() }+ };++ let shape_a = run(json!({+ "bool": {+ "must": { "hybrid": { "queries": legs, "fusion": { "type": "rrf", "k": 60 } } },+ "filter": [ { "term": { "ax_format": "eml" } } ]+ }+ }))+ .await;+ assert!(+ shape_a.total.value > 0,+ "#943: filtered hybrid with a semantic leg returned 0 hits"+ );+ assert!(+ shape_a+ .hits+ .iter()+ .all(|h| h.source["ax_format"] == json!("eml")),+ "every hit must be an eml doc: {:?}",+ shape_a+ .hits+ .iter()+ .map(|h| h.id.as_str())+ .collect::<Vec<_>>()+ );++ let legs_eml: Vec<Value> = legs+ .as_array()+ .unwrap()+ .iter()+ .map(|leg| {+ json!({ "query": {+ "bool": {+ "must": [leg["query"].clone()],+ "filter": [ { "term": { "ax_format": "eml" } } ]+ }+ }, "weight": leg["weight"] })+ })+ .collect();+ let shape_b = run(json!({+ "hybrid": { "queries": legs_eml, "fusion": { "type": "rrf", "k": 60 } }+ }))+ .await;+ let a: Vec<(String, f32)> = shape_a+ .hits+ .iter()+ .map(|h| (h.id.clone(), h.score))+ .collect();+ let b: Vec<(String, f32)> = shape_b+ .hits+ .iter()+ .map(|h| (h.id.clone(), h.score))+ .collect();+ assert_eq!(+ a, b,+ "#943: semantic-leg hybrid — shape A must equal the per-leg spelling"+ );+}++/// #943 defense-in-depth: shapes the Bool peel arm deliberately declines+/// (`must_not` beside the hybrid; a hybrid beside another should-clause) used+/// to silently return wrong hits — 0 hits, or the non-hybrid clause's hits+/// with the hybrid dropped. They must now fail loud (400-class invalid_query)+/// naming the supported spellings instead of answering.+#[tokio::test]+async fn unpeelable_hybrid_fails_loud_instead_of_returning_wrong_hits() {+ let idx = hyb943_index().await;+ let hybrid = json!({+ "hybrid": { "queries": hyb943_legs(), "fusion": { "type": "rrf", "k": 60 } }+ });++ // bool{must: hybrid, must_not: […]}: pre-fix 200 with 0 hits.+ let err = idx+ .search(&make_search(json!({+ "bool": {+ "must": hybrid,+ "must_not": [ { "term": { "ax_format": "txt" } } ]+ }+ })))+ .await+ .unwrap_err()+ .to_string();+ assert!(+ err.contains("hybrid") && err.contains("filter"),+ "#943: must_not-beside-hybrid must fail loud naming the supported spellings: {err}"+ );++ // bool{should: [hybrid, match]}: pre-fix 200 with the match half's hits+ // only (the hybrid clause silently matched nothing).+ let err = idx+ .search(&make_search(json!({+ "bool": {+ "should": [+ hybrid,+ { "match": { "title": { "query": "alpha beta", "operator": "and" } } }+ ]+ }+ })))+ .await+ .unwrap_err()+ .to_string();+ assert!(+ err.contains("hybrid"),+ "#943: a hybrid beside another should-clause must fail loud: {err}"+ );+}+fn make_search(query_json: Value) -> SearchRequest {parse_request(&json!({ "query": query_json, "size": 100 })).expect("parse_request")}diff --git a/engine/crates/xerj-query/src/ast.rs b/engine/crates/xerj-query/src/ast.rsindex a6662a238..d07587979 100644--- a/engine/crates/xerj-query/src/ast.rs+++ b/engine/crates/xerj-query/src/ast.rs@@ -995,6 +995,85 @@ impl QueryNode {}}+ /// Returns `true` if a `Hybrid` node appears anywhere in this subtree,+ /// including inside every wrapper (bool clauses, boost/name/constant+ /// decorators, knn/semantic filters, boosting/dis_max/pinned, span+ /// clauses) and inside `hybrid.queries[].query` itself.+ ///+ /// #943: the engine executes a hybrid ONLY from the short-circuit ladder+ /// in `search_inner` (root node, or a `bool{must:[hybrid], filter:[…]}`+ /// wrapper); anywhere else the doc matcher's catch-all silently matches+ /// nothing. Callers use this to fail loud (400) instead of answering with+ /// the wrong hit set — the engine for unpeelable shapes, the API layer+ /// for `post_filter` beside a hybrid (post_filter never reaches the+ /// engine, so the filter was silently ignored).+ pub fn contains_hybrid(&self) -> bool {+ fn walk(q: &QueryNode) -> bool {+ match q {+ QueryNode::Hybrid { .. } => true,+ QueryNode::MatchAll+ | QueryNode::MatchNone+ | QueryNode::Term { .. }+ | QueryNode::Terms { .. }+ | QueryNode::Range { .. }+ | QueryNode::Prefix { .. }+ | QueryNode::Wildcard { .. }+ | QueryNode::Exists { .. }+ | QueryNode::Ids { .. }+ | QueryNode::Script { .. }+ | QueryNode::Match { .. }+ | QueryNode::MatchPhrase { .. }+ | QueryNode::MultiMatch { .. }+ | QueryNode::QueryString { .. }+ | QueryNode::Fuzzy { .. }+ | QueryNode::Regexp { .. }+ | QueryNode::Intervals { .. }+ | QueryNode::MatchPhrasePrefix { .. }+ | QueryNode::SimpleQueryString { .. }+ | QueryNode::GeoDistance { .. }+ | QueryNode::GeoBoundingBox { .. }+ | QueryNode::GeoPolygon { .. }+ | QueryNode::GeoShape { .. }+ | QueryNode::SpanTerm { .. }+ | QueryNode::MoreLikeThis { .. }+ | QueryNode::Percolate { .. } => false,+ QueryNode::Bool {+ must,+ should,+ must_not,+ filter,+ ..+ } => must+ .iter()+ .chain(should)+ .chain(must_not)+ .chain(filter)+ .any(walk),+ QueryNode::Constant { query, .. }+ | QueryNode::Boosted { query, .. }+ | QueryNode::Named { query, .. }+ | QueryNode::FunctionScore { query, .. }+ | QueryNode::Nested { query, .. } => walk(query),+ QueryNode::Boosting {+ positive, negative, ..+ } => walk(positive) || walk(negative),+ QueryNode::DisMax { queries, .. } => queries.iter().any(walk),+ QueryNode::Pinned { organic, .. } => walk(organic),+ QueryNode::Knn { filter, .. } | QueryNode::SemanticSearch { filter, .. } => {+ filter.as_deref().is_some_and(walk)+ }+ QueryNode::SpanNear { clauses, .. } | QueryNode::SpanOr { clauses } => {+ clauses.iter().any(walk)+ }+ QueryNode::SpanNot { include, exclude } => walk(include) || walk(exclude),+ QueryNode::SpanFirst { match_query, .. } => walk(match_query),+ QueryNode::SpanContaining { little, big }+ | QueryNode::SpanWithin { little, big } => walk(little) || walk(big),+ }+ }+ walk(self)+ }+/// Rough structural depth — used by the planner for cost estimation.pub fn depth(&self) -> usize {match self {