Skip to content

Scope parser error messages to the current statement - #105480

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-parser-excessive-output-101509
Jun 26, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-parser-excessive-output-101509

Conversation

@groeneai

@groeneai groeneai commented May 20, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #101509.

Three error paths in tryParseQuery (lookahead lexical error, post-parse lexical error, unmatched parentheses) passed all_queries_end to the error formatter instead of the end of the current statement. Under clickhouse-local --ignore-error over a multi-statement input, each error included every subsequent statement, producing O(N^2) output for N malformed statements.

The fix walks a fresh iterator from the start of the token stream to the next ; (or end of input) and uses that as the error-message end. The result is clamped to at least last_token.end to keep writeQueryAroundTheError from underflowing size_t when parser backtracking pushes the highlighted token past the next semicolon. That underflow is the failure mode that killed the earlier attempt in PR #101708 as "Server died" in Fast test.

For the unmatched-parens path the reported paren list is also filtered to parens that fall inside the current statement, so the highlight loop's assert(current_position_to_hilite <= end) in writeQueryWithHighlightedErrorPositions cannot fire on parens belonging to later statements.

Regression test 04262_no_excessive_output_on_lexical_error.sh exercises all three paths: 10 identical bad statements produce 10 error mentions of the offending text (not 10 + 9 + ... + 1 = 55). A sanity case ensures 10 valid statements produce 0 error lines.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed an issue where running multiple statements in clickhouse-local --ignore-error would echo every subsequent statement inside the error message for each lexical error or unmatched-parenthesis error.

Version info

  • Merged into: 26.7.1.128

Three error paths in `tryParseQuery` (lookahead lexical error,
post-parse lexical error, unmatched parentheses) passed
`all_queries_end` to the error formatter instead of the end of the
current statement. Under `clickhouse-local --ignore-error` over a
multi-statement input, each error included every subsequent statement,
producing O(N^2) output for N malformed statements.

Compute the current statement end via a fresh iterator walk from the
start of the token stream. Clamp to `last_token.end` to keep
`writeQueryAroundTheError` from underflowing `size_t` when parser
backtracking pushes the highlighted token past the next `;` (the
failure mode that killed PR ClickHouse#101708 in `Fast test`).

Closes ClickHouse#101509.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session: cron:clickhouse-ci-task-worker:20260520-230000)

a) Deterministic repro? Yes. for _ in {1..10}; do printf 'SELECT 1 !;\n'; done | clickhouse-local --ignore-error 2>&1 | grep -cF 'SELECT 1' returns 55 without the fix and 10 with the fix. The 55 is the exact 10 + 9 + ... + 1 arithmetic-series pattern.

b) Root cause explained? Yes. Three error paths in tryParseQuery (lookahead lexical at line 307, post-parse lexical at line 339, unmatched parens at line 348) pass all_queries_end to the error formatter. writeQueryAroundTheError with hilite=true then writes the full byte range [query_begin, all_queries_end) into the error message, which includes every subsequent statement of a multi-statement input. PR #93876 only fixed the generic-syntax-error path (this_query_end_pos) and left these three.

c) Fix matches root cause? Yes. Each of the three sites now passes current_statement_end(min_end), a fresh walk from the start of the token stream to the next ; (or end of input), clamped to last_token.end. The clamp is not a defensive nice-to-have, it directly addresses the size_t underflow in writeQueryAroundTheError when parser backtracking has pushed the highlighted token past the next ; (that underflow is what killed PR #101708 in Fast test).

d) Test intent preserved / new tests added? New test 04262_no_excessive_output_on_lexical_error.sh covers all three paths with labeled output lines (so a CI diff identifies the regressing path) plus a sanity check that valid input produces zero error lines.

e) Demonstrated in both directions? Yes. Built without the patch: lookahead-lexical 55 / post-parse-lexical 55 / unmatched-parens 55 / no-false-positives 0. Built with the patch: lookahead-lexical 10 / post-parse-lexical 10 / unmatched-parens 10 / no-false-positives 0. Reference file matches the post-fix output exactly.

f) Fix is general? Yes. Same helper (current_statement_end lambda) used at all three sites. Did not touch the generic-syntax-error and excessive-input paths (lines 401, 411) since they use this_query_end_pos and are out of scope for #101509, but the helper would also apply there if a future fix decides to harden them.

@groeneai

groeneai commented May 20, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @evillique @alexey-milovidov @george-larionov: could you review? This is a follow-up to PR #93876 (which scoped only the generic syntax-error path) and supersedes the closed PR #101708. The clamp in the current_statement_end lambda guards against the size_t underflow in writeQueryAroundTheError that hit #101708 in Fast test.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1b595ba]

Summary: ✅


AI Review

Summary

This PR scopes the SQL parser's lexical-error and unmatched-parentheses diagnostics to the current statement for multi-statement input, and adds focused stateless coverage for the affected paths, including the max_query_size regression from the earlier attempt. I did not find unresolved correctness, safety, performance, or metadata issues that warrant inline review comments.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 21, 2026
The lambda walked tokens looking for `Semicolon` or `EndOfStream`, but once
the lexer is past `max_query_size`, `Lexer::nextToken` forces type
`ErrorMaxQuerySizeExceeded` on every call - including the natural
`EndOfStream`. The loop only checked `isEnd()`, so it never terminated:
each `++iter` pushed another zero-width error into `Tokens::data` and the
process appeared hung.

Surfaced as "Server died" in `Fast test` for test
`03328_syntax_error_exception`, which sends `SELECT '<long string>'` with
`max_query_size=20`. CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105480&sha=04a68f7fb9f730b55151fe49b994bd0eb875f396&name_0=PR&name_1=Fast%20test

Fix: stop the lambda on `ErrorMaxQuerySizeExceeded` too. Other lexer error
types (`Error`, `ErrorWrongNumber`, the unclosed-quote variants) are
recoverable - the lexer's `pos` keeps advancing past them and eventually
returns `EndOfStream` - so we still walk through them to reach the real
statement boundary. Confirmed locally that test `03328_syntax_error_exception`
case 3 (`SELECT ыыы'`) still reports `: ыыы'` in the error message.

Also extended the regression test `04262_no_excessive_output_on_lexical_error`
with a `max-query-size` path that exercises the hang directly: pre-fix the
shell call would not return within the test timeout, post-fix it returns
one error message immediately.

Verified with 20x `--test-runs` of both `03328_syntax_error_exception` and
`04262_no_excessive_output_on_lexical_error`: 40/40 pass.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fast test fix pushed (b302a7f)

Reproduced the Server died failure locally. Root cause: the current_statement_end lambda walked tokens checking only !isEnd() && != Semicolon, but once the lexer is past max_query_size, Lexer::nextToken forces ErrorMaxQuerySizeExceeded on every call (including overriding the natural EndOfStream). The loop never terminated; each ++iter pushed another zero-width error into Tokens::data. From a debug session: clickhouse-local --max_query_size=20 --query "SELECT '<300-byte-cyrillic-string>'" hangs at >30s on the parent commit, returns Code: 62 immediately on b302a7f.

The hang reproduces directly via tests/queries/0_stateless/03328_syntax_error_exception.sh case 1 (SELECT '<260-byte-string>' with max_query_size=20), which is exactly what Fast test runs.

Fix

Stop the loop on ErrorMaxQuerySizeExceeded as well. The other lexer error types (Error, ErrorWrongNumber, the unclosed-quote variants) are recoverable - the lexer's pos keeps advancing past them and eventually returns EndOfStream - so we still walk through them to reach the real statement boundary. I verified locally that the existing test 03328_syntax_error_exception case 3 (SELECT ыыы') still reports : ыыы' in the error message.

Pre-PR validation gate

(a) Deterministic repro? Yes - build/programs/clickhouse local --max_query_size=20 --query "SELECT '<long cyrillic string>'" hangs on the parent commit, returns immediately with the fix.
(b) Root cause explained? Yes - Lexer::nextToken at src/Parsers/Lexer.cpp:119 unconditionally overrides type to ErrorMaxQuerySizeExceeded whenever res.end > begin + max_query_size, even for EndOfStream. The lambda's !isEnd() check never sees end-of-input, so it spins.
(c) Fix matches root cause? Yes - explicit termination on the only token type that the lexer emits when it cannot make progress. Other error types still recover.
(d) Test intent preserved? Yes - original test paths in 04262_no_excessive_output_on_lexical_error still verify the three error paths produce O(N) instead of O(N^2) output. Added a new max-query-size path covering the previously-hanging case.
(e) Both directions demonstrated? Yes - parent commit hangs (>30s); b302a7f returns one error message. Verified with 20x --test-runs of 03328_syntax_error_exception and 04262_no_excessive_output_on_lexical_error: 40/40 pass locally.
(f) Fix is general? Yes - the lambda is called from all three error paths (lookahead lexical, post-parse lexical, unmatched parens), so one fix covers them all. Symmetric to this_query_end_pos walk at line 395 which already has the !isError() check.

Session: cron:clickhouse-ci-task-worker:20260521-011500

Fixes Build (arm_tidy) readability-use-std-min-max error introduced in
commit b302a7f.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed follow-up commit 8148731 to fix the Build (arm_tidy) failure on b302a7f.

clang-tidy 21 flagged the new if (paren.end > statement_end) statement_end = paren.end; block in the scoped-parens loop as readability-use-std-min-max. Replaced with statement_end = std::max(paren.end, statement_end). Identical semantics, one-line change. Builds cleanly on local clang-21 x86 debug.

Awaiting CI re-run.

(session cron:clickhouse-ci-task-worker:20260521-181500)

@robot2051

This comment was marked as outdated.

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA: 5e2f38256a3cc5bf7091e20006870095a2ca9f59

CI fully finished (Mergeable Check completed; 0 pending checks).

Check Test Disposition
Stateless tests (amd_tsan, parallel, 1/2) 00096_obfuscator_save_load, 00175_obfuscator_schema_inference flaky chronic trunk — tasks 2026-06-02-ci-00096obfuscatorsaveload-chronic-f / 2026-06-02-ci-00175obfuscatorschemainference-ab
Unit tests (asan_ubsan) (check-level) infra/chronic UBSan UntrackedMemoryCounter — task 2026-06-03-ci-p1-chronic-ubsan-in-untrackedmemoryc
Unit tests (asan_ubsan, function_prop_fuzzer) FunctionsStress.stress, AllTests follows the asan_ubsan check-level fail above (same UntrackedMemoryCounter teardown).
Unit tests (msan, function_prop_fuzzer) FunctionsStress infra/chronic msan-side counterpart of the same family.
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) 03100_lwu_07_merge_patches chronic flaky lightweight-updates merge-patches s3 test — unrelated to this parser-error-message scoping fix.

No PR-caused correctness failures. Awaiting human review.

Session: cron:our-pr-ci-monitor:20260604-213000

@clickhouse-gh

clickhouse-gh Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.50% 92.60% +0.10%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 31/31 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1b595ba

CI has fully finished (Finish Workflow + Mergeable Check passed; all test checks green on this master-merge head). Every red check has an owner below; only CH Inc sync is exempt.

Check / test Reason Owner
CH Inc sync — CH Inc sync (private, not actionable by us)

No functional/integration/stress/fuzzer/sanitizer/unit test failed on this head — the prior chronic flakies (AST fuzzer STID 1288-3bd5, obfuscator) did not recur after the master merge. Addresses issue #101509. Ready for review.

Session id: cron:our-pr-ci-monitor:20260625-170000

@alexey-milovidov alexey-milovidov self-assigned this Jun 26, 2026
@alexey-milovidov
alexey-milovidov merged commit 0209a7d into ClickHouse:master Jun 26, 2026
166 of 167 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 26, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…r-excessive-output-101509

Scope parser error messages to the current statement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default 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.

Incomplete fix: lexical error and unmatched parentheses paths still use all_queries_end, producing excessive output

4 participants