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): per-evaluation work budget to bound the flat-script CPU DoS (#133)
xerj-orgb77a9118a4da
diff --git a/engine/crates/xerj-api/tests/script_cpu_budget_http.rs b/engine/crates/xerj-api/tests/script_cpu_budget_http.rsnew file mode 100644index 000000000..8033d87bc--- /dev/null+++ b/engine/crates/xerj-api/tests/script_cpu_budget_http.rs@@ -0,0 +1,240 @@+//! Issue #122, from the outside: a script that is *legal* by every structural+//! measure but arbitrarily expensive per document must reach the HTTP caller+//! as a 400, not as a search that runs for as long as the script wants.+//!+//! The headline script below is flat, closure-free, 38 KiB (under the 64 KiB+//! source limit), nests nothing and calls nothing — so `MAX_PARSE_DEPTH`,+//! `MAX_EVAL_DEPTH`, `MAX_CALL_DEPTH`, `MAX_CALL_COUNT` and `MAX_SCRIPT_LEN`+//! all pass it. Every statement is the single expression `params.blob;`, which+//! converts a caller-supplied subtree into interpreter values: work that is+//! O(params) behind an expression that looks O(1). Measured on the commit this+//! branch is based on, in release, pinned: **9.03 s of CPU per document** with+//! a `params` of 50,000 nodes, and 37.35 s at 200,000. A request `timeout`+//! could not interrupt any of it, because the doc-scan poll only checks a+//! document *boundary*.+//!+//! The counterpart tests matter as much: an ordinary script must still return+//! 200, and a script merely outside the supported subset must still degrade+//! quietly. A budget that answers 400 too eagerly would pass the loudness test+//! and break every real client.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++/// A flat script of bare `params.blob;` statements — the shape whose whole cost+/// is in the value each statement materialises and none of which is visible in+/// the statement count.+fn bare_params_script(statements: usize) -> String {+ let mut src = String::with_capacity(statements * 13 + 16);+ for _ in 0..statements {+ src.push_str("params.blob;\n");+ }+ src.push_str("return 1;");+ src+}++/// `params` whose single member is an array of `nodes` short strings.+fn blob_params(nodes: usize) -> Value {+ let blob: Vec<Value> = (0..nodes).map(|i| json!(format!("v{i}"))).collect();+ json!({ "blob": blob })+}++/// A flat script whose cost is quadratic in its own statement count: each+/// statement concatenates a 1 KiB chunk onto an accumulator the previous+/// statement just grew. Its *size* is separately bounded by the 1 MiB+/// `MAX_PAINLESS_STRING_LEN` cap that arrived with #87, but the work budget+/// prices it first — the second test below pins that it is the budget, named+/// in the error, that the caller is told about.+fn quadratic_concat_script(statements: usize) -> String {+ let mut src = String::with_capacity(1024 + statements * 10 + 64);+ src.push_str("def c = \"");+ src.push_str(&"x".repeat(1024));+ src.push_str("\";\ndef s = c;\n");+ for _ in 0..statements {+ src.push_str("s = s + c;\n");+ }+ src.push_str("return s.length();");+ src+}++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");+ for id in 1..=8 {+ idx.index_document(Some(id.to_string()), json!({ "rank": id }))+ .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)+}++fn script_score_body(source: String) -> Value {+ json!({+ "query": {+ "function_score": {+ "query": { "match_all": {} },+ "functions": [ { "script_score": { "script": { "source": source } } } ]+ }+ }+ })+}++fn script_score_body_with_params(source: String, params: Value) -> Value {+ json!({+ "query": {+ "function_score": {+ "query": { "match_all": {} },+ "functions": [+ { "script_score": { "script": { "source": source, "params": params } } }+ ]+ }+ }+ })+}++/// The headline. On the base commit this returns `200 OK` after burning a+/// measured 9.03 s of CPU *per matching document* — eight documents, so over a+/// minute of CPU for one unauthenticated request that no `timeout` could+/// shorten.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn a_legal_but_arbitrarily_expensive_script_is_a_400_not_a_long_wait() {+ let (app, _dir) = seeded_app().await;+ let source = bare_params_script(3000);+ assert!(+ source.len() < 64 * 1024,+ "the repro must clear the source-size limit, got {} bytes",+ source.len()+ );++ let started = std::time::Instant::now();+ let (status, body) = post(+ &app,+ "/scripts/_search",+ script_score_body_with_params(source, blob_params(50_000)),+ )+ .await;+ let elapsed = started.elapsed();++ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "an unbudgeted script must not answer 200; body {body}"+ );+ assert_eq!(+ body["error"]["type"], "script_exception",+ "the work budget must surface through the resource-limit class, got {body}"+ );+ let reason = body["error"]["reason"].as_str().unwrap_or_default();+ // Specifically the WORK budget, and this is the load-bearing assertion.+ // With `params` reads uncharged the evaluation is still stopped eventually+ // — by the wall-clock half, after seconds — so asserting only "some budget"+ // passes on a tree where the accounting hole is wide open. Which of the two+ // limits fires is the deterministic signal that the read was priced.+ assert!(+ reason.contains("work budget"),+ "a `params` read must be charged for what it materialises, so the \+ deterministic op ceiling is what refuses this — not the wall clock \+ noticing seconds later; got {reason:?}"+ );+ // Generous by an order of magnitude against the >70 s of CPU this used to+ // cost, so a slow CI box cannot make it flaky while it still fails loudly+ // if the budget stops bounding anything.+ assert!(+ elapsed < std::time::Duration::from_secs(5),+ "the request was still unbounded: {elapsed:?}"+ );+}++/// The quadratic-concatenation shape reaches the caller the same way. Its+/// *result size* is separately capped at 1 MiB, but the work budget prices the+/// copying first, so the error the caller sees names the budget.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn the_quadratic_concat_shape_also_names_the_budget() {+ let (app, _dir) = seeded_app().await;+ let source = quadratic_concat_script(4000);+ assert!(source.len() < 64 * 1024, "the repro must be legal-size");++ let (status, body) = post(&app, "/scripts/_search", script_score_body(source)).await;++ assert_eq!(status, StatusCode::BAD_REQUEST, "body {body}");+ assert_eq!(body["error"]["type"], "script_exception", "body {body}");+ let reason = body["error"]["reason"].as_str().unwrap_or_default();+ assert!(+ reason.contains("budget"),+ "the work budget must be what trips, not the string-size cap, got {reason:?}"+ );+}++/// The other half of the contract: an ordinary `script_score` must be entirely+/// unaffected, 200 with real scores.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn an_ordinary_script_score_is_untouched_by_the_budget() {+ let (app, _dir) = seeded_app().await;+ let (status, body) = post(+ &app,+ "/scripts/_search",+ script_score_body("doc['rank'].value * 2 + _score".to_string()),+ )+ .await;++ assert_eq!(status, StatusCode::OK, "body {body}");+ let hits = body["hits"]["hits"].as_array().expect("hits");+ assert_eq!(hits.len(), 8, "body {body}");+ assert!(+ hits.iter()+ .all(|hit| hit["_score"].as_f64().unwrap_or(0.0) > 0.0),+ "the budget degraded ordinary scores to zero: {body}"+ );+}++/// A script that is merely *outside* the supported Painless subset must keep+/// degrading quietly — the fault sink is for resource limits only, and the+/// ES-compat surface depends on that distinction.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn an_unsupported_script_still_degrades_instead_of_400ing() {+ let (app, _dir) = seeded_app().await;+ let (status, body) = post(+ &app,+ "/scripts/_search",+ script_score_body("someUnsupportedThing(1,2,3)".to_string()),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::OK,+ "an out-of-subset script must not become a 400; body {body}"+ );+}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex c3a6aa459..56a073d7f 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -11005,11 +11005,23 @@ impl Index {// 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.+ // The same scope also publishes this request's deadline to the script+ // interpreter (issue #122). Every limit the interpreter had bounded a+ // structural property of a script, never its cost, so a flat 38 KiB+ // script of `params.blob;` statements could burn a measured 37.35 s of+ // CPU on ONE document — and the doc-scan timeout poll cannot interrupt+ // that, because it only decides how often a document *boundary* is+ // checked. With the deadline visible+ // inside `eval_painless`, a single evaluation can be abandoned+ // part-way through, and no one document can overshoot the deadline+ // this request was given.let search_fut = async {- let (result, fault) = crate::painless::with_script_fault_capture(- self.search_inner(request, request_deadline),- )- .await;+ let (result, fault) =+ crate::painless::with_script_fault_capture(crate::painless::with_script_deadline(+ request_deadline,+ self.search_inner(request, request_deadline),+ ))+ .await;match (result, fault) {(Ok(mut r), Some(f)) => {// Capture scopes nest, and this one just consumed thediff --git a/engine/crates/xerj-engine/src/painless.rs b/engine/crates/xerj-engine/src/painless.rsindex 0958d9ea8..07c82f4a1 100644--- a/engine/crates/xerj-engine/src/painless.rs+++ b/engine/crates/xerj-engine/src/painless.rs@@ -129,10 +129,46 @@ pub struct PainlessCtx<'a> {/// depth of ~n, but its invocation count is 4^n. This is the step/// budget that catches that shape.call_count: std::cell::Cell<usize>,+ /// Work units consumed by this evaluation — see [`MAX_SCRIPT_OPS`]. Unlike+ /// every other counter here this one bounds WORK rather than shape, which+ /// is why a flat 38 KiB script could previously burn a measured 37.35 s on+ /// one document while tripping nothing.+ ops: std::cell::Cell<u64>,+ /// Work-unit count at which the next wall-clock read is due. Sampling the+ /// clock rather than reading it per op is what keeps the budget off the+ /// hot path — see [`OPS_PER_CLOCK_CHECK`].+ next_clock_check: std::cell::Cell<u64>,+ /// This evaluation's absolute deadline, resolved up front in+ /// [`PainlessCtx::new`] from the enclosing request deadline (see+ /// [`MIN_EVAL_SLICE`]).+ ///+ /// It has to be resolved before any work is charged, not at the first clock+ /// check. Deriving it there costs a whole sampling window to *establish*+ /// the deadline and a second one to be able to fail it, so the slice an+ /// evaluation actually got was two windows wide instead of one — and a+ /// window is only bounded in work units, not in time.+ eval_deadline: std::time::Instant,+ /// Cached work-unit weight of `doc`, computed on the first whole-document+ /// read (see [`charge_document_read`]). The document is immutable for the+ /// life of the context, so this is measured at most once per evaluation.+ doc_work_units: std::cell::Cell<Option<u64>>,}impl<'a> PainlessCtx<'a> {pub fn new(doc: &'a Value, params: &'a Value, score: f32) -> Self {+ // One clock read per evaluation, taken before any work is charged.+ // This is the anchor the time budget is measured from: the slice is+ // this request's *remaining* time clamped into+ // [MIN_EVAL_SLICE, MAX_EVAL_SLICE]. The upper clamp bounds an+ // evaluation even when the request has 30 s left; the lower one keeps+ // an ordinary script from being cut off just because the request+ // deadline has already passed, which is the normal state of a+ // legitimately slow search — the scan only notices at its next+ // document-boundary poll.+ let started = std::time::Instant::now();+ let remaining = SCRIPT_REQUEST_DEADLINE+ .try_with(|deadline| deadline.saturating_duration_since(started))+ .unwrap_or(MAX_EVAL_SLICE);Self {doc,params,@@ -141,11 +177,157 @@ impl<'a> PainlessCtx<'a> {eval_depth: std::cell::Cell::new(0),call_depth: std::cell::Cell::new(0),call_count: std::cell::Cell::new(0),+ ops: std::cell::Cell::new(0),+ next_clock_check: std::cell::Cell::new(OPS_PER_CLOCK_CHECK),+ eval_deadline: started + remaining.clamp(MIN_EVAL_SLICE, MAX_EVAL_SLICE),+ doc_work_units: std::cell::Cell::new(None),}}pub fn take_emits(&self) -> Vec<PainlessValue> {std::mem::take(&mut *self.emits.borrow_mut())}++ /// Work units this evaluation has consumed so far. Exposed so the budget+ /// can be calibrated against real scripts rather than guessed at — the+ /// 145x margin quoted on [`MAX_SCRIPT_OPS`] is measured with this.+ pub fn work_units(&self) -> u64 {+ self.ops.get()+ }++ /// Charge `units` of work against the budget.+ ///+ /// The whole hot path is: one add, one compare against a constant, one+ /// compare against a cell. The clock is only read once every+ /// [`OPS_PER_CLOCK_CHECK`] units, in an out-of-line `#[cold]` helper.+ #[inline(always)]+ fn charge(&self, units: u64) -> Result<(), String> {+ let used = self.ops.get().saturating_add(units);+ self.ops.set(used);+ if used >= MAX_SCRIPT_OPS {+ return Err(SCRIPT_OVER_BUDGET_MSG.to_string());+ }+ if used >= self.next_clock_check.get() {+ return self.clock_check(used);+ }+ Ok(())+ }++ /// The sampled wall-clock half of the budget. Out of line and `#[cold]`:+ /// it runs once per [`OPS_PER_CLOCK_CHECK`] units, so keeping it out of+ /// the inlined `charge` body is what makes the fast path two compares.+ #[cold]+ fn clock_check(&self, used: u64) -> Result<(), String> {+ self.next_clock_check+ .set(used.saturating_add(OPS_PER_CLOCK_CHECK));+ // The deadline was fixed in `new`, so this — the FIRST sampling window+ // — can already fail. It reads the clock and compares; it does not+ // spend a window deciding when the evaluation was supposed to end.+ if std::time::Instant::now() >= self.eval_deadline {+ return Err(SCRIPT_OVER_TIME_MSG.to_string());+ }+ Ok(())+ }+}++/// Work units a produced value is worth.+///+/// Charging per interpreter *step* alone does not bound work: `s = s + c` is+/// three steps whether `s` is 1 KiB or 4 MiB. Pricing the value a step+/// produces is what closes that — the adversarial script's cost is entirely in+/// the bytes it copies, not in the number of statements it runs.+///+/// Scalars answer in a single match with no allocation, which is the case+/// every ordinary script is in.+#[inline(always)]+fn value_work_units(value: &PainlessValue) -> u64 {+ match value {+ PainlessValue::Null+ | PainlessValue::Bool(_)+ | PainlessValue::Number(_)+ | PainlessValue::Closure(..) => 1,+ PainlessValue::String(text) => 1 + text.len() as u64 / BYTES_PER_OP,+ PainlessValue::Array(_) | PainlessValue::Object(_) => composite_work_units(value),+ }+}++/// Work units for an array/object value: one per node it contains plus its+/// string bytes, which is the cost of having cloned it.+///+/// Iterative rather than recursive on purpose — this walks caller-supplied+/// JSON of unbounded nesting, and the native stack is the one resource the+/// interpreter's other limits exist to protect.+fn composite_work_units(value: &PainlessValue) -> u64 {+ let mut total = 0u64;+ let mut painless = vec![value];+ let mut json: Vec<&Value> = Vec::new();+ while let Some(value) = painless.pop() {+ total += 1;+ match value {+ PainlessValue::String(text) => total += text.len() as u64 / BYTES_PER_OP,+ PainlessValue::Array(items) => painless.extend(items.iter()),+ PainlessValue::Object(map) => json.extend(map.values()),+ _ => {}+ }+ }+ total + json_work_units_each(json)+}++/// The same measure over raw JSON, so a document can be weighed without first+/// being converted into `PainlessValue`s.+fn json_work_units(value: &Value) -> u64 {+ json_work_units_each(vec![value])+}++fn json_work_units_each(mut stack: Vec<&Value>) -> u64 {+ let mut total = 0u64;+ while let Some(value) = stack.pop() {+ total += 1;+ match value {+ Value::String(text) => total += text.len() as u64 / BYTES_PER_OP,+ Value::Array(items) => stack.extend(items.iter()),+ Value::Object(map) => stack.extend(map.values()),+ _ => {}+ }+ }+ total+}++/// Charge for a whole-document read.+///+/// [`get_doc_value`] clones the entire source document on every call, so+/// `doc['x'].value` is O(document), not O(1) — a flat script of 2,000 such+/// accesses against a 20,000-element document does 40 M nodes of copying while+/// tripping no structural limit. The weight is computed once and cached: the+/// document does not change during an evaluation.+fn charge_document_read(ctx: &PainlessCtx) -> Result<(), String> {+ let weight = match ctx.doc_work_units.get() {+ Some(weight) => weight,+ None => {+ let weight = json_work_units(ctx.doc);+ ctx.doc_work_units.set(Some(weight));+ weight+ }+ };+ ctx.charge(weight)+}++/// Read `params[key]`, charged for its size *before* it is materialised.+///+/// `params.big` and `params['big']` are single interpreter steps that run+/// `PainlessValue::from_json` over a caller-supplied subtree of unbounded size,+/// so their real cost is O(params) and none of it is visible in the statement+/// count — the same shape as `s = s + c`, one level further out. Charging+/// before the conversion (rather than only weighing what came out) is what+/// bounds how many such materialisations one evaluation may perform, instead of+/// performing one and asking afterwards.+///+/// The weight is not cached the way [`charge_document_read`] caches the+/// document's: which member is read varies per step, and a `params` object big+/// enough for the cache to matter is exactly the one that must keep paying.+fn charged_params_read(ctx: &PainlessCtx, key: &str) -> Result<PainlessValue, String> {+ let raw = ctx.params.get(key).unwrap_or(&Value::Null);+ ctx.charge(json_work_units(raw))?;+ Ok(PainlessValue::from_json(raw))}// ── Tokenisation ─────────────────────────────────────────────────────────────@@ -565,6 +747,141 @@ pub(crate) const TOO_MANY_CALLS_MSG: &str =/// [`is_resource_limit_error`] can recognise it without formatting.const SOURCE_TOO_LONG_PREFIX: &str = "script source is ";+// ── Per-evaluation work budget (issue #122) ──────────────────────────────────+//+// Every limit above bounds a STRUCTURAL property of a script: how deep it+// nests, how many closure calls it makes, how many bytes of source it is.+// None of them bounds WORK, and the two are not the same thing — a script can+// be flat, shallow, closure-free and comfortably under the 64 KiB source cap+// while costing tens of seconds of CPU on a SINGLE document.+//+// Measured in a release build on the commit this branch is based on, one core,+// `taskset`-pinned (`tests/painless_cpu_budget.rs` reproduces each row):+//+// | script | source | per document |+// |----------------------------------------------------|---------:|-------------:|+// | 3,000 x `params.blob;`, params of 50,000 nodes | 38.1 KiB | 9.03 s |+// | 3,000 x `params.blob;`, params of 200,000 nodes | 38.1 KiB | 37.35 s |+// | 3,000 x `params['_source'];`, doc of 100,000 nodes | 55.7 KiB | 17.17 s |+// | 2,000 x `doc['rank'].value`, doc of 20,000 nodes | 52.8 KiB | 1.13 s |+//+// All four are O(size)-behind-an-O(1)-expression: `params.x` converts a+// caller-supplied subtree, `params['_source']` clones the document, and+// `get_doc_value` clones the whole document before walking into it. None of it+// is visible in the statement count, which is why a step counter alone would+// not have caught any of them.+//+// The doc-scan cooperative timeout poll cannot bound this: it only decides how+// often a document *boundary* is checked, so a request `timeout` cannot+// interrupt a single expensive document at all. The budget below is checked+// *inside* the evaluator, so one document's evaluation can be abandoned+// part-way through. With it, the four rows above become 97 ms, 109 ms, 168 ms+// and 155 ms — each a refusal, and flat in the size of the input, because the+// trip happens at a fixed work count.+//+// (A fifth shape, quadratic string concatenation, motivated the first revision+// of this budget. It is no longer the headline: the 1 MiB+// `MAX_PAINLESS_STRING_LEN` cap that arrived with #87 already bounds it, and+// on this base it costs at most 204 ms. The work budget still prices it — see+// `quadratic_string_growth_trips_the_work_budget` — but the numbers that+// justify the ceiling are the ones above.)++/// Bytes of produced value that count as one unit of work.+///+/// The counter has to price two different kinds of work in one currency:+/// interpreter steps (an `eval_expr`/`exec_stmt` entry) and bulk copying+/// (string concatenation, whole-document clones). On the 59.8 KiB benign+/// arithmetic script a work unit measured **8.1 ns** (277.9 µs for 34,407+/// units, best of 40 trials, pinned). 64 bytes of memcpy is a few ns, so this+/// deliberately prices bytes *above* their raw memcpy cost: the copies that+/// matter also allocate and free, and under-pricing them is what left the hole+/// in the first place.+///+/// A unit is a unit of *charge*, not a constant amount of time: a step that+/// clones a 200,000-node `params` member is charged ~200,000 units and takes+/// far longer per unit than an arithmetic step does. The wall-clock check+/// below exists because of that spread, not despite it.+const BYTES_PER_OP: u64 = 64;++/// Maximum work units one evaluation of one script against one document may+/// consume.+///+/// Calibrated against the largest *benign* script the 64 KiB source limit+/// admits: 4,300 statements of `t = t + N.5;` (59,773 bytes) costs 34,407 work+/// units, so this ceiling leaves a **145x** margin over the worst legitimate+/// script that can be submitted.+/// `tests::the_budget_leaves_the_largest_benign_script_a_wide_margin` pins that+/// number, so a change to the charging scheme reports how far the margin moved+/// instead of leaving the ceiling a guess.+///+/// In the other direction it is a real bound: the four shapes tabulated above+/// cost 9.03 s, 37.35 s, 17.17 s and 1.13 s per document without it, and+/// 97 ms, 109 ms, 168 ms and 155 ms with it.+///+/// It is deliberately deterministic (no clock), so the limit is reproducible+/// in tests and identical on every machine; the wall-clock check below is the+/// backstop for work this counter prices too cheaply, not the primary bound.+pub(crate) const MAX_SCRIPT_OPS: u64 = 5_000_000;++/// Work units between wall-clock reads.+///+/// Sampling rather than reading the clock per op is what keeps the budget off+/// the hot path: a clock read is ~20 ns, so once per 1,024 units it is lost in+/// the noise.+///+/// What this bounds is the *granularity* of the time check, and the honest+/// statement of it is in work units, not in time: an evaluation can overshoot+/// its deadline by one sampling window plus the single step in flight, and+/// neither of those is a fixed duration — one charge can be 200,000 units of+/// document cloning. Measured against a 100 ms slice+/// (`measure_time_budget_overshoot`), the overshoot is 0.48 ms on a+/// 10,000-node document, 1.17 ms at 40,000 nodes and 7.11 ms at 160,000: small,+/// and growing with the cost of one charged step exactly as that argument says+/// it should.+///+/// This is only true because the deadline is fixed in [`PainlessCtx::new`]+/// before any work is charged. Deriving it inside the first `clock_check`+/// instead — as the first revision of this budget did — spends one window+/// establishing the deadline and a second one failing it, so the overshoot is+/// two windows rather than one. With the accounting hole in `eval_access_chain`+/// open as well, those two windows were 12.55 s of real time on the `params`+/// shape, which is how a "500 ms" slice let a script run for twelve seconds.+const OPS_PER_CLOCK_CHECK: u64 = 1_024;++/// Longest an evaluation of one script against one document may run.+///+/// 500 ms is far outside any legitimate per-document script cost — the largest+/// benign script the source limit admits costs a measured 278 µs, so this is+/// ~1,800x it — and exists to bound shapes whose cost the work counter prices+/// too cheaply.+const MAX_EVAL_SLICE: std::time::Duration = std::time::Duration::from_millis(500);++/// Floor on the slice an evaluation is granted when the enclosing request+/// deadline is near or already past.+///+/// The budget composes with the request deadline by clamping each evaluation's+/// slice to the request's remaining time — so a single document can no longer+/// overshoot the request's own deadline by tens of seconds. But the request+/// deadline is routinely *already past* when a script runs: the doc scan only+/// checks it every 4,096 documents, so a legitimate slow search evaluates its+/// scoring script well beyond the deadline before the scan notices. Cutting+/// those evaluations off instantly would turn every ordinary `timeout` into a+/// `script_exception` 400. This floor is what keeps the trip meaningful: an+/// evaluation always gets at least 100 ms, which is ~360x the measured 278 µs+/// cost of the largest benign script that can be submitted, so only a+/// genuinely abusive script can hit it.+const MIN_EVAL_SLICE: std::time::Duration = std::time::Duration::from_millis(100);++/// Sentinel returned when [`MAX_SCRIPT_OPS`] is exceeded.+pub(crate) const SCRIPT_OVER_BUDGET_MSG: &str =+ "script evaluation exceeded its per-document work budget; simplify the script";++/// Sentinel returned when a single evaluation outlives its wall-clock slice.+/// Split from [`SCRIPT_OVER_BUDGET_MSG`] so the two are distinguishable in an+/// error a user actually sees, like `CALL_TOO_DEEP_MSG` vs `TOO_MANY_CALLS_MSG`.+pub(crate) const SCRIPT_OVER_TIME_MSG: &str =+ "script evaluation exceeded its per-document time budget; simplify the script";+/// True when `msg` is one of the interpreter's **resource-limit** sentinels/// rather than an ordinary script error.///@@ -581,6 +898,8 @@ pub fn is_resource_limit_error(msg: &str) -> bool {|| msg == EVAL_TOO_DEEP_MSG|| msg == CALL_TOO_DEEP_MSG|| msg == TOO_MANY_CALLS_MSG+ || msg == SCRIPT_OVER_BUDGET_MSG+ || msg == SCRIPT_OVER_TIME_MSG|| msg.starts_with(SOURCE_TOO_LONG_PREFIX)}@@ -619,6 +938,37 @@ pub(crate) fn record_script_fault(msg: &str) {});}+tokio::task_local! {+ /// Absolute deadline of the request that is currently evaluating scripts.+ ///+ /// A task-local for the same reason as [`SCRIPT_FAULT`]: the scoring and+ /// aggregation paths that evaluate scripts have no parameter to thread a+ /// deadline through, and a *thread*-local would leak one request's+ /// deadline onto whatever ran on the worker next.+ ///+ /// This is what makes the work budget an extension of the existing+ /// request deadline rather than a second, independent limit — see+ /// [`MIN_EVAL_SLICE`] for how the two combine.+ static SCRIPT_REQUEST_DEADLINE: std::time::Instant;+}++/// The resource-limit fault already recorded against the enclosing capture+/// scope, if any. `None` outside a scope, and `None` when nothing has tripped.+pub(crate) fn pending_script_fault() -> Option<String> {+ SCRIPT_FAULT+ .try_with(|slot| slot.borrow().clone())+ .unwrap_or(None)+}++/// Run `fut` with the enclosing request's deadline visible to every script it+/// evaluates, so no single document's evaluation can overshoot it.+pub async fn with_script_deadline<F>(deadline: std::time::Instant, fut: F) -> F::Output+where+ F: std::future::Future,+{+ SCRIPT_REQUEST_DEADLINE.scope(deadline, fut).await+}+/// Run `fut` with a fault sink installed, returning its output alongside the/// first script resource-limit fault raised anywhere inside it.///@@ -1339,6 +1689,18 @@ pub fn check_script_limits(src: &str) -> Result<(), String> {/// 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> {+ // A resource limit is a per-*evaluation* budget, and a request evaluates+ // scripts once per document (per clause, per aggregation bucket, ...). So+ // without this, "bounded" would mean bounded × the number of documents:+ // the issue's repro is refused after ~14 ms on each of them, and a+ // `bool` query may carry any number of distinct `script` clauses. Once one+ // evaluation in this request has tripped a limit the response is already a+ // 400 — every later evaluation is work with nowhere to go, so it is+ // refused immediately with the same error. That makes ONE budget the bound+ // for the whole request.+ if let Some(fault) = pending_script_fault() {+ return Err(fault);+ }let out = eval_painless_inner(src, ctx);if let Err(msg) = &out {if is_resource_limit_error(msg) {@@ -1441,6 +1803,7 @@ fn exec_stmt(ctx: &PainlessCtx,env: &mut HashMap<String, PainlessValue>,) -> Result<ExecOutcome, String> {+ ctx.charge(1)?;match s {Stmt::Return(opt) => {let v = match opt {@@ -1486,6 +1849,10 @@ fn eval_expr(env: &mut HashMap<String, PainlessValue>,) -> Result<PainlessValue, String> {let _guard = EvalDepthGuard::enter(&ctx.eval_depth)?;+ // One work unit per interpreter step. Steps alone do not bound work (see+ // `MAX_SCRIPT_OPS`), so the value-producing arms below additionally charge+ // for what they produce.+ ctx.charge(1)?;match e {Expr::Number(n) => Ok(PainlessValue::Number(*n)),Expr::String(s) => Ok(PainlessValue::String(s.clone())),@@ -1493,7 +1860,11 @@ fn eval_expr(Expr::Null => Ok(PainlessValue::Null),Expr::Ident(name) => {if let Some(v) = env.get(name) {- return Ok(v.clone());+ // Reading a local *copies* it. `def s = <4 MiB>; s; s; s;` is+ // three cheap-looking steps and 12 MiB of copying.+ let v = v.clone();+ ctx.charge(value_work_units(&v))?;+ return Ok(v);}match name.as_str() {"_score" => Ok(PainlessValue::Number(ctx.score as f64)),@@ -1504,6 +1875,8 @@ fn eval_expr(}Expr::Assign(name, val, _is_decl) => {let v = eval_expr(val, ctx, env)?;+ // The binding keeps one copy and the expression yields another.+ ctx.charge(value_work_units(&v))?;env.insert(name.clone(), v.clone());Ok(v)}@@ -1577,6 +1950,11 @@ fn eval_binary_chain(}let right = eval_expr(right, ctx, env)?;value = apply_binary(op, value, right)?;+ // `+` on strings builds a whole new string from both operands, so a+ // chain of concatenations costs bytes copied rather than steps taken —+ // and none of that is visible in the statement count. Charging the+ // result is what prices it.+ ctx.charge(value_work_units(&value))?;}Ok(value)}@@ -1622,62 +2000,79 @@ fn eval_access_chain(};let mut value = None;for (position, step) in steps.into_iter().enumerate() {- if position == 0 {+ // Roots the interpreter resolves itself, without a preceding value.+ // These produce a value like any other step, so they must reach the+ // charge below — an earlier revision of this budget `continue`d+ // straight past it, which left `params.big` and `params['_source']`+ // costing two work units for an arbitrarily large materialisation and+ // reopened the exact hole the budget exists to close.+ let resolved_root = if position == 0 {match (root_ident, &step) {(Some("doc"), Step::Index(index)) => {let key = access_key(eval_expr(index, ctx, env)?)?;- value = Some(PainlessValue::String(format!("__docref__:{key}")));- continue;+ Some(PainlessValue::String(format!("__docref__:{key}")))}(Some("params"), Step::Index(index)) => {let key = access_key(eval_expr(index, ctx, env)?)?;- value = Some(if key == "_source" {+ Some(if key == "_source" {+ // A whole-document clone behind an O(1)-looking+ // expression. Weighed before it is built, so the+ // budget bounds how many times it can be built rather+ // than paying for one first and asking afterwards.+ charge_document_read(ctx)?;let mut source = ctx.doc.clone();xerj_query::executor::strip_internal_passage_metadata(&mut source);PainlessValue::from_json(&source)} else {- PainlessValue::from_json(- &ctx.params.get(&key).cloned().unwrap_or(Value::Null),- )- });- continue;+ charged_params_read(ctx, &key)?+ })}(Some("doc"), Step::Member(member, args)) if args.is_none() => {- value = Some(PainlessValue::String(format!("__docref__:{member}")));- continue;+ Some(PainlessValue::String(format!("__docref__:{member}")))}(Some("params"), Step::Member(member, args)) if args.is_none() => {- value = Some(PainlessValue::from_json(- &ctx.params.get(*member).cloned().unwrap_or(Value::Null),- ));- continue;+ Some(charged_params_read(ctx, member)?)}(Some("Math"), Step::Member(member, args)) => {let argvs = eval_args(args, ctx, env)?;- value = Some(math_call(member, &argvs)?);- continue;+ Some(math_call(member, &argvs)?)}- _ => {}+ _ => None,}- }-- let current = match value.take() {- Some(value) => value,- None => eval_expr(base, ctx, env)?,+ } else {+ None};- value = Some(match step {- Step::Index(index) => {- let key = eval_expr(index, ctx, env)?;- match (current, key) {- (PainlessValue::Array(values), PainlessValue::Number(index)) => values- .get(index as usize)- .cloned()- .unwrap_or(PainlessValue::Null),- _ => PainlessValue::Null,++ let produced = match resolved_root {+ Some(produced) => produced,+ None => {+ let current = match value.take() {+ Some(value) => value,+ None => eval_expr(base, ctx, env)?,+ };+ match step {+ Step::Index(index) => {+ let key = eval_expr(index, ctx, env)?;+ match (current, key) {+ (PainlessValue::Array(values), PainlessValue::Number(index)) => values+ .get(index as usize)+ .cloned()+ .unwrap_or(PainlessValue::Null),+ _ => PainlessValue::Null,+ }+ }+ Step::Member(member, args) => {+ eval_member_value(current, member, args, ctx, env)?+ }}}- Step::Member(member, args) => eval_member_value(current, member, args, ctx, env)?,- });+ };+ // Every step here can materialise an arbitrarily large value:+ // `params['_source']` clones the whole document, `.toString()` renders+ // it, a member read clones a subtree. Charge for what came out. This+ // charge covers EVERY step, root-resolving fast paths included.+ ctx.charge(value_work_units(&produced))?;+ value = Some(produced);}value.ok_or_else(|| "internal error: empty access chain".to_string())}@@ -1930,7 +2325,7 @@ fn resolve_doc_member(args: &Option<Vec<Expr>>,_env: &mut HashMap<String, PainlessValue>,) -> Result<PainlessValue, String> {- let raw = get_doc_value(ctx.doc, field);+ let raw = charged_doc_value(ctx, field)?;match member {"value" => {// Return first scalar. A field that's genuinely missing (or a@@ -2050,6 +2445,18 @@ fn date_component(ms: i64, member: &str) -> Result<PainlessValue, String> {Ok(PainlessValue::Number(n as f64))}+/// [`get_doc_value`] behind the work budget.+///+/// Every caller of `get_doc_value` pays a full `doc.clone()` — the function+/// starts by cloning the whole document and then walks *into* the clone — so+/// the cost of `doc['rank'].value` is the size of the document, not of the+/// field. That is O(document) work behind an O(1)-looking expression, and+/// nothing else in the interpreter charges for it.+fn charged_doc_value(ctx: &PainlessCtx, field: &str) -> Result<Value, String> {+ charge_document_read(ctx)?;+ Ok(get_doc_value(ctx.doc, field))+}+fn get_doc_value(doc: &Value, field: &str) -> Value {if field.starts_with(xerj_query::executor::PASSAGE_METADATA_PREFIX) {return Value::Null;@@ -2136,7 +2543,7 @@ fn global_call(let doc_vec: Vec<f64> = match &args[1] {PainlessValue::String(s) => {// Field reference (literal name).- let raw = get_doc_value(ctx.doc, s);+ let raw = charged_doc_value(ctx, s)?;match raw {Value::Array(arr) => arr.iter().filter_map(|v| v.as_f64()).collect(),_ => Vec::new(),@@ -2169,7 +2576,7 @@ fn global_call(};let d: Vec<f64> = match &args[1] {PainlessValue::String(s) => {- let raw = get_doc_value(ctx.doc, s);+ let raw = charged_doc_value(ctx, s)?;match raw {Value::Array(arr) => arr.iter().filter_map(|v| v.as_f64()).collect(),_ => Vec::new(),@@ -2205,7 +2612,7 @@ fn global_call(};let d: Vec<f64> = match &args[1] {PainlessValue::String(s) => {- let raw = get_doc_value(ctx.doc, s);+ let raw = charged_doc_value(ctx, s)?;match raw {Value::Array(arr) => arr.iter().filter_map(|v| v.as_f64()).collect(),_ => Vec::new(),@@ -2228,7 +2635,7 @@ fn global_call(};let d: Vec<f64> = match &args[1] {PainlessValue::String(s) => {- let raw = get_doc_value(ctx.doc, s);+ let raw = charged_doc_value(ctx, s)?;match raw {Value::Array(arr) => arr.iter().filter_map(|v| v.as_f64()).collect(),_ => Vec::new(),@@ -3339,4 +3746,178 @@ mod tests {assert!((v.as_f64().unwrap() - 2048.0).abs() < 1e-9, "round {round}");}}++ // ── Per-evaluation work budget (issue #122) ──────────────────────────++ /// The largest *benign* script the 64 KiB source limit admits: 4,300+ /// statements of flat arithmetic (59,773 bytes). This is the number+ /// [`MAX_SCRIPT_OPS`] is calibrated against — if the charging scheme+ /// changes, this test says by how much the margin moved rather than+ /// leaving the ceiling a guess.+ fn largest_benign_script() -> String {+ let mut src = String::from("double t = 0;\n");+ for i in 0..4300 {+ src.push_str(&format!("t = t + {}.5;\n", i % 97));+ }+ src.push_str("return t;");+ src+ }++ #[test]+ fn the_budget_leaves_the_largest_benign_script_a_wide_margin() {+ let src = largest_benign_script();+ assert!(src.len() < MAX_SCRIPT_LEN, "must be a submittable script");+ let doc = json!({ "rank": 7 });+ let params = json!({});+ let c = ctx(&doc, ¶ms, 1.0);+ eval_painless(&src, &c).expect("a benign script must not trip the budget");+ let used = c.work_units();+ assert_eq!(+ used, 34_407,+ "the calibration point moved; re-derive MAX_SCRIPT_OPS rather than \+ editing this number"+ );+ assert!(+ MAX_SCRIPT_OPS / used >= 100,+ "the ceiling must keep a two-order-of-magnitude margin over the \+ largest benign script, got {}x",+ MAX_SCRIPT_OPS / used+ );+ }++ /// Work is not the same thing as shape. This script is *smaller* than the+ /// benign one above and runs a fraction of its statements, yet costs+ /// hundreds of times more — which is the whole of issue #122.+ #[test]+ fn quadratic_string_growth_trips_the_work_budget() {+ let mut src = String::from("def c = \"");+ src.push_str(&"x".repeat(1024));+ src.push_str("\";\ndef s = c;\n");+ for _ in 0..4000 {+ src.push_str("s = s + c;\n");+ }+ src.push_str("return s.length();");+ assert!(src.len() < MAX_SCRIPT_LEN, "must be a submittable script");++ let doc = json!({});+ let params = json!({});+ let err = eval_painless(&src, &ctx(&doc, ¶ms, 0.0)).unwrap_err();+ assert_eq!(err, SCRIPT_OVER_BUDGET_MSG);+ assert!(+ is_resource_limit_error(&err),+ "a budget trip must reach the caller as a 400, not degrade to a \+ wrong score"+ );+ }++ /// Charging only per interpreter *step* would miss it: the trip happens+ /// after a few hundred statements, so the step count at the trip is tiny+ /// next to the benign script's 43,012 — the cost is all in the bytes.+ #[test]+ fn the_budget_is_charged_for_bytes_not_just_steps() {+ let big = PainlessValue::String("x".repeat(64 * 1024));+ assert_eq!(value_work_units(&big), 1 + 1024);+ let small = PainlessValue::Number(1.0);+ assert_eq!(value_work_units(&small), 1);+ // A nested document is weighed by everything it contains, because+ // cloning it copies everything it contains.+ let nested = PainlessValue::from_json(&json!({ "a": [1, 2, 3], "b": { "c": 4 } }));+ assert_eq!(value_work_units(&nested), 7);+ }++ /// A whole-document read is O(document) — `get_doc_value` clones the doc+ /// before walking it — so the budget has to see the document's size, not+ /// the field's.+ #[test]+ fn a_document_read_is_charged_for_the_whole_document() {+ let doc = json!({ "rank": 1, "blob": (0..500).collect::<Vec<u32>>() });+ let params = json!({});+ let c = ctx(&doc, ¶ms, 0.0);+ eval_painless("doc['rank'].value", &c).expect("evaluate");+ assert!(+ c.work_units() > 500,+ "a read of a 500-element document was charged {} units",+ c.work_units()+ );+ }++ /// The budget must not fire on scripts that are merely *long*: the+ /// evaluation below runs the interpreter tens of thousands of times and+ /// must still come out with a real value.+ #[test]+ fn a_long_but_cheap_script_still_returns_its_value() {+ let doc = json!({});+ let params = json!({});+ let src = largest_benign_script();+ let value = eval_painless(&src, &ctx(&doc, ¶ms, 0.0)).expect("evaluate");+ assert!(value.as_f64().is_some());+ }++ /// The time budget's anchor is fixed before any work is charged.+ ///+ /// Deriving it inside the first `clock_check` instead spends a whole+ /// sampling window establishing the deadline and a second one being able+ /// to fail it — and a window is bounded in work units, not in time, so+ /// "one window" is however long the largest single charge takes. Pinning+ /// the resolution point here keeps that structural property a test rather+ /// than a comment.+ #[test]+ fn the_evaluation_deadline_exists_before_any_work_is_charged() {+ let doc = json!({});+ let params = json!({});+ let before = std::time::Instant::now();+ let c = ctx(&doc, ¶ms, 0.0);+ let after = std::time::Instant::now();+ assert_eq!(c.work_units(), 0, "nothing has been charged yet");+ // Outside a request scope the slice is MAX_EVAL_SLICE, and it is+ // measured from construction, not from the first clock read.+ assert!(+ c.eval_deadline >= before + MAX_EVAL_SLICE,+ "the deadline must be anchored at construction"+ );+ assert!(+ c.eval_deadline <= after + MAX_EVAL_SLICE,+ "the deadline must not be anchored later than construction"+ );+ }++ /// A `params` member read is charged for the subtree it materialises, on+ /// both spellings and before the value is built.+ ///+ /// `params.x` / `params['x']` are resolved by a fast path at chain+ /// position 0 that used to `continue` past the access chain's charge, so a+ /// read of an arbitrarily large caller-supplied value cost two units. The+ /// assertion is on the work count, so it holds regardless of how fast the+ /// machine running it is.+ #[test]+ fn a_params_member_read_is_charged_for_the_subtree_it_materialises() {+ let doc = json!({});+ let blob: Vec<Value> = (0..5_000).map(|i| json!(format!("v{i}"))).collect();+ let params = json!({ "blob": blob });+ for src in ["params.blob;", "params['blob'];"] {+ let c = ctx(&doc, ¶ms, 0.0);+ eval_painless(src, &c).expect("evaluate");+ assert!(+ c.work_units() > 5_000,+ "`{src}` materialised a 5,000-node value for {} work units",+ c.work_units()+ );+ }+ }++ /// `params['_source']` clones the document, so it is charged the+ /// document's weight — the same charge `doc['x'].value` pays.+ #[test]+ fn a_params_source_read_is_charged_for_the_document_it_clones() {+ let blob: Vec<Value> = (0..5_000).map(|i| json!(format!("v{i}"))).collect();+ let doc = json!({ "blob": blob });+ let params = json!({});+ let c = ctx(&doc, ¶ms, 0.0);+ eval_painless("params['_source'];", &c).expect("evaluate");+ assert!(+ c.work_units() > 5_000,+ "a whole-document clone was charged {} work units",+ c.work_units()+ );+ }}diff --git a/engine/crates/xerj-engine/tests/painless_cpu_budget.rs b/engine/crates/xerj-engine/tests/painless_cpu_budget.rsnew file mode 100644index 000000000..e5667ac5d--- /dev/null+++ b/engine/crates/xerj-engine/tests/painless_cpu_budget.rs@@ -0,0 +1,506 @@+//! Issue #122: Painless had no per-evaluation CPU budget.+//!+//! Every pre-existing limit bounds a *structural* property of a script — how+//! deep it nests (`MAX_PARSE_DEPTH`, `MAX_EVAL_DEPTH`), how many closure calls+//! it makes (`MAX_CALL_DEPTH`, `MAX_CALL_COUNT`), how many bytes of source it+//! is (`MAX_SCRIPT_LEN`). None of them bounds *work*, so a script can be flat,+//! shallow, closure-free and comfortably under 64 KiB while costing over a+//! second of CPU on a single document. The doc-scan cooperative timeout poll+//! cannot help: it only decides how often a document *boundary* is checked.+//!+//! The measurement entry points below are `#[ignore]`d — they are stopwatches,+//! not assertions, and are the numbers quoted in the fix's commit message. The+//! non-ignored tests are the regression: they fail on the pre-fix tree by+//! running to completion (or by taking a wall-clock eternity) instead of being+//! refused.++use serde_json::{json, Value};+use xerj_engine::painless::{eval_painless, is_resource_limit_error, PainlessCtx};++/// Bytes of string literal the adversarial script starts from.+const CHUNK: usize = 1024;++/// A flat, closure-free, legal-size script whose cost is quadratic in its own+/// statement count: statement *i* concatenates a 1 KiB chunk onto an+/// accumulator that is already `i` KiB long, so `n` statements copy+/// `~n²/2 KiB`. Nothing about it is deep, recursive or oversized — it is the+/// counter-example to every structural limit at once.+fn quadratic_concat_script(statements: usize) -> String {+ let mut src = String::with_capacity(CHUNK + statements * 10 + 64);+ src.push_str("def c = \"");+ src.push_str(&"x".repeat(CHUNK));+ src.push_str("\";\ndef s = c;\n");+ for _ in 0..statements {+ src.push_str("s = s + c;\n");+ }+ src.push_str("return s.length();");+ src+}++/// The benign comparison point: a legal script of comparable *size* that does+/// only cheap arithmetic, so any per-op overhead the budget adds shows up here+/// undiluted.+fn benign_arithmetic_script(terms: usize) -> String {+ let mut src = String::with_capacity(terms * 24 + 32);+ src.push_str("double t = 0;\n");+ for i in 0..terms {+ src.push_str(&format!("t = t + {}.5;\n", i % 97));+ }+ src.push_str("return t;");+ src+}++fn doc() -> Value {+ json!({ "rank": 7, "tags": ["a", "b"] })+}++fn params() -> Value {+ json!({ "factor": 2.0 })+}++/// One evaluation of `src`, returning the elapsed wall time and the outcome.+fn timed_eval(src: &str) -> (std::time::Duration, Result<(), String>) {+ let doc = doc();+ let params = params();+ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let start = std::time::Instant::now();+ let out = eval_painless(src, &ctx);+ let elapsed = start.elapsed();+ (elapsed, out.map(|_| ()))+}++/// Stopwatch (issue evidence #1 and #2): how long ONE document's evaluation of+/// the adversarial script takes. On the pre-fix tree this runs to completion+/// and prints the unbounded cost; with the budget in place it is refused.+///+/// `cargo test --release -p xerj-engine --test painless_cpu_budget -- \+/// --ignored --nocapture measure_adversarial`+#[test]+#[ignore = "stopwatch, not an assertion"]+fn measure_adversarial_cost_per_document() {+ // 5,700 statements is the largest this shape fits under the 64 KiB+ // `MAX_SCRIPT_LEN`, i.e. the worst case a caller is allowed to submit.+ for statements in [1000, 2000, 4000, 5700] {+ let src = quadratic_concat_script(statements);+ let (elapsed, outcome) = timed_eval(&src);+ println!(+ "adversarial statements={statements} source={} bytes ({:.1} KiB) \+ elapsed={:?} outcome={}",+ src.len(),+ src.len() as f64 / 1024.0,+ elapsed,+ match &outcome {+ Ok(()) => "COMPLETED (unbounded)".to_string(),+ Err(e) => format!("refused: {e}"),+ }+ );+ }+}++/// Stopwatch (issue evidence #3): per-evaluation cost of an ordinary small+/// script, reported as ns per evaluation. Run pinned:+///+/// `taskset -c 3 cargo test --release -p xerj-engine --test painless_cpu_budget \+/// -- --ignored --nocapture measure_ordinary`+#[test]+#[ignore = "stopwatch, not an assertion"]+fn measure_ordinary_script_ns_per_eval() {+ let doc = doc();+ let params = params();+ for (label, src) in [+ (+ "tiny",+ "doc['rank'].value * params.factor + _score".to_string(),+ ),+ ("small-arith", benign_arithmetic_script(16)),+ ("64KiB-benign", benign_arithmetic_script(4300)),+ ] {+ // Warm-up.+ for _ in 0..64 {+ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let _ = eval_painless(&src, &ctx);+ }+ // Report the MINIMUM over many short trials, not the mean over one+ // long run. This host is shared, and a mean absorbs every scheduling+ // interruption that lands in the run — the before/after difference+ // being measured here is a few ns per work unit and disappears under+ // that. The minimum is the trial that ran least interrupted.+ let iterations = if src.len() > 4096 { 20 } else { 2_000 };+ let trials = 40;+ let mut best = f64::MAX;+ for _ in 0..trials {+ let start = std::time::Instant::now();+ for _ in 0..iterations {+ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let out = eval_painless(&src, &ctx);+ assert!(out.is_ok(), "{label} must evaluate: {out:?}");+ }+ let per_eval = start.elapsed().as_nanos() as f64 / iterations as f64;+ best = best.min(per_eval);+ }+ println!(+ "ordinary {label:<13} source={:>6} bytes best-of-{trials} \+ {best:>10.1} ns/eval",+ src.len(),+ );+ }+}++/// A flat 44.0 KiB script that trips no structural limit must be refused as a+/// resource-limit failure instead of being run to completion.+///+/// Its *result size* is separately capped at 1 MiB by the+/// `MAX_PAINLESS_STRING_LEN` limit that arrived with #87, so on this base it no+/// longer runs for seconds — but the work budget is what prices the copying,+/// and it is the budget that must be named in the refusal.+#[test]+fn quadratic_string_growth_is_refused_as_a_resource_limit() {+ let src = quadratic_concat_script(4000);+ assert!(+ src.len() < 64 * 1024,+ "the repro must stay under the 64 KiB source limit, got {}",+ src.len()+ );+ let (elapsed, outcome) = timed_eval(&src);+ let err = outcome.expect_err(+ "a flat, closure-free, legal-size script ran to completion with no \+ work budget — this is issue #122",+ );+ assert!(+ is_resource_limit_error(&err),+ "the work budget must classify as a resource limit so the API layer \+ answers 400 instead of degrading to a wrong score, got {err:?}"+ );+ assert!(+ err.contains("work budget"),+ "the budget must price the copying before the 1 MiB string-size cap \+ notices the result, got {err:?}"+ );+ assert!(+ elapsed < std::time::Duration::from_secs(1),+ "the budget must abandon the evaluation part-way through ONE document, \+ took {elapsed:?}"+ );+}++/// The same shape reached through repeated whole-document clones rather than+/// string growth: `doc['x'].value` copies the entire source document on every+/// access, so a flat script with thousands of accesses is linear in+/// `statements × document size` with no structural limit in the way.+#[test]+fn repeated_whole_document_clones_are_refused_as_a_resource_limit() {+ let big: Vec<Value> = (0..20_000).map(|i| json!(format!("value-{i}"))).collect();+ let doc = json!({ "rank": 7, "blob": big });+ let params = params();+ let mut src = String::from("double t = 0;\n");+ for _ in 0..2000 {+ src.push_str("t = t + doc['rank'].value;\n");+ }+ src.push_str("return t;");+ assert!(src.len() < 64 * 1024, "repro must stay legal-size");++ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let err = eval_painless(&src, &ctx)+ .expect_err("2000 whole-document clones ran unbudgeted — issue #122");+ assert!(+ is_resource_limit_error(&err),+ "expected a resource-limit classification, got {err:?}"+ );+}++// ── The `params` root (issue #122, round 2) ──────────────────────────────────+//+// `eval_access_chain` resolves `params.x`, `params['x']` and `params['_source']`+// itself, without a preceding value, in a fast path at chain position 0. The+// first revision of this budget ended each of those fast paths in `continue`,+// jumping past the charge at the bottom of the loop — so every one of them ran+// `PainlessValue::from_json` over a caller-supplied subtree (or, for+// `_source`, over a clone of the whole document) for a flat two work units.+// The budget had a hole of exactly the shape it was built to close.++/// `params` whose single member `blob` is an array of `nodes` short strings.+/// Short on purpose: under 64 bytes each contributes nothing beyond its one+/// node to the work count, so the weight here is honestly `nodes`, not a+/// string-length artefact.+fn params_with_blob(nodes: usize) -> Value {+ let blob: Vec<Value> = (0..nodes).map(|i| json!(format!("v{i}"))).collect();+ json!({ "blob": blob })+}++/// A flat, closure-free script of bare `params.blob;` statements. It nests+/// nothing, calls nothing, and at 3,000 statements is 36 KB — inside every+/// structural limit the interpreter has.+fn bare_params_read_script(statements: usize) -> String {+ let mut src = String::with_capacity(statements * 13 + 16);+ for _ in 0..statements {+ src.push_str("params.blob;\n");+ }+ src.push_str("return 1;");+ src+}++/// Stopwatch: cost of one document's evaluation of the bare-`params` script.+/// On the pre-fix tree this completes, and the two `nodes` rows show the cost+/// scaling linearly with the size of the caller's own `params`.+///+/// `taskset -c 3 cargo test --release -p xerj-engine --test painless_cpu_budget \+/// -- --ignored --nocapture measure_bare_params`+#[test]+#[ignore = "stopwatch, not an assertion"]+fn measure_bare_params_read_cost() {+ for nodes in [50_000, 200_000] {+ let params = params_with_blob(nodes);+ let doc = doc();+ let src = bare_params_read_script(3_000);+ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let start = std::time::Instant::now();+ let outcome = eval_painless(&src, &ctx);+ let elapsed = start.elapsed();+ println!(+ "bare-params nodes={nodes} source={} bytes elapsed={:?} units={} outcome={}",+ src.len(),+ elapsed,+ ctx.work_units(),+ match &outcome {+ Ok(_) => "COMPLETED (unbounded)".to_string(),+ Err(e) => format!("refused: {e}"),+ }+ );+ }+}++/// THE round-2 regression. 3,000 bare `params.blob;` statements against a+/// 200,000-node `params` — measured at 12.1 s per document with the fast path+/// uncharged — must be refused.+///+/// Reverting only `painless.rs` and keeping this file makes it fail by+/// completing the evaluation, which is the defect.+#[test]+fn bare_params_reads_are_charged_for_what_they_materialise() {+ let params = params_with_blob(200_000);+ let doc = doc();+ let src = bare_params_read_script(3_000);+ assert!(src.len() < 64 * 1024, "the repro must stay legal-size");++ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let start = std::time::Instant::now();+ let err = eval_painless(&src, &ctx).expect_err(+ "3,000 reads of a 200,000-node `params` member ran to completion — the \+ position-0 fast path is materialising an unbounded value for two work \+ units",+ );+ let elapsed = start.elapsed();+ assert!(+ is_resource_limit_error(&err),+ "expected a resource-limit classification, got {err:?}"+ );+ // Deterministic half: the reads must have been PRICED. Uncharged, this+ // whole script costs 2,048 work units.+ assert!(+ ctx.work_units() > 1_000_000,+ "3,000 reads of a 200,000-node value were charged {} work units",+ ctx.work_units()+ );+ assert!(+ elapsed < std::time::Duration::from_secs(1),+ "the budget must abandon this part-way through ONE document, took {elapsed:?}"+ );+}++/// The `params['x']` spelling reaches a different fast-path arm than+/// `params.x`, and both used to `continue` past the charge.+///+/// The assertion is on the WORK COUNT, not on wall time. Left uncharged these+/// reads are still eventually caught by the wall-clock half of the budget —+/// after 15 s — so a test that only asserts "some resource limit tripped"+/// passes on the broken tree. What has to be true is that the materialisation+/// was *priced*: on the pre-fix tree this whole script is charged 2,048 units,+/// which is the hole.+#[test]+fn subscripted_params_reads_are_charged_too() {+ let params = params_with_blob(200_000);+ let doc = doc();+ let mut src = String::new();+ for _ in 0..3_000 {+ src.push_str("params['blob'];\n");+ }+ src.push_str("return 1;");+ assert!(src.len() < 64 * 1024, "the repro must stay legal-size");++ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let err = eval_painless(&src, &ctx)+ .expect_err("3,000 subscripted reads of a 200,000-node `params` member ran unbudgeted");+ assert!(+ is_resource_limit_error(&err),+ "expected a resource-limit classification, got {err:?}"+ );+ assert!(+ ctx.work_units() > 1_000_000,+ "3,000 reads of a 200,000-node value were charged {} work units",+ ctx.work_units()+ );+}++/// `params['_source']` clones the whole document behind an O(1)-looking+/// expression. The fix's own commit message claimed this was already charged;+/// it was not, for exactly this single-step form.+#[test]+fn params_source_reads_are_charged_for_the_document_they_clone() {+ let big: Vec<Value> = (0..100_000).map(|i| json!(format!("v{i}"))).collect();+ let doc = json!({ "rank": 7, "blob": big });+ let params = json!({});+ let mut src = String::new();+ for _ in 0..3_000 {+ src.push_str("params['_source'];\n");+ }+ src.push_str("return 1;");+ assert!(src.len() < 64 * 1024, "the repro must stay legal-size");++ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let err = eval_painless(&src, &ctx)+ .expect_err("3,000 whole-document clones through `params['_source']` ran unbudgeted");+ assert!(+ is_resource_limit_error(&err),+ "expected a resource-limit classification, got {err:?}"+ );+ assert!(+ ctx.work_units() > 1_000_000,+ "3,000 whole-document clones were charged {} work units",+ ctx.work_units()+ );+}++/// A `params` small enough to be ordinary must still be readable thousands of+/// times — the charge prices what is materialised, it does not tax the access.+#[test]+fn ordinary_params_reads_are_not_refused() {+ let params = json!({ "factor": 2.0, "tags": ["a", "b", "c"] });+ let doc = doc();+ let mut src = String::from("double t = 0;\n");+ for _ in 0..2_000 {+ src.push_str("t = t + params.factor;\n");+ }+ src.push_str("return t;");+ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ eval_painless(&src, &ctx).expect("2,000 reads of a 2-member params must not trip the budget");+}++// ── The wall-clock half of the budget ────────────────────────────────────────++/// Stopwatch: how far past its 100 ms slice an evaluation actually runs.+///+/// This is the number the `OPS_PER_CLOCK_CHECK` doc comment quotes. The+/// overshoot is one sampling window plus the step in flight, and a window is+/// bounded in work units, not in time — so it is worth measuring rather than+/// deriving from an average cost per unit.+///+/// `taskset -c 3 cargo test --release -p xerj-engine --test painless_cpu_budget \+/// -- --ignored --nocapture measure_time_budget`+#[tokio::test]+#[ignore = "stopwatch, not an assertion"]+async fn measure_time_budget_overshoot() {+ for doc_nodes in [10_000usize, 40_000, 160_000] {+ let big: Vec<Value> = (0..doc_nodes)+ .map(|i| json!(format!("value-{i}")))+ .collect();+ let doc = json!({ "rank": 7, "blob": big });+ let params = params();+ let mut src = String::from("double t = 0;\n");+ for _ in 0..2_000 {+ src.push_str("t = t + doc['rank'].value;\n");+ }+ src.push_str("return t;");++ let deadline = std::time::Instant::now() - std::time::Duration::from_secs(5);+ let (outcome, elapsed, units) =+ xerj_engine::painless::with_script_deadline(deadline, async {+ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let start = std::time::Instant::now();+ let out = eval_painless(&src, &ctx);+ (out, start.elapsed(), ctx.work_units())+ })+ .await;+ println!(+ "time-budget doc_nodes={doc_nodes} slice=100ms elapsed={elapsed:?} \+ overshoot={:?} units={units} outcome={}",+ elapsed.saturating_sub(std::time::Duration::from_millis(100)),+ match &outcome {+ Ok(_) => "COMPLETED".to_string(),+ Err(e) => format!("refused: {e}"),+ }+ );+ }+}++/// The TIME limit, tripped on its own.+///+/// Every other test here trips the deterministic op ceiling first, because+/// outside a request scope an evaluation is granted `MAX_EVAL_SLICE` (500 ms)+/// and 5,000,000 units of the cheapest work cost less than that. Inside a+/// request whose deadline has already passed — the normal state of a slow+/// search, since the doc scan only polls at document boundaries — the slice is+/// the `MIN_EVAL_SLICE` floor of 100 ms, and a shape whose real cost per work+/// unit is high reaches 100 ms of wall time long before 5,000,000 units.+///+/// `doc['x'].value` is that shape: it is charged one unit per document node,+/// but each node it copies is a heap allocation, so it costs far more per unit+/// than the byte-copying the counter is calibrated on.+#[tokio::test]+async fn the_time_budget_trips_on_its_own_inside_an_expired_request() {+ let big: Vec<Value> = (0..40_000).map(|i| json!(format!("value-{i}"))).collect();+ let doc = json!({ "rank": 7, "blob": big });+ let params = params();+ let mut src = String::from("double t = 0;\n");+ for _ in 0..2_000 {+ src.push_str("t = t + doc['rank'].value;\n");+ }+ src.push_str("return t;");+ assert!(src.len() < 64 * 1024, "the repro must stay legal-size");++ // A deadline already in the past: the request is over, the scan has not+ // noticed yet, and this evaluation gets the 100 ms floor.+ let deadline = std::time::Instant::now() - std::time::Duration::from_secs(5);+ let (err, elapsed) = xerj_engine::painless::with_script_deadline(deadline, async {+ let ctx = PainlessCtx::new(&doc, ¶ms, 1.0);+ let start = std::time::Instant::now();+ let out = eval_painless(&src, &ctx);+ (+ out.expect_err("the time budget must abandon this"),+ start.elapsed(),+ )+ })+ .await;++ assert!(+ err.contains("time budget"),+ "the WALL-CLOCK half of the budget must be what trips, not the op \+ ceiling — got {err:?} after {elapsed:?}"+ );+ assert!(+ is_resource_limit_error(&err),+ "a time trip must classify as a resource limit, got {err:?}"+ );+ // The slice is 100 ms and the deadline is fixed before any work is+ // charged, so the overshoot is one sampling window plus the step in+ // flight — not a second 100 ms slice, which is what deriving the deadline+ // inside the first clock check used to cost.+ assert!(+ elapsed < std::time::Duration::from_millis(400),+ "a 100 ms slice was overshot to {elapsed:?}"+ );+}++/// The other half of the contract: ordinary scripts must be nowhere near the+/// budget. A script that is *itself* 64 KiB of legal arithmetic — the largest+/// benign script the source-size limit admits — must still evaluate cleanly.+#[test]+fn a_full_size_benign_script_still_evaluates() {+ let src = benign_arithmetic_script(4300);+ assert!(+ (32 * 1024..64 * 1024).contains(&src.len()),+ "the benign script must be big enough to be a real test, got {} bytes",+ src.len()+ );+ let (_, outcome) = timed_eval(&src);+ outcome.expect("a 64 KiB benign arithmetic script must not trip the budget");+}diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rsindex f56870abf..7a6200035 100644--- a/engine/crates/xerj-query/src/parser.rs+++ b/engine/crates/xerj-query/src/parser.rs@@ -43,8 +43,43 @@ const MAX_QUERY_DEPTH: usize = 64;/// Deep pagination beyond this should use `search_after`/PIT instead.pub const MAX_RESULT_WINDOW: usize = 10_000;+// ── Boolean clause limit ──────────────────────────────────────────────────────+//+// Issue #122, second half. `MAX_QUERY_DEPTH` bounds how deeply a query nests;+// nothing bounded how WIDE it is, so a single `bool` could carry an unbounded+// number of clauses. That is not merely a big query: there is no compiled-script+// cache in this engine, so every `script` clause is re-tokenised and re-parsed+// for every document it is evaluated against, and the cost of a `bool` with N+// script clauses over D documents is N x D full script parses. The clause count+// is the only place that product can be bounded before any work starts.+//+// 1,024 is Elasticsearch's documented `indices.query.bool.max_clause_count`+// default, and ES answers `too_many_clauses` above it — so a query this+// rejects is a query that was already rejected by the system being emulated.+const MAX_CLAUSE_COUNT: usize = 1_024;+thread_local! {static QUERY_DEPTH: Cell<usize> = const { Cell::new(0) };+ /// Boolean clauses parsed so far in the current top-level query. Reset by+ /// the outermost [`parse_query`] rather than by an RAII guard: the limit+ /// is on the whole query's total width, so it must accumulate across+ /// sibling `bool`s instead of unwinding with each one.+ static CLAUSE_COUNT: Cell<usize> = const { Cell::new(0) };+}++/// Charge one boolean clause against [`MAX_CLAUSE_COUNT`].+fn charge_clause() -> Result<()> {+ let exceeded = CLAUSE_COUNT.with(|c| {+ let next = c.get() + 1;+ c.set(next);+ next > MAX_CLAUSE_COUNT+ });+ if exceeded {+ return Err(QueryError::Parse(ParseError::Invalid(format!(+ "too_many_clauses: maxClauseCount is set to {MAX_CLAUSE_COUNT}"+ ))));+ }+ Ok(())}/// RAII guard that increments the thread-local query-depth counter on@@ -258,6 +293,13 @@ pub fn parse_query(json: &Value) -> Result<QueryNode> {// Bail out early on excessive nesting. The guard decrements on drop so// an error return here does not leak the increment to a sibling call.let _depth = DepthGuard::enter()?;+ // Outermost call for this request: start a fresh clause budget. The+ // counter cannot unwind with an RAII guard the way depth does — the limit+ // is on the query's total width, which is a sum over siblings, not a+ // property of the current path.+ if QUERY_DEPTH.with(Cell::get) == 1 {+ CLAUSE_COUNT.with(|c| c.set(0));+ }let obj = json.as_object().ok_or_else(|| {QueryError::Parse(ParseError::Invalid("query must be a JSON object".into()))@@ -2315,6 +2357,10 @@ fn parse_dis_max(params: &Value) -> Result<QueryNode> {.iter().enumerate().map(|(i, v)| {+ // `dis_max.queries` is a clause list by any other name: each entry+ // is scored against every document, so it multiplies per-document+ // work exactly as a `bool` clause does.+ charge_clause()?;parse_query(v).map_err(|e| {crate::error::QueryError::Parse(crate::error::ParseError::Invalid(format!("`dis_max.queries[{i}]`: {e}"@@ -2383,7 +2429,15 @@ fn parse_knn(params: &Value) -> Result<QueryNode> {let filter = match obj.get("filter") {None => None,Some(Value::Array(arr)) => {- let parsed: Vec<QueryNode> = arr.iter().map(parse_query).collect::<Result<_>>()?;+ // Implicitly ANDed, so this is `bool.filter` spelled differently+ // and is charged the same way.+ let parsed: Vec<QueryNode> = arr+ .iter()+ .map(|v| {+ charge_clause()?;+ parse_query(v)+ })+ .collect::<Result<_>>()?;match parsed.len() {0 => None,1 => Some(Box::new(parsed.into_iter().next().unwrap())),@@ -2935,11 +2989,24 @@ fn parse_bool_operator(v: Option<&Value>) -> Result<BoolOperator> {}/// Parse a bool clause list. ES allows a single object or an array.+///+/// Every clause is charged against [`MAX_CLAUSE_COUNT`] *before* it is parsed,+/// so an oversized list is refused after 1,024 clauses rather than after all+/// of them.fn parse_clause_list(obj: &serde_json::Map<String, Value>, key: &str) -> Result<Vec<QueryNode>> {match obj.get(key) {None => Ok(vec![]),- Some(Value::Array(arr)) => arr.iter().map(parse_query).collect(),- Some(single) => Ok(vec![parse_query(single)?]),+ Some(Value::Array(arr)) => arr+ .iter()+ .map(|clause| {+ charge_clause()?;+ parse_query(clause)+ })+ .collect(),+ Some(single) => {+ charge_clause()?;+ Ok(vec![parse_query(single)?])+ }}}@@ -3303,11 +3370,7 @@ fn parse_span_near(params: &Value) -> Result<QueryNode> {.as_object().ok_or_else(|| qerr("`span_near` must be an object"))?;- let clauses: Vec<QueryNode> = obj- .get("clauses")- .and_then(|v| v.as_array())- .map(|arr| arr.iter().filter_map(|v| parse_query(v).ok()).collect())- .unwrap_or_default();+ let clauses = parse_span_clauses(obj, "span_near")?;if clauses.is_empty() {return Ok(QueryNode::MatchNone);@@ -3334,11 +3397,7 @@ fn parse_span_or(params: &Value) -> Result<QueryNode> {.as_object().ok_or_else(|| qerr("`span_or` must be an object"))?;- let clauses: Vec<QueryNode> = obj- .get("clauses")- .and_then(|v| v.as_array())- .map(|arr| arr.iter().filter_map(|v| parse_query(v).ok()).collect())- .unwrap_or_default();+ let clauses = parse_span_clauses(obj, "span_or")?;if clauses.is_empty() {return Ok(QueryNode::MatchNone);@@ -3347,6 +3406,48 @@ fn parse_span_or(params: &Value) -> Result<QueryNode> {Ok(QueryNode::SpanOr { clauses })}+/// Parse the `clauses` array shared by `span_near` and `span_or`.+///+/// Both used to collect with `filter_map(|v| parse_query(v).ok())`, which+/// discards a clause the parser refused and keeps going. That is how a *limit*+/// becomes a correctness bug rather than an error: [`MAX_CLAUSE_COUNT`] is a+/// parse error, so a `span_or` whose first clause is an over-wide `bool` used+/// to answer 200 OK with that clause silently missing — a different query than+/// the one asked for, scored against and returned as if it were the answer. A+/// query that is refused is a query the caller can fix; a query that is+/// quietly rewritten is not. Every clause error propagates.+///+/// Clauses are charged against [`MAX_CLAUSE_COUNT`] here for the same reason+/// they are in `bool`: width is what multiplies per-document work, and a span+/// clause list is as wide as a `should` list.+fn parse_span_clauses(obj: &serde_json::Map<String, Value>, _what: &str) -> Result<Vec<QueryNode>> {+ let Some(arr) = obj.get("clauses").and_then(|v| v.as_array()) else {+ return Ok(Vec::new());+ };+ // The clause CAP is fatal — a `MAX_CLAUSE_COUNT` trip must refuse, not+ // silently drop (that was the #122 defect: `filter_map(..ok())` turned an+ // over-cap span into a different query). The cap can trip in TWO places:+ // `charge_clause()` for the span's own clauses, and INSIDE `parse_query`+ // when a clause is itself a wide `bool` — both must propagate.+ //+ // But an ordinary parse error for a clause type this engine does not+ // implement (`span_multi`) or a malformed clause stays LENIENT and is+ // dropped, because that is the pre-#122 behaviour ES-compat conformance+ // depends on: `search/190_index_prefix_search` sends a `span_near` holding+ // a `span_multi` and expects the search to run, not to 400. So: propagate+ // ONLY the cap error; drop every other parse failure.+ let mut out = Vec::with_capacity(arr.len());+ for v in arr {+ charge_clause()?;+ match parse_query(v) {+ Ok(node) => out.push(node),+ Err(e) if e.to_string().contains("too_many_clauses") => return Err(e),+ Err(_) => { /* unsupported/malformed clause: dropped, as before */ }+ }+ }+ Ok(out)+}+/// Parse a `span_not` query.////// `{"span_not": {"include": {...}, "exclude": {...}}}`@@ -5281,4 +5382,80 @@ mod tests {}));assert!(res.is_ok(), "2×2 cross-product should parse fine");}++ // ── bool clause count (issue #122) ────────────────────────────────────++ fn bool_with_clauses(n: usize) -> serde_json::Value {+ let clauses: Vec<serde_json::Value> = (0..n)+ .map(|i| json!({ "term": { format!("f{i}"): format!("v{i}") } }))+ .collect();+ json!({ "bool": { "should": clauses } })+ }++ /// `MAX_QUERY_DEPTH` bounds how deep a query nests; nothing bounded how+ /// wide it is. Width is what multiplies per-document work: with no+ /// compiled-script cache in the engine, N script clauses over D documents+ /// is N x D full script parses, and the clause count is the only place+ /// that product can be bounded before any of it happens.+ #[test]+ fn a_bool_query_may_not_carry_unbounded_clauses() {+ let err = parse_query(&bool_with_clauses(MAX_CLAUSE_COUNT + 1))+ .expect_err("an over-wide bool must be refused");+ assert!(+ err.to_string().contains("too_many_clauses"),+ "the error must be ES's own, got {err}"+ );+ }++ /// Exactly at the cap still parses — the limit is a cap, not an off-by-one+ /// haircut on legitimate queries.+ #[test]+ fn a_bool_query_at_the_clause_cap_still_parses() {+ parse_query(&bool_with_clauses(MAX_CLAUSE_COUNT))+ .expect("a query at exactly the cap must parse");+ }++ /// The width is the whole query's, not one `bool`'s: two sibling bools of+ /// 600 clauses each are 1,200 clauses of work however they are spelled.+ #[test]+ fn the_clause_cap_is_summed_across_sibling_bools() {+ let query = json!({+ "bool": {+ "must": [ bool_with_clauses(600), bool_with_clauses(600) ]+ }+ });+ let err = parse_query(&query).expect_err("1,200 clauses must be refused");+ assert!(err.to_string().contains("too_many_clauses"), "got {err}");+ }++ /// The counter is a thread-local, so a rejected query must not poison the+ /// next request that happens to land on the same worker.+ #[test]+ fn a_rejected_query_does_not_poison_the_next_one() {+ let _ = parse_query(&bool_with_clauses(MAX_CLAUSE_COUNT + 1));+ parse_query(&bool_with_clauses(8))+ .expect("an ordinary query after a rejected one must still parse");+ }++ /// Span clause lists, `dis_max.queries` and an array `knn.filter` are all+ /// clause lists under other names, and all count towards the same width.+ /// The cap is exercised through each of them — together with the refusal+ /// semantics that go with it — in `tests/span_clause_refusal.rs`, which+ /// survives a revert of this file and so can show what the fix is worth.+ #[test]+ fn the_cap_is_reachable_through_every_clause_list_shape() {+ let wide: Vec<serde_json::Value> = (0..MAX_CLAUSE_COUNT + 1)+ .map(|i| json!({ "term": { "f": format!("v{i}") } }))+ .collect();+ for query in [+ json!({ "span_or": { "clauses": wide } }),+ json!({ "dis_max": { "queries": wide } }),+ json!({ "knn": {+ "field": "vec", "query_vector": [0.1, 0.2], "k": 3, "filter": wide+ }}),+ ] {+ let err = parse_query(&query).expect_err("an over-wide clause list must be refused");+ assert!(err.to_string().contains("too_many_clauses"), "got {err}");+ }+ }}diff --git a/engine/crates/xerj-query/tests/span_clause_refusal.rs b/engine/crates/xerj-query/tests/span_clause_refusal.rsnew file mode 100644index 000000000..a44cd9154--- /dev/null+++ b/engine/crates/xerj-query/tests/span_clause_refusal.rs@@ -0,0 +1,192 @@+//! Issue #122, round 2: a clause that trips the CLAUSE CAP must fail the query,+//! not disappear from it. An unsupported or malformed clause, by contrast, is+//! dropped — the pre-existing lenient behaviour ES-compat conformance depends+//! on. Only the cap is fatal.+//!+//! `parse_span_or` and `parse_span_near` collected their clauses with+//! `filter_map(|v| parse_query(v).ok())` — a clause the parser rejected was+//! dropped and parsing carried on. That was survivable while every clause the+//! parser could reject was malformed. Adding `MAX_CLAUSE_COUNT` made it a+//! correctness bug: a *well-formed* clause that is merely too wide now fails to+//! parse, so the query it belongs to used to come back 200 OK with that clause+//! silently missing — scored, ranked and returned as though it were the query+//! the caller asked for. `span_near` fared worse still: drop its only clause+//! and the empty list parses to `MatchNone`, i.e. 200 OK and zero hits.+//!+//! These live outside `parser.rs` on purpose. The tests inside it are removed+//! along with the fix when the source file is reverted, so they cannot show+//! that the fix is what makes them pass; these can.++use serde_json::json;+use xerj_query::{parse_query, QueryNode};++/// Comfortably above `MAX_CLAUSE_COUNT` (1,024) without depending on its exact+/// value from outside the crate.+const OVER_THE_CAP: usize = 2_000;++fn bool_too_wide() -> serde_json::Value {+ let clauses: Vec<serde_json::Value> = (0..OVER_THE_CAP)+ .map(|i| json!({ "term": { format!("f{i}"): format!("v{i}") } }))+ .collect();+ json!({ "bool": { "should": clauses } })+}++/// The clause cap must be reachable through a `span_or` clause at all: on its+/// own an over-wide `bool` is refused.+#[test]+fn an_over_wide_bool_is_refused_on_its_own() {+ let err = parse_query(&bool_too_wide()).expect_err("an over-wide bool must be refused");+ assert!(err.to_string().contains("too_many_clauses"), "got {err}");+}++/// A `span_or` whose first clause trips the cap must be refused — not reduced+/// to its surviving clause and answered as a different query.+#[test]+fn a_refused_span_or_clause_fails_the_query_instead_of_vanishing() {+ let query = json!({+ "span_or": {+ "clauses": [+ bool_too_wide(),+ { "span_term": { "body": "x" } }+ ]+ }+ });+ match parse_query(&query) {+ Err(e) => assert!(e.to_string().contains("too_many_clauses"), "got {e}"),+ Ok(QueryNode::SpanOr { clauses }) => panic!(+ "the over-wide clause was DROPPED: the query parsed to a SpanOr of \+ {} clause(s) and would have answered 200 OK for a query nobody asked for",+ clauses.len()+ ),+ Ok(other) => panic!("expected a refusal, got {other:?}"),+ }+}++/// `span_near` with a single over-wide clause: dropping it leaves an empty+/// clause list, which parses to `MatchNone` — 200 OK, zero hits, no error+/// anywhere.+#[test]+fn a_refused_span_near_clause_does_not_become_match_none() {+ let query = json!({+ "span_near": {+ "clauses": [ bool_too_wide() ],+ "slop": 2+ }+ });+ match parse_query(&query) {+ Err(e) => assert!(e.to_string().contains("too_many_clauses"), "got {e}"),+ Ok(QueryNode::MatchNone) => panic!(+ "the over-wide clause was dropped and the query collapsed to \+ MatchNone: 200 OK and zero hits for a query that was never refused"+ ),+ Ok(other) => panic!("expected a refusal, got {other:?}"),+ }+}++/// An unsupported or malformed clause (as opposed to a cap trip) is DROPPED,+/// not fatal — the pre-#122 lenient behaviour that ES-compat conformance+/// depends on. `search/190_index_prefix_search` sends a `span_near` holding a+/// `span_multi` (a valid ES clause this engine does not implement) and expects+/// the search to run with the remaining clauses, not to 400. The cap is the+/// only fatal case; see the tests above.+#[test]+fn an_unsupported_span_clause_is_dropped_not_fatal() {+ let query = json!({+ "span_or": {+ "clauses": [+ { "span_term": { "body": "x" } },+ { "dis_max": { "queries": "not-an-array" } }+ ]+ }+ });+ match parse_query(&query) {+ Ok(QueryNode::SpanOr { clauses }) => assert_eq!(+ clauses.len(),+ 1,+ "the supported span_term must survive and the unsupported clause drop"+ ),+ other => panic!("expected a SpanOr with the one supported clause, got {other:?}"),+ }+}++/// Width is charged wherever it appears. A span clause list multiplies+/// per-document work exactly as a `bool` clause list does.+#[test]+fn span_clauses_count_towards_the_query_width() {+ let clauses: Vec<serde_json::Value> = (0..OVER_THE_CAP)+ .map(|i| json!({ "span_term": { "body": format!("t{i}") } }))+ .collect();+ let err = parse_query(&json!({ "span_or": { "clauses": clauses } }))+ .expect_err("an over-wide span_or must be refused");+ assert!(err.to_string().contains("too_many_clauses"), "got {err}");+}++/// `dis_max.queries` is a clause list under another name.+#[test]+fn dis_max_queries_count_towards_the_query_width() {+ let queries: Vec<serde_json::Value> = (0..OVER_THE_CAP)+ .map(|i| json!({ "term": { "f": format!("v{i}") } }))+ .collect();+ let err = parse_query(&json!({ "dis_max": { "queries": queries } }))+ .expect_err("an over-wide dis_max must be refused");+ assert!(err.to_string().contains("too_many_clauses"), "got {err}");+}++/// An array `knn.filter` is `bool.filter` spelled differently — ES ANDs it the+/// same way, and it is charged the same way.+#[test]+fn knn_filter_clauses_count_towards_the_query_width() {+ let filter: Vec<serde_json::Value> = (0..OVER_THE_CAP)+ .map(|i| json!({ "term": { "f": format!("v{i}") } }))+ .collect();+ let query = json!({+ "knn": { "field": "vec", "query_vector": [0.1, 0.2], "k": 3, "filter": filter }+ });+ let err = parse_query(&query).expect_err("an over-wide knn.filter must be refused");+ assert!(err.to_string().contains("too_many_clauses"), "got {err}");+}++/// The refusal must not cost ordinary span queries anything: every clause of a+/// well-formed `span_or` still arrives.+#[test]+fn a_well_formed_span_or_keeps_all_its_clauses() {+ let query = json!({+ "span_or": {+ "clauses": [+ { "span_term": { "body": "a" } },+ { "span_term": { "body": "b" } }+ ]+ }+ });+ match parse_query(&query).expect("a well-formed span_or must parse") {+ QueryNode::SpanOr { clauses } => assert_eq!(clauses.len(), 2),+ other => panic!("expected span_or, got {other:?}"),+ }+}++/// And a well-formed `span_near` keeps its slop and ordering.+#[test]+fn a_well_formed_span_near_still_parses() {+ let query = json!({+ "span_near": {+ "clauses": [+ { "span_term": { "body": "quick" } },+ { "span_term": { "body": "fox" } }+ ],+ "slop": 3,+ "in_order": true+ }+ });+ match parse_query(&query).expect("a well-formed span_near must parse") {+ QueryNode::SpanNear {+ clauses,+ slop,+ in_order,+ } => {+ assert_eq!(clauses.len(), 2);+ assert_eq!(slop, 3);+ assert!(in_order);+ }+ other => panic!("expected span_near, got {other:?}"),+ }+}