Repository navigation
fix(query): bound expression depth for long operator chains - #2927
Merged
Merged
Conversation
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]>
# Conflicts: # CHANGELOG.md
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]>
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
# Conflicts: # CHANGELOG.md
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]>
This was referenced Nov 10, 2026
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]>
This was referenced Nov 10, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed
The BQL parser's up-front nesting scan (
scan_delimitersincrates/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 costingBRACKET_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:Why
A chain of N binary operators (
AND,OR,+,-,*,/,%, comparisons,~) or N stackedNOTs 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,DisplayandDrop. 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 (
+ - * / % = != < <= > >= ~ !~ . [, andAND 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 longIN (...)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 queryfrom an argument, a file or stdin, the interactive shell, wasmquery/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 andtests/compatibility/bql-queries.tomlcomes 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:
1 + 1 + ...,AND,NOTsum(number) + 1 + ...(alsoORDER BY,sum(...) > 0 AND ...)HAVING sum(number) + 1 + ... > 0entry.meta.meta...OR account ~ ...(terms)sum(number)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:
HAVINGchain (707)sum(59)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
RecursionErroron a chain of 1,000+,*orNOTand on 200 nested parentheses, where rledger gives a positioned parse error. It readsAND/ORchains 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 oneIN (...)list or one regular expression with|alternatives, which cost almost nothing against the limit.How to test
expression_depth_test.rschecks 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 generatedORfilter 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.parity.rs) run 60 parentheses, 60 nested calls, a 55-level nestedIN, 59 calls aroundsum(number), and 55 brackets around a chain that brings the budget to exactly 720, all in the component as CI builds it, underEngine::default(). Then they run the queries one step past each limit, a 127-call nest, a 2,000-term aggregate chain, 4,000ANDs and 5,000NOTs. Each comes back as the nesting error, and after each one a following ordinary query still answers.wasm_expression_depth.rsruns the 4,000-termANDchain, the 5,000-NOTchain and 20,000-term+/OR ~chains throughParsedLedger::query. It checks that each returns the nesting error, then runs a normal query on a newParsedLedgerin the same module. It also checks that a 200-term generated filter runs.+ - * / % < > ! . [, 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 withmemory access out of bounds, and the component's past-the-limit test fails.Review round 1
MAX_NESTING_DEPTHdrops 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.HAVING,ORDER BY,sum(...) > 0 AND ...) and attribute chains.MAX_EXPR_DEPTHdrops 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.Review round 2
Nested single-element
IN (.1 IN (1 IN (... 1 ...))took time exponential in its depth: theINbranches triedset_literalfirst, which parsed the whole bracket, failed for want of a,, and leftadditiveto parse it again, so every level doubled the work.set_literalis now guarded bybracket_holds_a_comma, a lexical lookahead that reads to the bracket's closing)(strings and nested brackets skipped, lexed asstring_literalreads 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-elementx IN (y)included (pinned intest_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 n1)x n (native:parse(); component: a wholequerycall underEngine::default()):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_onceparses nestedINat 55 levels,NOT INat 51 (itsNOTcounts too),TRUE IN (in aWHERE, 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 nestedINas 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
INandNOT INgrew (doubling per level: 1.8 s at 16). Flat at 1 to 3 ms throughout: parentheses, nested calls (abs(),BETWEEN (...) AND,( ... IS NULL)andIS NOT NULL, window callssum(...) OVER (PARTITION BY ...), nestedFROM (SELECT ...)subqueries,FROM (filters, two-element setsIN (..., 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 inWHERE, and aliased targets. The other choice points re-parse nothing:subquery_from,table_fromandregular_fromfail on their first token when they do not apply,function_argsre-reads an expression only after a*(an error path),plus_atomand the statement alternatives start with distinct tokens, andstatement_errorsre-parses once per statement kind on the error path only.Nits. The bean-query note at
MAX_EXPR_DEPTHand in the CHANGELOG now says what bean-query does (above), anddocs/reference/bql.mdhas a "Long lists of alternatives" section with theIN (...)and regex forms. Theparity.rsdoc 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_commafound a,and the set then failed (a syntax error in its first element), theINfell back toadditive, 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 bynot_a_set, the inverse check, so such a bracket is parsed once, as a set. What everyINaccepts 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 wholequerycall underEngine::default()):The
NOT INform 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_timesholds, within 4 x (n + 1) literals: the 55-level nest of, 2)both valid and with1 +at the center, the, 2 2)and trailing,)variants,NOT INat 51 levels,IN ((...), 2)at 28 (two brackets a level) valid and broken, and1 + (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 with1 +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