Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(api): surface script resource-limit trips on _rank_eval, _explain and pivot transforms (#126)

xerj-orgbf42b6ef62b3
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index b57e369ae..3908b413a 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -20121,7 +20121,32 @@ pub async fn delete_by_query(
let response = run_delete_by_query(&idx, &search_req).await;
drop(handle);
- Json(response).into_response()
+ by_query_response(response)
+}
+
+/// Give a `_delete_by_query` / `_update_by_query` result the HTTP status its
+/// own body claims.
+///
+/// Both runners return a plain `Value` because the detached
+/// (`wait_for_completion=false`) path stores it as the `response` of a
+/// `_tasks/{id}` entry, which has no HTTP status of its own. The synchronous
+/// path then handed that value straight to `Json(..)` — always 200. So a
+/// refusal went out as `200 OK` carrying `{"error": {…}, "status": 400}`, and a
+/// client branching on the HTTP status read a completed run and then found no
+/// `deleted` / `updated` key (#123).
+///
+/// Every error body these runners produce — `script_limit_error_value` and
+/// `ApiError::into_value` — already carries the right code in `status`, so this
+/// reads it rather than re-deriving one. A successful run has no `status` key
+/// and stays 200.
+fn by_query_response(body: Value) -> Response {
+ let status = body
+ .get("status")
+ .and_then(Value::as_u64)
+ .and_then(|s| u16::try_from(s).ok())
+ .and_then(|s| StatusCode::from_u16(s).ok())
+ .unwrap_or(StatusCode::OK);
+ (status, Json(body)).into_response()
}
async fn run_delete_by_query(
@@ -20231,7 +20256,7 @@ pub async fn update_by_query(
let response = run_update_by_query(&idx, &search_req, script).await;
drop(handle);
- Json(response).into_response()
+ by_query_response(response)
}
async fn run_update_by_query(
@@ -26627,8 +26652,25 @@ pub async fn explain_doc(
ids_req.size = 1;
ids_req.from = 0;
+ // A Painless resource limit that tripped while answering this. It is
+ // REPORTED rather than refused, which is the opposite of what every other
+ // surface does, and deliberately so: `_explain` is a diagnostic endpoint.
+ //
+ // Most script faults here come from SCORING (`function_score`'s
+ // `script_score`, `rescore`), and scoring does not decide `matched` —
+ // that comes from the ids-filtered hit list. Refusing turned a correct
+ // 200 into a 400 for exactly the person trying to debug the script.
+ // Where the script IS load-bearing for matching, `matched: false` would be
+ // a confident negative, so it cannot simply be published silently either.
+ // Reporting the fault alongside the verdict satisfies both: the caller
+ // still gets the answer, and never gets it without being told a limit
+ // tripped.
+ let mut script_failure: Option<String> = None;
let matched = match idx.search(&ids_req).await {
- Ok(result) => !result.hits.is_empty(),
+ Ok(result) => {
+ script_failure = result.script_failure.clone();
+ !result.hits.is_empty()
+ }
Err(_) => false,
};
@@ -26642,6 +26684,24 @@ pub async fn explain_doc(
// Build a simple explanation tree.
let explanation = build_explanation(score as f32, &search_req.query);
+ // A tripped resource limit becomes an extra detail node rather than
+ // vanishing. `matched` above is still the verdict; this says what the
+ // engine refused to finish while reaching it, so a scoring-script fault
+ // is visible without costing the caller the answer.
+ let details = match &script_failure {
+ Some(reason) => json!([
+ explanation,
+ {
+ "value": 0.0,
+ "description": format!(
+ "a script hit a resource limit while answering this explain: {reason}"
+ ),
+ "details": []
+ }
+ ]),
+ None => json!([explanation]),
+ };
+
Json(json!({
"_index": index,
"_id": id,
@@ -26650,7 +26710,7 @@ pub async fn explain_doc(
"explanation": {
"value": score,
"description": description,
- "details": [explanation]
+ "details": details
}
}))
.into_response()
@@ -28734,6 +28794,8 @@ pub async fn rank_eval(
.and_then(Value::as_bool)
.unwrap_or(false);
+ let mut failures = serde_json::Map::new();
+
for req_spec in &body.requests {
let query_val = req_spec
.request
@@ -28761,6 +28823,28 @@ pub async fn rank_eval(
Ok(r) => r,
Err(_) => continue,
};
+ // A Painless resource limit tripped while scoring or matching this
+ // request. `_rank_eval` exists to *measure relevance quality*, so a
+ // `metric_score` computed over degraded scores (or over a ranking a
+ // fail-closed script truncated) does not just return a bad answer — it
+ // corrupts the number a caller would use to notice bad answers.
+ //
+ // The failure is recorded PER REQUEST rather than failing the batch.
+ // `failures` is the channel ES provides for exactly this, keyed by the
+ // request id, and a body of ten requests where one carries a bad script
+ // should not lose the other nine. The faulted request contributes
+ // nothing to `metric_score`, so the published number is computed only
+ // over requests that actually produced trustworthy scores.
+ if let Some(reason) = &result.script_failure {
+ failures.insert(
+ req_spec.id.clone(),
+ script_limit_error_value(reason)
+ .get("error")
+ .cloned()
+ .unwrap_or_else(|| json!({ "type": "script_exception", "reason": reason })),
+ );
+ continue;
+ }
let retrieved_ids: Vec<String> = result.hits.iter().take(k).map(|h| h.id.clone()).collect();
@@ -28813,7 +28897,7 @@ pub async fn rank_eval(
Json(json!({
"metric_score": mean_score,
"details": details,
- "failures": {}
+ "failures": Value::Object(failures)
}))
.into_response()
}
@@ -30149,7 +30233,10 @@ pub async fn start_transform(
}
Json(json!({ "acknowledged": true })).into_response()
}
- Err(msg) => {
+ // Same ES-shaped `script_exception` 400 the other script surfaces
+ // return, rather than rewording a refusal into a config error.
+ Err(TransformRunError::ScriptLimit(reason)) => script_limit_response(&reason),
+ Err(TransformRunError::Failed(msg)) => {
let e = xerj_common::XerjError::invalid_query(format!(
"transform [{id}] execution failed: {msg}"
));
@@ -30471,8 +30558,29 @@ fn flatten_bucket_metrics(
}
}
+/// Why a pivot transform run stopped early.
+///
+/// The runner used to fail with a bare `String`, which `start_transform`
+/// rendered as an `illegal_argument_exception`. A Painless resource-limit trip
+/// needs its own arm so it can reach the caller in the same ES-shaped
+/// `script_exception` 400 every other script surface uses (see #116) instead of
+/// being reworded into a generic config error.
+enum TransformRunError {
+ /// Configuration or engine failure.
+ Failed(String),
+ /// A script resource limit tripped while selecting or aggregating the
+ /// source documents.
+ ScriptLimit(String),
+}
+
+impl From<String> for TransformRunError {
+ fn from(msg: String) -> Self {
+ Self::Failed(msg)
+ }
+}
+
/// Run a pivot transform end to end. Returns the number of docs written to dest.
-async fn run_pivot_transform(state: &AppState, config: &Value) -> Result<usize, String> {
+async fn run_pivot_transform(state: &AppState, config: &Value) -> Result<usize, TransformRunError> {
let source_index = config
.pointer("/source/index")
.and_then(|v| {
@@ -30533,6 +30641,19 @@ async fn run_pivot_transform(state: &AppState, config: &Value) -> Result<usize,
}
let req = xerj_query::parse_request(&body).map_err(|e| e.to_string())?;
let res = src_idx.search(&req).await.map_err(|e| e.to_string())?;
+ // Both halves of a pivot can carry a user script: `source.query` (a
+ // `terms_set` `minimum_should_match_script`, say) and
+ // `pivot.aggregations` (a script-bucketed `terms`). Either one that
+ // trips a resource limit fails closed, so this page of buckets
+ // summarises fewer documents than the caller asked about. Writing that
+ // summary and acknowledging the run persists wrong numbers into `dest`,
+ // where every later query reads them as fact. Checked before the writes
+ // below — note the runner is not transactional, so buckets from earlier
+ // pages that completed cleanly stay written, as with any mid-run
+ // failure.
+ if let Some(reason) = &res.script_failure {
+ return Err(TransformRunError::ScriptLimit(reason.clone()));
+ }
let aggs = match res.aggs {
Some(a) => a,
None => break,
@@ -30585,6 +30706,16 @@ async fn run_pivot_transform(state: &AppState, config: &Value) -> Result<usize,
/// Run a rollup job end to end across every index matching `index_pattern`.
/// Returns the total number of rolled-up docs written to rollup_index.
+///
+/// Unlike `run_pivot_transform`, this one does **not** check
+/// `SearchResult::script_failure` (#123), and the reason is structural rather
+/// than a judgement call: no user script can reach it. The request body below
+/// is built entirely from the job config's `groups` and `metrics` — composite
+/// sources over `date_histogram` / `terms` / `histogram` with a `field`, and
+/// named metric aggs over a `field`. There is no `query` key and no place to
+/// put a `script`, so the search it issues carries none. Should a rollup job
+/// ever gain a query or a scripted metric, it needs the same check the pivot
+/// runner has.
async fn run_rollup_job(state: &AppState, job_id: &str, config: &Value) -> Result<usize, String> {
let index_pattern = config
.get("index_pattern")
diff --git a/engine/crates/xerj-api/tests/script_limits_remaining_surfaces_http.rs b/engine/crates/xerj-api/tests/script_limits_remaining_surfaces_http.rs
new file mode 100644
index 000000000..796dbad13
--- /dev/null
+++ b/engine/crates/xerj-api/tests/script_limits_remaining_surfaces_http.rs
@@ -0,0 +1,440 @@
+//! Issue #123: the surfaces PR #116 (issue #97) did not reach.
+//!
+//! #116 split Painless failures into "cannot evaluate" (degrade quietly, the
+//! ES-compat contract) and "refused because a resource limit tripped" (must
+//! surface), and wired the second class through ten request surfaces via
+//! `SearchResult::script_failure`. `_rank_eval`, `_explain` and the pivot
+//! transform runner were left reading the same field's absence as success.
+//!
+//! `_rank_eval` is the worst of the three: it exists to *measure relevance
+//! quality*, so a silently degraded score does not merely return a bad answer,
+//! it corrupts the number you would use to notice bad answers.
+//!
+//! The two `*_by_query` tests cover the second defect in the same issue: those
+//! handlers refused correctly but shipped the refusal as `200 OK` with a
+//! `{"error": …, "status": 400}` body, so a client branching on the HTTP status
+//! saw a success and then found no `deleted` / `updated` key.
+//!
+//! As in #116, the last test is the guard rail in the other direction: a
+//! script merely outside our Painless subset must keep scoring neutrally on a
+//! 200. A "fix" that turns every unparseable script into a 400 passes every
+//! loudness assertion here and breaks the compat surface.
+
+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. Short enough to clear the static
+/// source-size and parse-depth guards, so the limit can only trip
+/// mid-evaluation — the case with no error channel of its own.
+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);")
+}
+
+/// A `terms_set` whose `minimum_should_match_script` trips the call-depth
+/// limit. Unlike `script_score`, this one fails *matching* closed, so the
+/// affected surfaces under-select rather than mis-score.
+fn over_deep_matching_query() -> Value {
+ json!({
+ "terms_set": {
+ "tags": {
+ "terms": ["a", "b"],
+ "minimum_should_match_script": { "source": over_deep_script() }
+ }
+ }
+ })
+}
+
+/// One index, two documents, ready to search.
+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"], "team": "red" }),
+ )
+ .await
+ .expect("index_document");
+ idx.index_document(
+ Some("2".into()),
+ json!({ "rank": 3, "tags": ["a"], "team": "blue" }),
+ )
+ .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) {
+ send(app, Request::post(path), body).await
+}
+
+async fn send(
+ app: &axum::Router,
+ builder: axum::http::request::Builder,
+ body: Value,
+) -> (StatusCode, Value) {
+ let response = app
+ .clone()
+ .oneshot(
+ builder
+ .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 #123. `_rank_eval` scores each request with the same
+/// `Index::search` the other surfaces use, so a `script_score` past the
+/// call-depth limit degrades every hit to 0.0 — and then `_rank_eval`
+/// publishes a `metric_score` computed over that degraded ranking as a
+/// successful measurement.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn rank_eval_past_the_call_depth_limit_is_an_error_not_a_metric_score() {
+ let (app, _dir) = seeded_app().await;
+ let (status, body) = post(
+ &app,
+ "/scripts/_rank_eval",
+ json!({
+ "requests": [{
+ "id": "q1",
+ "request": {
+ "query": {
+ "function_score": {
+ "query": { "match_all": {} },
+ "functions": [
+ { "script_score": { "script": { "source": over_deep_script() } } }
+ ]
+ }
+ }
+ },
+ "ratings": [{ "_index": "scripts", "_id": "1", "rating": 3 }]
+ }],
+ "metric": { "precision": { "k": 2 } }
+ }),
+ )
+ .await;
+
+ // Reported per request, not by failing the batch: `failures` is the channel
+ // ES provides for exactly this, and a body of many requests must not lose
+ // the good ones because of one bad script.
+ assert_eq!(status, StatusCode::OK, "body: {body}");
+ assert_eq!(
+ body["failures"]["q1"]["type"], "script_exception",
+ "_rank_eval published a relevance measurement taken from scores a \
+ resource-limited script never produced, with no failure recorded: {body}"
+ );
+ assert!(
+ body["failures"]["q1"]["reason"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("closure call depth"),
+ "the reason must name the limit that tripped: {body}"
+ );
+ // The faulted request contributes nothing, so the published number is
+ // computed only over requests that produced trustworthy scores.
+ assert_eq!(
+ body["metric_score"].as_f64(),
+ Some(0.0),
+ "a faulted request must not contribute to metric_score: {body}"
+ );
+ assert!(
+ body["details"].get("q1").is_none(),
+ "a faulted request must not appear in details as if it had been measured: {body}"
+ );
+}
+
+/// A body where only ONE of several requests carries a limit-tripping script
+/// must still measure the others. Failing all of them was the first attempt.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn rank_eval_failure_is_scoped_to_the_offending_request() {
+ let (app, _dir) = seeded_app().await;
+ let (status, body) = post(
+ &app,
+ "/scripts/_rank_eval",
+ json!({
+ "requests": [
+ {
+ "id": "good",
+ "request": { "query": { "match_all": {} } },
+ "ratings": [{ "_index": "scripts", "_id": "1", "rating": 3 }]
+ },
+ {
+ "id": "bad",
+ "request": { "query": over_deep_matching_query() },
+ "ratings": [{ "_index": "scripts", "_id": "1", "rating": 3 }]
+ }
+ ],
+ "metric": { "precision": { "k": 2 } }
+ }),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK, "body: {body}");
+ assert_eq!(
+ body["failures"]["bad"]["type"], "script_exception",
+ "the offending request must be recorded: {body}"
+ );
+ assert!(
+ body["failures"].get("good").is_none(),
+ "a healthy request must not be marked failed: {body}"
+ );
+ assert!(
+ body["details"].get("good").is_some(),
+ "a healthy request must still be measured when a sibling fails: {body}"
+ );
+}
+
+/// A limit trip in the *matching* path truncates the ranking instead of
+/// skewing it: fewer retrieved ids, so precision/recall are computed over a
+/// selection the script silently cut short.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn rank_eval_refuses_a_ranking_a_script_limit_truncated() {
+ let (app, _dir) = seeded_app().await;
+ let (status, body) = post(
+ &app,
+ "/scripts/_rank_eval",
+ json!({
+ "requests": [{
+ "id": "q1",
+ "request": { "query": over_deep_matching_query() },
+ "ratings": [{ "_index": "scripts", "_id": "1", "rating": 3 }]
+ }]
+ }),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK, "body: {body}");
+ assert_eq!(
+ body["failures"]["q1"]["type"], "script_exception",
+ "_rank_eval measured a ranking that a fail-closed script truncated, with \
+ no failure recorded: {body}"
+ );
+ assert!(
+ body["details"].get("q1").is_none(),
+ "a truncated ranking must not be published as a measurement: {body}"
+ );
+}
+
+/// `_explain` answers a yes/no question — did this document match? — by
+/// running the query with an `ids` filter. A fail-closed script makes the
+/// answer `matched: false`, which is indistinguishable from a document that
+/// genuinely does not match.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn explain_past_the_call_depth_limit_is_an_error_not_an_unmatched_doc() {
+ let (app, _dir) = seeded_app().await;
+ let (status, body) = post(
+ &app,
+ "/scripts/_explain/1",
+ json!({ "query": over_deep_matching_query() }),
+ )
+ .await;
+
+ // `_explain` is a diagnostic endpoint, so the fault is REPORTED rather than
+ // refused: most script faults here come from scoring, which does not decide
+ // `matched`, and refusing turned a correct 200 into a 400 for exactly the
+ // person debugging the script. The caller still gets the verdict and never
+ // gets it without being told a limit tripped.
+ assert_eq!(status, StatusCode::OK, "body: {body}");
+ assert!(
+ body.get("matched").is_some(),
+ "_explain must still answer the question it was asked: {body}"
+ );
+ let details = body["explanation"]["details"]
+ .as_array()
+ .cloned()
+ .unwrap_or_default();
+ assert!(
+ details.iter().any(|d| d["description"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("resource limit")),
+ "_explain reported a match verdict decided by a script that was refused \
+ mid-evaluation, without disclosing it: {body}"
+ );
+ assert!(
+ details.iter().any(|d| d["description"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("closure call depth")),
+ "the disclosed fault must name the limit that tripped: {body}"
+ );
+}
+
+/// The second defect in #123. `run_delete_by_query` refuses correctly, but the
+/// handler wrapped the refusal in `Json(..)` alone — HTTP 200 carrying
+/// `{"error": …, "status": 400}`.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn delete_by_query_script_refusal_carries_its_own_http_status() {
+ let (app, _dir) = seeded_app().await;
+ let (status, body) = post(
+ &app,
+ "/scripts/_delete_by_query",
+ json!({ "query": over_deep_matching_query() }),
+ )
+ .await;
+
+ assert_eq!(body["error"]["type"], "script_exception", "body: {body}");
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "the refusal body said 400 while the HTTP status said OK, so a client \
+ branching on the status sees a successful delete: {body}"
+ );
+ assert!(
+ body.get("deleted").is_none(),
+ "a refused delete must not also report a deletion count: {body}"
+ );
+
+ // The refusal has to be a refusal: nothing may have been deleted.
+ let (count_status, count_body) = post(&app, "/scripts/_count", json!({})).await;
+ assert_eq!(count_status, StatusCode::OK, "body: {count_body}");
+ assert_eq!(count_body["count"], 2, "body: {count_body}");
+}
+
+/// Same defect on `_update_by_query`.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn update_by_query_script_refusal_carries_its_own_http_status() {
+ let (app, _dir) = seeded_app().await;
+ let (status, body) = post(
+ &app,
+ "/scripts/_update_by_query",
+ json!({ "query": over_deep_matching_query() }),
+ )
+ .await;
+
+ assert_eq!(body["error"]["type"], "script_exception", "body: {body}");
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "the refusal body said 400 while the HTTP status said OK: {body}"
+ );
+ assert!(
+ body.get("updated").is_none(),
+ "a refused update must not also report an update count: {body}"
+ );
+}
+
+/// A successful `_delete_by_query` must stay a 200 — the status now comes from
+/// the body, so this pins the non-error half of that mapping.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn delete_by_query_without_a_script_is_still_a_200() {
+ let (app, _dir) = seeded_app().await;
+ let (status, body) = post(
+ &app,
+ "/scripts/_delete_by_query",
+ json!({ "query": { "term": { "team": "blue" } } }),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK, "body: {body}");
+ assert_eq!(body["deleted"], 1, "body: {body}");
+}
+
+/// A pivot transform runs a composite aggregation over `source.query` and
+/// writes one document per bucket into `dest`. A fail-closed script in that
+/// query silently shrinks the source set, so the transform materialises a
+/// wrong summary and reports `acknowledged: true` over it — the same defect as
+/// an under-delete, except the wrong numbers are now persisted in an index
+/// that later queries will read as fact.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn pivot_transform_refuses_a_source_a_script_limit_truncated() {
+ let (app, _dir) = seeded_app().await;
+
+ let (put_status, put_body) = send(
+ &app,
+ Request::put("/_transform/t1"),
+ json!({
+ "source": { "index": "scripts", "query": over_deep_matching_query() },
+ "dest": { "index": "scripts_pivot" },
+ "pivot": {
+ "group_by": { "team": { "terms": { "field": "team" } } },
+ "aggregations": { "max_rank": { "max": { "field": "rank" } } }
+ }
+ }),
+ )
+ .await;
+ assert_eq!(put_status, StatusCode::OK, "body: {put_body}");
+
+ let (status, body) = post(&app, "/_transform/t1/_start", json!({})).await;
+
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "the transform wrote a summary of a source set a refused script had \
+ truncated, and acknowledged it: {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}"
+ );
+}
+
+/// The counterpart, restated for the new surfaces: a script our interpreter
+/// does not support is NOT a resource limit and must keep degrading quietly.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn unsupported_script_syntax_still_degrades_quietly_on_the_new_surfaces() {
+ let (app, _dir) = seeded_app().await;
+ let unsupported = json!({
+ "function_score": {
+ "query": { "match_all": {} },
+ "functions": [
+ { "script_score": { "script": { "source": "someUnsupportedThing(1,2,3)" } } }
+ ]
+ }
+ });
+
+ let (status, body) = post(
+ &app,
+ "/scripts/_rank_eval",
+ json!({
+ "requests": [{
+ "id": "q1",
+ "request": { "query": unsupported.clone() },
+ "ratings": [{ "_index": "scripts", "_id": "1", "rating": 3 }]
+ }]
+ }),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "an out-of-subset script must not turn _rank_eval into a 400: {body}"
+ );
+ assert!(body["metric_score"].is_number(), "body: {body}");
+
+ let (status, body) = post(&app, "/scripts/_explain/1", json!({ "query": unsupported })).await;
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "an out-of-subset script must not turn _explain into a 400: {body}"
+ );
+ assert_eq!(body["matched"], true, "body: {body}");
+}