Skip to content

Fix AST formatting roundtrip for SOME used as a function name - #120096

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-some-keyword-quoting
Sep 15, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-some-keyword-quoting

Conversation

@groeneai

@groeneai groeneai commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119879

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 non-idempotent formatting of a function named SOME: the name was printed unquoted, so the server read its own output back as the SOME array quantifier. formatQuery('SELECT 1 < SOME(a, b -> 1)') returned a query that re-parses to arrayExists, 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 SOME as the array-quantifier keyword. That lookahead needs exactly one expression before ), so SOME(a, b -> 1) rewinds and the tokens are re-read as an ordinary function named SOME. The formatter printed that name through backQuoteIfNeed, whose keyword list in writeProbablyQuotedStringImpl force-quotes identifiers the parser would read back as something else. some was missing while its quantifier twin all was 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 to arrayExists.

This adds the missing entry, which also covers the quantifier's subquery branch, where the argument becomes IN instead (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); persists user_defined/function_gate.sql as y -> (y < some(2)), and a restart turns SELECT gate(1) from 1 into ILLEGAL_TYPE_OF_ARGUMENT: Argument 2 of function arrayExists must be Array. With this fix the file keeps its quotes and reloads.

ANY breaks identically in the subquery spelling and is deliberately unchanged here: quoting any would back-quote the any aggregate function in every EXPLAIN SYNTAX and SHOW CREATE. It is tracked as a separate change.

Found by BuzzHouse (amd_debug) on an unrelated PR: CI report. The same list previously gained from/values (#102338), inf/nan/true/false (#116802) and top (#118754).

New test 05213_some_keyword_quoting pins the three carriers, formatting idempotency, unchanged ALL, somex/some_1 controls, and the quantifier feature itself.


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

Version info

  • Merged into: 26.9.1.1532 (included in 26.9 and later)

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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
rounds (one full pass plus two fix rounds, each re-reviewed). 9 items in total: 6 agreed and fixed in the
branch, 3 disagreed with recorded evidence. Nothing is left open.

# Sev Finding Verdict Evidence / action
1 ⚠️ The reason given for leaving the sibling keyword ANY alone rested on two spellings that cannot build a function node holding a subquery argument, so it proved less than it claimed. AGREE, fixed Measured the missing spelling on both arms. It does break, on master too, so the claim was wrong. The commit message and PR body now say exactly what was measured, and the PR body asks the owner to rule on including any.
2 ⚠️ The comment above the new predicate claimed a column named SOME is also read back as a quantifier, and that the rewrite is always arrayExists. Neither holds: the keyword match rewinds unless a bracket follows, and = rewrites to has. AGREE, fixed Both overclaims removed.
3 💡 The quantifier has a subquery form as well as an array form, and only the array form was covered by the test. AGREE, fixed One assertion added. It is a third live carrier: it aborts on the unpatched build and passes with the fix.
4 💡 The rewritten comment enumerated the subquery branch as IN, but modifyAST has three outcomes (= gives in, <> gives notIn over singleValueOrNull, >/< compare against min(*)/max(*)). AGREE, fixed Folded with item 5.
5 💡 The same comment named only "after a comparison operator", but the lookahead is also entered for LIKE, ILIKE, REGEXP and IS [NOT] DISTINCT FROM. AGREE, fixed Items 4 and 5 were both symptoms of my own round-1 prescription asking for an enumeration inside a two-line comment, which is hostage to every branch it omits. Replaced with a statement of the invariant instead, which closes both.
6 ⚠️ The commit message omitted the CI report URL and the corresponding PR link that the in-tree contributor rules require. AGREE, fixed .claude/CLAUDE.md:169 and :176. The second model rated this a nit; I raised it, because a commit message is permanent history where a PR body is editable, and it was free to fix while the branch was unpushed. The closest precedent, 0e55f2820fcf8, ends the same way.
7 ⚠️ Those links should be added in a follow-up commit rather than by amending. DISAGREE False premise, measured: git ls-remote for the branch was empty and gh pr list --state all returned [], so no published history existed to protect, and a commit message cannot be corrected except by rewriting its own commit. I accepted the requirement and rejected the mechanism.
8 💡 IdentifierQuotingRule::WhenNecessary is documented as {"distinct", "all", "table"}, which this change extends past. DISAGREE Correct as a fact, out of scope as a finding. git diff origin/master..HEAD -- src/Parsers/IdentifierQuotingStyle.h is empty; git blame dates that line to 2024-09-24, by which point it was already missing eight names, so this change is not what makes it incomplete. All three merged PRs that previously added names to the same list (#102338, #116802, #118754) left the header untouched, and the line already points at DB::writeProbablyQuotedStringImpl for the real definition. Noted here rather than fixed; I am not promising a follow-up for it.
9 💡 A fix-plan transcription added two back-quotes to a commit-message line that did not have them. DISAGREE Cosmetic, 2 characters, and consistent with the other back-quoted SQL spellings already in the message.

Severity: ❌ blocker / ⚠️ major / 💡 nit. No blockers were found in any round. DISAGREE verdicts carry
recorded evidence and are terminal per finding.

What I checked myself, beyond the second model, because these were the claims most worth falsifying:
Keyword::SOME has exactly one grammar site, so the mechanism is fully characterized; every path that
prints a function name into re-parsable SQL goes through the changed helper, the one bare print being
viewIfPermitted-guarded; both appendColumnNameImpl implementations write the name raw, so result-set
and distributed column names do not move and "only formatter output changes" holds; no test expectation
in the repository depends on a bare some identifier; any is a registered aggregate function and some
is not, which is what makes the two decisions genuinely different; and 5 of the 8 new assertions fail if
the predicate is removed, with the other 3 pinning that the quantifier feature itself still works.

Session id: cron:clickhouse-review-slot-8:20260914-221400

@clickhouse-gh clickhouse-gh Bot closed this Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dbaf809]

Summary: ✅


AI Review

Summary

This PR fixes AST formatting round-trips for a function named SOME by forcing the identifier to stay quoted, so re-parsing no longer rewrites it into the quantifier form. I did not find a code-level correctness gap in the patch or in the new stateless regression coverage.

PR Metadata

Changelog category is not semantically correct. This is a real user-visible formatter bug fix in src/, and the bug is still present on the current stable 26.8 branch, so categorizing it as CI Fix or Improvement would hide it from the release notes. Please replace the category with:

### Changelog category (leave one):
- Bug Fix

Changelog entry is required under that category, and the existing entry is specific enough once the category is corrected.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit dbaf809.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dbaf80935 with master f7c5fb368 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 36b76e15a; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: binary sizes, symbol sizes.

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4160d50

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 05182_join_order_conflict_detector_cast_null_propagation plan-shape reference diff under the randomized MergeTree setting auto_statistics_types; the runner's own minimization on this lane reports 183/183 failures with the randomized settings and 0/176 without, culprit --auto_statistics_types uniq_v2,uniq. Not caused by this PR, which touches only src/IO/WriteHelpers.cpp and its own new 05213_some_keyword_quoting test: the same signature is on true master (21 rows over 11 shas) and on 32 other pull requests, all since 2026-09-14 18:54Z #120084 (external, open)
Mergeable Check rollup of the row above, no independent failure #120084 (external, open)
PR rollup of the row above, no independent failure #120084 (external, open)

Session id: cron:our-pr-ci-monitor:20260915-030045

@PedroTadim PedroTadim self-assigned this Sep 15, 2026
Comment thread src/IO/WriteHelpers.cpp
&& !isParsedAsLiteral(s)
&& !isCaseInsensitiveEqual(s, "distinct")
&& !isCaseInsensitiveEqual(s, "all")
/// The parser can consume a bare `SOME` as the array-quantifier keyword, which rewrites the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai, what about the ANY quantifier?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 IN

ALL 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ groeneai
❌ claude
You have signed the CLA already but the status is still pending? Let us recheck it.

Comment thread src/IO/WriteHelpers.cpp
&& !isParsedAsLiteral(s)
&& !isCaseInsensitiveEqual(s, "distinct")
&& !isCaseInsensitiveEqual(s, "all")
/// The parser can consume a bare `SOME` as the array-quantifier keyword, which rewrites the

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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);   -- 1

26.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.

@PedroTadim
PedroTadim added this pull request to the merge queue Sep 15, 2026
Merged via the queue into ClickHouse:master with commit 27e094c Sep 15, 2026
177 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 Sep 15, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @PedroTadim — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

#120256 is real, but not introduced here: any was never in the force-quote list that this PR extended for some. The fix is open as #120175, which carries Closes: for that issue; details are on the issue thread.

@clickgapai

Copy link
Copy Markdown
Contributor
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:

  • Reproduces on: 26.8, 26.7, 26.6, 26.5, 26.4, 26.3
  • Does not reproduce on: master, 26.9
  • Tested versions: master, 26.9, 26.8, 26.7, 26.6, 26.5, 26.4, 26.3
  • Tested for context, not a backport target (outside the supported set): 26.6, 26.5, 26.4
  • Measured on the public release build (no private branch build published): 26.9, 26.8, 26.7, 26.6, 26.5, 26.4, 26.3
  • Bisect anchor (below the supported window, not a backport target): 26.2 clean
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.8, 26.7, 26.3.

CC component owner: @alexey-milovidov @vitlibar

Analysis metadata

comp-sql-syntax · Severity P2 · Finding phase_d_pr120096

  • Verified against master build 3d9e5ef147f1 (aarch64)
Introducing change: not identified
  • Secondary components: comp-testing

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-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-ci 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.

6 participants