Repository navigation
Reject an argument-less function in an expression restored from AST JSON - #120882
alexey-milovidov merged 13 commits into
Conversation
…tored from AST JSON
Through the clickhouse_json dialect a payload whose Function node has its
"arguments" member deleted terminates the server when it lands in a storage-key,
skip-index or TTL expression slot: an assertion failure on a debug build, a null
dereference under NDEBUG. Both settings that reach it (enable_json_ast_dialect
and dialect) are settable per query by any user, and a real server dies, not
only clickhouse local. Pre-existing on master.
ASTFunction::arguments is genuinely optional, because setNoEmptyArgs even erases
an empty list, so a table engine, a CODEC/STATISTICS element and an index TYPE
are legitimately argument-less and ASTFunction::readJSON cannot require the
member. The deserializer restores such a node into a slot the SQL parser fills
with ParserExpression, where the member is never absent, so the node is
parser-impossible and its consumers dereference the list unconditionally.
There are two such consumers, both reached from a storage-metadata builder that
runs the legacy TreeRewriter/ExpressionAnalyzer over the raw AST, and both
intercepting a function by NAME before any arity check:
checkFunctionIsInOrGlobalInOperator (Interpreters/misc.h) for the in family, and
ActionsMatcher::visit for arrayJoin and grouping.
That gives the rule for which slots to screen: exactly those whose expression a
storage-metadata builder (KeyDescription, IndicesDescription, TTLDescription)
analyses outside a query context. Beyond the CREATE and ALTER key, index and TTL
slots, three reach the same builders less obviously:
- ASTInsertQuery::partition_by, which StorageFile::write and StorageURL hand to
PartitionStrategyFactory and thence to KeyDescription::getKeyFromAST when the
path carries a wildcard;
- ASTAlterCommand::ttl, where the CREATE side already required an
ExpressionList of ASTTTLElement but the ALTER side imposed no type, so a
foreign child slipped through to TTLDescription::getTTLFromAST and was read
as a COLUMN TTL and analysed as a bare expression. That contract is restored
here as well, which is a second, non-crashing hole in the same slot: such a
payload formatted back as TTL <expr> while applying something else;
- the ARGUMENTS of ASTStorage::engine, which become key expressions in
registerStorageMergeTree's deprecated positional MergeTree(date, key,
granularity) branch. The engine node itself must stay unscreened, since it is
argument-less by construction, so the screen walks the argument list only;
an argument-less function in an argument position keeps an empty but present
list, and only the engine node drops the member.
Query-analyser slots are left alone because they measured non-fatal, not because
of a general rule about analyser arity checks: a column DEFAULT, a projection
body and an ALTER ... DELETE WHERE predicate answer a plain user error with the
process alive. UNIQUE KEY is left alone as an identifier-list contract rather
than an expression key.
ASTAssignment needs its own reader rather than a named-key screen:
ASTTTLElement::group_by_assignments is a plain ASTs member filled by a
hand-rolled loop that bypasses JSONObjectReader, so no container-level screen
reaches it. Screening the element's own reader also covers ALTER ... UPDATE and
the standalone UPDATE, which share it.
The crash sites stay unguarded deliberately: the boundary is the single place a
parser-impossible node can be refused, and there are 1,149 unconditional
arguments-> dereferences in src/ to chase otherwise.
Based on ClickHouse#120507, which introduces readExpressionChild.
Related: ClickHouse#120507
Related: ClickHouse#120743
Drop the engine-arguments helper's motivating example and the obvious 'restored generically' clause; the contracts stay.
Internal second-model reviewTwo review rounds over this tree, each with two independent passes: a cold read of the resulting code plus
Checked and deliberately left unscreened: Two claims I verified rather than assumed. "Left alone because measured non-fatal" for a column |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260918-151700 |
|
Workflow [PR], commit [f0b20ab] Summary: ✅
AI ReviewSummaryThis PR closes most of the Findings
Final Verdict❌ Changes requested. The remaining unscreened LLVM Coverage ReportMeasured on commit f0b20ab.
Changed lines: Changed C/C++ lines covered: 138/144 (95.83%) · Uncovered code |
The screen this branch adds covers the skip index `expression` slot, so an argument-less function in an index expression is rejected while the AST is deserialized instead of by `IndexDescription::initExpressionInfo` behind it. Two rows of 05218_ast_json_lambda_shape_query_analysis reported NUMBER_OF_ARGUMENTS_DOESNT_MATCH and TYPE_MISMATCH from that reader and now report BAD_ARGUMENTS for the `expression` key, which is what the Fast test run on c2662ac observed. The reader's own guards are untouched and stay reachable, through the dialect and from SQL: an `arguments` list that is present but the wrong size passes the screen and `extractNamesFromLambda` answers exactly as before. Measured on this head and on master, identical both ways: an index expression of `lambda(a)` gives NUMBER_OF_ARGUMENTS_DOESNT_MATCH, `lambda(a, a)` and `lambda(tuple(1), a)` give TYPE_MISMATCH. The first is added to the test as the screen's negative, so a future change that starts rejecting shapes the parser can write is caught here. Verified on the merged tree (build id 6e9883318badc1b29799803ebed662307b73019e): the test passes 10 runs without settings randomization and 5 with it, and the 85 tests of the AST JSON and dialect family pass except two that need a cluster and a writeable access storage this single-node run does not have (SKIPPED and OK respectively in the Fast test on c2662ac). Also corrects two comments in 05230 that the second-model gate flagged twice: `getIndexFromAST` is a member of `IndexDescription`, and of the three payloads under the second non-vacuity guard only the `MODIFY TTL` one replaces a whole node, the other two delete an `arguments` member like the rows above them.
| @@ -0,0 +1,67 @@ | |||
| -- A constraint expression is consumed before analysis: `ConstraintsDescription::update` hands it to | |||
There was a problem hiding this comment.
@groeneai can you reduce the number of tests added? We don't need that many
There was a problem hiding this comment.
Done in d706466: 43 queries across the four files instead of 109, and 219 test lines instead of 402.
- 05230's 35 round-trip rows collapse into 5 (one dense
CREATEcovering every screened slot, both engine forms, bothALTERforms), and its 17 rejection rows move into 05231, where the oracle is the screen's own message rather than a bareBAD_ARGUMENTS; theisValidJSON/countSubstringspayload guards those rows needed go with them. - 05231 drops the five routes that read a declaration node another row already covers:
ADD INDEX,CREATE INDEX,MODIFY COLUMN ... TTL,MODIFY TTL <expr>andMODIFY TTL ... GROUP BY ... SET. - 05226 collapses 7 accepted shapes into 2 and drops the
ASSUMEandMODIFY CONSTRAINTrejections, which reach the same reader as the rows that stay. 05227 loses itsINSERT ... VALUESrow, which took the async-insert path and hung for 600 s once while running locally.
What is left is one rejection per reader call site this PR changes. Replayed against this PR's base (#120507's head), 15 of those 16 storage-slot rows still abort the process and the sixteenth is accepted there, so nothing in the reduced set is decorative.
05226 and 05227 belong to the stacked #120507; I trimmed them here rather than re-pushing a PR you have already reviewed. Happy to move that part into #120507 instead if you prefer it there.
Review ask on ClickHouse#120882: fewer tests. One case per scenario now, with the breadth kept only where a reader can regress on its own. * 05230 (`.sql`, through `formatQueryFromJSON`) keeps just the shapes that must keep round-tripping: one dense CREATE covering every screened slot next to the argument-less `CODEC`/`STATISTICS`/`TYPE` functions, the two engine forms, the two ALTER forms, and the row that pins the slots deliberately left unscreened. Its 17 rejection rows move to 05231, where the assertion is the screen's own message instead of a bare error code, so the `isValidJSON`/`countSubstrings` payload guards they needed are gone as well. * 05231 (dialect) keeps one rejection per changed reader call site and drops the five routes that read a declaration node already covered by another row: `ADD INDEX`, `CREATE INDEX`, `MODIFY COLUMN ... TTL`, `MODIFY TTL <expr>` and `MODIFY TTL ... GROUP BY ... SET`. Its reference now records the slot key the screen reports, so a payload that failed to build cannot pass silently. * 05226/05227 collapse seven accepted shapes into two and drop the `ASSUME` and `MODIFY CONSTRAINT` rejections, which reach the same reader as the rows that stay. 05227 also loses its `INSERT INTO tc VALUES (1)` row, which asserted the error an unexpanded `COLUMNS(...) APPLY` constraint gives, took the async-insert path, and hung for 600 s once while running locally. 109 queries down to 43, 402 test lines down to 219, and every rejection row that stays still detects the defect: replayed against the base binary (89b1efa, ClickHouse#120507's head), 15 of the 16 storage-slot rows abort the process, and the sixteenth is accepted there while the screen now answers it with the list-of-TTL-elements contract.
CI finish ledger - d706466Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Rule 3c, not 3d, decided at the tree that ran: praktika pins the merge commit at run creation, and the Session id: cron:our-pr-ci-monitor:20260919-020058 |
CI finish ledger - 8a21e37Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
On the upgrade row and the "fix already present" rule: #118993 merged on 2026-09-12 and is on this branch (comparing its merge commit The To save a reader the check, these are not failures: the two Session id: cron:our-pr-ci-monitor:20260919-070137 |
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes15 object files changed (-3.51 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units75 translation units recompiled, 286 s compile time in total, 75 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
`ApplyWithSubqueryVisitor` and `ExecuteScalarSubqueriesVisitor` run over an unanalysed AST, and both
reach `checkFunctionIsInOrGlobalInOperator`, which dereferences `arguments` unconditionally. Five
slots reached them from `clickhouse_json` because they were restored with a raw `readChild` or a bare
`readChildOfType`, so a payload could put a function with no `arguments` member there:
* `ASTUpdateQuery::predicate`, visited by `InterpreterUpdateQuery::execute`
* `ASTAlterQuery::predicate` (`ALTER ... UPDATE`/`DELETE`), visited through
`replaceNonDeterministicToScalars` when `mutations_execute_subqueries_on_initiator` is set
* `ASTCreateQuery::select`, visited by `InterpreterCreateQuery` for a view definition
* `ASTAlterQuery::select` (`MODIFY QUERY`), visited by `InterpreterAlterQuery::execute`
* `ASTInsertQuery::select`, visited by `StorageDistributed::distributedWrite` when the
destination is `Distributed` (taken by default, `parallel_distributed_insert_select = 2`)
The two slots that hold a table function directly, `ASTInsertQuery::table_function` and
`ASTCreateQuery::as_table_function`, are screened for the same reason: the parser gives even a
zero-argument table function an empty `arguments` list, and `TableFunctionNumbers::executeImpl` reads
that list unconditionally, so `INSERT INTO FUNCTION numbers() SELECT 1` and `CREATE TABLE t AS
numbers()` without the member killed the server too. An intact `numbers()` payload is still accepted.
Each one killed a real server, measured on this branch's base (git hash 89b1efa) and on its
head: signal 6, stack `checkFunctionIsInOrGlobalInOperator` <- the visitor <- the interpreter.
`UPDATE` also died with the function nested one level deeper, and `CREATE VIEW` with it nested
inside a subquery, so the screen has to walk the subtree. Every payload now answers `BAD_ARGUMENTS`
naming the slot, the server stays up, and the intact payloads still apply.
The new `readScreenedChildOfType` keeps the existing node-type check and adds that walk. A query
subtree holds expressions and query-shape nodes only, which is the same property `readExpressionChild`
already relies on when it walks into a restored subquery, and the over-rejection A/B over 100,000
statements (every single-line statement of `tests/queries/0_stateless` plus the curated carriers)
reports 0 over-rejections, 0 new acceptances and 0 changed round-trips.
The remaining routes need no screen, also measured: `DELETE ... WHERE` reformats its predicate to
SQL text and re-parses it (`Code: 42`, and `Code: 341` with `validate_mutation_query = 0`), as do
`KILL QUERY WHERE` and `SHOW TABLES WHERE`; a plain `SELECT`, `EXPLAIN PLAN`, `EXPLAIN QUERY TREE`,
a projection `SELECT` and a column `DEFAULT` all reach the analyzer's arity check first; `EXPLAIN
SYNTAX`, `EXPLAIN AST`, `CREATE FUNCTION` and `ALTER ... UNLOCK SNAPSHOT` only format, and the last
two must keep accepting an argument-less function.
The two TTL containers additionally reject an empty list, which their element loops accepted
vacuously although `ParserTTLExpressionList` reads at least one element. The consequence was not
confined to the formatter: the `CREATE` side wrote `metadata/<db>/<table>.sql` with a bare `TTL`
clause, `SHOW CREATE TABLE` and `ATTACH` then failed with `Code: 62`, and a server holding such a
table did not start at all (`Caught exception while loading metadata: Code: 62 ... Syntax error`).
Both sides now answer `BAD_ARGUMENTS`, no table is created, and an existing TTL is preserved.
05231 gains one row per newly screened slot plus the two empty-list rows, and 05230 drops the
`ALTER ... DELETE WHERE` column of its unscreened-slots row, which is now screened. The `tk` fixture
carries the two materialized columns `supportsLightweightUpdate` requires, so the `UPDATE` row
reaches the predicate instead of stopping at that check, which makes it the crash route's own
oracle.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ABLE OVERRIDE `ASTTableExpression::table_function` and `ASTExplainQuery::table_function` were the two remaining table-function slots read from AST JSON without the argument-less-function screen, so a `clickhouse_json` payload with the function's `arguments` member deleted reached the table function itself: * `EXPLAIN AST optimize = 1 SELECT * FROM numbers()`: `ExplainAnalyzedSyntaxMatcher` builds the pre-analyzer `InterpreterSelectQuery` for every `SELECT` it walks, which resolves the table function from the restored AST (`JoinedTables::getLeftTableStorage` -> `Context::executeTableFunction`), and `TableFunctionNumbers::executeImpl` reads `function->arguments->children` unconditionally. A debug build aborts on `Assertion 'px != 0' failed`, a release build dereferences null. * `EXPLAIN TABLE OVERRIDE mysql() PARTITION BY x`: `InterpreterExplainQuery` executes that function directly, and `TableFunctionMySQL::parseArguments` answers a missing `arguments` list with a `LOGICAL_ERROR`, which aborts a debug or sanitizer build. A plain `SELECT * FROM <table function>()` is not affected: query analysis rebuilds the argument list from the query tree, and `enable_analyzer = 0` has been refused since v26.9, so the pre-analyzer interpreter is only reachable through `EXPLAIN AST optimize = 1`. Both slots hold a parser-produced node that always carries an `arguments` list, even for a zero-argument table function, so the screen rejects nothing the parser can produce: 100,000 corpus statements round-trip identically on both binaries. Co-Authored-By: Claude Opus 5 <[email protected]>
| setExplainedQuery(std::move(query_child)); | ||
|
|
||
| auto table_function_child = r.readChildOfType<ASTFunction>("table_function"); | ||
| auto table_function_child = r.readScreenedChildOfType<ASTFunction>("table_function"); |
There was a problem hiding this comment.
This only closes the table_function half of EXPLAIN, but a bare EXPLAIN AST optimize = 1 SELECT 1 WHERE 1 IN (1) is still reachable through the unchanged query child just above. ASTExplainQuery::readJSON still restores that as a raw ASTSelectQuery, and ASTSelectQuery::readJSON still uses plain readChild for prewhere/where/having/qualify/limit_* (src/Parsers/ASTSelectQuery.cpp:795-808). During EXPLAIN AST optimize = 1, ExplainAnalyzedSyntaxMatcher instantiates InterpreterSelectQuery on that restored SELECT (src/Interpreters/InterpreterExplainQuery.cpp:255-260), which still hits checkFunctionIsInOrGlobalInOperator before any arity guard and dereferences func.arguments unconditionally (src/Interpreters/misc.h:48). So the server-side null dereference this PR is fixing for view / INSERT ... SELECT / table-function queries remains reachable through EXPLAIN AST optimize = 1.
Please screen bare ASTSelectQuery expression slots too, or walk the whole ASTSelectQuery subtree during deserialization, and add a regression case for the EXPLAIN AST optimize = 1 route.
CI finish ledger - 87f76a8Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
No test-level Session id: cron:our-pr-ci-monitor:20260921-030432 |
Brings the branch up to date with origin/master (88dea5e). No master commit in that range touched any of the 22 files this branch changes, so the merge was clean with no conflicts, and the branch's diff against master is unchanged at +387/-136 across the same 22 files. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
@groeneai what about the latest failures? I want to see if there is a PR for the BuzzHouse one |
CI finish ledger - e62fae0Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
The Now the BuzzHouse one, since that is the question. It is not from this pull request (the diff is the #112978 fixes the grammar, and its The head you merged at 08:30Z today is still running. I will post its ledger when it finishes. Session id: cron:clickhouse-premium-slot-26:20260922-093145 |
|
@alexey-milovidov you have to give the final review on this PR. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a server crash when a
clickhouse_jsonpayload restores an expression holding a function with noargumentslist, a shape the SQL parser cannot produce: a storage key, a skip index, a TTL, anUPDATEor mutation predicate, a view orINSERT ... SELECTbody, or a table function. Such a payload is now rejected withBAD_ARGUMENTS, as is an emptyTTLlist, which was persisted as metadata that no longer loaded.Description
SET enable_json_ast_dialect = 1, dialect = 'clickhouse_json'is settable per query by any user. A payload whoseFunctionnode lost its"arguments"member terminates a real server once it reaches a reader of an unanalysed expression (SIGABRT on debug, a null dereference under NDEBUG). Pre-existing on master, not a #120507 regression.ASTFunction::argumentsis genuinely optional (a table engine, aCODECelement, an indexTYPE), soASTFunction::readJSONcannot require it. But the storage-metadata builders (KeyDescription,IndexDescription,TTLDescription),ApplyWithSubqueryVisitor,ExecuteScalarSubqueriesVisitorand the table-function factories dereference that list before any arity check, so each slot refuses it.Screened: every slot such a reader sees with no reparse or analyzer pass. Storage metadata:
PARTITION BY,PRIMARY KEY,ORDER BY,SAMPLE BY, a skip index, a TTL expression /DELETE WHERE/GROUP BY ... SET, a column TTL, theirALTERforms,INSERT INTO FUNCTION ... PARTITION BY, and the deprecated positionalMergeTree(date, key, granularity)arguments. Beyond it: a lightweightUPDATEpredicate, anALTER ... UPDATE/DELETEpredicate, a view body,MODIFY QUERY, anINSERT ... SELECTbody, and the four table-function slots (INSERT,CREATE ... AS, aSELECTtable expression,EXPLAIN TABLE OVERRIDE).ALTER MODIFY TTLalso regainsCREATE's list-of-ASTTTLElementcontract, and both TTL containers refuse an empty list:CREATEpersisted a bareTTLclause, after which the table failed toATTACHand the server failed to start.Left alone, measured non-fatal: a column
DEFAULT, a projection body,DELETE FROM, a plainSELECT's expressions,EXPLAIN PLAN;UNIQUE KEY;CREATE FUNCTIONandUNLOCK SNAPSHOT, which legitimately hold one; and the crash sites: the boundary is where a parser-impossible node belongs.Based on #120507 (which adds
readExpressionChild); its commits show until it merges. Family: #120743.Validation: 25 rejection routes crash or corrupt metadata pre-fix and answer
BAD_ARGUMENTSafter; 100,000 corpus statements round-trip identically on both binaries.Workflow [PR]
Sync PR [sync-upstream/pr/120882]
Version info
26.10.1.436-master(included in26.10and later)