Skip to content

Reject an argument-less function in an expression restored from AST JSON - #120882

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-json-ast-storage-expr-argumentless-function
Sep 22, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-json-ast-storage-expr-argumentless-function

Conversation

@groeneai

@groeneai groeneai commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

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 when a clickhouse_json payload restores an expression holding a function with no arguments list, a shape the SQL parser cannot produce: a storage key, a skip index, a TTL, an UPDATE or mutation predicate, a view or INSERT ... SELECT body, or a table function. Such a payload is now rejected with BAD_ARGUMENTS, as is an empty TTL list, 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 whose Function node 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::arguments is genuinely optional (a table engine, a CODEC element, an index TYPE), so ASTFunction::readJSON cannot require it. But the storage-metadata builders (KeyDescription, IndexDescription, TTLDescription), ApplyWithSubqueryVisitor, ExecuteScalarSubqueriesVisitor and 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, their ALTER forms, INSERT INTO FUNCTION ... PARTITION BY, and the deprecated positional MergeTree(date, key, granularity) arguments. Beyond it: a lightweight UPDATE predicate, an ALTER ... UPDATE/DELETE predicate, a view body, MODIFY QUERY, an INSERT ... SELECT body, and the four table-function slots (INSERT, CREATE ... AS, a SELECT table expression, EXPLAIN TABLE OVERRIDE). ALTER MODIFY TTL also regains CREATE's list-of-ASTTTLElement contract, and both TTL containers refuse an empty list: CREATE persisted a bare TTL clause, after which the table failed to ATTACH and the server failed to start.

Left alone, measured non-fatal: a column DEFAULT, a projection body, DELETE FROM, a plain SELECT's expressions, EXPLAIN PLAN; UNIQUE KEY; CREATE FUNCTION and UNLOCK 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_ARGUMENTS after; 100,000 corpus statements round-trip identically on both binaries.


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

Version info

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

…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.
@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 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two review rounds over this tree, each with two independent passes: a cold read of the resulting code plus
a second-model gate. Round 1 bounced 5 findings back to implementation; round 2 (this head) found no
blocker and no major of its own.

Finding Verdict
❌ ALTER ... MODIFY TTL restored its ttl slot generically, so a payload could put an argument-less function directly in the expression list instead of inside an ASTTTLElement. getTTLFromAST then reads such a child as a column TTL and analyses it, which is fatal. CREATE already enforced that container; ALTER did not. Agreed, fixed
❌ INSERT INTO FUNCTION ... PARTITION BY restored its expression unscreened, and a partitioned write hands it to KeyDescription::getKeyFromAST with no arity check in front. Same builder, same crash site. Agreed, fixed
⚠️ The deprecated positional MergeTree(date, key, granularity) syntax turns engine arguments into key expressions, which reach the same builder. The engine node itself must stay unscreened, being legitimately argument-less. Agreed, fixed (argument list only, measured for over-rejection)
⚠️ A neighbouring comment listed order_by/sample_by/ttl as generically restored; this change makes that false. Agreed, corrected
⚠️ The description generalised two measurements into "the analyser checks arity first" and "every SELECT slot". The analyzer guards the ordinary function case but not its lambda branch, so the universal was not defensible. Agreed, narrowed to what was measured
💡 Test comments name IndicesDescription::getIndexFromAST (the method is on IndexDescription), and say the three new payload guards replace a whole node, which holds only for the TTL one; the other two delete an arguments member like the earlier rows. Agreed and corrected here rather than in the file: wording only, and neither affects what the tests assert
💡 Of round 1's four code changes, three are independently load-bearing under a per-call-site mutation sweep. Screening the ALTER ttl slot itself is not, because every carrier inside a well-typed TTL list is already screened one level down; it is kept for symmetry with the sibling key slots and only improves the rejection message. Kept, and said here rather than claimed as four for four
💡 The children-array screen reports the JSON key as children rather than a slot name. Not changed: that is the accurate location of the node

Checked and deliberately left unscreened: UNIQUE KEY (an identifier-list contract), group_by_key (only
ever read through getColumnName(), never analysed), ttl_table and well-typed ALTER TTL elements (each
ASTTTLElement screens itself), an index TYPE and CODEC/STATISTICS elements (argument-less by
construction), projection ORDER BY (the analyzer regenerates that node before the key is built, on a path
that is not setting-gated), ASTPartition's value (its own shape and fields_count contract already makes
the two unguarded dereferences in getPartitionIDFromQuery unreachable), a stream watermark expression and
the mutation predicate (both analysed through the query analyzer, which guards a null argument list).

Two claims I verified rather than assumed. "Left alone because measured non-fatal" for a column DEFAULT is
not an artefact of the default settings: validateColumnsDefaults does still carry a legacy TreeRewriter
branch that would crash on this shape, but disabling the analyzer has been refused rather than ignored since
v26.9, so that branch is not user-reachable. And no persistence path deserialises AST JSON, so no stored
metadata can be rejected by the stricter reader and there is no ATTACH or restart compatibility obligation.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand: parseQueryToJSON a CREATE TABLE ... ORDER BY a IN (1), delete $.storage.order_by.arguments, send it back under enable_json_ast_dialect=1, dialect='clickhouse_json' -> Assertion 'px != 0' failed, rc 134. 20 such routes, no probabilistic component.
b Root cause explained? ASTFunction::arguments is optional (a table engine, a CODEC/STATISTICS element, an index TYPE are legitimately argument-less), so readJSON cannot require it; but the storage-metadata builders analyse the raw AST, where checkFunctionIsInOrGlobalInOperator (misc.h:48) and ActionsMatcher::visit intercept a function by name before any arity check and dereference that list.
c Fix matches root cause? The parser-impossible node is refused at the deserialization boundary, the layer #120507's review settled for this class. Guarding the crash sites was rejected on measurement: 48 arguments-> in ActionsVisitor.cpp, 1,149 across src/. A check keyed on a payload field was rejected too, measured bypassable by forging no_empty_args + kind.
d Test intent preserved / new tests added? Two new tests: 05230 (boundary, 17 negatives + 35 positives + do-not-screen controls) and 05231 (21 rejection routes over HTTP, positives that apply and read back a valid MODIFY TTL, closing with a liveness query). No existing test weakened.
e Both directions demonstrated? Yes. 20 routes: crash pre-fix, BAD_ARGUMENTS post-fix, on pristine master and on the pre-round head alike. A real server died pre-fix and survives post-fix. Both tests are [ FAIL ] on a pre-fix binary (05231 kills the server) and [ OK ] on the fixed one.
f Fix is general across code paths? Every route into each slot was enumerated and measured: the skip-index expression via CREATE TABLE, CREATE INDEX and ALTER ADD INDEX; the TTL expression via table TTL, ALTER MODIFY TTL and a type-substituted ttl list; the column TTL via CREATE TABLE and ALTER MODIFY COLUMN; the assignment RHS via TTL GROUP BY SET, ALTER ... UPDATE and standalone UPDATE; a partition key via INSERT INTO FUNCTION (StorageFile and StorageURL both read that slot); the deprecated positional engine arguments via CREATE and the ungated ATTACH. Members held outside IAST::children were enumerated separately, since the subtree walk cannot see them: group_by_assignments is a carrier and gets its own reader; group_by_key and COLUMNS(...) APPLY are measured non-carriers.
g Fix generalizes across inputs (params/datatypes/wrappers)? The screen is keyed on the node kind, not on a function name or a type, so it covers any function in any screened slot. Measured with in, notIn, arrayJoin and grouping, at the slot root and nested one and two levels deep, through CREATE, ALTER, CREATE INDEX and INSERT; and across engines (MergeTree, SummingMergeTree, Distributed, URL, ReplicatedMergeTree, Memory), where an argument-less function in an argument position keeps an empty-but-present list and only the engine node itself drops the member.
h Backward compatible? Yes: no setting, no SettingsChangesHistory.cpp entry, no format change. The only behaviour changes are BAD_ARGUMENTS for a hand-written payload that previously aborted the server, and the same for a ttl list whose child is not a TTL element, which ParserTTLExpressionList cannot produce. 100,000 corpus statements produce identical output on both binaries: 0 over-rejections, 0 new acceptances, 0 changed outputs.
i Invariants and contracts preserved? The screen inspects and returns the same node, so slot ownership, children order and tree hashes are untouched; readExpressionChildren returns readChildren()'s vector unchanged, so ASTAssignment's existing "exactly one child" check sees what it did before, and readFunctionChildWithExpressionArguments returns readChildOfType<ASTFunction>'s node unchanged. The rejection precedes any metadata construction and discards the whole command object, so no partial state is reachable.

Session id: cron:clickhouse-impl-self-slot-57:20260918-151700

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f0b20ab]

Summary: ✅


AI Review

Summary

This PR closes most of the clickhouse_json argument-less-function crash routes by screening storage metadata, mutation predicates, stored SELECT bodies, and table-function slots during AST JSON deserialization. One blocker remains: ASTExplainQuery::readJSON still restores the explained query child raw, so EXPLAIN AST optimize = 1 SELECT ... WHERE <function-without-arguments> can still reach the legacy InterpreterSelectQuery path and fail before the malformed payload is rejected with BAD_ARGUMENTS.

Findings
  • ❌ Blockers
  • [src/Parsers/ASTExplainQuery.cpp:39] The PR's boundary screen still has a reachable hole for EXPLAIN: query is read with plain readChild, so a forged clickhouse_json SELECT subtree keeps its unscreened where/prewhere/having/qualify/limit_* expressions from src/Parsers/ASTSelectQuery.cpp:754. During EXPLAIN AST optimize = 1, ExplainAnalyzedSyntaxMatcher constructs the old InterpreterSelectQuery, which runs ApplyWithSubqueryVisitor::visit before any analyzer-side arity check and still dereferences func.arguments unconditionally for IN/GLOBAL IN in src/Interpreters/InterpreterSelectQuery.cpp:647 and src/Interpreters/ApplyWithSubqueryVisitor.cpp:154. Suggested fix: reject malformed SELECT subtrees on the EXPLAIN path too, either by screening query when it is a SELECT/SELECT UNION subtree or by landing the broader ASTSelectQuery::readJSON screen before merge.
Final Verdict

❌ Changes requested. The remaining unscreened EXPLAIN query child leaves the crash class this PR is fixing still reachable.

LLVM Coverage Report

Measured on commit f0b20ab.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 138/144 (95.83%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 18, 2026
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.
@PedroTadim PedroTadim self-assigned this Sep 18, 2026
@@ -0,0 +1,67 @@
-- A constraint expression is consumed before analysis: `ConstraintsDescription::update` hands it to

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 can you reduce the number of tests added? We don't need that many

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 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 CREATE covering every screened slot, both engine forms, both ALTER forms), and its 17 rejection rows move into 05231, where the oracle is the screen's own message rather than a bare BAD_ARGUMENTS; the isValidJSON/countSubstrings payload 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> and MODIFY TTL ... GROUP BY ... SET.
  • 05226 collapses 7 accepted shapes into 2 and drops the ASSUME and MODIFY CONSTRAINT rejections, which reach the same reader as the rows that stay. 05227 loses its INSERT ... VALUES row, 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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d706466

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 (arm_tidy) master-side clang-tidy break: error: duplicate include [readability-duplicate-include] on src/Core/tests/gtest_settings.cpp, failing unit_tests_dbms.dir/Core/tests/gtest_settings.cpp.o. Not from this branch: 53 distinct PRs and true master carry the identical error between 18:26Z and 00:26Z. It entered master at 17:34Z when two PRs that each added #include <IO/VarInt.h> at a different position of the same block merged without a textual conflict (mine #118612 was one of them) #120930 (external, merged 2026-09-18 23:19:51Z), merged master @ 8a21e37548ba9
Finish Workflow / Post Hooks consequential, not an independent failure: new_tests_check.py reports both Bugfix validation (functional tests, amd64/aarch64) jobs as DROPPED (Dropped due to previous failure [Build (arm_tidy)]), so no per-arch job could report OK or XFAIL #120930 (external, merged), merged master @ 8a21e37548ba9
Mergeable Check, PR praktika rollups of the two rows above (Failed: Workflow Post Hook, Build (arm_tidy), Dropped: 149), no independent failure #120930 (external, merged), merged master @ 8a21e37548ba9
Sync - CH Inc sync (private, not actionable by me)

Rule 3c, not 3d, decided at the tree that ran: praktika pins the merge commit at run creation, and the
failing run 35401471471 was created at 2026-09-18T22:25:22Z, before the revert merged at 23:19:51Z, so that tree could
not contain the fix. The revert is now on this branch (8a21e37548ba9), where gtest_settings.cpp carries a
single IO/VarInt.h include again. My own change is byte-identical across the merge (unchanged
git patch-id) and the merge brings no submodule or other content change. CI is re-running on 8a21e37548ba9.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8a21e37

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, job-level death with no test row: RuntimeError: CI logs cluster query failed at ci/jobs/build_profile_diff_job.py:234, raised from compare_symbols (:1405) on the binary_symbols read. 268 distinct PRs carry it in the last 24 hours against 123 green runs #118708 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) job summary 10 errors, 3 too long, 1 unstable; the run errors are iceberg_suite_tpch, where TPC-H Q5 exceeds max_execution_time once the join-order cost model prices a relation with no row estimate as a single row. 152 distinct PRs plus true master in the last 24 hours #120762 (mine, open)
Upgrade check (amd_release) / Logical error: Method A not implemented for B the pre-upgrade previous-release server logs Method == not implemented for AST: SettingsConstraints::checkImpl to getNewValueToCheck to Field::operator== on a FieldFromAST setting value, reached by a plain SET over HTTP. The post-upgrade phase is clean (No Error messages after server upgrade reports OK) and the same signature fired on 3 unrelated PRs in 30 days #118993 (mine, merged), see the note below
Mergeable Check, PR praktika rollups of the three rows above, no independent failure #118708, #120762 and #118993 (all mine)

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 d5a23b55 with this head reports ahead 3534, behind 0), so the usual reading would be that the fix does not work. That is not what happened. The upgrade check first installs the PREVIOUS RELEASE package and exercises it, and that binary predates the fix and carries no backport, which is why the phase running my build is explicitly green while the older one is not. A backport label has been requested separately. Nothing here is reachable from this PR's diff, which touches the src/Parsers/AST* JSON read helpers and tests, and neither SettingsConstraints nor Field.

The Build (arm_tidy) break owned by my previous ledger on d706466844d5 is resolved: the master merge at this head picked up #120930, and that check now passes.

To save a reader the check, these are not failures: the two Bugfix validation (functional tests, amd64/aarch64) rows that read FAIL for 05230_ast_json_storage_expression_argumentless_function are the expected inverted result for a bugfix PR, and both jobs report check_status = success.

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

Comment thread src/Parsers/ASTAssignment.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f0b20ab31 with master de0be4574 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 5af633e4c; 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.

Object file sizes

15 object files changed (-3.51 KiB total), 0 added.

Object file Master PR Δ
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTAssignment.cpp.o 307.57 KiB 290.73 KiB -16.85 KiB (-5.48%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

`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.
@groeneai groeneai changed the title Reject an argument-less function in a storage-metadata expression restored from AST JSON Reject an argument-less function in an expression restored from AST JSON Sep 19, 2026
Comment thread src/Parsers/ASTJSONReadHelpers.h Resolved
…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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 87f76a8

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 infra: requests.exceptions.ReadTimeout against the CI logs cluster, surfacing as RuntimeError: CI logs cluster query failed at ci/jobs/scripts/log_cluster.py:333 through build_profile_diff_job.py:234 / compare_symbols. No test row is published, only the job-level error. Breadth today: 33 red runs over 33 distinct pull requests. #118708 (mine, open)
Performance Comparison (arm_release, master_head, 1/6) dashboard-verdict gate, not a slowdown this pull request causes. The shard's own report calls nothing slower (3 too long, 1 faster); the red comes only from the dashboard tier on order_by_read_in_order #1, client_time 0.0150 -> 0.0185 s. On arm_release over the last 14 days that same measurement has median 18 ms and 41% of 2523 runs across 655 other pull requests are at or above 18.5 ms, so the base run was fast rather than this run slow. The diff is parser-side JSON serialization only and cannot reach read-in-order execution. #121090 (mine, open)
Mergeable Check praktika rollup over the two rows above, no independent failure #118708 and #121090 (mine, open)
PR praktika rollup over the two rows above, no independent failure #118708 and #121090 (mine, open)

No test-level FAIL/ERROR row exists in CIDB at this head, and Fast test, Style check,
Config Workflow, Finish Workflow and CH Inc sync all pass.

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]>
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai what about the latest failures? I want to see if there is a PR for the BuzzHouse one

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e62fae0

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
BuzzHouse (amd_debug) / Inconsistent AST formatting (STID 1941-1bfa) trunk grammar bug, BACKUP ... SETTINGS <name> = DEFAULT does not round-trip (issue 112895) #112978 (mine, open)
Performance Comparison (arm_release, master_head, 3/6) / index_bulk_filtering #2 unpinned part layout, 59.8 ms against 106.3 ms, the shard's only named result #121260 (mine, open)
Build profile diff RuntimeError: CI logs cluster query failed in compare_opt_functions #121048 (merged), absent from the tree this job built (1f274c72b8d3) and present since the master merge you pushed
Sync - CH Inc sync (private, not actionable by me)

The Bugfix validation rows are not failures: that job inverts its own test results, and both arms
reported success on this head, which is what the added tests are there to do.

Now the BuzzHouse one, since that is the question. It is not from this pull request (the diff is the
AST JSON read path plus stateless tests, and the failing statement is plain SQL), and it reproduces
on a plain master build, 26.10.1.1. BACKUP and RESTORE accept SETTINGS <name> = DEFAULT only as
the first item of the list, because ParserBackupQuery::parseSettings parses items with
ParserSetQuery::parseNameValuePair, which has no DEFAULT branch. The formatter then always prints
the defaulted item last, so its own output no longer parses:

$ clickhouse format --oneline --query "BACKUP FROM SNAPSHOT Memory('b.zipx') TO Null SETTINGS iceberg_timestamp_ms = DEFAULT, parts_to_throw_insert = 829"
BACKUP FROM SNAPSHOT Memory('b.zipx') TO `Null` SETTINGS parts_to_throw_insert = 829, iceberg_timestamp_ms = DEFAULT

$ clickhouse format --oneline --query "BACKUP FROM SNAPSHOT Memory('b.zipx') TO Null SETTINGS parts_to_throw_insert = 829, iceberg_timestamp_ms = DEFAULT"
Code: 62. DB::Exception: Syntax error (query): failed at position 115 (end of query)

#112978 fixes the grammar, and its 04700_backup_settings_default_round_trip.sql covers this exact
shape (BACKUP FROM SNAPSHOT ... SETTINGS foo = DEFAULT, id = 'x'). It has been open since
2026-08-02 with no approval or change request on it yet.

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

@PedroTadim

Copy link
Copy Markdown
Member

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

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 22, 2026
Merged via the queue into ClickHouse:master with commit 88eed42 Sep 22, 2026
177 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 22, 2026
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