Skip to content

fix(query): close chain-length gap in Cypher and add matching guard for SQL (#5851 follow-up) - #5864

Merged
lvca merged 1 commit into
mainfrom
fix/5851-followup-sql-and-cypher-depth-guards
Aug 6, 2026
Merged

lvca merged 1 commit into
mainfrom
fix/5851-followup-sql-and-cypher-depth-guards

Conversation

@lvca

@lvca lvca commented Aug 6, 2026

Copy link
Copy Markdown
Member

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 WHERE

ExpressionRewriter's recursion guard (added in #5859) only fires from CypherASTBuilder#visitWhereClause. A long OR/AND/NOT/comparison/arithmetic chain written anywhere other than a top-level WHERE condition - a RETURN projection, an ORDER BY item, a function argument - was never rewritten and so never hit that guard. Confirmed with a real repro: a 30000-term OR chain in a RETURN projection still produced a StackOverflowError, this time inside CypherSemanticValidator#checkExpressionScope - a completely different, independent recursive walker from ExpressionRewriter.

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 same ParseTreeListener already 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 JavaCC SqlParser is dead code, unreferenced anywhere). It genuinely isn't at risk of the parenthesis-nesting StackOverflowError (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.

SQLAntlrParser now counts parenthesis nesting on the token stream (reusing the already-buffered CommonTokenStream, same technique the Cypher parser already used for its deprecated-syntax pre-check) before attempting any parse, rejecting past arcadedb.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

  • New CypherChainLengthGuardIssue5851FollowupTest (8 tests): long OR chain in RETURN, long AND chain in ORDER BY, long chained-comparison (a<b<c<...), long multiplication and power chains all now fail with CommandParsingException instead of StackOverflowError; short/legitimate versions of each still parse fine.
  • New 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.
  • Updated 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 than ExpressionRewriter), message assertions and doc comments updated accordingly; all still pass.
  • mvn -pl engine test across 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 compile clean.

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

…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.
@mergify

mergify Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 11 complexity

Metric Results
Complexity 11

View in Codacy

🟢 Coverage 100.00% diff coverage · -6.42% coverage variation

Metric Results
Coverage variation ✅ -6.42% coverage variation
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

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.

@lvca lvca self-assigned this Aug 6, 2026
@lvca lvca added this to the 26.9.1 milestone Aug 6, 2026
@lvca
lvca merged commit 2724575 into main Aug 6, 2026
10 checks passed
@lvca
lvca deleted the fix/5851-followup-sql-and-cypher-depth-guards branch August 6, 2026 23:10
@claude

claude Bot commented Aug 6, 2026

Copy link
Copy Markdown

Code review (post-merge) - PR #5864

I 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

  • Confirmed the eight (OP operand)* precedence rules in Cypher25Parser.g4 (expression OR, expression11 XOR, expression10 AND, expression9 NOT*, expression8 comparisons, expression6 +/-/||, expression5 * / %, expression4 ^) are all covered by the switch in checkChainLength, and the skipped levels (expression7 = expression6 comparisonExpression6?, expression3/expression2) are correctly not chains. Coverage is complete and each case uses the same generated accessor the AST builders use, so the count cannot drift.
  • Confirmed the SQL guard counts LPAREN/RPAREN only on DEFAULT_CHANNEL, so parens inside strings/comments are not miscounted (matches the test), and the depth > 0 guard on RPAREN avoids going negative on unbalanced input.

Observations (minor, none blocking)

  1. Behavior change worth a user-facing release note, not just the internals doc. The chain-length limit now rejects any (OP operand)* run longer than maxExpressionDepth (200) anywhere, not only pathological inputs. Machine-generated queries with large flat OR/AND chains (e.g. a 300-term a=1 OR a=2 OR ... built instead of an IN list) that previously parsed fine will now fail with CommandParsingException. The knob mitigates it, but this is a user-visible compatibility change and the failure message is the only signal a user gets. Worth calling out in the changelog.

  2. SQL_MAX_EXPRESSION_DEPTH is SCOPE.DATABASE but read via the global static. checkExpressionDepth reads GlobalConfiguration.SQL_MAX_EXPRESSION_DEPTH.getValueAsInteger(), and the Cypher guard reads CYPHER_MAX_EXPRESSION_DEPTH.getValueAsInteger() the same way, so a per-database override of either won't actually take effect at parse time. This is consistent between the two (and pre-existing for Cypher), so not a regression, but the SCOPE.DATABASE declaration implies a per-DB knob that isn't honored. Reading the per-database value, or documenting that it is effectively global, would remove the surprise.

  3. SQL guard covers ( nesting only. The ALL(*) fallback blowup is specific to the bare-( rule ambiguity, so this is the right target and there is no StackOverflow risk on the SQL side regardless. Just noting deep [/{ nesting is not bounded by this scan; fine given the established analysis, but if a similar prediction-cost pattern ever turns up for another construct this guard won't catch it.

  4. The timing assertion (isLessThan(5000)) is inherently environment-sensitive. A ~4ms rejection under a 5s ceiling is a huge margin so it won't flake in practice, but pure wall-clock assertions can misbehave on a heavily loaded/paused CI runner. Given the margin I'd leave it, but it's the one test I'd keep an eye on. (No @Tag needed since it's now fast.)

Overall: clean fix, good tests, and the documented residual (a composed depth budget) is the right call to flag rather than over-engineer.

lvca added a commit that referenced this pull request Aug 8, 2026
…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.
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