Skip to content

Make syntax error messages point at the mistake - #116806

Merged
qoega merged 9 commits into
masterfrom
improve-sql-error-messages
Sep 10, 2026
Merged

qoega merged 9 commits into
masterfrom
improve-sql-error-messages

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

Error messages for mistakes in SQL queries were surveyed by taking the queries of ClickBench, TPC-H, TPC-DS and the Join Order Benchmark (278 queries), damaging them at random - dropping a token, dropping a bracket or a comma, changing, dropping, inserting or transposing a single letter, swapping or duplicating a token, truncating the query - and comparing the reported error position with the position of the actual damage over the resulting 5560 errors.

For an ordinary syntax error the reported position turned out to be excellent: the median distance to the real mistake is 1 character, and 73% of the errors are reported within 5 characters of it. Two things stood out as bad, and this pull request fixes both.

Unmatched parentheses pointed at the wrong bracket. The median distance to the mistake was 31 characters, the 90th percentile 508, the maximum 3927 - by far the worst-localized syntax error. The reason is that the message reports the outermost bracket that is left unclosed, and bracket counting cannot tell which of the nested brackets the user actually forgot to close. In

SELECT a FROM (SELECT b FROM (SELECT c FROM (SELECT count(* AS cnt FROM numbers(10)) t3) t2) t1

the bracket of count( gets matched with the ) that was meant to close the innermost subquery, so the leftover bracket is the one at position 15:

Syntax error: failed at position 15 ((): (SELECT b FROM (SELECT c FROM (SELECT count(* AS cnt FROM numbers(10)) t3) t2) t1. Unmatched parentheses: (.

The token where the parser stopped is right next to the mistake, and it was simply discarded on this path. It is now reported, and every unclosed bracket is listed with its own position instead of only its character:

Syntax error: failed at position 68 (FROM): FROM numbers(10)) t3) t2) t1. Unmatched parentheses: '(' at position 15 is never closed.

The same reasoning applies in mirror image to a closing bracket that closes nothing. It can be excessive, and then it is itself the mistake, but it can just as well be the opening bracket that is missing:

CREATE TABLE hits WatchID BIGINT NOT NULL, ... 100 more columns ... )

and then the leftover closing bracket is as far from the mistake as the column list is long. Running the same damage over the CREATE TABLE statements of the same four benchmarks (2280 damaged statements) put the worst case at 2643 characters. The parser stops right where the opening bracket belongs — position 16 in CREATE TABLE t a UInt32, b UInt32), which is a — so its position is preferred there too, and the bracket is still named:

Syntax error: failed at position 16 (a): a UInt32, b UInt32) ENGINE = MergeTree ORDER BY a.
Unmatched parentheses: ')' at position 34 has no matching opening bracket.

Measured distance from the actual mistake:

corpus master this PR
queries (750 unmatched-bracket errors) median 31, p75 174, p90 508, max 3927, within 5 chars 13% median 14, p75 54, p90 197, max 2314, within 5 chars 34%
DDL (356 unmatched-bracket errors) median 1, p75 32, p90 184, max 2643, within 5 chars 57% median 1, p75 5, p90 14, max 34, within 5 chars 80%

No information is lost, because both positions are now in the message. A closing bracket that closes nothing also says what it fails to match: ')' at position 10 does not match '[' at position 8 instead of Unmatched parentheses: [).

A mistyped keyword was answered with a wall of alternatives. The list of expected alternatives has 34 items in the median and 151 for a typo in the leading SELECT, with nothing indicating which one was meant. The closest keyword is now named first:

SELEgT 1
Syntax error: failed at position 1 (SELEgT): SELEgT 1. Maybe you meant: SELECT. Expected one of: ...

This fires for 392 of the errors in the corpus, and in 98% of them the named keyword is the one the original query had at that place. The edit-distance thresholds are deliberately tighter than in NamePrompter, because here the candidates are keywords of the language rather than names taken from the query, so almost any short word is close to some keyword - hits is two edits away from WITH. A word containing a digit is never treated as a mistyped keyword either, which keeps aliases such as an1 from being matched against ANY.

Validated by running all 190 stateless tests that mention syntax errors; the only failures are unrelated environment ones (no ZooKeeper, no writeable access storage, no test clusters in the local setup).

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Improved syntax error messages. An unclosed bracket is now reported at the place where the parser stopped, which is next to the actual mistake, and every unclosed bracket is listed with its own position - previously the outermost bracket was blamed, which in a large query can be thousands of characters away from the mistake. A mistyped keyword is now named explicitly (Maybe you meant: SELECT.) instead of only being one item in a list of dozens of alternatives.


Workflow [PR]
Sync PR [sync-upstream/pr/116806]

Both changes come from a survey of the error messages that ClickHouse
produces for damaged benchmark queries: the queries of ClickBench, TPC-H,
TPC-DS and the Join Order Benchmark were mutated by dropping tokens and
changing single letters, and the resulting 5560 errors were compared
against the position of the actual damage.

For an ordinary syntax error the reported position is excellent - the
median distance to the real mistake is 1 character. The one path that
localizes badly is `Unmatched parentheses`, with a median of 31 and a
90th percentile of 508 characters, because it reports the position of the
outermost bracket that is left unclosed. Bracket counting cannot tell
which of the nested brackets the user forgot to close: in

    SELECT a FROM (SELECT count(* FROM t) x

the bracket of `count(` gets matched with the `)` that was meant to close
the subquery, so the leftover bracket is the one of the subquery. The
token where the parser stopped does not have that problem, and it was
simply thrown away. Report it, and list every unclosed bracket with its
own position instead of only printing the bracket characters. The median
distance to the mistake drops to 16 characters and the share of errors
reported within 5 characters of it grows from 13% to 33%.

A mistyped keyword, in turn, is answered with the whole list of
alternatives the parser could accept - 34 items in the median, and 151
for a typo in the leading `SELECT`, with no indication which one was
meant. Name the closest one:

    SELEgT 1
    Syntax error: failed at position 1 (SELEgT): SELEgT 1.
    Maybe you meant: SELECT. Expected one of: ...

On the same corpus this fires for 392 errors, and in 98% of them the
named keyword is the one the original query had at that place. The
thresholds are tighter than in `NamePrompter` because the candidates are
keywords rather than names from the query, so a short word is close to
some keyword almost always: `hits` is two edits away from `WITH`.
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [18cd5d4]

Summary: ✅


AI Review

Summary

This PR materially improves human-readable syntax diagnostics by moving unmatched-bracket errors closer to the real mistake and by naming likely keyword typos. One important consumer is still out of sync, though: the structured ParserDiagnostics / ch_parse error offsets keep reporting the old unmatched-bracket token, so browser/editor consumers still jump to the wrong byte even when the text message now points elsewhere.

Findings

⚠️ Majors

  • [src/Parsers/parseQuery.cpp:608] ParserDiagnostics.error_token no longer matches the cursor chosen for unmatched-parentheses messages. getUnmatchedParenthesesErrorMessage now selects between last_token and the fallback bracket, but tryParseQuery still hardcodes scoped_parens[0] into diagnostics. utils/wasm-parser/wasm_parser.cpp then serializes that stale token into error.begin / error.end, so a query such as SELECT count(* FROM numbers(10) still reports the ( to ch_parse while the text message reports FROM. Suggested fix: compute the chosen unmatched-parentheses error_token once and use it for both the message and ParserDiagnostics, or have the helper return both the string and the token.
Tests
  • ⚠️ Add a focused utils/wasm-parser/test.mjs case for unmatched parentheses / missing opening brackets that asserts error.begin / error.end match the token named by the message. The current new tests cover the plain-text and highlighted message paths, but not the JSON API that depends on ParserDiagnostics.error_token.
Final Verdict

Changes are not ready to merge yet: the new message-position contract is still broken for the WebAssembly / JSON parser API on unmatched-parentheses errors.

LLVM Coverage Report

Measured on commit 18cd5d4.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 79/80 (98.75%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 27, 2026
Comment thread src/Parsers/parseQuery.cpp Resolved
`utils/wasm-parser` lists the `src/Common` translation units it needs one
by one, so the keyword typo hint left `DB::levenshteinDistanceCaseInsensitive`
undefined at link time. The file only needs `PODArray` and `iota`, which
the build already has, and both configurations stay well under the size
ceiling: 1342695 bytes (102305 under) with formatting and DCL, 811172
bytes (63828 under) without them.
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 18cd5d449 with master 4d7f75efa (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

4 object files changed (+21.70 KiB total), 0 added.

Object file Master PR Δ
src/Parsers/CMakeFiles/clickhouse_parsers.dir/parseQuery.cpp.o 96.58 KiB 118.28 KiB +21.70 KiB (+22.47%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

8 translation units recompiled, 11 s compile time in total, 8 of them have a recent master baseline.

Job report

…g one

Applying the same measurement to DDL - the `CREATE TABLE` statements of
the same four benchmarks, damaged the same way, 2280 statements - showed
that the closing-bracket branch has the mirror image of the problem this
branch already fixes for openers.

A closing bracket that closes nothing can be excessive, and then it is
itself the mistake. But it can just as well be the *opening* bracket that
is missing:

    CREATE TABLE hits WatchID BIGINT NOT NULL, ... 100 columns ... )

and then the leftover closing bracket is as far from the mistake as the
column list is long - 2643 characters in the worst case in the corpus.
The parser stops right where the opening bracket belongs (position 16 in
`CREATE TABLE t a UInt32, b UInt32)`, which is `a`), so prefer its
position whenever it is before the bracket, and keep naming the bracket.

On the DDL corpus the distance from the mistake improves from p75 32,
p90 184, max 2643 to p75 5, p90 14, max 34, and the share reported within
5 characters from 57% to 80%: 101 statements improved, 1 worse. On the
query corpus of the first commit it is a strict improvement - p75 88 to
54, p90 354 to 197, 82 improved and none worse - because a query rarely
loses the opening bracket of a long list.
Comment thread src/Parsers/parseQuery.cpp Resolved
`getUnmatchedParenthesesErrorMessage` appended the token where the parser
stopped to the list of positions to highlight even when that token was one of
the unmatched brackets itself, as in

    CREATE TABLE t [a UInt32) ENGINE = Memory

where the parser stops at `[` while `checkUnmatchedParentheses` reports `[`
and `)`. `writeQueryWithHighlightedErrorPositions` requires strictly ascending
positions and computes `current_position_to_hilite - pos`, so a repeated
position made that difference negative and the query buffer was read out of
bounds. Deduplicate the positions after sorting them.

Addresses a review comment on the pull request. Adds highlighted cases to
`05045_syntax_error_messages_locate_the_mistake`; the client takes the
highlighting path with `--ignore-error`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The two CI reds on 1be0f8ff23d8 are unrelated to this pull request: Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) failed with a job-level session-timeout occurred during test execution (no individual test failure), and Integration tests (amd_llvm_coverage, 6/8) failed in test_insert_into_distributed/test.py::test_reconnect with AssertionError: assert '2' == '3'. Master has been merged in and the highlighter fix pushed, so both will be re-run.

@groeneai, investigate the failure: https://github.com/ClickHouse/ClickHouse/actions/runs/33284854699/job/99205760634 (test_insert_into_distributed/test.py::test_reconnect under LLVM coverage) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

Already fixed by #117133 (merged 2026-08-30 16:06Z), so no separate PR is needed.

The job you linked started 2026-08-30 04:19Z and its tree 1be0f8ff23d8 is 349 commits behind that merge, so it ran the pre-fix test. The current head 019b4a9f1044 has the fix as an ancestor, so the re-run exercises the fixed version.

CIDB, last 35 days: 10 failures of test_insert_into_distributed/test.py::test_reconnect, all between 2026-08-28 18:20Z and 2026-08-30 18:35Z, all on pull requests, none on master (9 on Integration tests (amd_llvm_coverage, 6/8), 1 on 4/8). On the 6/8 shard the rate went from 7 failures in 305 runs before that merge to 2 in 602 since, and both of those two ran on trees 76 commits behind the fix, still showing the old bare assertion at test.py:180. Nothing has failed on a tree that carries the fix.

Comment thread src/Parsers/parseQuery.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 9, 2026 19:22
… of the query

Without highlighting (the normal server-side exception path) the excerpt after
`failed at position N (end of query):` starts at the error position, so for
`SELECT (1, 2` there was nothing left to show and the message degraded to a bare `: .`.
When the parser stopped at `EndOfStream` or `;`, start the excerpt at the innermost
bracket that is never closed instead: it is the one nearest to the mistake, and the
excerpt then covers everything from that bracket to the end of the statement.

Addresses the AI Review Major on `src/Parsers/parseQuery.cpp`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
diagnostics->error_token = scoped_parens[0];
out_error_message = getUnmatchedParenthesesErrorMessage(
query_begin, statement_end, scoped_parens, hilite, query_description);
query_begin, statement_end, scoped_parens, last_token, hilite, query_description);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getUnmatchedParenthesesErrorMessage now derives a better error_token from last_token, but tryParseQuery still stores scoped_parens[0] in ParserDiagnostics. That breaks the documented "error_token is the token the error message points at" contract: utils/wasm-parser/wasm_parser.cpp serializes diagnostics.error_token into error.begin / error.end, so ch_parse("SELECT count(* FROM numbers(10)") will still point the browser/editor at the ( while the text message now says failed at position 16 (FROM).

Please drive diagnostics->error_token from the same selection as the message cursor here (or return that token from the formatter helper), and add a utils/wasm-parser/test.mjs case for unmatched parentheses so the JSON API cannot drift from the text error again.

@qoega qoega self-assigned this Sep 10, 2026
@qoega
qoega added this pull request to the merge queue Sep 10, 2026
Merged via the queue into master with commit 91aa950 Sep 10, 2026
175 checks passed
@qoega
qoega deleted the improve-sql-error-messages branch September 10, 2026 09:06
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants