Repository navigation
fix(query): close chain-length gap in Cypher and add matching guard for SQL (#5851 follow-up) - #5864
Conversation
…or SQL (#5851 follow-up) Two gaps found while auditing for the same failure class elsewhere in both engines. Cypher: ExpressionRewriter's recursion guard only fires from visitWhereClause, so a long OR/AND/NOT/comparison/arithmetic chain written outside a top-level WHERE (RETURN, ORDER BY, a function argument, ...) still overflowed the stack - this time inside CypherSemanticValidator#checkExpressionScope, a different recursive walker entirely. CypherExpressionDepthGuard now also bounds the term count of every (OP operand)*-shaped grammar rule directly, rejecting an oversized chain during parsing before any AST tree is built - protecting every downstream walker at once instead of requiring each one found and patched individually. SQL: the production parser (SQLAntlrParser, ANTLR4-based) is not at risk of a StackOverflowError from nested parentheses (far fewer stack frames per level than Cypher's grammar), but is at risk of something worse - its SLL-to-ALL(*) prediction fallback on the grammar's ambiguous LPAREN-prefixed alternatives grows so steeply with nesting depth that a query of only a few KB tied up a worker thread for minutes without crashing. SQLAntlrParser now counts parenthesis nesting on the token stream before attempting any parse, rejecting a query past the new arcadedb.sql.maxExpressionDepth in O(n) time.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 11 |
🟢 Coverage 100.00% diff coverage · -6.42% coverage variation
Metric Results Coverage variation ✅ -6.42% coverage variation Diff coverage ✅ 100.00% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (f0983b8) 152291 116912 76.77% Head commit (47a000c) 184671 (+32380) 129921 (+13009) 70.35% (-6.42%) Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch:
<coverage of head commit> - <coverage of common ancestor commit>Diff coverage details
Coverable lines Covered lines Diff coverage Pull request (#5864) 39 39 100.00% Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified:
<covered lines added or modified>/<coverable lines added or modified> * 100%
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
Code review (post-merge) - PR #5864I reviewed the diff against the actual grammar and surrounding parser code. This is a solid, well-reasoned fix: it attacks the root cause at the parse layer rather than chasing individual recursive walkers, the Cypher chain-length coverage matches the grammar exactly, and the SQL token-stream pre-scan is a clean, O(n) mitigation for the ALL(*) prediction blowup. Test coverage is thorough (positive + negative cases, config-knob effectiveness, string-literal edge case). Nice work. Verification I did
Observations (minor, none blocking)
Overall: clean fix, good tests, and the documented residual (a composed depth budget) is the right call to flag rather than over-engineer. |
…ream is eagerly filled (#5957) * fix(#5951): attach the SQL lexer's error listener before the token stream is eagerly filled SQLAntlrParser.tokenize() (added by #5864 for the expression-depth guard) calls tokens.fill() to eagerly lex the whole input, but the custom SQLErrorListener was attached to the lexer only afterwards. Any lexer-level error (e.g. a malformed \u escape) was therefore only printed by ANTLR's default listener and never thrown as a CommandSQLParsingException, letting the lexer's error recovery drop the bad token(s) and silently parse a different, bogus statement instead of failing. Move the lexer's error-listener setup ahead of tokenize() in all four entry points (parse, parseScript, parseExpression, parseCondition). * test(#5951): cover parseScript/parseExpression/parseCondition for the malformed-unicode-escape fix Code review on #5957 pointed out the fix touches all four SQLAntlrParser entry points but the regression test only exercised parse(). Add the same assertion through parseScript, parseExpression and parseCondition.
Summary
Follow-up to #5851 / PR #5859, requested after that PR merged: extend the same investigation to SQL, and audit other recursive Cypher AST walkers for the same failure class. Both turned up real, confirmed gaps.
Cypher: the chain-length guard only covered
WHEREExpressionRewriter's recursion guard (added in #5859) only fires fromCypherASTBuilder#visitWhereClause. A long OR/AND/NOT/comparison/arithmetic chain written anywhere other than a top-levelWHEREcondition - aRETURNprojection, anORDER BYitem, a function argument - was never rewritten and so never hit that guard. Confirmed with a real repro: a 30000-term OR chain in aRETURNprojection still produced aStackOverflowError, this time insideCypherSemanticValidator#checkExpressionScope- a completely different, independent recursive walker fromExpressionRewriter.Patching that one walker would just repeat the mistake with a new blind spot the next time some other pass (
CypherExpressionWalker, execution-time evaluation, anything not yet written) walks such a tree. Instead,CypherExpressionDepthGuard- the sameParseTreeListeneralready attached to the parser for nesting depth - now also bounds the term count of every(OP operand)*-shaped grammar rule directly: OR, XOR, AND,NOT*, chained comparisons, and the three arithmetic precedence levels. Each check uses that rule's own generated accessor (ctx.expression11(),ctx.NOT(), ...) - the exact same one every AST builder in the package calls - so the count can never drift from what would actually be folded into a tree. This rejects an oversized chain during parsing, before any tree is built, regardless of clause or which pass would eventually have walked it.SQL: not at risk of a stack overflow, but at risk of something worse
The production SQL parser is
SQLAntlrParser(ANTLR4-based, like Cypher's - the legacy hand-maintained JavaCCSqlParseris dead code, unreferenced anywhere). It genuinely isn't at risk of the parenthesis-nestingStackOverflowError(confirmed - its grammar's left-recursion elimination costs far fewer Java stack frames per nesting level than Cypher's precedence cascade). It is, however, at risk of something arguably worse: it resolves the ambiguity between several grammar rules that all start with a bare((a parenthesized expression, condition, or sub-statement) by trying a fast SLL prediction first and falling back to full ALL(*) prediction on failure. For deeply nested parentheses that fallback's cost grows steeply enough that ~6000 nested parens (a few KB) tied up a worker thread for well over two minutes of CPU without ever crashing - measured directly, and worse than a fast error since a slow hang isn't distinguishable from a legitimately slow query from the outside.SQLAntlrParsernow counts parenthesis nesting on the token stream (reusing the already-bufferedCommonTokenStream, same technique the Cypher parser already used for its deprecated-syntax pre-check) before attempting any parse, rejecting pastarcadedb.sql.maxExpressionDepth(default 200) in O(n) time. The same depth that previously burned 2+ minutes of CPU is now rejected in ~4ms. Counting on the token stream rather than raw characters means a(inside a string literal or comment - already lexed as part of that token - is never miscounted (covered by a test).Test plan
CypherChainLengthGuardIssue5851FollowupTest(8 tests): long OR chain inRETURN, long AND chain inORDER BY, long chained-comparison (a<b<c<...), long multiplication and power chains all now fail withCommandParsingExceptioninstead ofStackOverflowError; short/legitimate versions of each still parse fine.SqlExpressionDepthGuardIssue5851FollowupTest(5 tests): the 6000-paren hang is now rejected in single-digit ms; moderate nesting, nested function calls/sub-selects, and parens inside a string literal all still parse fine; the config is a real, effective knob.CypherExpressionDepthGuardIssue5851Test(9 tests, from fix(cypher): bound expression nesting depth to prevent StackOverflowError #5859) - the OR-chain and NOT-chain cases are now caught earlier (by the parser's chain-length check rather thanExpressionRewriter), message assertions and doc comments updated accordingly; all still pass.mvn -pl engine testacross the full opencypher top-level/parser/rewriter suite and the full SQL parser/antlr suite: 2744 tests, 0 failures, 0 errors.mvn -pl engine -am compileclean.Known residual (not fixed here, flagged for visibility)
The two guards (parser nesting ≤200, chain length ≤200 per level) compose: a deliberately-crafted input nesting many parenthesized groups, each containing its own near-limit chain, could in principle reach an AST depth well past either individual limit along one root-to-leaf path. This wasn't reproduced (it requires a much larger, more deliberately-constructed payload than either bug reported here), and closing it properly needs a running depth budget threaded through AST construction rather than two independent local checks - a larger change than this fix warrants. Noting it rather than quietly leaving it undocumented.
🤖 Generated with Claude Code