Repository navigation
fix(#5951): attach the SQL lexer's error listener before the token stream is eagerly filled - #5957
Conversation
…ream 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).
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 0 |
🟢 Coverage 100.00% diff coverage
Metric Results Coverage variation Report missing for 49715e21 Diff coverage ✅ 100.00% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (49715e2) Report Missing Report Missing Report Missing Head commit (b7f3dcc) 185484 130775 70.50% 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 (#5957) 12 12 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%1 Codacy didn't receive coverage data for the commit, or there was an error processing the received data. Check your integration for errors and validate that your coverage setup is correct.
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.
ReviewVerified the root-cause analysis directly against the code: Test coverage gap: the new Related, out-of-scope finding: Minor/optional: the four methods now duplicate an identical 6-line "build lexer, attach listener, tokenize" block. This duplication predates the PR (the methods were already structurally identical), so not a request to change here, but if this class gets touched again a small private helper (e.g. No correctness, performance, or security concerns with the change itself - it only reorders existing object construction/wiring, adds no allocations or dependencies, and tightens error handling rather than loosening it (fixing a case where malformed input was previously misparsed into a different, unintended query rather than rejected). |
… 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.
|
Addressed the code-review feedback:
All four |
ReviewVerified the root-cause analysis by reading I confirmed via Code quality
Test coverage
Out of scope, worth a follow-up issue: No security or performance concerns - the change only reorders existing object construction/listener wiring, no new allocations or hot-path impact. Nice, well-isolated fix with a clear root-cause writeup. |
|
Second review round: confirms the fix is correct and minimal, no security/performance concerns, test coverage called "exactly right". Remaining points:
No blocking issues raised across either review round. Waiting for the remaining CI checks ( |
|
`unit-tests` failed with an `OutOfMemoryError` in `ConcurrentSaltCacheTest.shouldNotOverflowInitialCapacityForVeryLargeMaxSize`. Confirmed this is unrelated to this PR and is a pre-existing, deterministic bug currently breaking `main` itself (verified against multiple independent CI runs on `main` today, e.g. run 31240206397, where `unit-tests`/`ha-integration-tests`/`integration-tests` all fail with the identical stack trace). Root cause: `ConcurrentSaltCache`'s integer-overflow guard clamps to `1 << 30` for `new ConcurrentHashMap<>(...)`, which is still large enough to OOM on construction. Filed as #5962 with a suggested fix; not fixing it here since it's a different subsystem entirely (server security cache sizing, not SQL parsing) and out of scope for this PR. Waiting for #5962 to be resolved (or for CI to re-run) so this PR's checks can go green. This PR's own diff, tests, and both code-review rounds remain clean. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #5957 +/- ##
==========================================
+ Coverage 68.10% 68.15% +0.04%
==========================================
Files 1797 1797
Lines 153141 153141
Branches 32436 32436
==========================================
+ Hits 104299 104367 +68
+ Misses 35442 35365 -77
- Partials 13400 13409 +9 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Final statusBoth Two CI jobs did fail, both confirmed unrelated pre-existing issues on
No branch protection / required status checks are configured on Summary of review feedback addressed across this PR's lifetime:
Ready to merge from my side. |
* fix: batch fixes for #5934, #5937, #5958 - #5934: CHECK DATABASE FIX's index-rebuild path dropped and rebuilt a corrupted bucket sub-index with no withIndexName()/withMetadata(), the same defect #5925 fixed for REBUILD INDEX. A single-bucket type lost its explicitly-named TypeIndex wrapper, and a FULL_TEXT/ GEOSPATIAL index lost its analyzer/precision settings, every time the check repaired one of their bucket sub-indexes. - #5937: the plain (unshaded) arcadedb-gremlin Maven coordinate crashed with a raw ExceptionInInitializerError/InvalidClassException the first time it ran a textual Gremlin query, because a downstream consumer's classpath resolves only the engine's ANTLR 4.13.2 runtime while TinkerPop's precompiled grammar needs 4.9.1's ATN format. ArcadeGremlin now recognizes that specific failure shape and raises an actionable CommandExecutionException pointing at the arcadedb-gremlin:shaded classifier, instead of leaking ANTLR internals. Textual Gremlin still requires the shaded classifier; this only makes the failure diagnosable. - #5958: Cypher25AntlrParser attached its CypherErrorListener to the parser but never to the lexer, unlike SQLAntlrParser after #5951/ #5957. Fixed for consistency and to guard future grammar changes; the regression test pins that lexically malformed input still raises CommandParsingException. * fix: address code review on #6031 - ArcadeGremlin.translateAntlrAtnMismatch: Codacy flagged the reference-identity cycle guard (next == c) as a raw == comparison on Throwable. Switched to Objects.equals(), which is null-safe and behaviorally identical since Throwable does not override equals(). - Cypher25AntlrParser.parseQuery: reuse a single CypherErrorListener instance for both lexer and parser, matching SQLAntlrParser's pattern (minor stylistic note from review; CypherErrorListener is stateless so this is behavior-preserving). * fix: address code review on #6031 (file-locking coverage) DatabaseChecker's index-rebuild loop dropped and rebuilt a corrupted bucket sub-index without holding the file lock RebuildIndexStatement.buildIndex() takes for the same drop+rebuild sequence. Wrap both steps in executeLockingFiles(idx.getFileIds(), ...), matching the sibling implementation, so a concurrent writer can't observe the index gone-then-back with entries missing and the commit-time lock-coverage check can't throw on the newly-created file. * fix: address code review on #6031 (deduplicate FULL_TEXT/GEOSPATIAL rebuild metadata) DatabaseChecker's new auto-fix rebuild path and RebuildIndexStatement.buildIndex() now had the same ~10-line FULL_TEXT/GEOSPATIAL metadata-reconstruction block copy-pasted verbatim. Factored into IndexMetadata.reconstructForRebuild(idx, typeName, propertyNames), a static helper both call, so a future third case or a bugfix to this logic only needs to be applied once. * fix: address code review on #6031 (retry the index-rebuild lock) DatabaseChecker's drop+rebuild lock (added to mirror RebuildIndexStatement's file-locking coverage) had no retry loop for lock contention, unlike RebuildIndexStatement.buildIndex(), which retries NeedRetryException / LockTimeoutException up to MAX_ATTEMPTS with backoff. Widening the locked section to cover both the drop and the create - the whole point of that fix - widens the window a concurrent writer can contend on, so add the same bounded retry. Unlike RebuildIndexStatement, which silently returns once attempts are exhausted, this rethrows: CHECK DATABASE FIX should fail loudly rather than quietly leave an index unrepaired while still reporting success. * fix: address code review on #6031 (document auto-mode fail-fast) Add the one-line comment code review suggested at the 'auto' -> java engine try/catch in ArcadeGremlin.executeStatement(boolean): the ATN-mismatch CommandExecutionException is unchecked, so it propagates past the catch (ScriptException e) used for the auto -> Groovy fallback, meaning 'auto' mode fails fast on this classpath defect instead of silently falling back to the insecure Groovy engine. Intentional, now documented at the call site. * docs: address code review on #6031 (document pre-existing retry race) Review round 5 correctly noted that retrying the whole drop+create body can re-enter with the drop already committed if create()'s bucket scan raises NeedRetryException, restarting from a different state than a clean retry assumes. Confirmed this exact shape already exists, unchanged, in RebuildIndexStatement.buildIndex() - not introduced by this PR, just given a second call site and (via the rethrow-on-exhaustion choice from the prior review round) more likely to surface if it happens. A proper fix (skip the drop on retry, or scope retry to lock acquisition only) needs to touch both call sites together, which is out of scope for this batch fix; documented the known race at the call site instead, and trimmed the now-lengthy comment block per the review's other minor note. * fix: address code review on #6031 (isolate lock-contention failure per index) DatabaseChecker's retry loop previously rethrew once LOCK_MAX_ATTEMPTS was exhausted, unwinding out of check() entirely. Since CheckDatabaseStatement has no catch around checker.check(), that aborted the WHOLE CHECK DATABASE FIX run - discarding every corrupted record already found and fixed, every index already rebuilt earlier in the affectedIndexes iteration, skipping every index still to come, and skipping the compress step - all because one index stayed lock-contended on a busy database (exactly the scenario the retry was added to survive). Isolate the failure to that one index instead: on exhausted retries, remove it from the reported rebuiltIndexes set (so the result doesn't claim a rebuild that didn't happen) and record a warning via addWarning(), matching this class's existing "reported, never silent" convention, then continue rebuilding the rest of affectedIndexes. An InterruptedException during the backoff sleep still aborts immediately, since that is a stop request rather than contention to ride out. * fix: address code review on #6031 (comment accuracy + plain-index test) - Refine the "known pre-existing race" comment on DatabaseChecker's retry loop: dropIndex() itself does not throw on retry (LocalSchema.dropIndexInternal no-ops once the name is gone); the actual risk is create() running a second time after a prior attempt's drop already committed, not resuming from where create() failed. Also note that capturing rebuildMetadata/ownerTypeIndex once before the loop (vs RebuildIndexStatement recomputing them per-attempt) is a hoist, not a behavior change, since both read idx before any attempt's drop. - Add fixPreservesExplicitNameOnPlainIndex to CheckDatabaseFixPreservesIndexMetadataTest, covering the plain (non-FULL_TEXT/GEOSPATIAL) TypeIndex-name-preservation case for CHECK DATABASE FIX's rebuild path, matching RebuildIndexPreservesNameTest's equivalent coverage for REBUILD INDEX. * fix: address code review on #6031 (recompute rebuild metadata per retry attempt) Real bug caught by review: rebuildMetadata was computed once, before the retry loop, so a retried FULL_TEXT rebuild reused the same FullTextIndexMetadata instance whose BM25 corpus counters (totalDocs/sumDocLength) had already been partially incremented by the failed attempt's create() call - addDocument() mutates the instance in place and is not reversed on rollback. Attempt N+1 then indexed every record again on top of attempt N's partial counts, inflating the corpus stats and skewing BM25 relevance scoring on any FULL_TEXT index whose rebuild needed more than one attempt. GEOSPATIAL was unaffected (GeoIndexMetadata has no equivalent mutable accumulator). Move IndexMetadata.reconstructForRebuild(...) inside the retry loop so each attempt gets a fresh, zeroed metadata instance, matching RebuildIndexStatement.buildIndex()'s per-attempt recomputation. ownerTypeIndex stays hoisted: it is a plain name read off idx, unaffected by attempt count. * docs: address code review on #6031 (explain hoisted retry-loop locals) Comment-only change: document why bucketName/indexType/unique/propNames/ typeName/pageSize/nullStrategy are safe to read once before the retry loop (plain idempotent reads off pre-drop idx/schema state, no mutable accumulator), unlike rebuildMetadata just below them, which for FULL_TEXT wraps a live BM25 counter and is recomputed per attempt for exactly that reason. * fix: address code review on #6031 (do not blame lock contention unconditionally) The retry-exhaustion warning unconditionally said "due to lock contention", but NeedRetryException reaching that branch can also come from the documented pre-existing race (a later attempt's create() failing after an earlier attempt's drop already committed) - in which case the index may be genuinely missing, not merely un-rebuilt, and "lock contention" is the wrong diagnosis to hand an operator. Reworded to state the rebuild did not finish and the index may be missing, point at re-running CHECK DATABASE FIX, and give a SELECT FROM schema:indexes query to verify - without claiming a specific root cause the code cannot actually distinguish from lastRetryFailure alone.
Summary
Fixes #5951.
SQLAntlrParser.tokenize()(added by #5864 for the parenthesis-nesting-depth DoS guard from #5851) callstokens.fill()to eagerly lex the entire input up front, but in all four parse entry points (parse,parseScript,parseExpression,parseCondition) the customSQLErrorListenerwas only attached to the lexer after that call returned. Any lexer-level tokenization error - e.g. a malformed\uunicode escape, which the grammar requires to have exactly 4 hex digits (SQLLexer.g4:467) - was therefore only printed by ANTLR's defaultConsoleErrorListener(to stderr) and never thrown as aCommandSQLParsingException. ANTLR's default lexer error recovery then silently dropped the offending token(s), and the parser went on to successfully parse a different, bogus statement out of the mangled remainder - instead of failing with a syntax error.This is what caused
PostgresWJdbcIT.parsingErrorMgmtto fail deterministically starting 2026-08-07:SELECT 'abc \u30 def';was silently reduced toSELECT def, which parses fine, so noPSQLExceptionwas ever raised.Root cause commit:
272457557(#5864), 2026-08-06 - one day before the reported CI failures began.Fix
Move the lexer's
removeErrorListeners()/addErrorListener(...)calls to beforetokenize(lexer)is invoked, in all fourSQLAntlrParsermethods. The parser's own listener setup was already correctly sequenced (it happens after the parser object is built, beforeparser.parse()/etc. run) and is unchanged.Test plan
SQLGrammarRegressionTest#malformedUnicodeEscapeRaisesParsingException, assertingparser.parse(...)throwsCommandSQLParsingExceptionfor both a single- and double-quoted string containing a malformed\uescape. Verified this test fails without the fix (reproducing the bug) and passes with it.SQLGrammarRegressionTest(50 tests, includes existing well-formed&-style unicode escape coverage): pass.com.arcadedb.query.sql.antlr.**+com.arcadedb.query.sql.parser.**(414 tests): pass.com.arcadedb.query.sql.**(2399 tests): pass.postgreswintegration testsPostgresWJdbcIT(43 tests, including the originally-failingparsingErrorMgmt) andPostgresProtocolIT(73 tests): pass.mvn compileacrossengine,server,postgresw: clean.🔗 https://claude.ai/code/session_0131GDFM4QGFC5URdReusH4A