Skip to content

fix(query): bound expression depth for long operator chains - #2927

Merged
robcohen merged 6 commits into
mainfrom
fix/bql-chain-depth
Nov 10, 2026
Merged

robcohen merged 6 commits into
mainfrom
fix/bql-chain-depth

Conversation

@robcohen

@robcohen robcohen commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

What changed

The BQL parser's up-front nesting scan (scan_delimiters in crates/rustledger-query/src/parser.rs) bounded bracket nesting (MAX_NESTING_DEPTH) but not operator chains. It now also bounds the depth of the expression tree (MAX_EXPR_DEPTH = 720, each bracket costing BRACKET_WEIGHT = 12), and brackets alone may nest 60 deep instead of 128. A query past either limit gets the same parse error deeply nested brackets already got, at the token that passes the limit:

syntax error at position 2889: expression nesting too deep (exceeds maximum of 720)

Why

A chain of N binary operators (AND, OR, +, -, *, /, %, comparisons, ~) or N stacked NOTs is parsed in a loop (foldl), but it builds a left-deep tree N levels deep. Everything that walks the tree after the parse recurses once per level: planning, evaluation, header naming, Display and Drop. A chain of some thousands of terms (rledger query a.bean "SELECT 1 + 1 + ... (20,000 terms)") overflowed the stack instead of returning an error. Brackets have the same problem at a smaller scale: on wasm32 the grammar's recursion takes about 4 KiB per bracket, and the WASI component on wasmtime's default 512 KiB stack ran out at 127 of the 128 brackets the old limit allowed.

How the bound works

The scan counts along the open path: each enclosing level's operators, 12 per open bracket, and the current item's operators plus its deepest closed bracket. Every operator token counts (+ - * / % = != < <= > >= ~ !~ . [, and AND OR NOT IN IS BETWEEN). That is an upper bound of the real depth: counting too many is safe, counting too few is not. The only token skipped is a decimal number's .. A , starts a new sibling item, so long IN (...) lists, argument lists and target lists cost nothing.

The query is refused before any tree is built, so nothing deep is ever walked or dropped. Every BQL entry point goes through rustledger_query::parse: rledger query from an argument, a file or stdin, the interactive shell, wasm query / ParsedLedger::query (and through them the MCP server), and the ffi-component. No separate path is needed.

Because the count is an upper bound, x ~ 'a' OR x ~ 'b' OR ... costs two per term, so about 360 alternatives fit. None of the 102 BQL queries in the docs, the MCP server's BQL guide and tests/compatibility/bql-queries.toml comes near either limit.

Sizing the limits

Each shape was run with both limits lifted on optimized builds, and its length bisected to the first that ran out of stack:

shape WASI component, wasmtime default (512 KiB) Node, main thread Node, worker thread native, 2 MiB thread
1 + 1 + ..., AND, NOT 2,716 3,439 3,439 3,727
aggregate target sum(number) + 1 + ... (also ORDER BY, sum(...) > 0 AND ...) 1,555 1,555 1,555 1,650
HAVING sum(number) + 1 + ... > 0 1,626 3,434 3,434 3,620
attribute chain entry.meta.meta... 1,480 3,437 3,437 3,727
OR account ~ ... (terms) 3,216 3,417 3,417 4,298
nested parentheses / calls 127 424 1,687 3,727 / 2,774
nested calls around sum(number) 126 423 1,555 1,650
nested subqueries 412 741 741 625

The costliest operator level is the component's attribute chain (1,480), and a bracket there costs about 12 aggregate-chain levels (4 KiB against 340 bytes). The limits keep at least half of every stack free, measured as the first failing length divided by the longest accepted one:

shape component Node main Node worker native 2 MiB
aggregate target (accepted: 708) 2.20x 2.20x 2.20x 2.33x
attribute chain (720) 2.06x 4.77x 4.77x 5.18x
plain chain (720) 3.77x 4.78x 4.78x 5.18x
HAVING chain (707) 2.30x 4.86x 4.86x 5.12x
nested parentheses (60) 2.12x 7.07x 28.1x 62.1x
nested calls around sum (59) 2.14x 7.17x 26.4x 28.0x
nested subqueries (60) 6.87x 12.4x 12.4x 10.4x

Mixed shapes cost less than the sum of their parts, so the weighted budget is conservative. A chain inside 30 or 60 brackets runs out at the same length as the chain alone, or within 4% of it (component: 1,555 for the bare aggregate chain and for it inside 60 parentheses, 1,495 inside 60 nested calls), because the brackets' stack is taken while parsing and the chain's while evaluating.

Against bean-query 0.2.0 (run on the same queries): it raises RecursionError on a chain of 1,000 +, * or NOT and on 200 nested parentheses, where rledger gives a positioned parse error. It reads AND / OR chains as one n-ary node and runs 4,000 terms of either, which rledger refuses past 720 (about 360 comparisons). That is a deliberate deviation, noted at the constant; the BQL reference now tells a generated filter to use one IN (...) list or one regular expression with | alternatives, which cost almost nothing against the limit.

How to test

cargo test -p rustledger-query --all-features --test expression_depth_test
cargo build -p rustledger-ffi-component --target wasm32-wasip2
cargo test -p rustledger-ffi-component-tests --test parity nesting_limits
cd crates/rustledger-wasm && wasm-pack test --node   # wasm_expression_depth.rs
  • expression_depth_test.rs checks every shape in the tables, and each counted operator on its own (%, /, *, -, <, <=, >, >=, !=, !~, ~, IN, IS NULL, BETWEEN ... AND, ['k'], .), at exactly the limit and one past it. It runs every shape at the limit to completion, including the attribute chain, and checks the error position. It also checks that long lists are not counted as chains, that a 300-term generated OR filter runs, and that 200,000-term chains are refused on a 256 KiB thread. The debug build takes over 11 KiB per aggregate-chain level, so the runs at the limit use a 64 MiB thread; the limits are sized from the optimized measurements above.
  • The component tests (parity.rs) run 60 parentheses, 60 nested calls, a 55-level nested IN, 59 calls around sum(number), and 55 brackets around a chain that brings the budget to exactly 720, all in the component as CI builds it, under Engine::default(). Then they run the queries one step past each limit, a 127-call nest, a 2,000-term aggregate chain, 4,000 ANDs and 5,000 NOTs. Each comes back as the nesting error, and after each one a following ordinary query still answers.
  • wasm_expression_depth.rs runs the 4,000-term AND chain, the 5,000-NOT chain and 20,000-term + / OR ~ chains through ParsedLedger::query. It checks that each returns the nesting error, then runs a normal query on a new ParsedLedger in the same module. It also checks that a 200-term generated filter runs.
  • Mutation checks: removing any one operator character from the count (+ - * / % < > ! . [, or = and ~ together, which share one rule) or any of the 6 operator words, counting <= as two operators, setting the bracket weight to 1, or counting a decimal's . fails at least one test. With the limits lifted, the native 200,000-term test overflows its stack, the wasm tests fail with memory access out of bounds, and the component's past-the-limit test fails.

Review round 1

  • Brackets in the WASI component. MAX_NESTING_DEPTH drops from 128 to 60, and each bracket now also costs 12 in the depth budget, so brackets and chains are bounded together. The component runs out at 127 brackets, so 60 leaves 2.12x. The calibration tables above were measured on all four runtimes. New component tests cover the bracket limit and a bracket-heavy mixed limit, and check that the instance answers afterwards.
  • Aggregate shapes. The worst operator shapes are aggregate chains (target, HAVING, ORDER BY, sum(...) > 0 AND ...) and attribute chains. MAX_EXPR_DEPTH drops from 1,000 to 720, which keeps 2x on every runtime for every shape measured. The doc comment carries the corrected measurements, and the tests cover the aggregate shapes.
  • Every counted operator is pinned. A straddle test for each counted operator; each removal was confirmed to fail a test (see Mutation checks).
  • Nits. The stray comma is gone, the CHANGELOG entry names this PR, and the attribute chain is run at the limit as well as parsed.

Review round 2

Nested single-element IN (. 1 IN (1 IN (... 1 ...)) took time exponential in its depth: the IN branches tried set_literal first, which parsed the whole bracket, failed for want of a ,, and left additive to parse it again, so every level doubled the work. set_literal is now guarded by bracket_holds_a_comma, a lexical lookahead that reads to the bracket's closing ) (strings and nested brackets skipped, lexed as string_literal reads them) and lets the set be tried only when a , follows at the bracket's own level. A set needs that , after its first element, and a first element's own commas are all inside brackets, so the check rejects only brackets the set branch would have failed on: the queries accepted and what they mean are unchanged, single-element x IN (y) included (pinned in test_in_reads_a_set_only_with_a_comma_at_its_own_level, with commas in strings, call arguments and subscripts, and brackets and quotes inside set elements).

Optimized builds, SELECT 1 IN ( x n 1 ) x n (native: parse(); component: a whole query call under Engine::default()):

n native before native after component before component after
14 61 ms 1.4 ms 130 ms 0.9 ms
18 850 ms 1.4 ms 1,321 ms 1.0 ms
20 3,550 ms 1.0 ms 5,018 ms 1.0 ms
55 (the deepest accepted) (2^35 x n=20) 3.3 ms (2^35 x n=20) 1.7 ms

The test counts parser work instead of timing it: in test builds the grammar counts literal operands read against a per-thread budget and panics past it. test_parse_nested_single_element_in_reads_each_literal_once parses nested IN at 55 levels, NOT IN at 51 (its NOT counts too), TRUE IN ( in a WHERE, and the 55-level form with a syntax error at the center, each within 4 x (n + 1) literals. With the lookahead disabled it fails in 0.1 s on the budget. The component's at-limit test now includes the 55-level nested IN as well.

Audit of the rest of the grammar. Each candidate was timed at nesting 2 to 16 (debug build), valid and with a syntax error at the center. Only IN and NOT IN grew (doubling per level: 1.8 s at 16). Flat at 1 to 3 ms throughout: parentheses, nested calls (abs(), BETWEEN ( ... ) AND, ( ... IS NULL) and IS NOT NULL, window calls sum(...) OVER (PARTITION BY ...), nested FROM (SELECT ...) subqueries, FROM ( filters, two-element sets IN (..., 2) (with the syntax error in a later element only: one in the first element still doubled per level, fixed in round 3), IN ( inside parentheses and in WHERE, and aliased targets. The other choice points re-parse nothing: subquery_from, table_from and regular_from fail on their first token when they do not apply, function_args re-reads an expression only after a * (an error path), plus_atom and the statement alternatives start with distinct tokens, and statement_errors re-parses once per statement kind on the error path only.

Nits. The bean-query note at MAX_EXPR_DEPTH and in the CHANGELOG now says what bean-query does (above), and docs/reference/bql.md has a "Long lists of alternatives" section with the IN (...) and regex forms. The parity.rs doc comments now say "a following query still answers".

Review round 3

Nested sets with a syntax error in a first element. When bracket_holds_a_comma found a , and the set then failed (a syntax error in its first element), the IN fell back to additive, which parsed the same bracket again as ( expr ). That retry can never succeed, since the , at the bracket's level comes before its ), but it doubled the work at every level. The fallback is now guarded by not_a_set, the inverse check, so such a bracket is parsed once, as a set. What every IN accepts and means, and the error a refused query gets, are unchanged.

Optimized builds, SELECT + 1 IN ( x n + 1 + + , 2) x n (native: parse(); component: a whole query call under Engine::default()):

n native before native after component before component after
14 97 ms 2.2 ms 121 ms 1.0 ms
20 5,813 ms 1.4 ms 8,677 ms 1.1 ms
55 (the deepest accepted) not run (doubles per level) 1.4 ms not run 3.3 ms

The NOT IN form was 6,264 ms native and 8,700 ms in the component at n=20 before, and 2.5 ms and 0.8 ms after. The single-element form from round 2 stays at 1 to 5 ms at 14, 20 and 55.

test_parse_nested_sets_read_each_literal_a_bounded_number_of_times holds, within 4 x (n + 1) literals: the 55-level nest of , 2) both valid and with 1 + at the center, the , 2 2) and trailing ,) variants, NOT IN at 51 levels, IN ((...), 2) at 28 (two brackets a level) valid and broken, and 1 + (1 IN (..., 2)) at 25. With the guard removed it fails in 0.2 s on the budget. The component's at-limit test now runs the 55-level , 2) nest, and the same nest with 1 + at the center, which must come back as a syntax error, not the nesting one, before a following query still answers.

Nits. The CHANGELOG entry now says nested sets parse quickly too, even with a syntax error inside. The round-2 audit sentence about two-element sets is corrected: they were flat only with the error in a later element.

🤖 Generated with Claude Code

The BQL pre-scan bounded bracket nesting (MAX_NESTING_DEPTH, 128) but not
operator chains. A chain of N binary operators (AND, OR, +, -, *, /, %,
comparisons, ~) or N stacked NOTs parses in a loop but builds a left-deep
tree N levels deep, and planning, evaluation, header naming, Display and
Drop each recurse once per level. A chain of some thousands of terms
overflowed the stack instead of returning an error.

scan_delimiters now also keeps an upper bound of the expression tree's
depth: every operator token and every bracket on the path counts one level,
a closed bracket's depth carries into the item around it, and a comma starts
a new sibling item (so long IN lists, argument lists and target lists cost
nothing). A query whose bound passes MAX_EXPR_DEPTH (1000) gets the same
"expression nesting too deep" parse error nested brackets get, at the
operator that passes the limit. The query is refused before any tree is
built, so nothing deep is ever walked or dropped. Every BQL entry point
(CLI, wasm, ffi-component, the MCP server through wasm) goes through
rustledger_query::parse, so all are covered.

The limit is sized from measurements with it lifted: an optimized wasm32
build ran every shape at 3,000 terms on its 1 MiB stack and trapped at
4,000; an optimized native rledger ran every shape at the limit with a
1 MiB main-thread stack. About 500 OR-joined comparisons fit.

bean-query recurses too and raises RecursionError on long enough chains;
rledger returns a positioned parse error instead (noted at the constant).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 10, 2026 09:00
robcohen and others added 2 commits November 10, 2026 04:07
Review round 1 of the expression-depth bound.

Brackets: the WASI component on wasmtime's default 512 KiB stack ran out
at 127 nested brackets, under the old 128 limit, as the grammar's
recursion takes about 4 KiB per bracket there. MAX_NESTING_DEPTH drops to
60, and each bracket now costs BRACKET_WEIGHT (12) in the expression-depth
budget, so brackets and operator chains are bounded together.

Aggregates: chains in an aggregate query's target, HAVING and ORDER BY,
and attribute chains, cost several times a plain chain per level.
MAX_EXPR_DEPTH drops from 1000 to 720. Bisected on optimized builds with
the limits lifted, the first failing length is at least twice the longest
accepted for every shape on the component, wasm in Node (main thread and
worker) and native 2 MiB threads; the doc comment carries the table.

Tests: every counted operator straddles the limit, aggregate, bracket and
subquery shapes straddle and run at it, the attribute chain runs at it,
and the component tests run the bracket and mixed limits, refuse one step
past them, and check the instance answers afterwards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 51.5ms ± 1.2ms 754.3ms ± 8.4ms 14.7x 44.9 MB / 51.1 MB
investment 81.5ms ± 1.4ms 2786.1ms ± 11.2ms 34.2x 46.9 MB / 59.1 MB
fifo 78.6ms ± 0.9ms 15431.1ms ± 78.7ms 196.3x 49.0 MB / 59.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 50.9ms ± 0.4ms 51.5ms ± 1.2ms +1.0% ✅ within noise 45.1 MB → 44.9 MB (-0.3%)
investment 82.1ms ± 1.1ms 81.5ms ± 1.4ms -0.7% ✅ within noise 47.0 MB → 46.9 MB (-0.1%)
fifo 78.3ms ± 1.1ms 78.6ms ± 0.9ms +0.4% ✅ within noise 48.7 MB → 49.0 MB (+0.5%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.6ms, investment 0.8ms, fifo 0.6ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@codecov

codecov Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.76119% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/parser.rs 97.76% 6 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 826
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 3 commits November 10, 2026 09:07
Review round 2.

`1 IN (1 IN (... 1 ...))` took time exponential in its depth: the IN
branches tried set_literal first, which parsed the whole bracket, failed
for want of a `,` after the first element, and left additive to parse it
again, so every level doubled the work (3.5 s at 20 levels natively, and
the 55 levels the limits accept were out of reach). set_literal is now
guarded by bracket_holds_a_comma, a lexical lookahead to the bracket's
closing `)` that lets the set be tried only when a `,` follows at the
bracket's own level. A set needs that `,`, and a first element's commas
are all inside brackets, so what every IN accepts and means is unchanged.
After the fix the 20-level form parses in about 1 ms, natively and in the
WASI component.

A test-build-only literal counter bounds parser work in the new test, so
it fails fast on the old grammar instead of timing it. The rest of the
grammar was timed at increasing nesting (parentheses, calls, BETWEEN,
IS NULL, windows, FROM subqueries and filters, two-element sets): only IN
and NOT IN grew.

Also: the bean-query note at MAX_EXPR_DEPTH and in the CHANGELOG now says
bean-query runs long AND/OR chains (rledger refuses them past the limit)
and raises RecursionError on 1,000 `+`, `*` or `NOT`; the BQL reference
shows IN lists and regex alternation for long lists of alternatives; and
the component test comments are reworded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review round 3.

When bracket_holds_a_comma found a `,` and the set then failed (a syntax
error in its first element), the IN fell back to additive, which parsed
the same bracket again as `( expr )`. That retry can never succeed, as
the `,` at the bracket's level comes before its `)`, but nested, it
doubled the work at every level: `1 IN (1 IN (1 +, 2), 2)` 20 levels
deep took 5.8 s natively and 8.7 s in the WASI component. The fallback
is now guarded by not_a_set, the inverse check, so such a bracket is
parsed once, as a set; the 55 levels the limits accept now take a few
milliseconds. What every IN accepts and means is unchanged.

The literal-budget test covers the nested sets, valid and broken, with
the NOT IN, `IN ((...), 2)`, `, 2 2)`, trailing `,)` and `1 + (...)`
variants, and fails without the guard. The component's at-limit test
runs the 55-level nest. The CHANGELOG entry covers nested sets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit d21a576 into main Nov 10, 2026
63 of 64 checks passed
@robcohen
robcohen deleted the fix/bql-chain-depth branch November 10, 2026 18:39
robcohen added a commit that referenced this pull request Nov 10, 2026
Keeps both CHANGELOG Fixed entries (#2928 and #2927).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

1 participant