Skip to content

Let the promql dialect keep tokens the SQL lexer rejects - #115073

Merged
alexey-milovidov merged 31 commits into
ClickHouse:masterfrom
valerypetrov:promql-dialect-lexer-115071
Oct 1, 2026
Merged

alexey-milovidov merged 31 commits into
ClickHouse:masterfrom
valerypetrov:promql-dialect-lexer-115071

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

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 PromQL queries with regex label matchers (=~, !~) being rejected under --dialect promql.

Closes #115071.


Under --dialect promql, ParserPrometheusQuery reads the raw query text and hands it to the PromQL grammar; it walks the SQL tokens only to find where the statement ends. But tryParseQuery scans those tokens for lexer errors before the parser runs, and ~ is not a SQL token, so the query was rejected before it ever reached the PromQL grammar:

$ clickhouse local --dialect promql -q 'up{instance="host1"}'
Code: 471. ... The name of a TimeSeries table to use with promql dialect is not specified

$ clickhouse local --dialect promql -q 'up{instance=~"host2|host3"}'
Code: 62. ... Unrecognized token: Syntax error: failed at position 13 (~)

The equality matcher gets through to a missing-setting error; the regex matcher dies at the ~ with a SQL lexical error. It is not specific to -q — stdin and --queries-file fail identically. The grammar itself already has the tokens (PromQLLexer.g4: RE : '=~', NRE : '!~'), and the same expression works when passed as a string to the table function, which is what makes the limitation easy to miss.

IParser gains consumesRawText(), false by default and overridden by ParserPrometheusQuery. tryParseQuery skips its two lexical-error rejections for such parsers, since a token the SQL lexer does not recognise is not an error for a parser that reads the text itself. No call site changes, and any future dialect parser in the same position gets the behaviour by overriding one method.

This is safe because the lexer does not stop at an unrecognised character — it consumes it and returns an Error token (Lexer.cpp:546), so statement-boundary detection still finds the terminating semicolon.

Kusto solves the same problem with an entire parallel parseKQLQuery.{h,cpp}; PromQL needs only the boundary scan, so a virtual on IParser seemed proportionate. Happy to go the separate-entry-point route instead if maintainers prefer the consistency.


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

Version info

  • Merged into: 26.10.1.1129-master (included in 26.10 and later)

The promql dialect parses the raw query text with its own grammar and uses the SQL
tokens only to find the end of the statement, but tryParseQuery rejected the query
first when the lexer produced an error token, so no PromQL regex matcher could run.

Closes ClickHouse#115071

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XvXEBdaJTCCnUdunCf8icr
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f0fa8bc]

Summary: ✅


AI Review

Summary

This PR fixes the raw-text dialect handoff so PromQL regex matchers like =~ / !~ are no longer rejected by the SQL lexer before the PromQL grammar sees them, while still preserving native ClickHouse handling for SET, SET ROLE, and SET TRANSACTION SNAPSHOT. The current head also closes the follow-up regressions around max_query_size, semicolons inside PromQL # comments, multi-statement parsing, and foreign SET forms in the polyglot dialect; the added stateless tests cover those paths directly.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit f0fa8bc.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 121/126 (96.03%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 17, 2026
Comment thread src/Parsers/parseQuery.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f0fa8bc47 with master 5ac4352fc (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.

Compile time of recompiled translation units

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

Job report

@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Aug 17, 2026
… check for them too

The raw-text carve-out disabled the lexical pre-scan entirely, so an
oversized PromQL query would never hit the terminal
ErrorMaxQuerySizeExceeded error and would fall through into the
dialect parser's own scan loop, which doesn't check for it either.

Separately, TokenIterator::isValid() treats any error token (not just
EndOfStream) as end-of-stream, since the Error* enum values sit after
EndOfStream. checkUnmatchedParentheses relies on isValid() to walk the
token stream, so a lexer-rejected token appearing before a later
closing paren (e.g. sum(up{instance=~"...")) made the '(' read as
unmatched. Skip that check for raw-text parsers too.
Comment thread src/Parsers/parseQuery.cpp Resolved
Raw text starting with tokens that happen to match INSERT_INTO (e.g.
promql text like "INSERT INTO x FORMAT Values ...") skipped the
pre-scan entirely via case 1's carve-out, losing the
ErrorMaxQuerySizeExceeded bailout for that input and falling through
to the dialect parser's own scan loop, which doesn't check for it
either.
It has the exact same shape as ParserPrometheusQuery: it consumes the
remaining input itself as opaque foreign SQL and only uses the SQL
tokens to find the statement end, so a lexer-rejected token in that
foreign syntax shouldn't fail parseQuery.cpp's pre-scan before
parseImpl() ever runs.
Comment thread src/Parsers/parseQuery.cpp Resolved
ParserPrometheusQuery and ParserPolyglotQuery both try a plain SET
query first and only consume the raw text if that fails. The pre-scan
was keying its lexical strictness off consumesRawText() alone, so a
malformed SET (e.g. containing a token the SQL lexer rejects) skipped
the ordinary lexical check and got reinterpreted as dialect text
instead of reporting a normal syntax error.
Comment thread src/Parsers/parseQuery.cpp Resolved
The bareword "SET" heuristic misfired on raw dialect text whose first
identifier just happens to be spelled "set" (e.g. a PromQL metric
named set{...}), rejecting valid queries with a spurious lexical
error. A throwaway ParserSetQuery parse - the exact grammar
ParserPrometheusQuery/ParserPolyglotQuery use for the real decision -
correctly rejects "set{" and keeps the raw-text carve-out for it.
Comment thread src/Parsers/parseQuery.cpp Resolved
valerypetrov and others added 3 commits August 17, 2026 21:24
A failed ParserSetQuery trial can't tell "this doesn't start with
SET" from "this starts with SET but the rest is malformed" - both
return false, so a query like SET max_threads = ~1 was wrongly
falling back to the dialect parser instead of getting the ordinary
SQL syntax error. Expected::max_parsed_pos already tracks how far a
parse attempt got regardless of success, so check whether it advanced
past the trial's starting position: if it did, the SET keyword itself
matched and we're committed to SET grammar even though the rest
failed, so the ordinary lexical check still applies.
… progress

Any partial progress of the throwaway ParserSetQuery flipped committed_to_set,
so a PromQL metric named 'set' (e.g. set{instance=~"host2|host3"}) lost the
raw-text carve-out: the bareword 'set' matched the SET keyword, the failed
identifier parse at '{' advanced Expected::max_parsed_pos, and the prescan
rejected the valid '~' before PromQL ever saw it.

Probe only for a 'SET <identifier>' prefix instead. Every real SET statement
- valid or malformed - starts that way and keeps the strict lexical prescan
(so 'SET max_threads = ~1' still gets the ordinary SQL error), while a bare
metric 'set' continued by '{', '[', '@', an operator or end of query cannot,
matching how ParserPrometheusQuery/ParserPolyglotQuery themselves dispatch.
The probe now also runs only for raw-text parsers.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XvXEBdaJTCCnUdunCf8icr
Comment thread src/Parsers/parseQuery.cpp Resolved
valerypetrov and others added 2 commits August 19, 2026 18:52
The SET <setting> shorthand accepted 'set or' / 'set offset' and left the
rest of a PromQL query unparsed. Share one committed-to-SET discriminator
between tryParseQuery and the promql/polyglot dialect parsers, commit on
any 'SET <non-PromQL-keyword identifier>' prefix so a malformed SET
without '=' keeps the ordinary lexical error, and only try ParserSetQuery
when committed.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
valerypetrov and others added 3 commits August 25, 2026 21:21
…tedToSetQuery

ParserIdentifier accepts any bareword unconditionally, and none of these
four keywords are in is_promql_keyword, so the general "SET <setting>
that is not a PromQL keyword" branch a few lines down already returns
true for all of them. The special-cased early return can never fire a
different verdict than the fallthrough, so it's dead.

Co-Authored-By: Claude Opus 5 <[email protected]>
Gating on isCommittedToSetQuery is right -- it stops the `SET <setting>`
shorthand swallowing foreign text that merely starts with `set`. Returning its
result directly is not: ParserSetQuery deliberately declines `SET TRANSACTION
...` so ParserTransactionControl can take it, and ParserPolyglotQuery is the
only top-level parser for this dialect, so a decline became a syntax error
instead of reaching the transpiler.

Trying the SET parser and falling through on failure keeps both properties.

The prometheus parser deliberately keeps the direct return: a declined SET
there has nowhere useful to fall through to, and reporting the SET error beats
reporting a PromQL parse error for the same input.

Co-Authored-By: Claude Opus 5 <[email protected]>
`SET` with no setting name is not distinguishable from a malformed query over
a metric named `set`, so the active dialect reports it rather than the SQL
lexer. Pin that with `SET ~` / `SET ~1`, and pin `set # trailing comment`
alongside it: `#` lexes as a SQL Error token but opens a PromQL comment
(PromQLLexer.g4 SL_COMMENT), so committing to SET on the token after the
keyword would reject valid PromQL.

Cover the polyglot half of the same carve-out in 04039: a real SET still
reaches the SQL parser, and `SET ~` reaches the dialect parser rather than
being stopped by the lexer before it. Assert on the error naming polyglot
rather than on the absence of `Unrecognized token` -- the sqlite transpiler
passes `SET ~` through verbatim, so the re-parse of the transpiled SQL
reports the lexical error anyway, nested inside the transpiler error.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Thanks — the mechanism is right. isCommittedToSetQuery does return false for SET ~, so the input keeps consumes_raw_text = true and reaches the dialect parser instead of the lexical-error path. Two things I found checking it, though.

The polyglot half of the finding doesn't reproduce. SET ~ under --dialect polyglot still reports Unrecognized token. The sqlite transpiler accepts SET ~ and returns it verbatim, so ParserPolyglotQuery re-parses that output with the ordinary ParserQuery, whose prescan rejects the ~ as before — the lexical error just arrives wrapped in "Error while parsing the SQL query generated by polyglot transpiler". Nothing was lost on that path, so the concern is promql-only.

On promql, the delta is smaller than it looks:

master:  Code: 62.  Unrecognized token: Syntax error: failed at position 5 (~)
this PR: Code: 756. token recognition error at: '~' at position 4 while parsing PromQL query: SET ~

Same character, and the second additionally names the grammar that rejected it. SET dialect = 'clickhouse' is unaffected — it has an identifier followed by =, so it takes the TokenType::Equals branch and is fully committed to SET. Recovering from a wrong dialect never went through this path.

The suggested rule breaks valid PromQL. parseQuery.cpp cannot evaluate the raw-text grammar, so the only approximation available there is token adjacency: an error token immediately after the SET keyword means a malformed SET. That rejects PromQL comments:

contrib/antlr4-grammars/promql/PromQLLexer.g4:225:  SL_COMMENT : '#' .*? '\n' -> channel(COMMENTS);

# lexes as a SQL Error token, so set # comment\n — valid PromQL, checked against a build — would be reclassified as a malformed SET and rejected. The wider reading ("any error token in a statement starting with SET") is worse: it rejects set{instance=~"host2|host3"}, which is the case this PR exists to fix.

So the ambiguity is real, and I think it is correctly resolved in favour of the active dialect: set is a legal metric name, and SET <no identifier> <junk> is not distinguishable from a malformed query over that metric without importing the dialect grammar into the SQL layer.

On the tests — added to 04910:

  • SET ~ and SET ~1, pinning the no-identifier path to the PromQL error
  • set # trailing comment, so the comment-breaking rule above cannot be introduced later by accident

and to 04039, for the polyglot side of the same carve-out:

  • SET dialect = 'clickhouse' still handled as ClickHouse SQL
  • SET ~ reaching the transpiler rather than being stopped by the lexer before it

One related thing your comment made me look at, which I've left alone as out of scope: ParserPrometheusQuery::parseImpl checks table_name.empty() before parsing the text, so with no promql_table set, any malformed query — not just SET — reports the missing-table error rather than the syntax error. Moving that check below the PrometheusQueryTree construction would fix it for every input at once. Happy to do it here or in a follow-up if you think it belongs.

alexey-milovidov and others added 2 commits September 23, 2026 01:36
…ex_matcher`

Master renamed the insertable `time_series` column of the `TimeSeries` table
engine to `samples`, so the test's fixture insert failed with
`NO_SUCH_COLUMN_IN_TABLE` after merging master.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (clean, no conflicts). The previous only red (Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6) session timeout) was unrelated, as @groeneai analysed above; this push starts a fresh CI run.

After the merge, 04910_promql_dialect_regex_matcher needed a one-line update: master renamed the insertable time_series column of the TimeSeries engine to samples, so the fixture insert failed with NO_SUCH_COLUMN_IN_TABLE. Fixed in 0bc49b6. With a local build of the merged head, both 04910_promql_dialect_regex_matcher and 04039_polyglot_sql_transpiler pass.

Comment thread src/Parsers/parseQuery.cpp Resolved
…omment

`ParserPrometheusQuery` took the statement end from the SQL token stream, but the SQL lexer
treats `#` as a comment only when a space follows it, so in `up #keep ; comment` the `;` ended
the statement and the rest was rejected as a second statement. Now the end is found by scanning
the raw text with the PromQL lexical rules (`#` comments, quoted and backquoted strings). When the
SQL tokens straddle that end (e.g. an apostrophe in a comment opens a SQL string literal running
past it), the parser fails with a clear error instead of guessing a split.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Address review: the SQL prescan in `tryParseQuery` stops at the first `;`,
which may be inside a PromQL `#keep ; ...` comment, so a query crossing
`max_query_size` only after it reached `ParserPrometheusQuery`, whose
lookahead waited for `EndOfStream` while the lexer returned
`ErrorMaxQuerySizeExceeded` forever. The lookahead now fails on that token,
and `tryParseQuery` reports it as the lexical error even for raw-text
parsers. `ParserPolyglotQuery` had the same unbounded loop.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
valerypetrov and others added 2 commits September 23, 2026 09:16
The lookahead advanced the maximum parsed position of the shared `Tokens` to the end of input, and `tryParseQuery` reports that position as the end of the query, so in multi-statement input every statement after the first PromQL one was skipped. Scan the PromQL text only up to the next SQL `;` that is not inside a PromQL comment or string. This also removes the dead store `clang-tidy` reported for `text_end`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Picks up a2ff290, which fixed the REPLICA_ALREADY_EXISTS race in
test_active_node_owned_by_another_server that was the only red.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The lookahead rescanned the text from the start of the statement for every
SQL `;` token. When many `;` sit in a PromQL `#` comment, as in `up #;;;;...`,
parsing took quadratic time: 1.3 s for a 250 KB query, against 0.08 s for the
same length without `;`. The scanner now keeps its position and whether it is
inside a comment or a string between calls, so each byte is read once. The
result is the same as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits September 28, 2026 09:05
…ach the transpiler

`ParserPolyglotQuery` took any `SET` that `ParserSetQuery` could parse a prefix of,
so MySQL `SET SESSION sql_mode = 'ANSI_QUOTES'` was read as the shorthand `SET SESSION`
(`SESSION = true`) followed by trailing junk, and `tryParseQuery` rejected it before
`polyglot_transpile` ever saw it. Now the ClickHouse `SET` path is taken only when it
consumes the whole statement; otherwise the input falls through to the transpiler.

Addresses the review comment on `src/Parsers/Polyglot/ParserPolyglotQuery.cpp`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits September 28, 2026 13:47
…r path

The previous fix sent every `SET` that `ParserSetQuery` parsed only partially to
`polyglot_transpile`. That was too broad: `SET max_threads = 1 garbage` and
`SET ROLE NONE garbage` then failed inside the transpiler instead of reporting the
ordinary excess-input `SYNTAX_ERROR`. Now only a `SET` that stops right after the
`SET <setting>` shorthand (as in MySQL `SET SESSION sql_mode = ...`) falls through.
Any other successfully parsed `SET` / `SET ROLE` is kept, and the caller reports the
trailing token.

Addresses the review comment on `src/Parsers/Polyglot/ParserPolyglotQuery.cpp`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A `SET` that stopped right after the `SET <identifier>` shorthand was
always rewound and sent to `polyglot_transpile`, so a malformed ClickHouse
shorthand like `SET max_threads garbage` got a transpiler failure instead of
the ordinary syntax error. Restrict the rewind to words MySQL and PostgreSQL
put after `SET` that are not ClickHouse settings (`SESSION`, `GLOBAL`,
`LOCAL`, `PERSIST`, `PERSIST_ONLY`, `NAMES`, `CHARACTER`, `TIME`).

Addresses review feedback on ClickHouse#115073

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`ParserSetQuery` parses `SET TIME ZONE 'tz'` itself, so `TIME` is not a foreign-only
prefix: a shorthand `SET TIME` followed by junk is a malformed ClickHouse `SET` and must
report the ordinary syntax error rather than go to `polyglot_transpile`. Drop it from
`isForeignSetPrefix` and add the case to `04039`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…nd polyglot dialects

`isCommittedToSetQuery` commits to SET for `SET TRANSACTION SNAPSHOT 1`, but `ParserSetQuery`
declines `SET TRANSACTION ...`, so `ParserPrometheusQuery` rejected the valid statement and
`ParserPolyglotQuery` passed it to the transpiler. Try `ParserTransactionControl` after
`ParserSetRoleQuery` and `ParserSetQuery`, as `ParserQuery` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 5ac4352fc

Suite Baseline Current Delta
Prometheus compliance 98.70% 98.70% +0.00%
Extended support (upstream engine tests) 86.75% 86.75% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 532 -> 532 (+0) 3 -> 3 (+0) 4 -> 4 (+0)
Extended support (upstream engine tests) 635 -> 635 (+0) 79 -> 79 (+0) 18 -> 18 (+0)

Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream 3da2514eff5c.

Note: Prometheus compliance score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit d237a56 Oct 1, 2026
149 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
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 comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... 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.

PromQL dialect: regex label matchers (=~ / !~) are rejected by the SQL tokenizer

5 participants