Skip to content

feat(engine): add local functions and lambdas to Painless - #88

Merged
xerj-org merged 2 commits into
xerj-org:mainfrom
Vinz2168:feat/painless-local-functions-lambdas
Aug 1, 2026
Merged

xerj-org merged 2 commits into
xerj-org:mainfrom
Vinz2168:feat/painless-local-functions-lambdas

Conversation

@Vinz2168

Copy link
Copy Markdown
Collaborator

Summary

OpenSearch's UBI sample dashboards filter via a Supplier-style boolean helper, which needs two Painless features xerj didn't support:

  • Top-level local function declarations: <type> name(<type> arg, ...) { ... }
  • Lambda literals: (a, b) -> expr / (a, b) -> { stmts }, stored as a closure value and invoked either by calling the function/variable name directly, or via any .method(args) call on a closure value (s.get(), fn.apply(x), pred.test(x), ...) — the method name is ignored, only positional args matter, covering Supplier/Function/BiFunction/Predicate etc. without hard-coding each functional interface. Closures run in a fresh scope seeded only with their bound parameters, with no access to the caller's other locals.

Adapted to the current ParsedExpr/eval_access_chain parser structure: a lambda literal is a parse-time leaf (its own body is depth-guarded independently via the normal statement-parsing path), and closure invocation is wired into eval_member_value (the .method() dispatch point) and the Expr::Call case.

The new PainlessValue::Closure variant made two existing conversions (aggs.rs's painless_value_to_json, es_compat.rs's painless_to_json) non-exhaustive; both now map a closure to Value::Null, the same fail-closed treatment already used for script errors — a script's top-level result is never meaningfully a function value.

This is one of three independent PRs from the same investigation (the others: #86 flat_object alias, #87 script query support). Combined with #87, this unblocks the "Top Searches Without Results" UBI dashboard panel, which filters via exactly this shape of script.

Test plan

  • cargo fmt --check
  • cargo clippy --workspace --all-targets -- -D warnings
  • cargo test -p xerj-engine -p xerj-query -p xerj-api --lib (351 passed; the 2 failures in snapshot_path_security_tests are pre-existing on main, unrelated to this change)
  • Verified together with feat(query): add script query support #87 on a combined local branch against a real OpenSearch Dashboards 3.6.0 instance importing the UBI sample dashboards: the "Top Searches Without Results" panel (which uses exactly this local-function/lambda shape) renders real data with no errors.

🤖 Generated with Claude Code

https://claude.ai/code/session_014PRCbyt7Y2HDyhG1tbQTeL

OpenSearch's UBI sample dashboards filter via a Supplier-style boolean
helper, which needs two Painless features xerj didn't support:

- Top-level local function declarations: `<type> name(<type> arg, ...) { ... }`
- Lambda literals: `(a, b) -> expr` / `(a, b) -> { stmts }`, stored as
  a closure value and invoked either by calling the function/variable
  name directly, or via any `.method(args)` call on a closure value
  (`s.get()`, `fn.apply(x)`, `pred.test(x)`, ...) — the method name is
  ignored, only positional args matter, covering Supplier/Function/
  BiFunction/Predicate etc. without hard-coding each functional
  interface. Closures run in a fresh scope seeded only with their bound
  parameters, with no access to the caller's other locals.

Adapted to the current `ParsedExpr`/`eval_access_chain` parser
structure: a lambda literal is a parse-time leaf (its own body is
depth-guarded independently via the normal statement-parsing path), and
closure invocation is wired into `eval_member_value` (the `.method()`
dispatch point) and the `Expr::Call` case.

The new PainlessValue::Closure variant made two existing conversions
(aggs.rs's painless_value_to_json, es_compat.rs's painless_to_json)
non-exhaustive; both now map a closure to Value::Null, the same
fail-closed treatment already used for script errors — a script's
top-level result is never meaningfully a function value.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014PRCbyt7Y2HDyhG1tbQTeL
@xerj-org

xerj-org commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Reviewed for inclusion in v1.0.0-rc.9. Holding it — there are two shapes here that abort the process, and I reproduced both in the real crate under the release profile. Detail below so it's actionable rather than just a "no".

Method note: every finding was sent to an independent verifier told to refute it, and I re-ran the two most serious ones myself against 11e61f3 rather than trusting the report.

The design is closer than it looks

call_closure seeds a fresh scope containing only the parameters, so a function cannot see its own name and plain self-recursion by name is impossible. That's a deliberate, sensible choice and it's why the obvious def f() { f(); } shape is safe.

What it doesn't prevent is self-application: a closure passed as an argument is bound in the callee's scope, so f(f, n) recurses.

Blocker 1 — a 156-byte script aborts the process

def f = (g, n) -> { if(true){if(true){…×10…} return g(g, n); …} }; return f(f, 1);

check_script_limits returns Ok(()), then on a thread with tokio's default 2 MiB worker stack:

fatal runtime error: stack overflow, aborting
(signal: 6, SIGABRT)

Root cause: EvalDepthGuard::enter is called in exactly one place, eval_expr (painless.rs:1097). exec_stmt (:1048), Stmt::If's recursion (:1066), Stmt::Block's (:1075), exec_body (:1007) and call_closure (:1027) charge nothing. That was safe before this PR because statement nesting was bounded once by MAX_PARSE_DEPTH = 100 and could never be re-entered. Closure invocation re-enters exec_stmt from eval_expr, so MAX_PARSE_DEPTH stops being a total and becomes a per-call-level multiplier — worst case 500 × 100 ≈ 50,000 exec_stmt frames. Each closure call costs one unit of the 500-unit eval budget but up to ~95 extra native frames.

The guard's own doc comment (:938-941) says it is "Incremented on entry to eval_expr/exec_stmt" — that describes the pre-PR world and the code now contradicts it.

Worth knowing how narrowly this hides: the simple shape def f = (g,x) -> g(g,x); return f(f,1); is correctly bounded in release, returning script evaluation exceeded maximum depth even on a 512 KiB stack. I checked that first and briefly concluded the PR was safe. It's only when the body contains nested blocks that the frame multiplier outruns the counter. With panic = "abort" (engine/Cargo.toml:110) a stack overflow is a process abort, so if scripts are reachable unauthenticated this is a node kill.

Blocker 2 — no step or time budget; depth bounds the call path, not the call tree

def f = (g, n) -> n <= 0 ? 1 : g(g,n-1) + g(g,n-1) + g(g,n-1) + g(g,n-1); return f(f, 9);

89 bytes, check_script_limits Ok, 262,144 invocations in 0.82 s — measured in the real crate. Each +1 to n multiplies by 4: n=11 is ~13 s, n=15 ~56 minutes, and this is per matched document. Depth never exceeds ~9, so MAX_EVAL_DEPTH never fires. Branching factor is limited only by the 64 KiB source cap, and ~249 levels are reachable.

Before this PR no Painless construct could loop or recurse at all, so "there is no step budget" was fine. Adding closures changes that premise.

Also confirmed

  • Every closure value deep-clones its entire body AST (PainlessValue::Closure(params.clone(), body.clone())) — a 55 KB script peaks at ~4.7 GB RSS.
  • Argument arity is never checked — missing args become Null, extra args are dropped. Silently wrong results rather than an error.
  • No capture, no hoisting, no recursion by name — int secret = 99; def f = () -> secret; doesn't see secret, so ES-correct scripts that rely on capture will silently score every document rather than erroring.
  • try_parse_lambda swallows the depth-limit sentinel, defeating the up-front 400.

What would make this shippable

A dedicated call-depth counter in call_closure (something small like 32–64, independent of the expression budget), plus a step budget threaded through evaluation so an exponential call tree terminates with a bounded error. Arity checking and Rc/Arc for closure bodies instead of deep clones would close the other two. The feature itself is a good addition — it's the resource bounds that need to exist before it's reachable from a query.

For context on why this got the scrutiny: this repo has already shipped and fixed an unauthenticated stack-overflow DoS from nested SQL WHERE parens, the same from nested query_string parens, and an oversized Painless expression exhausting the native stack. Any new recursive construct gets held to that history.

Addresses maintainer review findings on the original closures PR — the
two crash-class findings verified directly before fixing:

- Confirmed by diffing against upstream: EvalDepthGuard::enter is
  called in exactly one place, eval_expr. exec_stmt, exec_body and
  call_closure charge nothing. Statement nesting was previously bounded
  once by MAX_PARSE_DEPTH at parse time and could never be re-entered
  at eval time — closures change that by re-entering exec_stmt from
  inside eval_expr on every call, turning MAX_PARSE_DEPTH into a
  per-call-level multiplier instead of a total.

  Fixes both shapes the review demonstrated:
  - Self-application with a nested-statement body (`f(f, n)` where f's
    body has several nested `if`s) can re-enter exec_stmt far more
    times than the expression-eval budget accounts for. Fixed with a
    new call_depth counter (MAX_CALL_DEPTH = 32), independent of
    eval_depth, charged once per call_closure invocation.
  - An exponential call tree (`g(g,n-1) + g(g,n-1) + g(g,n-1) +
    g(g,n-1)`) never exceeds a call *depth* of ~n, so a depth counter
    alone doesn't bound it — measured at 262,144 invocations for n=9.
    Fixed with a call_count budget (MAX_CALL_COUNT = 10,000) across
    the whole script evaluation.

- try_parse_lambda swallowed every error from parsing a lambda body,
  including the MAX_PARSE_DEPTH sentinel, and silently backtracked —
  defeating check_script_limits's up-front 400 for a script whose
  lambda body is what makes it too deep. Once `(params) ->` is
  consumed there is no other valid parse in this grammar, so any
  error from the body onward is now propagated instead of swallowed.

- Every closure value deep-cloned its entire body AST on construction
  (`body.clone()` on a `Vec<Stmt>`) — with the call-count fix above
  already bounding the invocation count, this is no longer a path to
  unbounded memory, but it's still needless allocation on every call
  that passes a closure as an argument. Switched closure bodies to
  Rc<Vec<Stmt>>, shared from the AST node at parse time, so cloning a
  closure value is a refcount bump instead of an AST copy.

- Also added: argument-count checking in call_closure (a wrong-arity
  call now errors instead of silently defaulting missing args to
  Null / dropping extras).

Not addressed here (agreed lower-severity follow-ups): no capture, no
hoisting, no recursion by name — a script relying on lexical capture
still silently sees an undefined-identifier error rather than the
value, which is at least fail-closed rather than fail-open, but isn't
the ES-correct behavior either.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014PRCbyt7Y2HDyhG1tbQTeL
@Vinz2168

Vinz2168 commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Both blockers confirmed before fixing — diffed EvalDepthGuard::enter call sites against upstream/main directly and confirmed it's only in eval_expr, exactly as reported.

  • Blocker 1 (nested-statement self-application): added a call_depth counter in PainlessCtx, independent of eval_depth, charged once per call_closure invocation via a new CallGuard RAII type (MAX_CALL_DEPTH = 32, in the range you suggested). Added a regression test with the same shape (f(f,n) where f's body has 10 nested ifs) — confirmed it errors cleanly instead of aborting.
  • Blocker 2 (exponential call tree): added call_count, a total-invocation budget across the whole evaluation (MAX_CALL_COUNT = 10,000), since depth alone never bounds this shape. Regression test with your exact n=9 repro now trips the guard in ~0.05s instead of running the full tree.
  • try_parse_lambda swallowing the depth sentinel: fixed — once (params) -> is consumed there's no other valid parse in this grammar, so every error from the body onward now propagates instead of being swallowed into a silent backtrack.
  • Deep-clone AST per closure value: switched closure bodies to Rc<Vec<Stmt>>, shared from the AST node at parse time (Stmt::FnDecl/Expr::Lambda now own the Rc directly, so .clone() at every construction site is a refcount bump, not a copy) — this was a mostly mechanical change once the guards above already bound total invocation count.
  • Also added arity checking in call_closure (wrong arg count now errors instead of silently defaulting missing args to Null).

Not addressed (agree, lower severity, tracking separately): no capture/hoisting/recursion-by-name — a script relying on lexical capture still errors on the undefined identifier rather than seeing the value, which is fail-closed but not ES-correct.

Full suite green: cargo fmt --check, cargo clippy --workspace --all-targets -- -D warnings, cargo test -p xerj-engine -p xerj-query -p xerj-api --lib (only the 2 pre-existing, unrelated snapshot_path_security_tests failures).

🤖 Generated with Claude Code

@xerj-org

xerj-org commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Housekeeping, not a review comment.

We've just added a Contributor License Agreement to the project (#93). Until now contributions here were covered only by Apache-2.0 §5's inbound=outbound clause, which gives no explicit patent grant — worth tightening for a project this size.

Once #93 merges, a cla-bot check will appear on this PR and it will be red until you're covered. Signing is one small pull request, once per contributor — not per PR:

  1. Read CLA.md
  2. Open a PR adding your GitHub username to .contributors
  3. Comment @cla-bot check back here and it turns green

That PR is the signature — it comes from your own account, so the commit history is the record.

To be explicit about something: we did not add anyone to the signed list on their behalf, including you. That file asserts a person has signed, and that's not ours to assert for someone else — hence the ask rather than a quiet edit.

Sorry for the extra step on work that's already in flight. Thanks for the contributions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants