Repository navigation
Reject AST shapes the parser cannot produce in the AST JSON format - #120725
alexey-milovidov merged 18 commits into
Conversation
…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.
Internal second-model review (3 rounds, 2 blockers fixed)Each round is an independent cold read plus a separate model, adjudicated against the recorded ❌ Blockers found and fixed in this PR
💡 Nits
Confirmed rather than assumed: the accepted shapes are still exactly what the parser produces Session id: cron:clickhouse-review-slot-11:20260918-032400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260918-001600 |
|
Workflow [PR], commit [ebf5870] Summary: ✅
AI ReviewSummaryThis PR hardens Findings❌ Blockers
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 ReportMeasured on commit ebf5870.
Changed lines: Changed C/C++ lines covered: 74/79 (93.67%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
| @@ -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 | |||
There was a problem hiding this comment.
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.
| "'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 " |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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.
| "'arguments' and 'parameters' cannot have an expression list child during AST JSON deserialization"); | ||
|
|
||
| r.readAlias(*this); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 = 1tuple 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.
There was a problem hiding this comment.
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.
CI finish ledger - bb79cdaEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
The 154 remaining checks pass; nothing here is caused by this PR's diff ( Session id: cron:our-pr-ci-monitor:20260919-000617 |
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| if (parameters) | ||
| { | ||
| for (const auto & child : parameters->children) | ||
| if (child->as<ASTExpressionList>() || isBareSelectQuery(child.get())) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - 47d7ba7Every 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
Measured, so the shard verdict is not misread as a perf regression: all 1304 per-query rows on this run are Session id: cron:our-pr-ci-monitor:20260919-170416 |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
|
|
||
| static bool containsBareSelectQuery(const IAST * node) | ||
| { | ||
| const auto * list = node ? node->as<ASTExpressionList>() : nullptr; |
There was a problem hiding this comment.
@groeneai I am seeing a recursive call, do a stack check
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
@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]>
|
@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.
|
Fixed. Merged master into the branch; head is The only conflict was the include block of 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 |
| 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())) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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]>
…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]>
Closes: #120679
Related: #120175 (comment)
Changelog category (leave one):
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 withBAD_ARGUMENTSinstead of formatting into SQL that parses back as a different query.Description
What breaks.
IAST::createFromJSONaccepted a bareSelectWithUnionQueryamong a function'sargumentsorparametersunder any name. Namedanyit formats asany(SELECT 1), which parses back as1 IN (SELECT 1): a different query, no error. Throughdialect = 'clickhouse_json'it reaches DDL:CREATE VIEWis accepted silently, the metadata storesAS 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
parametersand the window suffix never print;readJSONgated 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
ASTExpressionListchild ofargumentsorparametersis rejected: a child there is an expression, which a list is not, and the formatter prints its children inline, so one argument becomes several.APPLYandREPLACEown expression positionsASTFunction::readJSONnever sees, so both get the same checks. The union reader rejects a one-element chain whose element is another union, whichParserSelectWithUnionQuerylifts, and both set operation readers reject an element carrying output options.Validation. 24 shapes now raise
BAD_ARGUMENTS, each a row in04339_ast_json_review_followup_hardeningfailing on master. Positive controls for every conjunct, includingGROUPING 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
ExplainQueryorOrderByElement, and a locally validview(<select>), which SQL allows only as a table function. Rejecting the first by node type would also reject parser output, sinceORDER BY tuple(a DESC, b DESC)puts one in a function's arguments, so the rule needs the parent contextreadJSONlacks.Workflow [PR]
Sync PR [sync-upstream/pr/120725]
Version info
26.10.1.625-master(included in26.10and later)