Repository navigation
Let the promql dialect keep tokens the SQL lexer rejects - #115073
alexey-milovidov merged 31 commits into
Conversation
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
|
Workflow [PR], commit [f0fa8bc] Summary: ✅
AI ReviewSummaryThis PR fixes the raw-text dialect handoff so PromQL regex matchers like Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit f0fa8bc.
Changed lines: Changed C/C++ lines covered: 121/126 (96.03%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units1046 translation units recompiled, 6495 s compile time in total, 1046 of them have a recent master baseline. |
… 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.
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.
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.
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.
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
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
…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
|
Thanks — the mechanism is right. The polyglot half of the finding doesn't reproduce. On promql, the delta is smaller than it looks: Same character, and the second additionally names the grammar that rejected it. The suggested rule breaks valid PromQL.
So the ambiguity is real, and I think it is correctly resolved in favour of the active dialect: On the tests — added to
and to
One related thing your comment made me look at, which I've left alone as out of scope: |
…lect Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
…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]>
|
🕵 Merged current After the merge, |
…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]>
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]>
…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]>
…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]>
PromQL Compliance ReportBaseline: S3 master
Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream Note: Prometheus compliance score is unchanged vs baseline. |
Changelog category (leave one):
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,ParserPrometheusQueryreads the raw query text and hands it to the PromQL grammar; it walks the SQL tokens only to find where the statement ends. ButtryParseQueryscans 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: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-filefail 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.IParsergainsconsumesRawText(), false by default and overridden byParserPrometheusQuery.tryParseQueryskips 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
Errortoken (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 onIParserseemed 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
26.10.1.1129-master(included in26.10and later)