Repository navigation
Fix AST formatting roundtrip for SOME used as a function name - #120096
Conversation
On the right-hand side of a comparison the parser reads SOME as the array-quantifier keyword. That lookahead (ParserExpressionImpl::tryParseOperand) requires exactly one expression before the closing parenthesis, so SOME(a, b -> 1) fails it, rewinds, and the tokens are re-read as an ordinary function call named SOME whose argument list folds a, b -> body into a single lambda. ASTFunction::formatImpl printed that name through backQuoteIfNeed, which force-quotes a curated list of keyword-valued identifiers in writeProbablyQuotedStringImpl. The list existed for exactly this problem and already carried the quantifier twin ALL, but not SOME, so the name was emitted bare. Re-parsing the emitted text, the bare SOME matched the keyword again, and the content was now a single expression because the formatter had parenthesised the lambda parameter list, so the quantifier path fired and rewrote the node to arrayExists. The trees no longer matched, and on a build with assertions the format-and-re-parse consistency check in executeQuery.cpp raised LOGICAL_ERROR. Two more spellings reach the same abort. The parser drops the ALL aggregate qualifier, so SOME(ALL 2) also collapses to one expression on the way back. And the quantifier has a second branch: a subquery argument, which is rewritten to IN rather than to arrayExists, so `SOME`((SELECT 1)) breaks too. Quoting the name fixes all three at once, because it acts before the parser chooses a branch. ANY is deliberately left out of the list. A function named ANY with a non-subquery argument round-trips unchanged, but the back-quoted subquery spelling `ANY`((SELECT 1)) does not, on master as much as here: the name is emitted bare and read back as the quantifier, so the node becomes IN. Adding any to this list would fix that at the cost of back-quoting the any aggregate function in every EXPLAIN SYNTAX and SHOW CREATE output, which is a different change with a different blast radius, so this commit keeps to the name CI produced. Only formatter output changes. The parser has always accepted both spellings, so metadata written by a new server is readable by an old one and vice versa, and no setting or serialization surface is involved. Found by BuzzHouse (`amd_debug`) on an unrelated pull request: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119879&sha=0199ffe61fe62ba19ccb3c42c9335eab0a34b431&name_0=PR&name_1=BuzzHouse%20%28amd_debug%29 Related: ClickHouse#119879 Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Before publishing I reviewed this change independently and then ran a second model over it, for three
Severity: ❌ blocker / What I checked myself, beyond the second model, because these were the claims most worth falsifying: Session id: cron:clickhouse-review-slot-8:20260914-221400 |
|
Workflow [PR], commit [dbaf809] Summary: ✅
AI ReviewSummaryThis PR fixes AST formatting round-trips for a function named PR Metadata
### Changelog category (leave one):
- Bug Fix
Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit dbaf809.
Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing Binary sizes
|
| Binary | Master | PR | Δ |
|---|---|---|---|
programs/clickhouse-stripped |
718.85 MiB | 747.20 MiB | +28.35 MiB (+3.94%) |
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.
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
7 translation units recompiled, 5 s compile time in total, 7 of them have a recent master baseline.
Symbol sizes ⚠️
| Binary | Symbol | Master | PR | Δ |
|---|---|---|---|---|
programs/clickhouse-keeper |
_ZZN24TopLevelDomainLookupHash7isValidEPKcmE8wordlist |
new | 864.07 KiB | +864.07 KiB |
programs/clickhouse |
_ZZN24TopLevelDomainLookupHash7isValidEPKcmE8wordlist |
new | 864.07 KiB | +864.07 KiB |
programs/clickhouse-keeper |
wordlist |
new | 242.38 KiB | +242.38 KiB |
programs/clickhouse |
wordlist |
new | 242.38 KiB | +242.38 KiB |
programs/clickhouse |
rd_kafka_properties |
new | 131.25 KiB | +131.25 KiB |
programs/clickhouse-keeper |
_ZGRN2DB12_GLOBAL__N_15nounsE_ |
new | 102.33 KiB | +102.33 KiB |
programs/clickhouse |
_ZGRN2DB12_GLOBAL__N_15nounsE_ |
new | 102.33 KiB | +102.33 KiB |
programs/clickhouse |
a_2 |
new | 82.50 KiB | +82.50 KiB |
programs/clickhouse-keeper |
a_2 |
new | 82.50 KiB | +82.50 KiB |
CI finish ledger - 4160d50Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260915-030045 |
| && !isParsedAsLiteral(s) | ||
| && !isCaseInsensitiveEqual(s, "distinct") | ||
| && !isCaseInsensitiveEqual(s, "all") | ||
| /// The parser can consume a bare `SOME` as the array-quantifier keyword, which rewrites the |
There was a problem hiding this comment.
There are two quantifier forms here and they behave differently.
The array/expression form this PR fixes has no ANY counterpart. ANY is excluded from that path deliberately (ExpressionListParsers.cpp:3582-3583: "ANY is excluded from the array form because any is also an aggregate function"; the guard is (some_kw || all_kw) at :3596), so a function named ANY is never read back as a quantifier there. Measured on this branch's build:
formatQuerySingleLine('SELECT 1 < ANY(a, b -> 1)') -> SELECT 1 < ANY((a, b) -> 1) (idempotent)
formatQuerySingleLine('SELECT 1 < ANY([1, 2, 3])') -> SELECT 1 < ANY([1, 2, 3]) (not rewritten)
formatQuerySingleLine('SELECT 1 < SOME([1, 2, 3])') -> SELECT arrayExists(lambda(tuple(_a), 1 < _a), [1, 2, 3])
The subquery form does break for ANY, since that path is shared by all three keywords (:3592):
-- both measured on this branch, debug build
SELECT 1 = `any`((SELECT 1));
-- Logical error: 'Inconsistent AST formatting', executeQuery.cpp:2499, SIGABRT
-- original: equals(1, any(Subquery))
-- re-parsed: in(1, Subquery)
SELECT formatQuerySingleLine('CREATE VIEW v AS SELECT 1 = `any`((SELECT 1))');
-- CREATE VIEW v AS SELECT 1 = any((SELECT 1)) <- quotes dropped, so the stored text means INALL survives that only because all is already in this list.
The same one-line predicate is not free for any, though. Nothing in src/ registers a function named some, so quoting it changes no output anywhere. any is a registered aggregate (AggregateFunctionAny.cpp:453), so the predicate would back-quote every any(...) the formatter emits: EXPLAIN SYNTAX, stored view/MV DDL, SHOW CREATE; 8 files under tests/queries/0_stateless/*.reference record formatted any(...) today. The narrower option is to quote the name in ASTFunction::formatImpl only when the single argument is a subquery, which leaves any(x) printing as it does now.
My plan is to keep this PR to the array-quantifier fix and send ANY separately, so that formatting change can be judged on its own. If you would rather have it here, say so and I will fold it in.
There was a problem hiding this comment.
Sent as #120175, with the narrower ASTFunction predicate.
New since the comment above: it does not need a typed back-quote at all. FunctionNameNormalizer rewrites the registered aliases any_value and first_value to any inside the interpreter, which is after the parse-time format check, so plain CREATE VIEW v AS SELECT 1 = first_value((SELECT 1)) stores = any((SELECT 1)) and system.tables.create_table_query reads that view back as 1 IN (SELECT 1), with nothing reported.
Co-Authored-By: Claude Opus 5 <[email protected]>
|
|
| && !isParsedAsLiteral(s) | ||
| && !isCaseInsensitiveEqual(s, "distinct") | ||
| && !isCaseInsensitiveEqual(s, "all") | ||
| /// The parser can consume a bare `SOME` as the array-quantifier keyword, which rewrites the |
There was a problem hiding this comment.
This looks like the right code fix, but the PR metadata should not be CI Fix or Improvement. The bug is user-visible in src/ and is still present on 26.8 too (writeProbablyQuotedStringImpl there still lacks some while ExpressionListParsers.cpp already has the SOME quantifier path), so leaving it under the CI-only category would drop it from the release notes. Please switch the template category to Bug Fix; the existing changelog entry is already specific enough for that category.
There was a problem hiding this comment.
Agreed, and switched: the category is now Bug Fix (user-visible misbehavior in an official stable release).
I checked your premise on an official 26.8.4.11 build before changing it, because the debug-only Inconsistent AST formatting check would not justify that category on its own. It holds, through a supported path:
CREATE FUNCTION some AS (x) -> x + 100;
CREATE FUNCTION gate AS (y) -> y < `some`(2);
SELECT gate(1); -- 126.8.4.11 writes the second one to user_defined/function_gate.sql as CREATE FUNCTION gate AS y -> (y < some(2)), i.e. without the back-quotes. A fresh server process re-reads that file, and the same query then answers
Code: 43. DB::Exception: Argument 2 of function arrayExists must be Array. Found UInt8 instead. (ILLEGAL_TYPE_OF_ARGUMENT)
instead of 1. So a released server persists a definition it cannot read back, which is the user-visible half you are pointing at. With this fix the file keeps its back-quotes and reloads.
I did not keep the changelog entry as written. It led with the debug/sanitizer LOGICAL_ERROR, which is the wrong symptom for a release note under this category, so it now names the formatter output and the persisted-function effect instead. The new test does fail without the fix (5 of its 8 output lines differ on 26.8.4.11), so Bugfix validation has a reproducer to catch.
|
@groeneai @PedroTadim — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Reproducer-- Formatter output does not survive a re-parse
SELECT formatQuerySingleLine(formatQuerySingleLine('SELECT 1 = `SOME`((SELECT 1))'));
-- 26.3.33.24 .. 26.8.11.7: SELECT 1 IN (SELECT 1) fixed: SELECT 1 = `SOME`((SELECT 1))
SELECT formatQuerySingleLine(formatQuerySingleLine('SELECT 1 < SOME(a, b -> 1)'));
-- 26.6.8.7 .. 26.8.11.7: SELECT arrayExists(lambda(tuple(_a), 1 < _a), ((a, b) -> 1)) fixed: SELECT 1 < `SOME`((a, b) -> 1)
-- User-visible: a UDF body is persisted without the quotes and changes meaning after a restart
CREATE FUNCTION some AS (x) -> x + 100;
CREATE FUNCTION gate2 AS (y) -> y = `some`((SELECT 1));
SELECT gate2(101); -- 1
-- restart (or re-run clickhouse-local with the same --path); user_defined/function_gate2.sql now holds y -> (y = some((SELECT 1)))
SELECT gate2(101); -- 0 on 26.3.33.24 and 26.8.11.7 (re-read as y IN (SELECT 1)); 1 with the fix
-- 26.6.8.7 .. 26.8.11.7: CREATE FUNCTION gate AS (y) -> y < `some`(2) instead fails after restart with ILLEGAL_TYPE_OF_ARGUMENT (Argument 2 of function arrayExists must be Array)Results:
Backport the fix to CC component owner: @alexey-milovidov @vitlibar Analysis metadata
Introducing change: not identified
|
Related: #119879
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed non-idempotent formatting of a function named
SOME: the name was printed unquoted, so the server read its own output back as theSOMEarray quantifier.formatQuery('SELECT 1 < SOME(a, b -> 1)')returned a query that re-parses toarrayExists, and a user-defined function whose body compared against`some`(...)was persisted without the quotes and then failed to load after a restart.Description
On the right of a comparison the parser reads
SOMEas the array-quantifier keyword. That lookahead needs exactly one expression before), soSOME(a, b -> 1)rewinds and the tokens are re-read as an ordinary function namedSOME. The formatter printed that name throughbackQuoteIfNeed, whose keyword list inwriteProbablyQuotedStringImplforce-quotes identifiers the parser would read back as something else.somewas missing while its quantifier twinallwas present, so the name came out bare, and re-parsing matched the keyword again (the formatter had parenthesised the lambda parameters, so the content was a single expression), rewriting the node toarrayExists.This adds the missing entry, which also covers the quantifier's subquery branch, where the argument becomes
INinstead (1 = `SOME`((SELECT 1))): quoting acts before the parser picks a branch. Only formatter output changes and the quoted spelling has always parsed, so existing metadata still loads.Not debug-only, which is why the category is
Bug Fix. On official 26.8.4.11,CREATE FUNCTION some AS (x) -> x + 100; CREATE FUNCTION gate AS (y) -> y < `some`(2);persistsuser_defined/function_gate.sqlasy -> (y < some(2)), and a restart turnsSELECT gate(1)from1intoILLEGAL_TYPE_OF_ARGUMENT: Argument 2 of function arrayExists must be Array. With this fix the file keeps its quotes and reloads.ANYbreaks identically in the subquery spelling and is deliberately unchanged here: quotinganywould back-quote theanyaggregate function in everyEXPLAIN SYNTAXandSHOW CREATE. It is tracked as a separate change.Found by BuzzHouse (
amd_debug) on an unrelated PR: CI report. The same list previously gainedfrom/values(#102338),inf/nan/true/false(#116802) andtop(#118754).New test
05213_some_keyword_quotingpins the three carriers, formatting idempotency, unchangedALL,somex/some_1controls, and the quantifier feature itself.Workflow [PR]
Sync PR [sync-upstream/pr/120096]
Version info
26.9.1.1532(included in26.9and later)