Repository navigation
Reject an argument-less function in a constraint expression restored from AST JSON - #120507
Conversation
…from AST JSON
A `clickhouse_json` payload whose constraint expression is an `ASTFunction` with
no `arguments` list kills the server on `CREATE TABLE`/`ALTER TABLE`. Measured on
pristine master (debug): rc=134, `Assertion 'px != 0' failed`, backtrace
ComparisonGraph<ASTPtr>::ComparisonGraph
<- ConstraintsDescription::buildGraph() ConstraintsDescription.cpp:152
<- ConstraintsDescription::update() ConstraintsDescription.cpp:388
<- InterpreterCreateQuery::getConstraintsDescription InterpreterCreateQuery.cpp:841
and, for `and`/`or`/`not`, in `TreeCNFConverter::splitMultiLogic` - that
backtrace was captured with an `and` payload, and `splitMultiLogic` recurses only
into those three names. 12 of 19 malformed shapes killed the process, `in` among
them at a site I did not measure. `enable_json_ast_dialect` is not readonly, so
any client that can set it reaches this with one DDL statement.
`ASTFunction::arguments` is optional because `setNoEmptyArgs` clears an empty
list, so a table engine, a `CODEC`/`STATISTICS` element and an index `TYPE` are
argument-less functions and `writeJSON` emits no `"arguments"` member for them;
`ASTFunction::readJSON` therefore cannot require it, and rejecting a missing
member there would break `CODEC(LZ4)`, `STATISTICS(tdigest)` and
`INDEX ... TYPE minmax` (existing tests 04653, 04307, 04337, 04344, 04350).
Inside an expression the parser can never build such a node, because
`ParserFunction::parseImpl` only creates a function after an opening
parenthesis. The constraint slot was read through the untyped `readChild`, and
constraint expressions are the one thing consumed before analysis, so the null
list reached two consumers that dereference it unconditionally.
The screen goes at the deserialization boundary, in the slot's owner: the only
layer that knows the slot is an expression. It joins `readSpecialFunctionChild`
/ `readIdentifierChild` / `readChildOfType`, whose own doc comment already names
this failure mode ("null-dereference path instead of failing here with
BAD_ARGUMENTS"). Blast radius on SQL users: none.
Its scope is the subtree reachable through `IAST::children`, which is exactly the
crash surface. `ASTFunction` registers its `arguments` list as a child
(`ASTFunction.cpp:227`), so that walk reaches every argument of every nested
function - and it is also the only way the unanalyzed consumers reach anything:
`countAtoms` and `expressionContainsArrayJoin` recurse over `IAST::children`,
while `splitMultiLogic`, `traversePushNot` and `traverseCNF` recurse over
`arguments->children`, a subset of it. `ComparisonGraph` does not recurse at all -
it calls `getArguments` on the atom itself (`:293`, `:336`), and the atoms come
from `traverseCNF`. So a node that owns an AST outside `children`, namely
`ASTColumnsApplyTransformer`'s `parameters` and `lambda`, is out of reach for
those consumers as well as for this check. Measured: a nested argument-less
function there is accepted, persists as `x -> greater()`, and fails INSERT with
`UNKNOWN_IDENTIFIER` - the same error a *well-formed* `COLUMNS(...) APPLY`
constraint gives, because that matcher is never expanded in a constraint at all.
05227 pins that boundary instead of widening the walk: a mechanical sweep of
`src/Parsers/**/readJSON` counts dozens of such member slots across ~20 node
types, so enumerating ownership edges would be a large diff that silently
re-opens whenever a node is added.
Alternatives rejected, both measured:
* Guarding the crash sites. `TreeCNFConverter` alone has ~25 unguarded
`func->arguments->children` reads, so each further shape would need its own
guard; `ComparisonGraph.cpp:44-47` (01e999e) already documents the
assumption that a caller screened this out.
* Filtering in `ConstraintsDescription::filterConstraintsForOptimization`.
That mechanism distrusts *stored* metadata, and this shape can never be
stored: a null list formats as `()`, so what persists is `CHECK greater()`,
which reparses into the already-safe empty-list shape.
The walk visits every child, including a nested query: `ParserSubquery` accepts
only a SELECT (an `EXPLAIN` subquery is restricted to SELECT queries too), so no
argument-less slot can appear inside one. It needs no stack check of its own -
it is a bounded second pass over a tree the deserializer has already built under
its own depth and element limits, and a deep payload hits `TOO_DEEP_AST`
identically before and after this change.
A present but empty argument list stays untouched: `CHECK greater()` still
creates the table and still fails at INSERT with
`NUMBER_OF_ARGUMENTS_DOESNT_MATCH`. Shapes that used to be accepted and fail
later at INSERT (`notEquals`, `empty`, `isNull`, `plus`, an unknown name) are
now rejected at parse time inside this dialect.
Tests: 05226 covers the boundary through `formatQueryFromJSON` (both crash
sites, a nested occurrence, an `ASSUME` constraint, `ALTER ... ADD CONSTRAINT`,
plus the accepted shapes as over-rejection controls); 05227 drives the real DDL
entry point. It sends the payloads over HTTP rather than through
`clickhouse client --dialect clickhouse_json`, because the client deserializes
them itself: in the client form the test passed against an unfixed server that
had never seen the payload.
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewThis change was reviewed cold by a second model against the resulting code, then adjudicated. Round 2
Also noticed, not acted on: one row of my own payload matrix labelled "well-formed control" is itself a |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260917-010800 |
|
Workflow [PR], commit [3bf1a46] Summary: ✅
AI ReviewSummaryThis PR hardens Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 3bf1a46.
Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units76 translation units recompiled, 321 s compile time in total, 76 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.20 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
| /// `function_name` is either `CODEC` or `STATISTICS`. Returns nullptr when the key is absent. | ||
| ASTPtr readSpecialFunctionChild(const char * key, const char * function_name) const; | ||
|
|
||
| /// Read a child AST node filling a parser-produced *expression* slot, and reject an `ASTFunction` |
There was a problem hiding this comment.
Trimmed in 89b1efa: 11 lines down to 5, keeping only what a reader cannot get from the code below it, namely why the check cannot sit in ASTFunction::readJSON (its slots legitimately hold a function with no argument list). The ParserFunction/setNoEmptyArgs mechanics, the named consumers and the children scope argument moved to the commit message, and the scope boundary itself is pinned by test 05227 rather than by prose.
|
|
||
| void rejectArgumentlessFunctions(const IAST & ast, const char * key) | ||
| { | ||
| const auto * function = ast.as<ASTFunction>(); |
There was a problem hiding this comment.
@groeneai this has recursive calls; can you check for stack overflows?
There was a problem hiding this comment.
Checked, and added checkStackSize() in 89b1efa.
The walk cannot be the first recursion to run out of stack: it starts only after the subtree is built, and uses one small frame per level against the four larger frames per level of the createFromJSON -> readJSON -> readChild/readChildren cycle that built it. Measured on this branch, debug build, with a 5000-level nested constraint expression (10000 AST levels):
- default settings:
Code: 167 TOO_DEEP_AST, "JSON nesting depth exceeds the limit derived from max_ast_depth (8000)", before a single node is constructed; max_ast_depthraised to 2000 or to 5100: SIGSEGV inside that construction cycle (IAST::createFromJSON,ASTFromJSON.cpp:366, underreadChildrenandASTExpressionList::readJSON), so the new walk never runs.
The second row reproduces identically on pristine master, so it is pre-existing rather than something this PR introduces: raising max_ast_depth also raises the JSON nesting bound derived from it (max_ast_depth * 8), past what the stack carries. Let me know if you want an issue for it.
Both changes are review requests on ClickHouse#120507. The doc comment keeps only what a reader cannot derive from the code below it: why the check cannot live in `ASTFunction::readJSON`, whose slots legitimately hold a function with no argument list. The rest (the `ParserFunction::parseImpl` and `setNoEmptyArgs` mechanics, the named consumers, the `children` ownership edge) is in the previous commit message and, for the ownership edge, pinned by test 05227. `checkStackSize()` makes the walk safe on its own terms. It could not be the first recursion to exhaust the stack: it runs after the tree is built, one small frame per level, against the four larger frames per level of the `createFromJSON` -> `readJSON` -> `readChild`/`readChildren` cycle that built it. Measured on this branch, debug build, with a 5000-level nested constraint expression (10000 AST levels): * default settings: `Code: 167 TOO_DEEP_AST`, "JSON nesting depth exceeds the limit derived from max_ast_depth (8000)", before any node is constructed; * `max_ast_depth` raised to 2000 or to 5100: SIGSEGV inside that construction cycle (`ASTFromJSON.cpp:366` <- `readChildren` <- `ASTExpressionList::readJSON` <- `createFromJSON` ...), so the new walk never runs. Identical on pristine master, so that is pre-existing and not what this PR touches. Co-Authored-By: Claude Opus 5 <[email protected]>
|
While checking that recursion I re-measured the other untyped expression slots, found the description too broad on that point, and have corrected it. Through the same
The six that abort land in My plan is a separate PR wiring the same validator into those slots, since each one needs its own over-rejection check (engine, |
|
The follow-up promised above is open as #120882. It wires the same screen into the storage-key, skip-index and TTL expression slots, plus |
CI finish ledger - 89b1efaEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
No failure on this head is reachable from this PR's diff, which rejects an argument-less function in a Session id: cron:our-pr-ci-monitor:20260918-170449 |
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.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…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
Related: #120483
Related: #120380
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a server crash on
CREATE TABLE/ALTER TABLEwhen a constraint expression restored through theclickhouse_jsondialect held a function without anargumentslist. Such a payload now fails withBAD_ARGUMENTSwhile the AST is deserialized, so shapes that used to be accepted and fail later atINSERT(for examplenotEqualswith no argument list) are rejected at parse time inside that dialect.Description
A client that can
SET enable_json_ast_dialect = 1(it is notreadonly) kills the server with one DDL statement: aclickhouse_jsonpayload whose constraint expression is a function without an"arguments"member.ASTFunction::argumentsis optional, becausesetNoEmptyArgsclears an empty list - a table engine and an indexTYPEare argument-less functions - soASTFunction::readJSONcannot require the member. Inside an expression the parser can never build such a node (ParserFunction::parseImplneeds an opening parenthesis), and the constraint machinery is the one consumer reading an expression before analysis:ConstraintsDescription::update()hands it toTreeCNFConverter::splitMultiLogicand toComparisonGraph, which both dereferenceargumentsunconditionally. 12 of 19 malformed shapes killed the process, the reported one inComparisonGraph'sgetArguments.So the shape is rejected where it enters the process, by a new
JSONObjectReader::readExpressionChildused for the declaration'sexprslot - joining the slot validators already inASTJSONReadHelpers, whose own comment names this failure mode. Nothing outside JSON deserialization changes, and a present-but-empty argument list (CHECK greater(), which the parser does produce) behaves exactly as before.Both crash sites are left unchanged on purpose:
ComparisonGraph<ASTPtr>is constructed in only two places, both inConstraintsDescription, so neither is reachable with a null list once the boundary rejects, while guarding instead would take ~25 separate guards inTreeCNFConverteralone. The other untyped expression slots are not screened here: columnDEFAULT, projections and theALTER UPDATEpredicate report ordinary user errors, while the storage key, a skip-index expression and table or columnTTLstill abort on master through a different consumer, which needs its own PR.The crash reproduces on pristine master and stops here (re-checked by reverting only the new call site); a 42-statement round-trip sweep across both builds shows no over-rejection.
Workflow [PR]
Sync PR [sync-upstream/pr/120507]
Version info
26.10.1.211(included in26.10and later)