Skip to content

Reject an argument-less function in a constraint expression restored from AST JSON - #120507

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-json-ast-constraint-argumentless-function
Sep 19, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-json-ast-constraint-argumentless-function

Conversation

@groeneai

@groeneai groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120483
Related: #120380

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 server crash on CREATE TABLE/ALTER TABLE when a constraint expression restored through the clickhouse_json dialect held a function without an arguments list. Such a payload now fails with BAD_ARGUMENTS while the AST is deserialized, so shapes that used to be accepted and fail later at INSERT (for example notEquals with no argument list) are rejected at parse time inside that dialect.

Description

A client that can SET enable_json_ast_dialect = 1 (it is not readonly) kills the server with one DDL statement: a clickhouse_json payload whose constraint expression is a function without an "arguments" member.

ASTFunction::arguments is optional, because setNoEmptyArgs clears an empty list - a table engine and an index TYPE are argument-less functions - so ASTFunction::readJSON cannot require the member. Inside an expression the parser can never build such a node (ParserFunction::parseImpl needs an opening parenthesis), and the constraint machinery is the one consumer reading an expression before analysis: ConstraintsDescription::update() hands it to TreeCNFConverter::splitMultiLogic and to ComparisonGraph, which both dereference arguments unconditionally. 12 of 19 malformed shapes killed the process, the reported one in ComparisonGraph's getArguments.

So the shape is rejected where it enters the process, by a new JSONObjectReader::readExpressionChild used for the declaration's expr slot - joining the slot validators already in ASTJSONReadHelpers, 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 in ConstraintsDescription, so neither is reachable with a null list once the boundary rejects, while guarding instead would take ~25 separate guards in TreeCNFConverter alone. The other untyped expression slots are not screened here: column DEFAULT, projections and the ALTER UPDATE predicate report ordinary user errors, while the storage key, a skip-index expression and table or column TTL still 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

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

…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

This change was reviewed cold by a second model against the resulting code, then adjudicated. Round 2
(cold re-review of the fixes plus a fresh gate pass over them) returned no findings. Round 1 findings
and verdicts:

Finding Verdict
❌ The new screen walks IAST::children, so it does not see a function nested in ASTColumnsApplyTransformer's parameters/lambda, which that node owns outside children. A CHECK COLUMNS('a') APPLY (x -> x > 0) payload with the nested argument list deleted is accepted. Confirmed, and fixed as a scope statement plus a test rather than a wider walk. Nothing behind that edge dereferences the list: the unanalyzed consumers reach nodes only through children (splitMultiLogic / traversePushNot / traverseCNF over the arguments->children subset, and ComparisonGraph does not recurse at all), and the APIs that do cross it are null-safe (updateTreeHashImpl never reads arguments; appendColumnNameImpl and toLiteral guard for it). Measured: the payload creates the table, degrades to the safe x -> greater() form, and fails INSERT with the same UNKNOWN_IDENTIFIER a well-formed COLUMNS(...) APPLY constraint gives, because that matcher is never expanded in a constraint at all.
❌ The commit message attributed the in shape's crash to TreeCNFConverter::splitMultiLogic. Confirmed and fixed. splitMultiLogic acts only on and/or/not, and the captured backtrace was taken with the and payload; the message is now only as wide as the measurement.
⚠️ The changelog category should be Critical Bug Fix, since the defect terminates the server process. Disagreed. Critical Bug Fix is a release signal I do not select proactively; it is for a maintainer to ask for. Bug Fix is what I used for the sibling defect in this feature (#120483). Happy to switch if a maintainer prefers it.
⚠️ Provenance links sat inside the template's HTML comment, so they would not have rendered or linked. Fixed before publishing.
💡 The MODIFY CONSTRAINT case was covered as a positive round-trip but not as a negative. Added, with its own parseability guard. Both forms reach the same typed slot.
💡 Comment length on the new declaration. Kept by the pre-publication comment pass: it states why ASTFunction::readJSON cannot require the member, which is not derivable from the code below it, and it matches the register of the sibling slot validators in that header.

Also noticed, not acted on: one row of my own payload matrix labelled "well-formed control" is itself a
malformed payload, so that row never demonstrated what it was for. The over-rejection conclusion rests
instead on the greater() empty-list row, a 44-statement round-trip sweep across both builds, and the
positive round-trips pinned in the .sql test. Separately verified while enumerating what else could
carry this shape: a WHERE clause restored from JSON cannot reach the same code, because the pass that
would feed it there runs only under the old analyzer, which has been frozen off since v26.9, and is
skipped for the one query kind that may still request it.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One clickhouse local run of a saved payload with --enable_json_ast_dialect 1 --dialect clickhouse_json gives rc=134, Assertion 'px != 0' failed, every time, with no randomized setting involved. The same payload over HTTP aborts a real server.
b Root cause explained? Yes. ASTFunction::arguments is optional (setNoEmptyArgs clears an empty list), so ASTFunction::readJSON cannot require it; the constraint expr slot was read untyped, and ConstraintsDescription::update() passes the expression unanalyzed to TreeCNFConverter::splitMultiLogic and ComparisonGraph, which dereference arguments unconditionally.
c Fix matches root cause? Yes. The parser-impossible shape is rejected at the deserialization boundary by a new readExpressionChild, next to the existing slot validators in ASTJSONReadHelpers. Not a guard at the crash sites: TreeCNFConverter alone has ~25 unguarded arguments->children reads.
d Test intent preserved / new tests added? Yes. Nothing existing was weakened; two new tests cover both crash sites, CHECK and ASSUME, CREATE and ALTER, and three entry points (formatQueryFromJSON, HTTP dialect, clickhouse-local).
e Both directions demonstrated? Yes. 12 of 19 payload shapes kill the pristine build and all answer BAD_ARGUMENTS with the fix; both new tests fail on the pristine build (the .sh one by aborting the server) and pass with it. Reverting only the new call site brings the crash back.
f Fix is general across code paths? Yes. Every JSON route to a constraint expression runs the fixed reader (ASTColumns::readJSON and ASTAlterCommand::readJSON both type the declaration), and both routes are tested. ComparisonGraph<ASTPtr> has two construction sites, both in ConstraintsDescription, so the crash site is unreachable with a null list; ComparisonGraph<QueryTreeNodePtr> is safe by construction. Other untyped expression slots were measured to be analyzed before use.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 19 function shapes x CREATE/INSERT/SELECT x both analyzers, at root and nested; a 42-statement round-trip sweep covers subqueries, EXPLAIN subqueries, lambdas, Nullable/Decimal/Array/tuple wrappers and parametric aggregates. Boundaries: absent arguments rejected, present-but-empty list unchanged, absent expr keeps its old error, non-function root accepted.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, serialization or metadata change, so no SettingsChangesHistory.cpp entry; nothing persisted can carry the shape (a null list formats as () and reparses safely). The one deliberate change, inside the experimental dialect only, is that five shapes which used to fail later at INSERT now fail at parse time; it is named in the changelog entry.
i Invariants and contracts preserved? Yes. readExpressionChild keeps readChild's "nullptr when the key is absent" contract, so the pre-existing Missing 'expr' error still fires; the empty-argument-list shape and the INSERT-time NUMBER_OF_ARGUMENTS_DOESNT_MATCH reporter are unchanged. The walk is a bounded second pass over a tree already built under the deserializer's depth and element limits, measured to hit TOO_DEEP_AST identically before and after.

Session id: cron:clickhouse-impl-self-slot-57:20260917-010800

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3bf1a46]

Summary: ✅


AI Review

Summary

This PR hardens clickhouse_json deserialization for ConstraintDeclaration by rejecting parser-impossible ASTFunction nodes with no arguments list before constraint optimization reaches the existing unconditional dereferences in TreeCNFConverter and ComparisonGraph. I reviewed the current PR head, the full diff, prior inline discussion, and the current Praktika report, and I did not find any remaining correctness, safety, or coverage issues in the scoped fix.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 3bf1a46.

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

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. labels Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3bf1a46df with master 95f5e92cb (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

76 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.
The matched translation units cost +67.8 s (+27%) in total before that adjustment.

Job report

/// `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`

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

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>();

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 this has recursive calls; can you check for stack overflows?

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.

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_depth raised to 2000 or to 5100: SIGSEGV inside that construction cycle (IAST::createFromJSON, ASTFromJSON.cpp:366, under readChildren and ASTExpressionList::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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 clickhouse_json entry point, the missing-arguments shape still takes the server down in slots this PR does not screen, on pristine master as well as on this branch:

Statement the payload is built from (arguments member deleted) Result
ORDER BY a IN (1), PRIMARY KEY a IN (1), SAMPLE BY a IN (1) Assertion 'px != 0' failed, process down
INDEX i arrayJoin([a]) TYPE minmax GRANULARITY 1 same
TTL grouping(a) (table), d DateTime TTL arrayJoin([now()]) (column) same
DEFAULT in(1, [1]), PROJECTION p (SELECT arrayJoin([a])) Code: 42 / Code: 35, server alive

The six that abort land in checkFunctionIsInOrGlobalInOperator (Interpreters/misc.h:48), reached from TreeRewriter::normalize as it walks the expression before any arity check, so a different consumer from the constraint route fixed here.

My plan is a separate PR wiring the same validator into those slots, since each one needs its own over-rejection check (engine, CODEC, STATISTICS and index TYPE slots legitimately hold argument-less functions). Tell me if you would rather have them in this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 ALTER MODIFY ORDER BY/SAMPLE BY/TTL and INSERT INTO FUNCTION ... PARTITION BY, and it is based on this branch, so its diff shows these two commits until this one merges.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 89b1efa

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
Build profile diff CI infrastructure, not this diff. Every read of the CI logs cluster timed out (urllib3.exceptions.ReadTimeoutError: ... Read timed out, 26 occurrences, ending in RuntimeError: CI logs cluster query failed), so no comparison ran and the job exited ERROR. The linked PR turns exactly this case (a 5xx or a timeout from that cluster) into a SKIPPED result carrying the cause, instead of failing the check on the cluster's health. #118708 (mine, open)
PR Praktika rollup over the row above, no independent failure #118708 (mine, open)

No failure on this head is reachable from this PR's diff, which rejects an argument-less function in a
constraint expression restored from AST JSON and adds one stateless test. 156 of 176 checks passed and
18 were skipped, including Finish Workflow, Mergeable Check, Style check, both Fast test legs,
both Bugfix validation (functional tests, *) legs, CH Inc sync, the full build matrix, all 7 AST
fuzzer flavours, all 4 BuzzHouse flavours, and every Stateless, Integration, Stress, Upgrade and Unit
test job. 0 FAIL/ERROR test rows at this commit.

Session id: cron:our-pr-ci-monitor:20260918-170449

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 18, 2026
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.
@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 8b9fd5b Sep 19, 2026
177 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
pull Bot pushed a commit to sjoerd2025/ClickHouse that referenced this pull request Sep 22, 2026
…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
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-self PR origin: self-found defect (impact-bar validated) 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.

4 participants