Skip to content

Reject AST shapes the parser cannot produce in the AST JSON format - #120725

Merged
alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:fix-json-ast-bare-select-argument-120175
Sep 24, 2026
Merged

alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:fix-json-ast-bare-select-argument-120175

Conversation

@groeneai

@groeneai groeneai commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120679
Related: #120175 (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 a silently corrupted query when a node restored from the AST JSON format (formatQueryFromJSON, dialect = 'clickhouse_json') carried a shape the parser cannot produce, such as a bare select query argument or an expression list where an argument was expected. Such a node is now rejected with BAD_ARGUMENTS instead of formatting into SQL that parses back as a different query.

Description

What breaks. IAST::createFromJSON accepted a bare SelectWithUnionQuery among a function's arguments or parameters under any name. Named any it formats as any(SELECT 1), which parses back as 1 IN (SELECT 1): a different query, no error. Through dialect = 'clickhouse_json' it reaches DDL: CREATE VIEW is accepted silently, the metadata stores AS SELECT 1 IN (SELECT 1), and the view is unreadable (Code: 47).

Root cause. The formatter prints the two parser-producible shapes through early-return branches, so parameters and the window suffix never print; readJSON gated only their name and argument list.

Change. A bare select query node of any buildable type is accepted only for those two shapes, with no parameters, window, NULLS action or output options, which also closes four holes under those names. An ASTExpressionList child of arguments or parameters is rejected: a child there is an expression, which a list is not, and the formatter prints its children inline, so one argument becomes several. APPLY and REPLACE own expression positions ASTFunction::readJSON never sees, so both get the same checks. The union reader rejects a one-element chain whose element is another union, which ParserSelectWithUnionQuery lifts, and both set operation readers reject an element carrying output options.

Validation. 24 shapes now raise BAD_ARGUMENTS, each a row in 04339_ast_json_review_followup_hardening failing on master. Positive controls for every conjunct, including GROUPING SETS. No round trip regresses: 48 union, set operation and pipe queries format identically.

Shapes that stay open, the owner's call: a node the format builds that is not an expression, such as ExplainQuery or OrderByElement, and a locally valid view(<select>), which SQL allows only as a table function. Rejecting the first by node type would also reject parser output, since ORDER BY tuple(a DESC, b DESC) puts one in a function's arguments, so the rule needs the parent context readJSON lacks.


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

Version info

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

groeneai and others added 4 commits September 17, 2026 10:36
…e in the AST JSON format

IAST::createFromJSON accepted a bare SelectWithUnionQuery among an
ASTFunction's arguments or parameters under any function name. The parser
produces that shape only inside the table functions view and viewIfPermitted:
ViewLayer is their only producer, it emits exactly view(<select>) or
viewIfPermitted(<select>, <function>), and makeASTFunction never sets
parameters. Every other select parsed in an expression context is wrapped in an
ASTSubquery.

formatImplWithoutAlias prints those two shapes through dedicated branches that
emit the name and the select and then return: tryGetQueryArgument matches any
single-argument function whose argument is a select, name-agnostic and
parameters-agnostic, and the viewIfPermitted ... ELSE printer is its sibling.
Both return before finishFormatWithWindow and neither prints parameters, so
every other field of such a node is absent from the formatted text. readJSON
gated a bare select only under (is_view || is_view_if_permitted) && arguments,
and checked only the name and the argument list.

Seven payloads were therefore accepted with no error and no debug abort.
Formatted as any(SELECT 1), the text parses back as SELECT 1 IN (SELECT 1)
through the aggregate-to-IN rewrite, so the query silently becomes a different
one; submitted through dialect = clickhouse_json, CREATE VIEW then stores
AS SELECT 1 IN (SELECT 1) under the column name equals(1, any(_subquery_1)) and
the view cannot be read again (UNKNOWN_IDENTIFIER). Under other names the text
does not parse back at all. Three of the seven are holes under the two names the
old gate already covered: a select in parameters printed view(SELECT 1)(), and
an OVER clause or a RESPECT NULLS clause was dropped from the output.

The gate is replaced by one predicate stating the invariant once. A bare select
in arguments or parameters, following nested expression lists, is accepted only
when the node is one of the two parser-producible table function nodes and
carries nothing those branches would drop: no parameters, no window, no NULLS
action. Each conjunct is derived from a field the printers omit rather than
guessed. The walk follows only the ASTExpressionList spine, because an
expression list legitimately holds select queries and cannot reject them in its
own readJSON, while any other node type is reached by its own readJSON call and
gated there; a select nested under a function is thus rejected by composition.

The check stays at the deserialization boundary, where the parser-impossible
node enters. Quoting the name in the formatter's query-argument branch was
measured to move any() only from a silent rewrite to unparseable text, which is
where the other names already were, and it would break the legitimate view
printer. Nothing outside JSON deserialization changes: parseQueryToJSON
serializes parser-produced ASTs only, so no round trip can regress, and the
case-insensitive name handling and the canonicalization to the spelling the
parser emits are unchanged.

Tests: 04339_ast_json_review_followup_hardening gains one row per rejected
carrier and one positive control per conjunct (the legitimate view(SELECT 1),
a window function, IGNORE NULLS, and a parametric aggregate), plus the
position() anchor the three replace()-mutated rows need in order not to go
vacuous. The view and viewIfPermitted shape tests 04824 and 04828 are
unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
The gate added in the previous commit tested the argument node with
`as<ASTSelectWithUnionQuery>()`. `IAST::as` goes through `typeid_cast`,
whose pointer form matches the exact type, so the three other select
query node types the JSON factory registers (`SelectQuery`,
`SelectIntersectExceptQuery`, `ProjectionSelectQuery`) walked straight
past it: `ASTExpressionList::readJSON` does not type-check its children,
and at format time the generic path prints each of them as a bare query.
Measured on master, `{"type":"Function","name":"any","arguments":
[{"type":"SelectQuery", ...}]}` formats to `any(SELECT 1)`, which parses
back as `1 IN (SELECT 1)` - the same silent rewrite the gate exists to
stop - and a `ProjectionSelectQuery` in the same position formats
identically.

The accepted shape is deliberately not widened: `ViewLayer` parses the
`view` / `viewIfPermitted` query argument with
`ParserSelectWithUnionQuery` and both formatter branches match only that
class, so `view` carrying a bare `SelectQuery` is rejected too, and a
test row pins that boundary from the other side. The error message now
names `SelectWithUnionQuery` instead of "the select query", which for
that payload described something it satisfies.

19 round trips through `parseQueryToJSON` covering projections, set
operations, scalar subqueries, `view(...)`, materialized views, CTEs and
`INSERT ... SELECT` produce byte-identical output before and after, as
expected: the only producer of `ASTProjectionSelectQuery` attaches it to
`ASTProjectionDeclaration`, never to a function's argument list.
`ASTSelectWithUnionQuery::readJSON` ends with `readOutputOptionsJSON`, so a
JSON payload can attach `INTO OUTFILE` / `FORMAT` / `SETTINGS` to the very
select child the gate accepts as a `view` or `viewIfPermitted` query
argument. `ASTQueryWithOutput::formatImpl` is `final` and appends that
suffix unconditionally, including when the function is printed through the
query-argument branch, while `ParserSelectWithUnionQuery` parses no output
option at all and `ViewLayer` requires `)` right after the select. Measured
on master, the three shapes that can reach it format to text that does not
parse back: ``view(SELECT 1 FORMAT `Null`)``,
`view((SELECT 1) SETTINGS max_threads = 1)` and
``viewIfPermitted(SELECT 1 INTO OUTFILE 'f' ELSE `null`('x UInt8'))``, each
a syntax error on reparse rather than a different query.

The accepted shape therefore also requires `!hasOutputOptions()` on the
select child, which covers all five output-option members in one call; the
`compression` / `compression_level` members and the `APPEND` / `TRUNCATE` /
`AND STDOUT` flags cannot arrive on their own, since `readOutputOptionsJSON`
already rejects them without an `out_file`.

A query-local `SETTINGS` inside `view(...)` is unaffected: the parser
attaches it to the inner `ASTSelectQuery`, not to the union query, so
`view(SELECT 1 SETTINGS max_threads = 1)` still round-trips byte-identically
and is now pinned by a positive control.
Drop the containsBareSelectQuery block, which narrated the walk the code shows, and the design narration in the readJSON guard comment, keeping the parser, formatter and output-option invariants.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, 2 blockers fixed)

Each round is an independent cold read plus a separate model, adjudicated against the recorded
measurements.

❌ Blockers found and fixed in this PR

  • A bare select argument bypassed the new gate for three of the four select node types. IAST::as
    goes through typeid_cast, which matches the exact type only, so a check on
    ASTSelectWithUnionQuery missed ASTSelectQuery, ASTSelectIntersectExceptQuery and
    ASTProjectionSelectQuery, all registered in the AST JSON factory: any(<SelectQuery>) still
    formatted to any(SELECT 1) and reparsed as 1 IN (SELECT 1). All four are matched now, one
    regression row per carrier; the accepted shapes stay SelectWithUnionQuery-only, with a row
    pinning that boundary under the name view itself.
  • The accepted view / viewIfPermitted shape still admitted query output options on the select
    child.
    ASTQueryWithOutput::formatImpl is final, so an INTO OUTFILE / FORMAT / SETTINGS
    suffix restored by readJSON prints even through the query-argument branch, and ViewLayer (which
    requires ) right after the select) can never produce one. Rejected now; per-select SETTINGS
    inside view(SELECT ... SETTINGS ...) is parser-producible and stays accepted, with a positive
    control.

⚠️ Raised, verified real, and left to the node that owns it

  • Two shapes reachable inside the accepted select: a redundant single-element nested
    SelectWithUnionQuery (ParserSelectWithUnionQuery lifts that wrapper, so no parse produces it),
    and a nested select carrying query output options. Both are real, and neither needs a function:
    ASTSelectWithUnionQuery::readJSON applies no rule to a nested element, so
    SELECT 0 UNION ALL (SELECT 1 UNION ALL SELECT 2 FORMAT Null) formats to exactly that text and
    cannot be parsed back with no view and no function argument anywhere in it. A recursive check in
    ASTFunction::readJSON would close only the view(...) instance; one rule in
    ASTSelectWithUnionQuery::readJSON closes every instance, which is your call rather than mine.

⚠️ Verified, deliberately not widened

  • The gate is select-family only: any with an ExplainQuery argument prints any(EXPLAIN SELECT 1),
    and ParserSubquery accepts an EXPLAIN subquery, so the reparse rewrites = any(<subquery>) to
    in. The obvious widening is unsafe, because ASTSetQuery returns QueryKind::Set and is a
    legitimate parser-produced argument element of a table function (printed as SETTINGS ...), while
    ASTProjectionSelectQuery does not override getQueryKind() at all, so a query-kind gate needs its
    own carve-out list and parser sweep. Noted in the description; your call whether to close it too.
  • A bare select is likewise accepted among ASTColumnsApplyTransformer::parameters. Established by
    reading only, so I claim no consequence; a different node with a different formatter.

💡 Nits

  • A helper comment claimed to list "the node types whose formatImpl prints a bare query", broader
    than the four select types it lists. Reworded.
  • is_view_shape restates ASTFunction::tryGetQueryArgument(); reusing that accessor would bind the
    boundary check to the printer it defends. Left alone to keep the diff minimal.
  • The accepted shape still admits six ASTFunction flags no parse produces beside a bare select
    (kind, is_operator, is_compound_name, no_empty_args, compute_after_window_functions,
    prefer_subquery_to_function_formatting), each verified format-neutral for these two names.
  • A select reaching the subtree through a window definition is not covered: partition_by is read as
    an untyped expression list while order_by elements are type-checked. That is that node's boundary.

Confirmed rather than assumed: the accepted shapes are still exactly what the parser produces
(ViewLayer is the only producer; viewExplain and the Kusto in rewrite both wrap their select in an
ASTSubquery), every rejection carrier is the sole oracle for its conjunct and fails on an unfixed
binary, and no test or source file referenced any error message this PR replaced.

Session id: cron:clickhouse-review-slot-11:20260918-032400

@clickhouse-gh clickhouse-gh Bot closed this Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One formatQueryFromJSON call with a bare select query node under the name any, 100% on demand, no randomization. Unfixed: prints any(SELECT 1), rc=0, for a SelectWithUnionQuery, a SelectQuery and a ProjectionSelectQuery alike; likewise view(SELECT 1 FORMAT `Null`) and view((SELECT 1) SETTINGS max_threads = 1) for a select child carrying query output options.
b Root cause explained? Yes. The two early-return printers for the parser-producible bare-select shapes (tryGetQueryArgument and the viewIfPermitted ... ELSE form) emit only the name and the select, skipping parameters and the whole finishFormatWithWindow suffix; readJSON gated only the name and argument list of those shapes. The same two printers also always append ASTQueryWithOutput's INTO OUTFILE / FORMAT / SETTINGS suffix (formatImpl is final), which ParserSelectWithUnionQuery can never produce there.
c Fix matches root cause? Yes. One predicate at the deserialization boundary where the parser-impossible node enters. Quoting the name in the formatter was measured to move any only from a silent IN rewrite to unparseable text, so it was rejected.
d Test intent preserved / new tests added? Yes. 04339_ast_json_review_followup_hardening extended in place: 5 positive controls (one per conjunct), 1 anchor row, 14 negatives, each proven non-vacuous by being named individually on the unfixed arm. 04824 / 04828, the view / viewIfPermitted shape tests, are untouched and pass byte-identically.
e Both directions demonstrated? Yes, three ways: per payload on both binaries (14 of 14); the test file [ OK ] on the fix and [ FAIL ] on the master snapshot, whose log names every negative row individually; and end-to-end through dialect = 'clickhouse_json', where the unfixed arm stores an unreadable view (Code: 47) and the fixed arm rejects the DDL.
f Fix is general across code paths? Yes. Both list carriers (arguments, parameters), nested expression-list spines, all three window / NULLS carriers, and all four select query node types the JSON factory registers are covered by the single predicate, so the gate cannot be bypassed by swapping the "type" field; a nested function is covered by composition through its own readJSON. window_definition is typed as ASTWindowDefinition, so those two lists are the only routes for a select to become a direct child of an ASTFunction; a select deeper inside another node is that node's own boundary. No ASTFunction subclass exists in src/. The output-option conjunct is written once for both accepted shapes, so view and viewIfPermitted cannot drift apart.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. All four select node types (SelectQuery, SelectWithUnionQuery, SelectIntersectExceptQuery, ProjectionSelectQuery), all four name spellings (case-insensitive, as before), both accepted shapes, argument counts 0/1/2 and 2-with-wrong-type, parameters present/absent, window present/absent, all three NullsAction values, UNION selects, nesting depth 1 and 2, composition through tuple, and the query-output-option dimension exhaustively: of ASTQueryWithOutput's five members plus three flags, exactly three can reach an accepted select (compression / compression_level / the flags are already rejected without an out_file by readOutputOptionsJSON), and each of those three has a measured row.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or serialization change, so no SettingsChangesHistory.cpp entry. Only inputs no parseQueryToJSON output can contain are newly rejected: it serializes parser-produced ASTs only, and ViewLayer is the sole parser producer of a bare select argument.
i Invariants and contracts preserved? Yes. The throw precedes readAlias and any hand-off, so no partially built AST escapes; the canonicalization still runs on every accepted shape, keeping QueryNormalizer's case-sensitive name == "view" compare satisfied. The other tryGetQueryArgument() consumers are strictly narrowed, never widened.

Session id: cron:clickhouse-impl-slot-4:20260918-001600

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ebf5870]

Summary: ✅


AI Review

Summary

This PR hardens clickhouse_json deserialization for several parser-impossible AST shapes around ASTFunction, set-operation queries, and column transformers. The direction is correct and most of the earlier gaps are closed, but two silent-rewrite cases remain: one new hole in the set-operation output-option validation, and one previously discussed expression-slot hole that can still persist unreadable SQL UDF metadata.

Findings

❌ Blockers

  • [src/Parsers/ASTSelectWithUnionQuery.cpp:291] The new hasQueryOutputOptions(select_child) guard only sees output clauses that survive deserialization into the child AST node. A malformed payload can put format_ast / settings_ast / out_file directly on an ASTSelectQuery or ASTSelectIntersectExceptQuery element; those readers ignore unknown keys, so the clause is silently dropped instead of being rejected. That also bypasses the new view(SELECT ...) hardening when the lone inner ASTSelectQuery carries the output option this way. Suggested fix: reject output-option keys in the child readers, or validate the raw JSON object for each set-operation element before deserializing it, and add a regression row where a SelectQuery child carries format_ast.
  • [src/Parsers/ASTFunction.cpp:322] [dismissed by author -- https://github.com/Reject AST shapes the parser cannot produce in the AST JSON format #120725#discussion_r4047183192] The new “expression position must hold an expression” invariant is still incomplete: direct parser-owned wrappers like ASTOrderByElement / ASTWindowDefinition still pass through arguments and parameters, because this check only rejects nested ASTExpressionList and bare selects. That is still enough to persist broken metadata: a clickhouse_json CREATE FUNCTION ... AS (x) -> plus(<OrderByElement>, x) stores SQL that UserDefinedSQLObjectsDiskStorage::tryLoadObject later cannot parse and silently ignores on startup (src/Functions/UserDefined/UserDefinedSQLObjectsDiskStorage.cpp:108). Suggested fix: tighten these expression slots to the parser-produced node shapes that are actually valid there, or at minimum reject the known non-expression wrappers and add a regression covering the stored-UDF case.
Final Verdict

❌ Changes requested. The patch is close, but it still leaves one silent drop of output clauses in set-operation children and one still-open persisted-UDF corruption path from malformed AST JSON.

LLVM Coverage Report

Measured on commit ebf5870.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 74/79 (93.67%) · Uncovered code

Full report · Diff report

Comment thread src/Parsers/ASTFunction.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit ebf58700ccf574df481808d7fe7f9a6ac743e830 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@PedroTadim PedroTadim self-assigned this Sep 18, 2026
Comment thread src/Parsers/ASTFunction.cpp Outdated
@@ -270,46 +288,43 @@ void ASTFunction::readJSON(const Poco::JSON::Object & json)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Window function requires either a non-empty 'window_name' or a 'window_definition' child during AST JSON deserialization");

/// The parser produces a bare `SelectWithUnionQuery` function argument only inside the table
/// functions `view` and `viewIfPermitted` (`ViewLayer` is their only producer): `view(SELECT ...)`
/// The parser produces a bare select query function argument only inside the table functions

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 trim all these comments

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.

Done in 1d14484. Added comment lines in this PR: src/ 22 -> 7 (0.13 per added code line, from 0.39), tests 29 -> 14.

Per block: the bare select gate 13 -> 3, the expression list check 3 -> 1, the APPLY and REPLACE blocks 3 -> 1 each, the isBareSelectQuery declaration 2 -> 1, the two test section headers 16 -> 5 and 10 -> 5. What went is the formatter and QueryTreeBuilder narration, which belongs in the commit message; what stayed is only the parser-side property each check enforces, which the code below it does not show.

Re-reading that block turned up one description error, now fixed: an accepted view(<select>) in an expression position rather than a table-function one still formats as SELECT view(SELECT 1), which does not reparse. It behaves identically on master and fails closed at analysis (Code: 46, nothing gets stored), so I did not widen this PR for it, but the description no longer claims ExplainQuery is the only shape left open.

Comment thread src/Parsers/ASTFunction.cpp Outdated
"'viewIfPermitted' with a select query argument must have exactly two arguments, a select query "
"followed by a function, and no parameters during AST JSON deserialization");
}
"A select query argument is only allowed in the table function 'view' (exactly one argument, a "

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 trim this exception message

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.

Done in 1d14484:

A select query argument is only allowed in 'view(SELECT ...)' or 'viewIfPermitted(SELECT ..., f(...))' during AST JSON deserialization

The two examples carry what the old enumeration spelled out, since neither of them shows parameters, a window, a NULLS action or output options, and the check itself sits right above the throw. No test asserted on the old text.

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.

Correction to the text I quoted above: the fallback is separated by ELSE, not a comma, so the message reads A select query argument is only allowed in 'view(SELECT ...)' or 'viewIfPermitted(SELECT ... ELSE f(...))' during AST JSON deserialization as of dcdc05f.

An AST JSON payload can put an ASTExpressionList directly among the children of
a function's arguments or parameters. No parse produces that, and nothing
downstream accepts it: QueryTreeBuilder::buildExpression rejects the child with
UNSUPPORTED_METHOD, while the formatter prints the child's own children inline,
so one logical argument silently becomes several. Measured before this commit:

  plus + [[1, 2]]        formats as  plus(1, 2)     reparses as two arguments
  quantile params [[0.5]] formats as quantile(0.5)(x)
  plus + [[], 1]         formats as  plus(, 1)      does not parse at all

Reject the child at the same readJSON boundary that already rejects a bare
select query argument. The check is scoped to a function's own two lists: a
nested expression list is parser-producible elsewhere, in
GROUP BY GROUPING SETS ((a, b), (c)), which now has a round-trip test row.

Reported by clickhouse-gh[bot] on
ClickHouse#120725 (comment)
ASTColumnsApplyTransformer carries its own parameters list, assigned to
ASTFunction::parameters only later, so the check added in the previous commit
does not see it. Measured before this commit: a nested list holding 0.5 and 0.9
formats as SELECT * APPLY quantiles(0.5, 0.9), identical to the parser-produced
two-parameter shape, and an empty nested list formats as APPLY quantiles().

Found by a second-model review of the previous commit.
…ressions

The two column transformers hold expression positions of their own that
ASTFunction::readJSON never sees: APPLY carries its own parameters list, and each
REPLACE replacement carries the replacement expression as its single child.
Measured before this commit, both accept a bare select query and an expression
list, and the formatter prints them:

  APPLY   quantiles + [SELECT 1]    formats as  SELECT * APPLY quantiles(SELECT 1)
  REPLACE a <- [SELECT 1]           formats as  SELECT * REPLACE (SELECT 1 AS a)
  REPLACE a <- [[a, 1]]             formats as  SELECT * REPLACE ( a, 1 AS a)

None of the three reparses. Move the select node type predicate to
ASTJSONReadHelpers, where both readers can use it, instead of repeating the
enumeration of buildable select types.

Found by a second-model review of the previous commit.
@groeneai groeneai changed the title Reject a select query function argument that the parser cannot produce in the AST JSON format Reject function arguments that the parser cannot produce in the AST JSON format Sep 18, 2026
Requested by @PedroTadim in review. Each of this PR's own comment blocks is cut
to the invariant a reader cannot derive from the code below it, dropping the
formatter and QueryTreeBuilder narration that belongs in the commit messages,
and the two test section headers to one sentence of shape plus the row
inventory. The bare select argument message keeps both accepted shapes but names
them by example instead of enumerating every excluded field, which the reader
can see in the check itself.

Comments and one message string only; no check, no accepted or rejected shape
changes. The 04339 rows all still hold, and the whole AST JSON family stays
green.
…N format

`ParserQueryWithOutput` parses `INTO OUTFILE`, `FORMAT`, `SETTINGS` and the
compression clauses for the outermost query only, and `ParserSelectWithUnionQuery`
never parses them for a chain element, so an `ASTSelectWithUnionQuery` carrying
output options inside `list_of_selects`, or inside an `ASTSelectIntersectExceptQuery`,
is a shape no parse produces. Measured over 13 queries that nest `SETTINGS` and
`FORMAT` in union, intersect, except, subquery, CTE, view and INSERT SELECT
positions: none produces a nested element with output options.

`ASTSelectWithUnionQuery::formatQueryImpl` wraps such an element in parentheses and
`ASTQueryWithOutput` prints its options inside them, so `formatQueryFromJSON` emitted
`SELECT 0 UNION ALL (SELECT 1 UNION ALL SELECT 2 FORMAT Null)` and
`SELECT 1 INTERSECT ALL (SELECT 2 FORMAT Null)`, neither of which reparses
(`Code: 62`). Under the `view` argument this is the second half of the bare select
blessing hole: `SELECT * FROM view(SELECT 0 UNION ALL (SELECT 1 UNION ALL SELECT 2
FORMAT Null))` is a syntax error too.

The predicate lives in `ASTJSONReadHelpers` because both set operation nodes need it,
and it is a `dynamic_cast`, so it covers every `ASTQueryWithOutput` select form rather
than one exact type.
@groeneai groeneai changed the title Reject function arguments that the parser cannot produce in the AST JSON format Reject AST shapes the parser cannot produce in the AST JSON format Sep 18, 2026
"'arguments' and 'parameters' cannot have an expression list child during AST JSON deserialization");

r.readAlias(*this);
}

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 still leaves the new "expression position must hold an expression" invariant incomplete. ASTExpressionList::readJSON accepts any registered child type, and ASTFromJSON still builds parser-owned wrappers like OrderByElement, StorageOrderByElement, and WindowDefinition. None of those are parser-produced in a function-argument / parameter / APPLY-parameter / REPLACE-expression slot, but this check only rejects nested ASTExpressionList and bare selects, so a payload like {"type":"Function","name":"plus","arguments":{"type":"ExpressionList","children":[{"type":"OrderByElement","direction":1,"nulls_direction":1,"expression":{"type":"Literal","value":{"field_type":"UInt64","value":1}}}]}} still formats as plus(1 ASC). That means malformed clickhouse_json can still pass the new boundary and emit SQL the parser cannot produce. I think this needs a shared "parser-produced expression node" predicate (or at least rejection of the remaining sort/window wrappers here and in the copied APPLY / REPLACE checks), plus a regression row.

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.

Reproduced on bb79cdab, and the consequence is worse than a broken round trip.

Your payload gives plus(1 ASC); the WindowDefinition and parameters variants give plus(PARTITION BY 1, 2) and quantile(1 ASC)(2). None reparse, and a SQL UDF persists the text: CREATE FUNCTION f AS (x) -> plus(<OrderByElement>, x) through dialect = 'clickhouse_json' is accepted with no error and writes user_defined/function_f.sql holding CREATE FUNCTION f AS x -> plus(1 ASC, x). The next start re-parses that file in UserDefinedSQLObjectsDiskStorage::tryLoadObject, fails, and returns nullptr ("will ignore it"), so the function is silently gone. Byte-identical on the pre-PR master snapshot, so this PR did not introduce it. The expression paths fail closed: the query tree builder gives Code: 1 ... Expected identifier, literal, matcher, function, subquery. Actual 1 ASC, and CREATE VIEW stores no metadata at all.

The remedy as written cannot be taken, because one of its three types is parser-produced in exactly that slot:

CREATE TABLE t (`a` UInt32, `b` UInt32) ENGINE = MergeTree
ORDER BY tuple(a DESC, b DESC) SETTINGS allow_experimental_reverse_key = 1

tuple gets two StorageOrderByElement arguments there, and formatQueryFromJSON(parseQueryToJSON(q)) is byte-identical to q today. SetQuery is the same story: mysql(..., SETTINGS connection_wait_timeout = 123) and icebergS3(..., SETTINGS iceberg_metadata_file_path = '...') both put one in arguments.

Over 12,292 test-suite queries that parseQueryToJSON accepts, the direct child types of arguments are Literal, Function, Identifier, Subquery, Asterisk, QualifiedAsterisk, ColumnsRegexpMatcher, SelectWithUnionQuery, StorageOrderByElement, SetQuery, and of parameters the first three; OrderByElement and WindowDefinition do not occur. Your three are not a closed set either: Assignment (plus(c = 1, 2)) and DataType (plus(UInt8, 2)) are accepted too, and those two reparse, so they change the AST silently instead of failing.

The rule that terminates is therefore a whitelist of those types, not a blacklist of three, and even a whitelist cannot reject StorageOrderByElement or SetQuery in the wrong parent: legitimacy is position-dependent and readJSON has no parent context, children being deserialized before parents. Same reason I gave for view(<select>) in an expression position.

I am not widening this PR to that whitelist while it is queued: it would rewrite the invariant, the exception message and the test block for the third time today, and whether this boundary should validate children by node type at all is a question about the format's contract, whose class umbrella #120743 was closed as not planned earlier today. The open-shapes line in the description now names this one. If the reviewer prefers the whitelist here rather than separately, say so and I will add it.

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.

Yes, I still think this should be fixed in this PR. The current head still accepts non-expression parser-owned wrappers in these slots beyond ASTExpressionList and bare select nodes, so the expression-position invariant is still incomplete and the persisted-SQL-UDF case from this thread remains reachable.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bb79cda

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

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 5/6) / Check Results 10 errors, 3 too long: the whole Run Errors table is one test, iceberg_suite_tpch, whose measured run exceeds the harness 15 s query cap and aborts the file #120762 (mine, open)
Build profile diff the job's binary_symbols read against the CI logs cluster failed, so compare_symbols raised #118708 (mine, open)
Mergeable Check, PR praktika aggregators, red only because of the two rows above #120762 and #118708 (mine, open)

The 154 remaining checks pass; nothing here is caused by this PR's diff (src/Parsers/ plus one
stateless test).

Session id: cron:our-pr-ci-monitor:20260919-000617

if (parameters)
{
for (const auto & child : parameters->children)
if (child->as<ASTExpressionList>() || isBareSelectQuery(child.get()))

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.

While we are tightening ASTColumnsApplyTransformer::readJSON, the lambda branch is still weaker than the parser-produced invariant. ExpressionElementParsers only enters lambda mode for lambda(tuple(<single identifier>), body) and derives lambda_arg from that tuple, but the current guard still accepts any ASTFunction with two children and any non-empty lambda_arg. A payload like a plus(1, 2) node now passes, formats back as APPLY plus(1, 2), and the legacy applyColumnsApplyTransformer path still consumes arguments[1] as the lambda body. I think this needs isASTLambdaFunction(lambda_function), an exactly-one-identifier check on the tuple, and validation that it matches lambda_arg.

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 on the mechanism, and I measured the consequence before deciding. Your reading of the parser is right: ExpressionElementParsers.cpp:1891-1911 requires name == "lambda", isASTLambdaFunction, a tuple first argument with exactly one child, that child an identifier, lambda_arg derived from it, and setIsLambdaFunction(true). readJSON checks only arguments && children.size() >= 2, so five shapes get in, not one. Through --dialect=clickhouse_json --enable_json_ast_dialect=1:

payload in the lambda slot formats as executes as
valid lambda (control) APPLY x -> (x + 1) 1
plus(1, 2) plain (yours) APPLY plus(1, 2) Code: 42, passed 3 should be 2
plus(1, 2) with is_operator APPLY 1 + 2 Code: 42, passed 3 should be 2
tuple with two identifiers APPLY (x, y) -> (x + 1) Code: 36, expect 2 arguments. Actual: 1
tuple holding a literal APPLY lambda(tuple(7), x + 1) Code: 36, argument is not identifier
lambda_arg disagreeing with the tuple APPLY x -> (x + 1) 1, identical to the control

I am not adding the guard, because the checks you name already exist one layer down: QueryTreeBuilder.cpp:655-673 does the identifier and arity checks, and enable_analyzer is obsolete and frozen at 1 since v26.9 (SET enable_analyzer = 0 gives Code: 452), so no reachable query skips them.

That also settles the applyColumnsApplyTransformer half. Its only callers are TranslateQualifiedNamesVisitor and JoinToSubqueryTransformVisitor, both old analysis. The analyzer never reads lambda_arg: QueryTreeBuilder.cpp:1210-1213 builds the transformer from lambda alone and Analyzer/ColumnTransformers.cpp:110 re-derives lambda_arg from it. The mismatch row above is the proof, since a deliberately wrong lambda_arg still returns the control's answer. Two of your three checks would guard a field nothing reachable reads.

The discriminator against the bug this PR fixes is persistence. CREATE VIEW v AS SELECT COLUMNS('.*') APPLY <bad lambda> FROM numbers(1) through the JSON dialect is rejected at creation with those same codes and writes no metadata at all, so a second process over the same path reports Code: 60; the valid payload in the same probe creates a view that reloads and returns 1. The shape this PR rejects stores the view and then cannot read it back.

What remains is an unparsable or non-idempotent round trip, which is the class closed as not planned with the invalid label on #120743 yesterday. The lambda guard is also master code from the merged #120175 rather than this PR's diff. I am not widening the PR here, and I am not filing this separately.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 47d7ba7

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
Performance Comparison (arm_release, master_head, 5/6) perf-harness error, not a query regression. The shard reports 10 errors, 4 too long, and the 10 errors are all iceberg_suite_tpch failing to ATTACH its Iceberg tables: Code 481 PATH_ACCESS_DENIED, with the left/db segment doubled in the server's user_files root. #120964 (mine, merged 2026-09-19 10:45Z). This head predates that commit, so the next push to this branch picks the fix up.
Mergeable Check, PR praktika aggregators reflecting the row above #120964 (mine, merged 2026-09-19)

Measured, so the shard verdict is not misread as a perf regression: all 1304 per-query rows on this run are success, with zero slower, zero unstable and zero FAIL/ERROR. Master reproduces the identical 10 errors signature two commits before e502343bccdf1 and is green at e502343bccdf1 itself, which is the merge commit of #120964.

Session id: cron:our-pr-ci-monitor:20260919-170416

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 5cc8b733-769b-40ad-98b3-701acc6feb71
  • MIRAI run: 038cf500-c035-4faa-9ee0-3a508b03c19f
  • PR check IDs:
    • clickbench_1155995_1789993730
    • clickbench_1156001_1789993730
    • clickbench_1156007_1789993730
    • tpch_adapted_1_official_1156019_1789993730
    • tpch_adapted_1_official_1156029_1789993730
    • tpch_adapted_1_official_1156067_1789993730


static bool containsBareSelectQuery(const IAST * node)
{
const auto * list = node ? node->as<ASTExpressionList>() : nullptr;

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 I am seeing a recursive call, do a stack check

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.

Done in 5771d82: checkStackSize() as the first statement of containsBareSelectQuery, matching rejectArgumentlessFunctions in ASTJSONReadHelpers.cpp. That helper is the only recursion this PR adds; every other check it introduces is a single-level loop over one children list.

I should be straight that this guard cannot fire before the reader's own bounds. At the default max_ast_depth = 1000 a nested-ExpressionList payload reaches the walk at 850 levels and is rejected with BAD_ARGUMENTS, and 2000 levels is rejected earlier with TOO_DEEP_AST. The walk frames are much smaller than the three reader frames per level above them, so no test arm can redden on it alone and I did not add one.

Looking for a payload that would reach it turned up a real one a layer up. createFromJSON -> ASTExpressionList::readJSON -> readChildren -> createFromJSON has no stack check, and max_ast_depth bounds nodes on the path rather than stack, so raising it raises how deep that descent runs. On a debug build:

SELECT formatQueryFromJSON('{"type":"Function","name":"any","arguments":' ||
    repeat('{"type":"ExpressionList","children":[', 1500) ||
    '{"type":"Literal","value":{"field_type":"UInt64","value":1}}' ||
    repeat(']}', 1500) || '}')
SETTINGS max_ast_depth = 100000, max_ast_elements = 0;

SIGSEGV, with no log line and no stack trace. Under gdb it is createFromJSON at ASTFromJSON.cpp:364, below about 1500 repetitions of those three frames. The default limit of 1000 does not crash, so the margin is roughly 1.4x in this build.

I left that fix out of this PR deliberately. checkStackSize() in createFromJSON fires at about 700 levels in a debug build, which is below the default max_ast_depth and below the 1000-node bound 04654_ast_json_depth_guard_max_ast_depth_zero.sh case 1 asserts, so it turns that test's expected TOO_DEEP_AST into TOO_DEEP_RECURSION and makes the accepted depth depend on the build type. Reconciling the stack budget with the depth ceiling needs its own change, so I will send a separate PR for it unless you would rather have it here.

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 #121693.

Two corrections to what I wrote above, both measured. The 04654 case that is stack-sensitive is case 3, not case 1: case 1 is rejected by the raw-text bracket pre-scan before any recursion runs, so it never reaches a guard. And the narrowing does reach default settings, not only a raised max_ast_depth: the node descent trips at about 688 levels in a debug build, so payloads at node depth 800 and 999 return a result today and raise TOO_DEEP_RECURSION with the guard. It is disclosed in the PR body.

The descent I described here also turned out not to be the only one. Poco::JSON::Parser recurses over the whole document before the first AST node is built, so a valid single-node payload carrying an ignored deeply nested array segfaults inside the text parser, where no check in createFromJSON can observe it. #121693 guards all three recursions.

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov you have to give the final review on this PR.

The helper walks nested ASTExpressionList children, so its depth is the depth of
the subtree the JSON reader just built. checkStackSize() as the first statement
is the idiom the neighbouring AST JSON validation walk already uses
(rejectArgumentlessFunctions in src/Parsers/ASTJSONReadHelpers.cpp), and it is
the only recursion this PR adds: every other check it introduces is a
single-level loop over one children list.

Measured, so the guard is honest about what it can do: at the default
max_ast_depth = 1000 the reader's own per-node depth counter bounds the tree, so
a nested-list payload reaches this walk at about 850 levels and is rejected with
BAD_ARGUMENTS, while 2000 levels is rejected earlier with TOO_DEEP_AST. The walk
frames are far smaller than the reader frames above them, so this check cannot
fire before those bounds do, and no test arm can redden on it alone. It is here
so the property holds if the helper is later called from a deeper context.

Co-Authored-By: Claude Opus 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix conflicts.

One conflict, in src/Parsers/ASTJSONReadHelpers.cpp: the include block.
This branch adds ASTProjectionSelectQuery.h, ASTQueryWithOutput.h,
ASTSelectIntersectExceptQuery.h and ASTSelectQuery.h for isBareSelectQuery
and hasQueryOutputOptions; master added ASTSelectWithUnionQuery.h, which
this branch had added too, so git took that line outside the conflict.
Resolution keeps all five includes in alphabetical order.

Master's new readExpressionChildren, readFunctionChildWithExpressionArguments,
screenArgumentlessFunctions and readScreenedChildOfType in the same two files
merged without conflict and are kept verbatim. contrib/avro and contrib/cctz
took master's pins. The other four source files this branch touches are
unchanged on master since the previous merge, and no helper of this branch
became a duplicate of a master one.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed. Merged master into the branch; head is ebf58700ccf574df481808d7fe7f9a6ac743e830, and GitHub now reports the PR as mergeable.

The only conflict was the include block of src/Parsers/ASTJSONReadHelpers.cpp: this branch adds ASTProjectionSelectQuery.h, ASTQueryWithOutput.h, ASTSelectIntersectExceptQuery.h and ASTSelectQuery.h for isBareSelectQuery/hasQueryOutputOptions, and master added ASTSelectWithUnionQuery.h, which this branch had added too. I kept all five, in alphabetical order. Master's new readExpressionChildren, readFunctionChildWithExpressionArguments, screenArgumentlessFunctions and readScreenedChildOfType merged with no conflict and are untouched; contrib/avro and contrib/cctz took master's pins.

The diff against the new base is byte-identical to the pre-merge one apart from that one include line now being master's, so nothing in the fix itself changed. I rebuilt on the merged tree and ran the 59 *ast_json* stateless tests: all pass.

throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`SelectWithUnionQuery` 'list_of_selects' must contain only select queries during AST JSON deserialization");
/// `ParserQueryWithOutput` attaches output options to the outermost query only.
if (hasQueryOutputOptions(select_child.get()))

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 catches output clauses that survive deserialization into the child AST node. A malformed clickhouse_json payload can attach format_ast / settings_ast / out_file directly to an ASTSelectQuery or ASTSelectIntersectExceptQuery element; those readers ignore unknown keys, so hasQueryOutputOptions(select_child) stays false and the clause is silently dropped on reformat instead of being rejected.

That leaves the exact invariant this PR is tightening still bypassable. It also leaks back into the view(SELECT ...) hardening: if the lone inner ASTSelectQuery carries format_ast this way, the outer ASTSelectWithUnionQuery passes here, ASTFunction::readJSON sees no output options on view_select, and the payload is accepted as view(SELECT 1) instead of being rejected.

I think the child readers need to reject output-option keys explicitly (or the parent needs to validate the raw JSON object before deserializing each element), plus a regression row for a SelectQuery child carrying format_ast.

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.

Verified in the code and measured on both sides. The first half is right: hasQueryOutputOptions does return false for an ASTSelectQuery or ASTSelectIntersectExceptQuery element. The reason is that neither can hold output options at all:

ASTSelectQuery : public IAST
ASTSelectIntersectExceptQuery : public ASTSelectQuery
ASTSelectWithUnionQuery : public ASTQueryWithOutput

out_file / format_ast / settings_ast are members of ASTQueryWithOutput, so of the three types list_of_selects accepts, only ASTSelectWithUnionQuery has them, and ASTSelectQuery::readJSON has no slot those keys could land in. The dynamic_cast fails because there is nothing there, so no clause is dropped: the key is an unknown key, and no readJSON under src/Parsers/ rejects unknown keys.

Measured with formatQueryFromJSON on this head (ebf5870) against a master build without this PR (95a6488):

output-option keys attached to master 95a6488 head ebf5870
a SelectQuery element (also with the outfile flags) SELECT 1 UNION ALL SELECT 2 identical
a SelectIntersectExceptQuery element, or its child SELECT 1 INTERSECT DISTINCT SELECT 2 identical
the inner SelectQuery of view(...) SELECT * FROM view(SELECT 1) identical
a nested SelectWithUnionQuery element: format_ast (SELECT 1 FORMAT JSON) UNION ALL SELECT 2 BAD_ARGUMENTS
the same element: out_file (SELECT 1 INTO OUTFILE '/tmp/x.tsv') UNION ALL SELECT 2 BAD_ARGUMENTS
the same element: settings_ast ((SELECT 1) SETTINGS max_threads = 1) UNION ALL SELECT 2 BAD_ARGUMENTS

The three rows master accepts all fail to reparse (Code: 62 at the JSON, OUTFILE and SETTINGS token), which is the break this check exists to stop. compression, compression_level and the flags without an out_file were already rejected by readOutputOptionsJSON, so all five members of hasOutputOptions() are covered.

On the rows you name the accepted AST is not degraded either: parseQueryToJSON(formatQueryFromJSON(payload)) is byte-identical to parseQueryToJSON('SELECT 1 UNION ALL SELECT 2') and to parseQueryToJSON('SELECT * FROM view(SELECT 1)') respectively, and the round trip is idempotent.

The view leak does not follow. That slot takes arguments->children[0]->as<ASTSelectWithUnionQuery>(), so only the one type that can carry output options is accepted there and its options are rejected; a bare SelectQuery or a ProjectionSelectQuery in the same slot is rejected for the wrong shape.

So I am declining this one. The regression row you ask for passes byte-identically on master, so it would not be a regression test for this change, and rejecting specific raw JSON keys on two node types is a different invariant (unknown-key strictness) that closes nothing measured here.

rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Sep 23, 2026
Deserializing an AST from JSON (formatQueryFromJSON, the clickhouse_json
dialect) recursed with no stack check. Its only bound was a counter compared
against effectiveJSONDeserializationMaxDepth(), i.e. max_ast_depth when set and
1000 otherwise. A count is not a stack budget: safety is
stack_size / per_level_frame_cost, and both factors move independently of any
setting. Measured per-level cost in a debug build is ~6.1 KiB for the AST node
descent, ~1.0 KiB for the structured Field descent and ~65 B per JSON container
level, so the 1000-level ceiling is only ~1.4x safe on an 8 MiB stack and is
unsafe at 4 MiB, while raising max_ast_depth removes the bound outright.

On v26.8.11.7-lts a 1500-level nested AST JSON document at
max_ast_depth = 100000 terminated the process with SIGSEGV, zero output and no
stack trace, the overflow having prevented the fault handler from running.

Three distinct recursions are involved and none checked the stack:

  - createFromJSON(const Poco::JSON::Object &), the AST node descent;
  - readFieldFromObjectImpl, the structured Field descent, which adds no AST
    nodes and so is bounded only by its own limit;
  - Poco::JSON::Parser's own descent over the JSON text, which completes before
    a single AST node exists, so no check inside createFromJSON can observe it.
    A valid one-node Literal carrying an ignored 200000-level array member was
    enough to exit 139.

checkStackSize() is now called on each recursive entry, after that recursion's
existing bound check so that whenever a bound is the binding limit its own
message still wins. The check is unconditional because the stack, not a
setting, is the thing being bounded; gating it on the ceiling would leave the
default-settings 4 MiB crash reachable by construction.

DB::Exception derives from Poco::Exception, so the existing
catch (const Poco::Exception &) converted the handler's TOO_DEEP_RECURSION into
BAD_ARGUMENTS. A catch (const Exception &) { throw; } clause is ordered before
it. That was the failure mode which looks like a working guard.

Two stale comments are corrected: our Poco fork does enforce setDepth
(ParserImpl.cpp:145 in handleArray and :165 in handleObject both test
_currentDepth >= _depth, against a JSON_DEFAULT_DEPTH of 1000), so the claim
that the bracket pre-scan is the actual enforcement was wrong, and it was the
stated reason that pre-scan exists. One line records in its place what the
setDepth call does here, which the call alone does not show: it RAISES that
1000-level default to the pre-scan's budget, and that is what makes the deep
text descent reachable at all.

Rejected alternative: capping the ceiling with min(max_ast_depth, 1000). It
rejects input that works today (formatQueryFromJSON(parseQueryToJSON(...)) of a
600-nested-abs query, AST depth ~1204, returns 3016 bytes at
max_ast_depth = 200000 and is rejected at 1000), and it still would not bound
the stack: a depth-900 payload SIGSEGVs at default settings on a 4 MiB stack.

Deliberate consequence: accepted depth is now stack-bounded rather than
count-bounded. checkStackSize() permits 50% of the thread stack (5% under
TSAN), and the bisected trip depths sit at exactly that fraction of the
previous crash depth (711 against 1459 node levels, 4302 against 8565 Field
levels). In a debug build, node payloads deeper than ~690 are therefore
rejected where they previously succeeded up to 1000. Release frames are smaller
so that window sits deeper, which was not measured. A recursion bounded by the
stack cannot also promise a count.

Tests: three arms in 04056_ast_json_limits, one per guarded recursion, each
verified by its captured stack frames to trip the guard it names rather than a
neighbouring limit, and each exiting 139 on the unfixed binary. Every one of
those thresholds scales as 1 / per_level_frame_cost, which is a build property,
so the depths are placed with margin over the depth at which the UNFIXED binary
crashes (13.7x and 2.9x in a debug build) rather than over the guard's own trip
depth: that is what keeps the pre-fix failure reachable in a build whose frames
are cheaper. For the same reason the arms assert only that a controlled error
replaces the crash, never which of the three guards reports it. 04654 case 3
asserted which of two bounds rejects a payload; once the recursion is
stack-bounded that is a property of the build's stack budget (measured: the
Field bound's own message at 8 MiB, TOO_DEEP_RECURSION at a TSAN-parity 840 KiB
budget), so that arm now asserts the controlled rejection. It still fails on an
unrelated error.

Field::restoreFromDump is left alone: its dump parser is flat, so a nested dump
is rejected with CANNOT_RESTORE_FROM_FIELD_DUMP before it can recurse, measured
at depth 20000 for both Array_ and Tuple_ shapes.

Related: ClickHouse#120725

Co-Authored-By: Claude Opus 5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 24, 2026
Merged via the queue into ClickHouse:master with commit 2b5b353 Sep 24, 2026
176 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Oct 3, 2026
…e log scan

Stress worker 1 (`--database=test_1`) runs with
`memory_tracker_fault_probability=0.05`. Work that the stress phase leaves
behind keeps the settings of the query that created it and is executed again
by the upgraded server after the restart:

- a distributed DDL entry stores the initiator's changed settings
  (`DDLLogEntry`) and `DDLTaskBase::makeQueryContext` applies them, so a
  queued `BACKUP ... ON CLUSTER` of `test_1` replays with fault injection and
  `BackupsWorker` logs `Failed to make internal backup ... fault injected` at
  `<Error>`;
- a pending `Distributed` batch is sent with its stored settings, and the
  receiving async-insert flush logs `AsynchronousInsertQueue: Failed insertion
  ... fault injected` at `<Error>` with an empty query id, so the existing
  `} <Error> executeQuery: Code:` entry does not cover it.

Seen on three unrelated PRs in 90 days (ClickHouse#123464, ClickHouse#117943, ClickHouse#120725); in each job
these lines were the only output of the scan. Nothing enables fault injection
on the upgraded server itself, so the message can only come from carried-over
stress work. Ignore it as a fixed string, the same string the stress smoke
check already tolerates (`ci/jobs/scripts/stress/stress.py`). It is
MemoryTracker's message for both injection sites and does not match a real
`memory limit exceeded` error.

The large DDL backlog in the ClickHouse#123464 job comes from the previous release
(26.9) wedging its DDLWorker on `KILL PART_MOVE_TO_SHARD ... ON CLUSTER`,
which ClickHouse#122132 fixed on master only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-bot PR origin: review-bot finding 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.

any with a bare select argument still formats to the IN quantifier

4 participants