Skip to content

Fix AST formatting roundtrip for any used as a function name with a subquery argument - #120175

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-any-function-subquery-quoting
Sep 17, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-any-function-subquery-quoting

Conversation

@groeneai

@groeneai groeneai commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120256
Related: #120096 (comment)

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 formatting of a function named any holding a single subquery argument: SELECT 1 = `any`((SELECT 1)) lost its back-quotes, and because a bare ANY before a subquery is the SQL quantifier, that text reads back as IN. Any such query round-tripped through the formatter, such as a stored view definition or SHOW CREATE, silently changed meaning.

Description

any is an aggregate function, and before a subquery it is also the ANY quantifier that the parser rewrites to IN. The formatter dropped the back-quotes, so the statement means two things across a format: SELECT 1 = `any`((SELECT NULL)) returns NULL, the formatted SELECT 1 = any((SELECT NULL)) returns 0. On a debug build the divergence trips the format-and-re-parse check as a LOGICAL_ERROR.

No back-quote has to be typed. any_value and first_value are registered aliases that FunctionNameNormalizer canonicalises to any inside the interpreter, after that check has run, so nothing is reported. Measured: 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) while its declared column name still says equals(1, any(_subquery_1)).

ParserKeyword{Keyword::ANY} matches a BareWord only, so the quoted spelling is safe. The force-quote list in writeProbablyQuotedStringImpl does that for all, and #120096 adds some, but any cannot join it: it is the only such name that is a registered function, so an entry would back-quote every any(...) in EXPLAIN SYNTAX, SHOW CREATE, stored definitions and AggregateFunction(any, T) type text.

Instead ASTFunction::formatImplWithoutAlias quotes the name only when it is any with a single subquery argument, the one shape the parser misreads. Name resolution uses the unquoted string, so the change can only add back-quotes. It keys on shape, not on the comparison context, so SELECT any((SELECT 1)) is quoted too; harmless, and the test pins it. The keyword-list entry I mentioned on #120096 stays available if you prefer the uniform shape, at the cost above.

New test 05218_any_function_subquery_quoting pins the shape plus the RESPECT NULLS, view-definition and alias carriers, with anyLast, any_value, any(number), the two-argument call and ALL as controls; seven of its thirteen lines redden when the change is reverted.


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

Version info

  • Merged into: 26.10.1.34 (included in 26.10 and later)

`any` is an aggregate function, and a bare `ANY` before a subquery is also
the SQL quantifier that the parser rewrites to `IN` at parse time
(ExpressionListParsers.cpp, `ParserKeyword{Keyword::ANY}` matches a BareWord
token only, never a quoted identifier). ASTFunction::formatImplWithoutAlias
printed the name through `backQuoteIfNeed`, whose force-quote list in
`writeProbablyQuotedStringImpl` holds `all` but not `any`, so a function
literally named `any` holding one subquery argument was emitted bare and its
own output read back as the quantifier: `equals(1, any(Subquery))` became
`in(1, Subquery)`.

The two spellings are different queries, so this is not only a debug-build
assertion. Measured: SELECT 1 = `any`((SELECT NULL)) returns NULL while the
formatter's output SELECT 1 = any((SELECT NULL)) returns 0, and with a
multi-row subquery the quoted form raises INCORRECT_RESULT_OF_SCALAR_SUBQUERY
where the unquoted one returns a boolean. Every text path is affected: stored
view and MV definitions, SHOW CREATE, system.tables.create_table_query, and
the query an initiator sends to shards. Under `#ifndef NDEBUG` the same
divergence aborts on the format-consistency check in executeQuery.cpp.

The query text does not have to contain a back-quote for this to happen.
`any_value` and `first_value` are registered aliases of `any`, and
FunctionNameNormalizer rewrites them to the canonical name inside the
interpreter, which is after the parse-time format-consistency check has run,
so nothing aborts even on a debug build. Measured on a debug server:
`CREATE VIEW v AS SELECT 1 = first_value((SELECT 1))`, ordinary unquoted SQL,
stored `AS SELECT 1 = any((SELECT 1))` in its metadata file, and
`system.tables.create_table_query` for that view then read back
`AS SELECT 1 IN (SELECT 1)` while the view's declared column name still said
`equals(1, any(_subquery_1))`. That is a view returning a different value
from the one its own definition asked for, in a release build, with no
back-quote typed anywhere.

`any` cannot join the force-quote list, which is why this is a formatter
predicate instead. That list is consulted for every identifier and function
name, and `any` is the only entry it would need which is a registered
function, so an entry would back-quote every `any(...)` in EXPLAIN SYNTAX and
SHOW CREATE output, in stored view/MV definitions, and the inner aggregate
name of `AggregateFunction(any, T)` type text on disk. `any` is also
perfectly safe as an identifier (`ORDER BY any`, `t.any`, `SELECT 1 AS any`,
`HAVING 1 = any` all round-trip today), so quoting it in all positions is the
wrong granularity.

The predicate keys on name plus argument shape rather than on the enclosing
comparison, so `SELECT any((SELECT 1))` is quoted as well even though the
quantifier could not have been parsed there. That is harmless: quoting a
function name never affects name resolution, so the change can only ever add
a pair of back-quotes.

The `tryGetQueryArgument()` branch is deliberately left alone. A single bare
`ASTSelectWithUnionQuery` argument is not parser-reachable for any name but
`view`/`viewIfPermitted`, and quoting there would make the text a syntax
error rather than a faithful round-trip, so that shape belongs to the JSON
boundary that can construct it.

New test 05218_any_function_subquery_quoting pins the shape, formatting
idempotency, the `RESPECT NULLS` and view-definition carriers, and the alias
carrier as an executed `CREATE VIEW` whose stored definition is then read
back through `system.tables`. `anyLast`, `any_value`, `any(number)`, the
two-argument call and `ALL` are the controls against over-quoting. The
formatter cases are formatted and not executed, because a regressed formatter
aborts a debug server on the offending shape instead of reddening one line.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 10 findings over 2 rounds, Gate B
returning 3 then 0; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The registered aliases any_value and first_value reach the same defect without the test covering them: FunctionNameNormalizer canonicalises them to any inside the interpreter, after the parse-time format check has run AGREE, fixed @ 13af7c7 Measured on both arms before editing. Base stores = any((SELECT 1)) for CREATE VIEW v AS SELECT 1 = first_value((SELECT 1)) and system.tables.create_table_query reads it back as 1 IN (SELECT 1), with nothing reported. Now pinned as an executed CREATE VIEW plus a formatter control, and it is why the description leads with that carrier
2 ❌ Add some to the same predicate, since writeProbablyQuotedStringImpl does not force-quote it either DISAGREE The mechanism is real, the prescription is not. Nothing in src/ registers a function or aggregate named some, so unlike any it can be force-quoted unconditionally at zero blast radius, which is what #120096 does one layer down. A shape-specific some branch here becomes unreachable the moment that merges
3 💡 The test preamble claimed that executing the unquoted spelling aborts a debug build AGREE, fixed @ 13af7c7 Inverted: the unquoted text parses straight to in(1, Subquery) and round-trips. It is the quoted spelling that aborts, and only under the old formatter
4 💡 05218 named any_value as a control in prose but had no such statement AGREE, fixed @ 13af7c7 Independent half of finding 1; the control is now a reference line that must stay byte-identical in both arms
5 💡 The predicate comment's third sentence was a cross-file claim about WriteHelpers.cpp, and false for SOME until #120096 merges AGREE, fixed @ 13af7c7 Sentence deleted; the predicate itself is byte-identical to the reviewed revision
6 💡 The commit message rendered a back-quoted query through a markup workaround AGREE, fixed @ 13af7c7 Written literally
7 ⚠️ The description proved user-visibility only through the back-quoted spelling, which is the weaker half of the case and the half that invites a category downgrade AGREE, fixed in the description Rewritten so the alias carrier (ordinary SQL, no back-quote typed, nothing reported) is its own paragraph. Two residual nits are noted and not blocking: partial inline-code markup in the commit message, and one imprecise word in a test comment

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260915-112300

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

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0f7ac5d]

Summary: ✅


AI Review

Summary

This PR fixes the common SQL path by forcing quotes around any when ASTFunction formats a single ASTSubquery argument, which preserves round-tripping for stored definitions and formatter output. The remaining problem is that the same invariant is still open on the JSON-AST surface: formatQueryFromJSON / dialect = clickhouse_json can still build an any(SELECT ...) shape that bypasses the new predicate and formats back to SQL with different semantics.

Findings

⚠️ Majors

  • [src/Parsers/ASTFunction.cpp:498-501] This only covers the ASTSubquery carrier. IAST::createFromJSON still accepts ASTFunction(name = 'any', arguments = [ASTSelectWithUnionQuery]), and formatImplWithoutAlias exits through tryGetQueryArgument before reaching quantifierNameNeedsQuoting, so formatQueryFromJSON / clickhouse_json still serialize the AST as bare any(SELECT ...) and a comparison re-parses it as the ANY quantifier. Suggested fix: either reject non-view / non-viewIfPermitted bare-query arguments in readJSON, or extend the special handling to the tryGetQueryArgument path and add a focused JSON-AST regression.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Close the remaining JSON-AST carrier for any with a single query argument, either at formatting time or at the readJSON boundary.

LLVM Coverage Report

Measured on commit 0f7ac5d.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 15, 2026
@PedroTadim PedroTadim self-assigned this Sep 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0f7ac5d46 with master bdd39260f (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

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

Job report

static bool quantifierNameNeedsQuoting(const String & name, const ASTPtr & arguments)
{
return equalsCaseInsensitive(name, "any") && arguments && arguments->children.size() == 1
&& arguments->children[0]->as<ASTSubquery>();

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 only fixes the parser-produced ASTSubquery carrier. IAST::createFromJSON still accepts an ASTFunction named any whose sole child is a bare ASTSelectWithUnionQuery, and formatImplWithoutAlias returns via tryGetQueryArgument before it ever reaches this predicate. On that supported JSON surface (formatQueryFromJSON and dialect = clickhouse_json), the AST still serializes as bare any(SELECT ...), which a comparison re-parses as the ANY quantifier instead of the function.

If the intent is to keep the tryGetQueryArgument path unquoted, this PR still needs the matching BAD_ARGUMENTS check in readJSON for non-view / non-viewIfPermitted bare-query arguments; otherwise the round-trip contract remains broken for JSON AST input.

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.

Confirmed, and the mechanism is exactly as described. I built the payload by hand and measured it on a debug master build (bdd39260f887d, whose readJSON differs from today's master only by #120483's lambda check):

-- payload: parseQueryToJSON('SELECT 1 = `any`((SELECT 1))'), with the Subquery
-- wrapper replaced by its bare SelectWithUnionQuery child
formatQueryFromJSON(payload)                            -> SELECT 1 = any(SELECT 1)
formatQuerySingleLineOrNull('SELECT 1 = any(SELECT 1)') -> SELECT 1 IN (SELECT 1)

It reaches stored DDL too. CREATE VIEW v AS SELECT 1 = <any + bare select> submitted with dialect = clickhouse_json is accepted with no error and no debug abort, and in the next process:

create_table_query = CREATE VIEW default.v (`equals(1, any(_subquery_1))` Nullable(UInt8)) AS SELECT 1 IN (SELECT 1)
SELECT * FROM v -> Code: 47. Unknown expression identifier `equals(1, any(_subquery_1))`. (UNKNOWN_IDENTIFIER)

The readJSON gate you name is the right remedy; quoting the tryGetQueryArgument path is measurably not. With the name quoted the emitted text is unparseable, which is where every sibling name already sits: in the same payload foo, some and all all return NULL from formatQuerySingleLineOrNull (the last two are force-quoted in writeProbablyQuotedStringImpl), and the foo shape executed through the dialect gives Code: 46 UNKNOWN_FUNCTION. So any is not special at that boundary, it is only the one name whose breakage is silent instead of loud.

The gate is not any-specific either: ASTFunction::readJSON rejects a bare SelectWithUnionQuery argument only under if ((is_view || is_view_if_permitted) && arguments), so every other name passes with one. #120483, merged this morning, added only the is_lambda_function shape check there.

That is a different layer and a different entry surface from this PR, whose carrier is the parser-produced ASTSubquery shape reachable from plain SQL, and the gate covers every function name rather than any. So I am sending it as a separate PR rather than widening this one, and I will link it here.

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.

Yes, let's do it in a follow-up PR. I can try to review it.

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.

Thanks. The follow-up is in progress; I will post its link here when it opens and request you as a reviewer.

Heads-up on scope: the same check also closes three shapes the current view / viewIfPermitted gate lets through (a bare select in parameters, and a window or NULLS clause silently dropped from view(SELECT ...)), so it is a little wider than the any carrier alone.

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.

Opened as #120725. It adds the readJSON check at this boundary, extended past the shape asked for here: all four select query node types the AST JSON factory can build are matched, in parameters as well as arguments, and the accepted view / viewIfPermitted shape additionally rejects a window, a NULLS action and query output options on the select, each of which the formatter drops or prints unparseably.

@PedroTadim
PedroTadim added this pull request to the merge queue Sep 17, 2026
Merged via the queue into ClickHouse:master with commit c6c58c1 Sep 17, 2026
178 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 17, 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-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. groeneai-origin-review-human PR origin: human review feedback on a groeneai PR 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.

Formatter unquotes any: a quoted any(subquery) call re-parses as IN

3 participants