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(painless): surface script resource-limit trips instead of a wrong score (#116)
xerj-org45f917456fb7
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 5f30e668e..d330d0621 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -5245,6 +5245,37 @@ fn find_script_limit_violation(v: &Value) -> Option<String> {}}+/// ES-shaped `script_exception` 400 for a script that hit one of the+/// interpreter's resource limits at *run* time.+///+/// `find_script_limit_violation` catches the statically-detectable limits up+/// front. The rest — closure call depth, total invocation count — depend on+/// the data and can only trip mid-evaluation, where the caller is a scoring or+/// aggregation path with no error channel. Those paths substituted a neutral+/// value (`0.0`, `[]`) and served it as if the script had succeeded; this is+/// what they surface instead.+pub(crate) fn script_limit_response(reason: &str) -> Response {+ (+ StatusCode::BAD_REQUEST,+ Json(script_limit_error_value(reason)),+ )+ .into_response()+}++/// The same body as a bare value, for the multi-search surfaces that embed a+/// per-sub-request error object inside a 200 envelope rather than failing the+/// whole HTTP call.+pub(crate) fn script_limit_error_value(reason: &str) -> Value {+ json!({+ "error": {+ "root_cause": [{ "type": "script_exception", "reason": reason }],+ "type": "script_exception",+ "reason": reason,+ },+ "status": 400,+ })+}+/// Parse an ES time-units string to milliseconds: `"500ms"`, `"30s"`,/// `"2m"`, `"1h"`, `"1d"`, `"5micros"`, `"100nanos"`, bare number =/// millis. Sub-millisecond values round up to 1 ms so `timeout=100nanos`@@ -6264,12 +6295,44 @@ fn profile_shard_count(n: i64) -> u64 {n.clamp(1, 1024) as u64}+/// `POST /{index}/_search`.+///+/// Thin wrapper over [`search_impl`] that installs the Painless fault sink for+/// every script this handler evaluates *itself* — `script_fields` and+/// `runtime_mappings` emit-scripts run during response assembly, outside the+/// spawned search task, so they are not covered by the engine-side capture in+/// `Index::search`. Both used to drop a failed script's value on the floor+/// (`if let Ok(pv) = …`), which is right for a script outside our Painless+/// subset but wrong for a resource-limit trip: the field silently vanished+/// from the response with no error anywhere. A limit fault now fails the+/// request.pub async fn search(State(state): State<AppState>,Path(index): Path<String>,Query(params): Query<EsSearchQueryParams>,body: EsSearchJson,-) -> impl IntoResponse {+) -> Response {+ // `Box::pin` is load-bearing, not style. `search_impl`'s future is+ // enormous (thousands of lines of inlined async state), and without the+ // box this wrapper's future embeds a second copy of it by value —+ // `memory_api`'s recall test, which calls this handler directly, overflows+ // its stack on the extra copy. Boxing keeps the wrapper pointer-sized.+ let (response, fault) = xerj_engine::painless::with_script_fault_capture(Box::pin(+ search_impl(state, index, params, body),+ ))+ .await;+ match fault {+ Some(reason) => script_limit_response(&reason),+ None => response,+ }+}++async fn search_impl(+ state: AppState,+ index: String,+ params: EsSearchQueryParams,+ body: EsSearchJson,+) -> Response {let started = Instant::now();// Closed-index handling is deferred to after index resolution below so// `ignore_unavailable` / `expand_wildcards` are honored per ES semantics.@@ -8417,6 +8480,13 @@ pub async fn search(}Ok(Err(e)) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),Ok(Ok(result)) => {+ // A Painless resource limit tripped somewhere in scoring or+ // aggregation. Those paths have no error channel, so they+ // fell back to neutral values — the hits below carry wrong+ // scores. Fail the request instead of serving them.+ if let Some(reason) = &result.script_failure {+ return script_limit_response(reason);+ }if result.timed_out {any_timed_out = true;}@@ -15089,6 +15159,13 @@ pub async fn count_docs(let search_body = json!({ "query": query_val, "size": 0, "from": 0 });if let Ok(req) = xerj_query::parse_request(&search_body) {if let Ok(result) = idx.search(&req).await {+ // A script resource limit in the filter (terms_set's+ // `minimum_should_match` script, say) makes matching+ // fail-closed, so the count under-reports with nothing+ // to distinguish it from a genuine zero.+ if let Some(reason) = &result.script_failure {+ return script_limit_response(reason);+ }total += result.total.value;}}@@ -15134,7 +15211,12 @@ pub async fn count_docs(let search_body = json!({ "query": query_val, "size": 0, "from": 0 });match xerj_query::parse_request(&search_body) {Ok(req) => match idx.search(&req).await {- Ok(result) => result.total.value,+ Ok(result) => {+ if let Some(reason) = &result.script_failure {+ return script_limit_response(reason);+ }+ result.total.value+ }Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),},Err(e) => {@@ -16556,6 +16638,9 @@ pub async fn search_with_scroll(match idx.search(&full_req).await {Ok(result) => {+ if let Some(reason) = &result.script_failure {+ return script_limit_response(reason);+ }total_count += result.total.value;for hit in result.hits {all_hits.push((idx_name.clone(), hit));@@ -17354,6 +17439,13 @@ pub async fn reindex(Ok(r) => r,Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),};+ // A script resource limit in `source.query` makes matching fail-closed,+ // so this batch is a subset of the documents the caller asked to copy.+ // Reporting a completed reindex over a silently truncated source is the+ // same class of defect as a silently wrong score.+ if let Some(reason) = &results.script_failure {+ return script_limit_response(reason);+ }let batch_size = results.hits.len();if batch_size == 0 {@@ -17950,6 +18042,7 @@ async fn msearch_impl(let mut total_relation = "eq";let mut merged_aggs: Option<Value> = None;let mut search_error: Option<String> = None;+ let mut script_failure: Option<String> = None;for idx_name in &index_names {let idx = match state.engine.get_index(idx_name) {@@ -17961,6 +18054,16 @@ async fn msearch_impl(};match idx.search(&search_req).await {Ok(result) => {+ // A Painless resource limit tripped during scoring/aggs:+ // the hits carry degraded scores. Report this sub-request+ // as failed rather than merging wrong numbers in. Tracked+ // separately from `search_error` so it keeps the ES+ // `script_exception` / 400 shape the other script surfaces+ // use, instead of a bare 500.+ if let Some(reason) = result.script_failure {+ script_failure = Some(reason);+ break;+ }total_count += result.total.value;if result.total.relation == xerj_query::executor::TotalHitsRelation::Gte {total_relation = "gte";@@ -17979,6 +18082,11 @@ async fn msearch_impl(}}+ if let Some(reason) = script_failure {+ responses.push(script_limit_error_value(&reason));+ continue;+ }+if let Some(err) = search_error {responses.push(json!({"error": { "reason": err },@@ -19820,6 +19928,12 @@ async fn run_delete_by_query(Ok(r) => r,Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_value(),};+ // A script resource limit makes matching fail-closed, so the selection is+ // a subset of what the caller asked to delete. Deleting that subset and+ // reporting success is both destructive and wrong; refuse instead.+ if let Some(reason) = &results.script_failure {+ return script_limit_error_value(reason);+ }let total = results.hits.len() as u64;let mut deleted = 0u64;@@ -19925,6 +20039,11 @@ async fn run_update_by_query(Ok(r) => r,Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_value(),};+ // Same reasoning as `run_delete_by_query`: a fail-closed script selection+ // would update an arbitrary subset and call it a complete run.+ if let Some(reason) = &results.script_failure {+ return script_limit_error_value(reason);+ }let total = results.hits.len() as u64;let mut updated = 0u64;@@ -23975,6 +24094,9 @@ pub async fn search_template(for (name, idx) in &handles {match idx.search(&search_req).await {Ok(result) => {+ if let Some(reason) = &result.script_failure {+ return script_limit_response(reason);+ }total += result.total.value;merged_hits.extend(result.hits.into_iter().map(|h| (name.clone(), h)));}@@ -24168,10 +24290,15 @@ async fn msearch_template_impl(let mut merged_hits: Vec<Value> = Vec::new();let mut total_count: u64 = 0;+ let mut script_failure: Option<String> = None;for idx_name in &index_names {if let Ok(idx) = state.engine.get_index(idx_name) {if let Ok(result) = idx.search(&search_req).await {+ if let Some(reason) = result.script_failure {+ script_failure = Some(reason);+ break;+ }total_count += result.total.value;for h in result.hits {let source = if h.source.is_null() {@@ -24190,6 +24317,13 @@ async fn msearch_template_impl(}}+ if let Some(reason) = script_failure {+ // Degraded scores — report this sub-request as failed instead of+ // publishing them as if the script had run.+ responses.push(script_limit_error_value(&reason));+ continue;+ }+let took_ms = started.elapsed().as_millis() as u64;responses.push(json!({"took": took_ms,@@ -27861,6 +27995,9 @@ pub async fn async_search_submit(for (name, idx) in &handles {match idx.search(&req).await {Ok(result) => {+ if let Some(reason) = &result.script_failure {+ return script_limit_response(reason);+ }total_value += result.total.value;any_gte = any_gte|| result.total.relation == xerj_query::executor::TotalHitsRelation::Gte;diff --git a/engine/crates/xerj-api/tests/script_limits_http.rs b/engine/crates/xerj-api/tests/script_limits_http.rsnew file mode 100644index 000000000..2b93f6319--- /dev/null+++ b/engine/crates/xerj-api/tests/script_limits_http.rs@@ -0,0 +1,271 @@+//! Issue #97, from the outside: a Painless **resource limit** must reach the+//! HTTP caller instead of being absorbed into a plausible-looking answer.+//!+//! These tests deliberately touch nothing but the wire. They compile against+//! the pre-fix engine (no `SearchResult::script_failure`, no+//! `is_resource_limit_error`), so running them on the unfixed tree shows the+//! real defect: `200 OK` with `_score: 0.0` from a scoring script that never+//! ran, and a `script_fields` entry that silently vanished.+//!+//! The counterpart matters just as much: a script that is merely *outside* our+//! Painless subset must keep degrading quietly, because the ES-compat surface+//! depends on it. A fix that turns every unparseable script into a 400 would+//! pass the loudness tests and break real clients.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++/// Self-application recursion that runs past `MAX_CALL_DEPTH` (32), with the+/// recursive call wrapped in nested blocks — the shape from the PR #88+/// process-abort repro. Short enough to clear the static source-size and+/// parse-depth guards, so the limit can only trip mid-evaluation, which is+/// exactly the case that had no error channel.+fn over_deep_script() -> String {+ let open = "if(true){".repeat(10);+ let close = "}".repeat(10);+ format!("def f = (g, n) -> {{ {open} return g(g, n); {close} return 0; }}; return f(f, 1);")+}++/// One index, one document, ready to search.+///+/// The `TempDir` is returned, not `keep()`-ed: each test gets its own data+/// directory and gives it back when it ends.+async fn seeded_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);++ state+ .engine+ .create_index("scripts", xerj_common::types::Schema::empty())+ .expect("create_index");+ let idx = state.engine.get_index("scripts").expect("get_index");+ idx.index_document(Some("1".into()), json!({ "rank": 7, "tags": ["a", "b"] }))+ .await+ .expect("index_document");+ idx.refresh().await.expect("refresh");+ (xerj_api::router::build_es_compat_router(state), dir)+}++async fn post(app: &axum::Router, path: &str, body: Value) -> (StatusCode, Value) {+ let response = app+ .clone()+ .oneshot(+ Request::post(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");+ let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ (status, value)+}++/// The headline of #97. `apply_function_score` returns a bare `f32`, so it+/// mapped the call-depth error to `0.0` and the request succeeded with a score+/// that no script produced.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn script_score_past_the_call_depth_limit_is_an_error_not_a_zero_score() {+ let (app, _dir) = seeded_app().await;+ let (status, body) = post(+ &app,+ "/scripts/_search",+ json!({+ "query": {+ "function_score": {+ "query": { "match_all": {} },+ "functions": [+ { "script_score": { "script": { "source": over_deep_script() } } }+ ]+ }+ }+ }),+ )+ .await;++ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "a scoring script that hit the closure call-depth limit was served as a \+ successful search: {body}"+ );+ assert_eq!(body["error"]["type"], "script_exception", "body: {body}");+ assert!(+ body["error"]["reason"]+ .as_str()+ .unwrap_or_default()+ .contains("closure call depth"),+ "the reason must name the limit that tripped: {body}"+ );+}++/// `script_fields` are evaluated by the `_search` handler itself, during+/// response assembly and outside the engine's search task. The old+/// `if let Ok(pv)` dropped a limit trip on the floor and the field just wasn't+/// in the response — indistinguishable from a script that legitimately+/// returned nothing.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn script_field_past_the_call_depth_limit_is_an_error_not_a_missing_field() {+ let (app, _dir) = seeded_app().await;+ let (status, body) = post(+ &app,+ "/scripts/_search",+ json!({+ "query": { "match_all": {} },+ "script_fields": {+ "computed": { "script": { "source": over_deep_script() } }+ }+ }),+ )+ .await;++ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "a script_field that hit the closure call-depth limit vanished from an \+ otherwise successful response: {body}"+ );+ assert_eq!(body["error"]["type"], "script_exception", "body: {body}");+}++/// A script-bucketed terms agg mapped a limit trip to "no buckets" — an empty+/// aggregation that reads as a legitimate answer.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn script_bucketed_agg_past_the_call_depth_limit_is_an_error_not_empty_buckets() {+ let (app, _dir) = seeded_app().await;+ let (status, body) = post(+ &app,+ "/scripts/_search",+ json!({+ "size": 0,+ "query": { "match_all": {} },+ "aggs": { "by_script": { "terms": { "script": { "source": over_deep_script() } } } }+ }),+ )+ .await;++ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "a script-bucketed agg that hit the call-depth limit returned buckets as \+ a complete answer: {body}"+ );+ assert_eq!(body["error"]["type"], "script_exception", "body: {body}");+}++/// `_delete_by_query` selects with the same matching machinery. A fail-closed+/// script trip there means deleting an arbitrary subset and reporting a+/// completed run — destructive as well as wrong.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn delete_by_query_refuses_a_selection_a_script_limit_truncated() {+ let (app, _dir) = seeded_app().await;+ let (_, body) = post(+ &app,+ "/scripts/_delete_by_query",+ json!({+ "query": {+ "terms_set": {+ "tags": {+ "terms": ["a", "b"],+ "minimum_should_match_script": { "source": over_deep_script() }+ }+ }+ }+ }),+ )+ .await;++ assert_eq!(+ body["error"]["type"], "script_exception",+ "delete_by_query ran against a silently truncated selection: {body}"+ );+ assert!(+ body.get("deleted").is_none(),+ "a refused delete must not also report a deletion count: {body}"+ );+}++/// The other half of the contract, and the reason the error type has to+/// distinguish the two classes: a script our interpreter simply doesn't+/// support is NOT a resource limit. It must keep degrading to a neutral score+/// on a 200, exactly as before, or every out-of-subset script in the ES-compat+/// surface becomes a spurious 400.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn unsupported_script_syntax_still_degrades_quietly() {+ let (app, _dir) = seeded_app().await;+ for source in [+ "someUnsupportedThing(1,2,3)",+ "unknown_identifier_here",+ "doc['missing'].value.someMethodWeDoNotHave()",+ ] {+ let (status, body) = post(+ &app,+ "/scripts/_search",+ json!({+ "query": {+ "function_score": {+ "query": { "match_all": {} },+ "functions": [ { "script_score": { "script": { "source": source } } } ]+ }+ }+ }),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::OK,+ "an out-of-subset script must not become a 400 ({source}): {body}"+ );+ assert_eq!(body["hits"]["total"]["value"], 1, "body: {body}");+ }+}++/// A search that trips a limit must not leave the response cache poisoned with+/// its degraded scores, and the fault must not be re-reported against the next+/// caller of a different query.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn a_faulted_search_is_neither_cached_nor_replayed() {+ let (app, _dir) = seeded_app().await;+ let bad = json!({+ "query": {+ "function_score": {+ "query": { "match_all": {} },+ "functions": [+ { "script_score": { "script": { "source": over_deep_script() } } }+ ]+ }+ }+ });++ let (first, _) = post(&app, "/scripts/_search", bad.clone()).await;+ assert_eq!(first, StatusCode::BAD_REQUEST);+ let (second, body) = post(&app, "/scripts/_search", bad).await;+ assert_eq!(+ second,+ StatusCode::BAD_REQUEST,+ "the repeat request was served the cached degraded result: {body}"+ );++ let (clean, body) = post(+ &app,+ "/scripts/_search",+ json!({ "query": { "match_all": {} } }),+ )+ .await;+ assert_eq!(+ clean,+ StatusCode::OK,+ "an unrelated request inherited another one's script fault: {body}"+ );+}diff --git a/engine/crates/xerj-engine/Cargo.toml b/engine/crates/xerj-engine/Cargo.tomlindex afc704bab..028484792 100644--- a/engine/crates/xerj-engine/Cargo.toml+++ b/engine/crates/xerj-engine/Cargo.toml@@ -52,6 +52,7 @@ default = []# candle/tokenizer toolchain; enable via xerj-server's `neural` feature.neural = ["xerj-ai/neural"]onnx-experimental = ["xerj-ai/onnx-experimental"]+stackprobe = [][dev-dependencies]tempfile = { workspace = true }diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex a8c43fc8f..0a7070a4f 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -8924,6 +8924,7 @@ impl Index {timed_out: any_timed_out,profile: None,max_score: None,+ script_failure: None,})}@@ -9170,6 +9171,7 @@ impl Index {timed_out,profile: None,max_score: None,+ script_failure: None,})}@@ -9947,6 +9949,7 @@ impl Index {timed_out: true,profile: None,max_score: None,+ script_failure: None,}};// M3 framework: response cache. Hash the request shape and the@@ -10203,7 +10206,37 @@ impl Index {|| peel_nested_knn_query(&request.query).is_some();let is_multi_thread = tokio::runtime::Handle::current().runtime_flavor()== tokio::runtime::RuntimeFlavor::MultiThread;- let search_fut = self.search_inner(request, request_deadline);+ // Capture Painless resource-limit faults for the whole search, nested+ // sub-searches and aggregations included. The scoring paths+ // (`apply_function_score`, `apply_rescore`, terms_set+ // `min_should_match`, script-bucketed aggs) return bare values with no+ // error channel, so without this a script that trips the closure+ // call-depth limit degrades to a score of 0.0 and the caller is served+ // a wrong number with nothing to notice. Surfacing it on the result+ // makes the API layer fail the request instead.+ let search_fut = async {+ let (result, fault) = crate::painless::with_script_fault_capture(+ self.search_inner(request, request_deadline),+ )+ .await;+ match (result, fault) {+ (Ok(mut r), Some(f)) => {+ // Capture scopes nest, and this one just consumed the+ // fault. A search running *inside* another request's+ // capture (a sub-search issued from the `_search` handler,+ // for instance) would therefore hide the fault from that+ // outer scope, and its caller may well be one of the many+ // `if let Ok(result) = idx.search(..)` sites that never+ // look at `script_failure`. Re-raise so the fault is+ // surfaced by default and only stops here when this is the+ // outermost scope.+ crate::painless::record_script_fault(&f);+ r.script_failure = Some(f);+ Ok(r)+ }+ (other, _) => other,+ }+ };let search_result = if is_multi_thread && !cooperative_vector_query {let fut = async move {tokio::task::block_in_place(|| {@@ -10238,8 +10271,11 @@ impl Index {// any coalesced followers (identical query ⇒ identical// timed-out response) so they return now instead of// waiting for the closed channel and then recomputing an- // equally-slow query.- if r.timed_out {+ // equally-slow query. The same holds for a script+ // resource-limit fault: its degraded scores must not be+ // replayed to later callers, and the fault itself must not+ // be re-reported against an unrelated request.+ if r.timed_out || r.script_failure.is_some() {if let Some(tx) = &sf_leader {let _ = tx.send(Some(Arc::new(r.clone())));}@@ -10290,6 +10326,7 @@ impl Index {timed_out: true,profile: None,max_score: None,+ script_failure: None,};// Hand the timed-out response to any coalesced followers so// they return immediately rather than waiting for the closed@@ -13840,6 +13877,7 @@ impl Index {timed_out: deadline_exceeded,profile,max_score: population_max_score,+ script_failure: None,})}@@ -22009,6 +22047,7 @@ fn knn_result_from_scored(timed_out: false,profile: None,max_score: None,+ script_failure: None,}}diff --git a/engine/crates/xerj-engine/src/painless.rs b/engine/crates/xerj-engine/src/painless.rsindex 14e1a3e0b..f91a6572c 100644--- a/engine/crates/xerj-engine/src/painless.rs+++ b/engine/crates/xerj-engine/src/painless.rs@@ -58,11 +58,11 @@ pub enum PainlessValue {/// scripts. `.toString()` renders it in ES's HashMap-like format/// (`{key=value, key=value}`, keys alphabetically sorted).Object(serde_json::Map<String, Value>),- /// A local function or lambda value: parameter names + `Rc`-shared body+ /// A local function or lambda value: parameter names + `Arc`-shared body/// statements (cheap to clone — see [`Expr::Lambda`]). Invoked either/// as a bare call (`name(args)`) or via any `.method(args)` call on the/// value — see the module doc comment.- Closure(Vec<String>, std::rc::Rc<Vec<Stmt>>),+ Closure(Vec<String>, std::sync::Arc<Vec<Stmt>>),}impl PainlessValue {@@ -370,12 +370,33 @@ pub enum Expr {/// `var x = expr` (declare); `x = expr` (assign).Assign(String, Box<Expr>, bool /* is_decl */),/// `(params) -> expr` / `(params) -> { stmts }` — a closure literal.- /// The body is `Rc`-shared (not owned `Vec<Stmt>`) so producing the+ /// The body is `Arc`-shared (not owned `Vec<Stmt>`) so producing the/// `PainlessValue::Closure` this evaluates to — which happens on every/// evaluation of the literal, e.g. once per call when a closure is/// itself an argument passed to a recursive call — is a cheap refcount/// bump rather than a deep AST clone.- Lambda(Vec<String>, std::rc::Rc<Vec<Stmt>>),+ ///+ /// `Arc` rather than `Rc` so `PainlessValue` is `Send`/`Sync` — a shared+ /// closure body was the only thing keeping it off a thread boundary.+ ///+ /// The atomic refcount does not show up above the noise floor. A/B'd with+ /// `measure_closure_clone_cost` (`stackprobe` feature, release build):+ /// a 240-closure-invocation script timed against a closure-free script of+ /// the same statement shape, reported as their **ratio** because wall-clock+ /// on a shared host swings ±40 % between runs while the ratio does not.+ /// Three runs each, same binary, alternating source:+ ///+ /// | build | closure/arith ratio |+ /// |-------|--------------------------|+ /// | `Arc` | 3.328, 3.334, 3.224 |+ /// | `Rc` | 3.367, 3.344, 2.360 |+ ///+ /// The `Arc`–`Rc` gap (~1 %) is an order of magnitude smaller than `Rc`'s+ /// own run-to-run spread, i.e. not resolvable here: a closure call+ /// allocates a fresh `HashMap` scope, which dominates a refcount either+ /// way. `MAX_CALL_COUNT` caps closure calls at 10 000 per evaluation, so+ /// the worst case is bounded regardless.+ Lambda(Vec<String>, std::sync::Arc<Vec<Stmt>>),}/// Parser-only expression wrapper carrying the exact AST depth in O(1).@@ -411,8 +432,8 @@ pub enum Stmt {/// `<type> name(<type> param, ...) { body }` — a local function/// declaration. Parameter/return types are parsed and discarded (the/// interpreter is dynamically typed); only names and the body matter.- /// `Rc`-shared body for the same reason as [`Expr::Lambda`].- FnDecl(String, Vec<String>, std::rc::Rc<Vec<Stmt>>),+ /// `Arc`-shared body for the same reason as [`Expr::Lambda`].+ FnDecl(String, Vec<String>, std::sync::Arc<Vec<Stmt>>),}// ── Resource limits ──────────────────────────────────────────────────────────@@ -459,6 +480,32 @@ pub(crate) const EVAL_TOO_DEEP_MSG: &str =/// (~50,000) before `eval_depth` ever objects, which is enough native/// stack frames to abort the process even in a release build. Kept small/// and independent of the expression budget.+///+/// **32 is not a guess and must not be raised.** Measured in a release build+/// by probing the stack address at each call level (`stackprobe` feature,+/// `measure_stack_per_call_level`), with the recursive call placed *inside*+/// the closure body's nested blocks so every call level also pays that+/// body's `exec_stmt` frames:+///+/// | nested blocks in body | bytes / call level | total at depth 32 |+/// |----------------------:|-------------------:|------------------:|+/// | 1 | 2,272 | 69 KiB |+/// | 10 | 6,160 | 186 KiB |+/// | 50 | 23,440 | 710 KiB |+/// | 90 (parser max) | 40,720 | 1.20 MiB |+///+/// The adversarial worst case already consumes 1.20 MiB (1,262,320 bytes) of+/// the 2 MiB tokio worker stack, leaving ~0.8 MiB for the axum/search/+/// segment-scan frames underneath it. Doubling the ceiling would overflow, so+/// #97's "just raise it" option is not available. The cost per level is+/// `O(MAX_PARSE_DEPTH)` because a closure body's statement nesting is not+/// charged against any shared budget — lifting this ceiling safely requires+/// charging body nesting against a single stack budget, not a bigger number+/// here.+///+/// Reproduce with:+/// `cargo test --release -p xerj-engine --lib --features stackprobe -- \+/// --nocapture measure_stack_per_call_level`pub(crate) const MAX_CALL_DEPTH: usize = 32;/// Maximum total closure invocations across one script evaluation.@@ -471,10 +518,91 @@ pub(crate) const MAX_CALL_DEPTH: usize = 32;/// that bounds the call tree's total size rather than its depth.pub(crate) const MAX_CALL_COUNT: usize = 10_000;-/// Sentinel returned when [`MAX_CALL_DEPTH`] or [`MAX_CALL_COUNT`] is-/// exceeded.+/// Sentinel returned when [`MAX_CALL_DEPTH`] is exceeded. Split from+/// [`TOO_MANY_CALLS_MSG`] so the two very different remedies (recurse less+/// vs. call less) are distinguishable in an error a user actually sees.+pub(crate) const CALL_TOO_DEEP_MSG: &str =+ "script evaluation exceeded maximum closure call depth; reduce the recursion depth";++/// Sentinel returned when [`MAX_CALL_COUNT`] is exceeded.pub(crate) const TOO_MANY_CALLS_MSG: &str =- "script exceeded the maximum closure call depth or invocation count";+ "script evaluation exceeded the maximum closure invocation count";++/// Prefix of the (length-carrying) oversize-source error, so+/// [`is_resource_limit_error`] can recognise it without formatting.+const SOURCE_TOO_LONG_PREFIX: &str = "script source is ";++/// True when `msg` is one of the interpreter's **resource-limit** sentinels+/// rather than an ordinary script error.+///+/// This distinction is load-bearing. Most script call sites deliberately+/// swallow errors and fall back to a neutral value, because a script outside+/// our Painless subset must keep degrading gracefully rather than turn into a+/// spurious 400 (see `check_script_limits`). A resource-limit trip is the+/// opposite case: the script was *understood*, we simply refused to finish+/// running it, so falling back to `0.0` / `[]` publishes a value that looks+/// like a real answer and is not. Callers use this to fail loudly on limits+/// while keeping the graceful path for everything else.+pub fn is_resource_limit_error(msg: &str) -> bool {+ msg == TOO_DEEP_MSG+ || msg == EVAL_TOO_DEEP_MSG+ || msg == CALL_TOO_DEEP_MSG+ || msg == TOO_MANY_CALLS_MSG+ || msg.starts_with(SOURCE_TOO_LONG_PREFIX)+}++tokio::task_local! {+ /// First resource-limit fault raised by any script evaluated inside the+ /// current [`with_script_fault_capture`] scope.+ ///+ /// A task-local (not a thread-local): the scoring and aggregation paths+ /// that evaluate scripts sit behind `f32`/`Value`-returning signatures+ /// with no error channel of their own — `apply_function_score`,+ /// `score_query_against_doc`, `doc_matches_query`, `run_terms` — and are+ /// reached from ~90 call sites, so threading a sink through them is not+ /// viable. A *thread*-local would mis-attribute a fault to whichever+ /// request happened to be running on the worker after an `.await`; a+ /// task-local follows the task across await points and across worker+ /// threads, so a fault can only ever be read by the request that caused+ /// it. Faults raised outside any scope are dropped (`try_with` fails),+ /// which is the correct behavior for unit tests and sync helpers that+ /// already read the `Result` directly.+ static SCRIPT_FAULT: std::cell::RefCell<Option<String>> ;+}++/// Record a resource-limit fault against the enclosing capture scope, if any.+/// First fault wins — later ones are almost always the same limit tripping on+/// the next document.+///+/// Also used to *re-raise* a fault that an inner scope already consumed (see+/// `Index::search`): scopes nest, so a sub-search's own capture would otherwise+/// hide the fault from the request-level capture that wraps it.+pub(crate) fn record_script_fault(msg: &str) {+ let _ = SCRIPT_FAULT.try_with(|slot| {+ let mut slot = slot.borrow_mut();+ if slot.is_none() {+ *slot = Some(msg.to_string());+ }+ });+}++/// Run `fut` with a fault sink installed, returning its output alongside the+/// first script resource-limit fault raised anywhere inside it.+///+/// This is how a limit trip deep in the scoring path becomes visible to the+/// caller instead of silently degrading to a wrong score.+pub async fn with_script_fault_capture<F>(fut: F) -> (F::Output, Option<String>)+where+ F: std::future::Future,+{+ SCRIPT_FAULT+ .scope(std::cell::RefCell::new(None), async move {+ let out = fut.await;+ let fault = SCRIPT_FAULT.with(|slot| slot.borrow_mut().take());+ (out, fault)+ })+ .await+}// ── Parser ───────────────────────────────────────────────────────────────────@@ -600,7 +728,7 @@ impl<'a> Parser<'a> {if self.match_punct('(') {let params = self.parse_fn_params()?;let body = self.parse_block_or_stmt()?;- return Ok(Stmt::FnDecl(name, params, std::rc::Rc::new(body)));+ return Ok(Stmt::FnDecl(name, params, std::sync::Arc::new(body)));}if !self.match_punct('=') {return Err(format!("expected '=' after var name '{}'", name));@@ -950,7 +1078,7 @@ impl<'a> Parser<'a> {let body = self.parse_block_or_stmt()?;Ok(Some(ParsedExpr::leaf(Expr::Lambda(params,- std::rc::Rc::new(body),+ std::sync::Arc::new(body),))))}fn parse_primary(&mut self) -> Result<ParsedExpr, String> {@@ -1022,7 +1150,7 @@ impl<'a> CallGuard<'a> {fn enter(ctx: &'a PainlessCtx) -> Result<Self, String> {let depth = ctx.call_depth.get();if depth >= MAX_CALL_DEPTH {- return Err(TOO_MANY_CALLS_MSG.to_string());+ return Err(CALL_TOO_DEEP_MSG.to_string());}let count = ctx.call_count.get();if count >= MAX_CALL_COUNT {@@ -1068,10 +1196,27 @@ pub fn check_script_limits(src: &str) -> Result<(), String> {}}+/// Evaluate a Painless script.+///+/// Every resource-limit failure is *also* recorded against the enclosing+/// [`with_script_fault_capture`] scope on the way out, so the many call sites+/// that legitimately swallow the `Err` (to keep out-of-subset scripts+/// degrading gracefully) cannot turn a refused evaluation into a plausible+/// wrong value that nobody ever notices.pub fn eval_painless(src: &str, ctx: &PainlessCtx) -> Result<PainlessValue, String> {+ let out = eval_painless_inner(src, ctx);+ if let Err(msg) = &out {+ if is_resource_limit_error(msg) {+ record_script_fault(msg);+ }+ }+ out+}++fn eval_painless_inner(src: &str, ctx: &PainlessCtx) -> Result<PainlessValue, String> {if src.len() > MAX_SCRIPT_LEN {return Err(format!(- "script source is {} bytes, exceeds the {}-byte limit",+ "{SOURCE_TOO_LONG_PREFIX}{} bytes, exceeds the {}-byte limit",src.len(),MAX_SCRIPT_LEN));@@ -1102,6 +1247,13 @@ fn exec_body(Ok(last)}+#[cfg(feature = "stackprobe")]+thread_local! {+ /// (max_depth_seen, stack addr at call depth 1, min stack addr seen)+ pub static STACK_PROBE: std::cell::Cell<(usize, usize, usize)> =+ const { std::cell::Cell::new((0, 0, usize::MAX)) };+}+/// Invoke a closure (local function or lambda) with the given positional/// arguments, in a fresh scope seeded only with the bound parameters — no/// access to the caller's locals, matching the target scripts' needs@@ -1114,6 +1266,17 @@ fn call_closure(ctx: &PainlessCtx,) -> Result<PainlessValue, String> {let _guard = CallGuard::enter(ctx)?;+ #[cfg(feature = "stackprobe")]+ {+ let probe = 0u8;+ let addr = &probe as *const u8 as usize;+ STACK_PROBE.with(|p| {+ let (d, top, min) = p.get();+ let depth = ctx.call_depth.get();+ let top = if depth == 1 { addr } else { top };+ p.set((d.max(depth), top, min.min(addr)));+ });+ }if args.len() != params.len() {return Err(format!("wrong number of arguments: expected {}, got {}",@@ -2128,6 +2291,180 @@ mod tests {// — if the guard regresses, the test process itself stack-overflows (or// takes minutes) and aborts/hangs, a hard failure either way.+ #[cfg(feature = "stackprobe")]+ #[test]+ fn measure_closure_clone_cost() {+ // Rc-vs-Arc A/B on a loaded machine: wall-clock alone swings ±70%, so+ // report the closure-heavy time NORMALISED by a closure-free script of+ // similar shape measured in the same process. Only the closure script+ // pays the shared-body refcount, so the ratio isolates atomic-vs-+ // non-atomic while machine load cancels out.+ let doc = json!({});+ let params = json!({});+ // Many closure invocations at depth 1 — recursion can't be used for+ // this, `MAX_CALL_DEPTH` caps it at 32 calls. A flat `f(1)+f(1)+…`+ // chain gets ~240 calls per evaluation (bounded by MAX_EVAL_DEPTH),+ // each paying an `env.get(..).clone()` of the closure value plus its+ // drop, which is exactly the refcount traffic in question.+ let calls = 240;+ let closure_src = format!(+ "def f = (x) -> x + 1; return f(1){};",+ "+f(1)".repeat(calls)+ );+ // Same statement/expression shape, no closures at all.+ let arith_src = format!("return 1{};", "+1".repeat(calls));++ let run = |src: &str, iters: u32| {+ for _ in 0..40 {+ let _ = eval_painless(src, &ctx(&doc, ¶ms, 0.0));+ }+ let mut best = std::time::Duration::MAX;+ for _ in 0..5 {+ let t = std::time::Instant::now();+ for _ in 0..iters {+ let _ = eval_painless(src, &ctx(&doc, ¶ms, 0.0));+ }+ best = best.min(t.elapsed() / iters);+ }+ best+ };++ let closure = run(&closure_src, 2000);+ let arith = run(&arith_src, 2000);+ let per_call = (closure.as_secs_f64() - arith.as_secs_f64()) / calls as f64;+ println!(+ "closure {:?}/eval | arith {:?}/eval | ratio {:.3} | delta {:.2}ns/call",+ closure,+ arith,+ closure.as_secs_f64() / arith.as_secs_f64(),+ per_call * 1e9,+ );+ assert!(+ eval_painless(&closure_src, &ctx(&doc, ¶ms, 0.0)).is_ok(),+ "the closure benchmark must actually run all its calls"+ );+ }++ #[cfg(feature = "stackprobe")]+ #[test]+ fn measure_stack_per_call_level() {+ for nest in [1usize, 10, 50, 90, 95] {+ let h = std::thread::Builder::new()+ .stack_size(2 * 1024 * 1024)+ .spawn(move || {+ let doc = json!({});+ let params = json!({});+ // The recursive call sits INSIDE the nested blocks, so+ // every call level pays `nest` extra exec_stmt frames.+ let src = format!(+ "def f = (g, n) -> {{ {} return g(g, n); {} return 0; }}; return f(f, 1);",+ "if(true){".repeat(nest),+ "}".repeat(nest),+ );+ let r = eval_painless(&src, &ctx(&doc, ¶ms, 0.0));+ let (depth, top, min) = STACK_PROBE.with(|p| p.get());+ println!(+ "nest={nest:3} max_depth={depth} total_stack={} bytes_per_level={} err={:?}",+ top - min,+ (top - min) / (depth.max(2) - 1),+ r.as_ref().err()+ );+ })+ .unwrap();+ h.join().unwrap();+ }+ }++ // ── #97: resource limits must be loud, not absorbed ──────────────────────++ #[test]+ fn resource_limits_are_distinguishable_from_ordinary_script_errors() {+ let doc = json!({});+ let params = json!({});+ // Every limit the interpreter can trip must classify as one.+ for src in [+ format!("{}1.0{}", "(".repeat(5000), ")".repeat(5000)), // parse depth+ format!("1{}", "+1".repeat(MAX_EVAL_DEPTH)), // eval depth+ "def f = (g, n) -> g(g, n); return f(f, 1);".to_string(), // call depth+ "def f = (g,n) -> n <= 0 ? 1 : g(g,n-1) + g(g,n-1) + g(g,n-1) + g(g,n-1); \+ return f(f, 9);"+ .to_string(), // call count+ format!("\"{}\"", "x".repeat(MAX_SCRIPT_LEN)), // source size+ ] {+ let err = eval_painless(&src, &ctx(&doc, ¶ms, 0.0)).unwrap_err();+ assert!(+ is_resource_limit_error(&err),+ "limit trip not classified as a resource limit: {err:?}"+ );+ }+ // Ordinary script errors must NOT classify — the call sites that+ // swallow them keep degrading gracefully, which is the behavior the+ // ES-compat surface depends on.+ for src in [+ "someUnsupportedThing(1,2,3)",+ "unknown_identifier_here",+ "1 +",+ "((",+ ] {+ if let Err(err) = eval_painless(src, &ctx(&doc, ¶ms, 0.0)) {+ assert!(+ !is_resource_limit_error(&err),+ "ordinary script error misclassified as a resource limit: {err:?}"+ );+ }+ }+ }++ #[tokio::test]+ async fn fault_capture_sees_a_limit_a_caller_swallowed() {+ let doc = json!({});+ let params = json!({});+ let src = "def f = (g, n) -> g(g, n); return f(f, 1);";+ // Exactly what `apply_function_score` does: map any error to a+ // plausible score and move on. The fault must still surface.+ let (score, fault) = with_script_fault_capture(async {+ let c = ctx(&doc, ¶ms, 0.0);+ eval_painless(src, &c)+ .ok()+ .and_then(|v| v.as_f64())+ .unwrap_or(0.0)+ })+ .await;+ assert_eq!(score, 0.0, "the swallowing caller still degrades");+ assert_eq!(fault.as_deref(), Some(CALL_TOO_DEEP_MSG));+ }++ #[tokio::test]+ async fn fault_capture_stays_quiet_for_ordinary_errors_and_successes() {+ let doc = json!({"x": 3});+ let params = json!({});+ let (_, fault) = with_script_fault_capture(async {+ let c = ctx(&doc, ¶ms, 0.0);+ let _ = eval_painless("doc['x'].value * 2", &c);+ let _ = eval_painless("someUnsupportedThing(1)", &c);+ })+ .await;+ assert_eq!(fault, None);+ }++ #[tokio::test]+ async fn fault_capture_scopes_do_not_leak_into_each_other() {+ let doc = json!({});+ let params = json!({});+ let (_, first) = with_script_fault_capture(async {+ let c = ctx(&doc, ¶ms, 0.0);+ let _ = eval_painless("def f = (g, n) -> g(g, n); return f(f, 1);", &c);+ })+ .await;+ assert!(first.is_some());+ let (_, second) = with_script_fault_capture(async {+ let c = ctx(&doc, ¶ms, 0.0);+ let _ = eval_painless("1 + 1", &c);+ })+ .await;+ assert_eq!(second, None, "a fault leaked out of its own scope");+ }+#[test]fn self_application_with_nested_statement_body_does_not_abort() {// Mirrors the exact shape that stack-overflowed in release: adiff --git a/engine/crates/xerj-engine/tests/painless_script_limits.rs b/engine/crates/xerj-engine/tests/painless_script_limits.rsnew file mode 100644index 000000000..c8ae1acb5--- /dev/null+++ b/engine/crates/xerj-engine/tests/painless_script_limits.rs@@ -0,0 +1,305 @@+//! Regression tests for issue #97: a Painless resource limit must never be+//! absorbed into a plausible-looking value.+//!+//! PR #88 bounded closure recursion correctly — the process no longer aborts.+//! But the scoring paths (`apply_function_score`, `apply_rescore`, terms_set+//! `min_should_match`, script-bucketed aggs) return bare `f32`/`Value` with no+//! error channel, so they mapped the limit error to `0.0` / `[]`. A scoring+//! script that recursed past `MAX_CALL_DEPTH` therefore produced a WRONG SCORE+//! and reported success. These tests pin the loud behavior.++use serde_json::{json, Value};+use tempfile::TempDir;+use xerj_common::config::Config;+use xerj_common::types::Schema;+use xerj_engine::Engine;+use xerj_query::parse_request;++fn test_engine() -> (Engine, TempDir) {+ let dir = TempDir::new().expect("tempdir");+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_str().unwrap().to_string();+ config.storage.flush_size_mb = 4096;+ config.storage.flush_interval_secs = 3600;+ let engine = Engine::new(config).expect("engine::new");+ (engine, dir)+}++/// Self-application recursion that runs past `MAX_CALL_DEPTH` (32). The+/// closure body wraps the recursive call in nested blocks, the shape from the+/// original process-abort repro.+fn over_deep_script() -> String {+ let nested_open = "if(true){".repeat(10);+ let nested_close = "}".repeat(10);+ format!(+ "def f = (g, n) -> {{ {nested_open} return g(g, n); {nested_close} return 0; }}; \+ return f(f, 1);"+ )+}++async fn seed(engine: &Engine) -> std::sync::Arc<xerj_engine::index::Index> {+ engine.create_index("scripts", Schema::empty()).unwrap();+ let idx = engine.get_index("scripts").unwrap();+ idx.index_document(Some("1".into()), json!({ "rank": 7, "tags": ["a", "b"] }))+ .await+ .expect("index");+ idx.refresh().await.expect("refresh");+ idx+}++fn script_score_request(source: String) -> xerj_query::ast::SearchRequest {+ parse_request(&json!({+ "query": {+ "function_score": {+ "query": { "match_all": {} },+ "functions": [ { "script_score": { "script": { "source": source } } } ]+ }+ }+ }))+ .expect("parse_request")+}++/// The headline of #97: a `script_score` that trips the call-depth limit used+/// to return `_score: 0.0` and a 200-shaped success. It must now surface the+/// limit on the result so the API layer can fail the request.+#[tokio::test]+async fn script_score_over_call_depth_reports_a_failure_not_a_score() {+ let (engine, _dir) = test_engine();+ let idx = seed(&engine).await;++ let req = script_score_request(over_deep_script());+ let result = idx.search(&req).await.expect("search");++ let failure = result.script_failure.as_deref().unwrap_or_else(|| {+ panic!(+ "call-depth limit was swallowed: search succeeded with scores {:?} \+ and no script_failure — this is the silent wrong-score bug",+ result.hits.iter().map(|h| h.score).collect::<Vec<_>>()+ )+ });+ assert!(+ failure.contains("closure call depth"),+ "expected the closure-call-depth limit to be named, got {failure:?}"+ );+}++/// A script the interpreter simply doesn't support must keep degrading+/// gracefully — the fault sink is for *resource limits* only. Without this the+/// fix would turn every out-of-subset script into a failed search.+#[tokio::test]+async fn ordinary_script_error_still_degrades_gracefully() {+ let (engine, _dir) = test_engine();+ let idx = seed(&engine).await;++ let req = script_score_request("someUnsupportedThing(1,2,3)".to_string());+ let result = idx.search(&req).await.expect("search");+ assert!(+ result.script_failure.is_none(),+ "an unsupported-syntax script must not be reported as a resource-limit \+ failure, got {:?}",+ result.script_failure+ );+}++/// The production runtime is multi-threaded, and `Index::search` then runs the+/// whole search body inside `block_in_place` + `Handle::block_on`. The fault+/// sink is a *task*-local, so this pins that it survives that hand-off — a+/// current-thread-only test would pass while production stayed silently wrong.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn call_depth_limit_survives_the_multi_thread_block_in_place_path() {+ let (engine, _dir) = test_engine();+ let idx = seed(&engine).await;++ let req = script_score_request(over_deep_script());+ let result = idx.search(&req).await.expect("search");+ assert!(+ result.script_failure.is_some(),+ "the multi-thread block_in_place path lost the fault; scores {:?}",+ result.hits.iter().map(|h| h.score).collect::<Vec<_>>()+ );+}++/// `terms_set`'s `minimum_should_match_script` is a *matching* path, not a+/// scoring one: a script error makes the doc unsatisfiable (fail-closed), so a+/// limit trip silently removes documents from the result set.+#[tokio::test]+async fn terms_set_min_should_match_script_over_call_depth_reports_a_failure() {+ let (engine, _dir) = test_engine();+ let idx = seed(&engine).await;++ let req = parse_request(&json!({+ "query": {+ "terms_set": {+ "tags": {+ "terms": ["a", "b"],+ "minimum_should_match_script": { "source": over_deep_script() }+ }+ }+ }+ }))+ .expect("parse_request");++ let result = idx.search(&req).await.expect("search");+ assert!(+ result.script_failure.is_some(),+ "terms_set min_should_match swallowed the call-depth limit and reported \+ {} hits as a complete answer",+ result.total.value+ );+}++/// The `Rc<Vec<Stmt>>` follow-up note on #97: a shared closure body was the+/// only thing keeping `PainlessValue` off a thread boundary. This fails to+/// compile if it regresses to `Rc`.+#[test]+fn painless_values_can_cross_a_thread_boundary() {+ fn assert_send_sync<T: Send + Sync>() {}+ assert_send_sync::<xerj_engine::painless::PainlessValue>();+}++/// The rescore path has the same shape (`Err(_) => 0.0`) and the same bug.+#[tokio::test]+async fn rescore_script_over_call_depth_reports_a_failure() {+ let (engine, _dir) = test_engine();+ let idx = seed(&engine).await;++ // `parse_request` doesn't read `rescore` (the API layer builds it), so+ // attach the stage directly.+ let mut req = parse_request(&json!({ "query": { "match_all": {} } })).expect("parse_request");+ req.rescore = vec![xerj_query::ast::RescoreQuery {+ window_size: 10,+ query: None,+ script: Some(xerj_query::ast::ScriptRescore {+ source: over_deep_script(),+ params: json!({}),+ query_weight: 1.0,+ rescore_query_weight: 1.0,+ score_mode: None,+ }),+ }];++ let result = idx.search(&req).await.expect("search");+ assert!(+ result.script_failure.is_some(),+ "rescore swallowed the call-depth limit; scores {:?}",+ result.hits.iter().map(|h| h.score).collect::<Vec<_>>()+ );+}++/// Script-bucketed aggregations run inside the search too, and mapped a failed+/// script to "no buckets" — an empty aggregation that looks like a legitimate+/// answer.+#[tokio::test]+async fn script_bucketed_terms_agg_over_call_depth_reports_a_failure() {+ let (engine, _dir) = test_engine();+ let idx = seed(&engine).await;++ let req = parse_request(&json!({+ "size": 0,+ "query": { "match_all": {} },+ "aggs": {+ "by_script": { "terms": { "script": { "source": over_deep_script() } } }+ }+ }))+ .expect("parse_request");++ let result = idx.search(&req).await.expect("search");+ assert!(+ result.script_failure.is_some(),+ "the terms-agg script path swallowed the call-depth limit; aggs {:?}",+ result.aggs+ );+}++/// A failed search must not poison the response cache, and the fault must not+/// be replayed against the next (innocent) caller of the same query.+#[tokio::test]+async fn script_failure_is_not_cached_or_replayed() {+ let (engine, _dir) = test_engine();+ let idx = seed(&engine).await;++ let bad = parse_request(&json!({+ "query": {+ "function_score": {+ "query": { "match_all": {} },+ "functions": [ { "script_score": { "script": { "source": over_deep_script() } } } ]+ }+ }+ }))+ .expect("parse_request");+ assert!(idx+ .search(&bad)+ .await+ .expect("search")+ .script_failure+ .is_some());+ assert!(+ idx.search(&bad)+ .await+ .expect("search")+ .script_failure+ .is_some(),+ "the second identical request must fail too, not be served a cached \+ result whose scores are the degraded ones"+ );++ let good: xerj_query::ast::SearchRequest =+ parse_request(&json!({ "query": { "match_all": {} } })).expect("parse_request");+ let clean = idx.search(&good).await.expect("search");+ assert!(+ clean.script_failure.is_none(),+ "an unrelated request inherited another request's script fault: {:?}",+ clean.script_failure+ );+}++/// Run `src` to completion on a thread with exactly the 2 MiB stack a tokio+/// worker gets, and return the error. If the call-depth guard regresses, the+/// recursion overflows that stack and the whole test process aborts — this+/// cannot fail quietly.+fn eval_on_a_2mib_stack(src: String) -> String {+ std::thread::Builder::new()+ .stack_size(2 * 1024 * 1024)+ .spawn(move || {+ let doc = Value::Object(serde_json::Map::new());+ let params = Value::Object(serde_json::Map::new());+ let ctx = xerj_engine::painless::PainlessCtx::new(&doc, ¶ms, 0.0);+ let err = xerj_engine::painless::eval_painless(&src, &ctx)+ .expect_err("the call-depth guard must trip");+ assert!(+ xerj_engine::painless::is_resource_limit_error(&err),+ "call-depth trip must classify as a resource limit, got {err:?}"+ );+ err+ })+ .expect("spawn")+ .join()+ .expect("the closure-recursion guard let the stack overflow")+}++/// PR #88's process-abort repro must stay dead: the shape from the issue —+/// closure self-application with 10 nested `if(true){}` blocks in the body.+/// Measured at ~186 KiB of the 2 MiB stack in release.+#[test]+fn nested_block_closure_recursion_does_not_abort_on_a_2mib_stack() {+ let err = eval_on_a_2mib_stack(over_deep_script());+ assert!(err.contains("closure call depth"), "got {err:?}");+}++/// The adversarial worst case for the same repro: the body nested as deep as+/// the parser allows, so every call level also pays ~90 `exec_stmt` frames.+/// Measured at 40,720 bytes/level → 1.20 MiB at `MAX_CALL_DEPTH` = 32, which+/// is why that ceiling cannot be raised. Release only — debug frames are+/// several times larger and would legitimately need more than 2 MiB.+#[cfg(not(debug_assertions))]+#[test]+fn worst_case_nested_block_recursion_still_fits_a_2mib_stack() {+ let nest = 90;+ let src = format!(+ "def f = (g, n) -> {{ {} return g(g, n); {} return 0; }}; return f(f, 1);",+ "if(true){".repeat(nest),+ "}".repeat(nest),+ );+ let err = eval_on_a_2mib_stack(src);+ assert!(err.contains("closure call depth"), "got {err:?}");+}diff --git a/engine/crates/xerj-query/src/executor.rs b/engine/crates/xerj-query/src/executor.rsindex 0db2bfa79..e85f72dfd 100644--- a/engine/crates/xerj-query/src/executor.rs+++ b/engine/crates/xerj-query/src/executor.rs@@ -157,6 +157,17 @@ pub struct SearchResult {/// Used for ES `max_score` with collapse + track_scores (search/111).#[serde(skip_serializing_if = "Option::is_none", default)]pub max_score: Option<f32>,+ /// A Painless **resource-limit** trip (call depth, eval depth, invocation+ /// count, source size) hit while scoring or aggregating this request.+ ///+ /// The scoring paths have no error channel — `apply_function_score` and+ /// friends return a bare `f32` — so before this field a script that blew+ /// the closure call-depth limit silently scored the document `0.0` and+ /// the caller got a wrong number with no indication anything failed.+ /// Populated from the interpreter's fault sink; the API layer turns it+ /// into an error response rather than serving the degraded scores.+ #[serde(skip_serializing_if = "Option::is_none", default)]+ pub script_failure: Option<String>,}impl SearchResult {@@ -173,6 +184,7 @@ impl SearchResult {timed_out: false,profile: None,max_score: None,+ script_failure: None,}}}