Skip to content

Hash the AST members that getTreeHash did not see - #114171

Merged
alexey-milovidov merged 47 commits into
masterfrom
tree-hash-completeness
Aug 26, 2026
Merged

alexey-milovidov merged 47 commits into
masterfrom
tree-hash-completeness

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

Related: #110833

This is the getTreeHash part of #110833, split off because it stands on its own: it fixes wrong results that have nothing to do with that pull request's motivation (comparing stored table definitions). Only the src/Parsers changes were taken; the sameAST helper and the metadata comparison stay in #110833.

IAST::getTreeHash identifies an AST subtree, and several callers use it as the identity of an expression or of a query: Context::executeTableFunction caches the result of a table function under it, ExecuteScalarSubqueriesVisitor caches the value of a scalar subquery, ActionsVisitor keys prepared sets, ComparisonGraph and WhereConstraintsOptimizer decide whether two expressions are the same one.

The default implementation hashes only getID and children, so anything a node keeps outside children is invisible to it, and a number of nodes keep meaningful state there. Two ASTs that mean different things then get the same hash, and a caller that treats the hash as an identity silently substitutes one for the other. For example, on master:

SELECT
    (SELECT count() FROM view(SELECT 1 AS x UNION ALL SELECT 1)) AS union_all,
    (SELECT count() FROM view(SELECT 1 AS x UNION DISTINCT SELECT 1)) AS union_distinct
   ┌─union_all─┬─union_distinct─┐
1. │         2 │              2 │
   └───────────┴────────────────┘

The second view returns 2 instead of 1: union_mode is not a child of ASTSelectWithUnionQuery and was not hashed, so the two calls got the same cache key. The same happens for INTERSECT against EXCEPT, for LIMIT 2 against OFFSET 2 (the same literal in a different role), for WITH FILL ... TO 5 against WITH FILL ... STEP 5, for a window frame bounded from below against one bounded from above, and for APPLY(quantile(0.1)) against APPLY(quantile(0.9)).

This change hashes the members that are part of an element's meaning and are not children:

  • ASTSelectQuery, ASTProjectionSelectQuery, ASTOrderByElement - the role each child plays (WHERE against HAVING, the limit against the offset, the WITH FILL upper bound against the step), which is recorded only in positions. ASTSelectQuery::group_by_with_grouping_sets was missing as well.
  • ASTSelectWithUnionQuery - union_mode and list_of_modes; ASTSelectIntersectExceptQuery - final_operator.
  • ASTWindowDefinition - the frame and the parent window name; ASTWindowListElement - the name the window is bound to.
  • ASTWithElement - the name the CTE is bound to, MATERIALIZED, and the column aliases.
  • ASTQueryWithOutput - the INTO OUTFILE modifiers; ASTQueryWithTableAndOutput - TEMPORARY and an explicit UUID.
  • ASTSetQuery - is_standalone, the settings reset with = DEFAULT, the query parameters, and the node's own identity, which this override skipped altogether.
  • ASTTTLElement - the mode, the destination, the GROUP BY key and assignments, and the recompression codec.
  • ASTIndexDeclaration, ASTConstraintDeclaration, ASTProjectionDeclaration - the declared name (and the index granularity, and CHECK against ASSUME).
  • ASTCollation - the collation name; ASTStreamSettings - the cursor tree and the watermark column and idle timeout.

Follow-up fixes in the same area, found by the debug build's format+parse round-trip check and by review:

  • A per-column PRIMARY KEY is normalized by ParserCreateQuery into the storage definition, but primary_key_specifier stayed true on the column declarations while formatting never printed it, so once the flag was hashed, such a CREATE no longer round-tripped format+parse to the same tree hash and the debug build reported the Inconsistent AST formatting logical error. The parser now clears the flag when its meaning is transferred; where it does survive - ALTER TABLE ... ADD/MODIFY COLUMN - formatting now prints PRIMARY KEY instead of silently dropping it.
  • ParserQueryWithOutput canonicalizes the output-option children to the end of children, and most parsers add the database/table children first, but several clone implementations rebuilt them in a different order, so a clone of CHECK TABLE t FORMAT JSONEachRow or SHOW CREATE TABLE t INTO OUTFILE 'x' hashed differently than the original. The clones now rebuild children in the parser's order. Along the way: ASTDropQuery::clone and ASTUndropQuery::clone did not clear the copied children (the clone kept the source's children and appended the cloned ones on top), ASTOptimizeQuery::clone pushed deduplicate_by_columns into children while the parser keeps it member-only, and ASTCheckTableQuery::partition, ASTWatchQuery::limit_length, and the where_expression / limit_length of SHOW COLUMNS / SHOW INDEXES were left shared with the source instead of being cloned.
  • The static_asserts pinning the size of the AST nodes are checked only on 64-bit targets: the wasm32 parser build has a different layout.

Two more fixes in the same area:

  • ASTColumnsApplyTransformer reached its non-child parameters and lambda through updateTreeHashImpl rather than updateTreeHash, which stops at the node itself and never descends into it, so the 0.5 of APPLY(quantile(0.5)) was not hashed.
  • ASTWithAlias hashed the alias without its length, so the alias ran into whatever the node writes next and foo followed by Identifier_bar produced the same byte stream as the alias bar on Identifier_foo.

ASTCollation::readJSON and ASTWithElement::readJSON put a member into children that neither the parser nor clone puts there, so an AST restored from JSON had a shape - and a hash - that no parsed AST has, and clone of it dropped the child again. They now reproduce the parser's shape. ASTTTLElement::clone left the recompression codec shared with the source, which the new unit test surfaced.

New tests: 04836_tree_hash_ast_identity covers the wrong results above, and gtest_tree_hash_completeness covers the members that no pair of queries can differ in on their own, by editing the JSON serialization of the AST, plus the JSON round-trip shape.

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):

Fix wrong results for a query that calls the same table function twice with arguments that differ only in a part of the query that was not taken into account by the AST hash, such as UNION ALL against UNION DISTINCT, INTERSECT against EXCEPT, LIMIT against OFFSET, or the bounds of a window frame. The second call reused the result of the first one.


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

Version info

  • Merged into: 26.9.1.186 (included in 26.9 and later)

`IAST::getTreeHash` identifies an AST subtree, and its callers use it as the
identity of an expression or of a query: `Context::executeTableFunction` caches
the result of a table function under it, `ExecuteScalarSubqueriesVisitor` caches
the value of a scalar subquery, `ActionsVisitor` keys prepared sets,
`ComparisonGraph` and `WhereConstraintsOptimizer` decide whether two expressions
are the same one.

The default implementation hashes only `getID` and `children`, so anything a
node keeps outside `children` is invisible to it, and a number of nodes keep
meaningful state there. Two ASTs that mean different things then get the same
hash, and a caller that treats the hash as an identity silently substitutes one
for the other:

    SELECT
        (SELECT count() FROM view(SELECT 1 AS x UNION ALL SELECT 1)),
        (SELECT count() FROM view(SELECT 1 AS x UNION DISTINCT SELECT 1))

returns `2` twice, because `union_mode` is not a child of
`ASTSelectWithUnionQuery`, so the second `view` reuses the result cached for the
first one. The same happens for `INTERSECT` against `EXCEPT`, for `LIMIT 2`
against `OFFSET 2`, for `WITH FILL ... TO 5` against `WITH FILL ... STEP 5`, for
a window frame bounded from below against one bounded from above, and for
`APPLY(quantile(0.1))` against `APPLY(quantile(0.9))`.

Hash the members that are part of an element's meaning and are not children: the
role each child plays in `ASTSelectQuery`, `ASTProjectionSelectQuery` and
`ASTOrderByElement`, the set operation of `ASTSelectWithUnionQuery` and
`ASTSelectIntersectExceptQuery`, the frame of `ASTWindowDefinition`, the name a
CTE or a window is bound to, the `INTO OUTFILE` modifiers, `TEMPORARY` and an
explicit `UUID`, the contents of `ASTSetQuery`, the members of `ASTTTLElement`,
the declared name of an index, a constraint and a projection, the collation
name, and the cursor and watermark of `ASTStreamSettings`.

`ASTColumnsApplyTransformer` reached its non-child `parameters` and `lambda`
through `updateTreeHashImpl` rather than `updateTreeHash`, which stops at the
node itself, so the `0.5` of `APPLY(quantile(0.5))` was not hashed.
`ASTWithAlias` hashed the alias without its length, so the alias ran into
whatever the node writes next.

`ASTCollation::readJSON` and `ASTWithElement::readJSON` put a member into
`children` that neither the parser nor `clone` puts there, so an AST restored
from JSON had a shape - and a hash - that no parsed AST has, and `clone` of it
dropped the child again. `ASTTTLElement::clone` left the recompression codec
shared with the source.
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [18dbf2a]

Summary: ✅


AI Review

Summary

This PR fixes a large number of real getTreeHash and AST-JSON completeness gaps, but two JSON-side mismatches are still present in the current code. Both break the core contract the change is trying to establish: SQL parsed by the server and the equivalent clickhouse_json payload should reconstruct the same AST identity.

Findings

⚠️ Majors

  • [src/Parsers/ASTAlterQuery.cpp:1409] ASTAlterQuery::readJSON still rebuilds children in a different order than ParserAlterQuery, so ALTER queries change getTreeHash on JSON round-trip even when the SQL text is unchanged.
  • Suggested fix: restore command_list before database / table, matching ParserAlterQuery, and add a focused hashOfJSONRoundTrip("ALTER TABLE t ADD COLUMN x UInt64") regression.
  • [src/Parsers/ASTDropQuery.cpp:194] ASTDropQuery::readJSON still accepts database_and_tables shapes that the SQL parser never leaves on the final AST. Only multi-table DROP should keep that list; single-target or empty lists still lead to parser-impossible or non-canonical ASTs.
  • Suggested fix: accept database_and_tables only for kind == Drop && size > 1, or canonicalize the single-entry case to the single-table form before the AST escapes deserialization.
Final Verdict

Needs changes before merge. The remaining gaps are still in the core scope of the PR: AST identity and clickhouse_json round-trip correctness.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 1205/1238 (97.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 10, 2026
Comment thread src/Parsers/IAST.h Resolved
`default_specifier`, `null_modifier`, `ephemeral_default`,
`primary_key_specifier` and the role each child plays (recorded only in
`packed_indices`) carry meaning and were invisible to `getTreeHash`, so
`x UInt8 DEFAULT 1` and `x UInt8 MATERIALIZED 1` hashed equally, and so
did `x String COMMENT 'a'` and `x String TTL 'a'`.

`clone` and `readJSON` inserted the column `SETTINGS` child last, while
`ParserColumnDeclaration` inserts it right after the codec, so a copy of
a column declaration with `SETTINGS` and a `TTL` had a different shape -
and a different tree hash - than the original.
Comment thread src/Parsers/ASTQueryWithOutput.cpp Resolved
alexey-milovidov and others added 4 commits August 12, 2026 06:55
… in ALTER

`ParserCreateQuery` moves a per-column PRIMARY KEY into the storage
definition, but left `primary_key_specifier = true` on the column
declarations, while `ASTColumnDeclaration::formatImpl` never printed it.
Once `updateTreeHashImpl` started hashing the flag, such a CREATE query no
longer round-tripped format+parse to the same tree hash, and the debug
build aborted with the `Inconsistent AST formatting` logical error on
`02904_empty_order_by_with_setting_enabled`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114171&sha=46aea500ea76a0badba990b99cb6459c88b549e0&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29

Clear the flag when its meaning is transferred to the storage definition,
and print `PRIMARY KEY` where it does survive - `ALTER TABLE ... ADD/MODIFY
COLUMN`, which used to silently drop it from the formatted query.

Part of #114171

Co-Authored-By: Claude Fable 5 <[email protected]>
`ParserQueryWithOutput` canonicalizes the output-option children to the end
of `children`, and most parsers add the database/table children first, but
several `clone` implementations rebuilt them in a different order, so the
copy hashed differently than the original (`CHECK TABLE t FORMAT
JSONEachRow`, `SHOW CREATE TABLE t INTO OUTFILE 'x'`, ...). Reorder
`cloneOutputOptions`/`cloneTableOptions` to match each parser.

Also found along the way:
* `ASTDropQuery::clone` and `ASTUndropQuery::clone` did not clear the
  copied `children`, so the clone kept the source's children and appended
  the cloned ones on top of them.
* `ASTOptimizeQuery::clone` pushed `deduplicate_by_columns` into
  `children` while the parser keeps it member-only.
* `ASTCheckTableQuery::partition`, `ASTWatchQuery::limit_length`, and the
  `where_expression`/`limit_length` of SHOW COLUMNS / SHOW INDEXES were
  left shared with the source instead of being cloned.

Adds a clone-hash gtest for these roots and a format+parse round-trip gtest
for the members this pull request made significant.

Part of #114171

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Parsers/ASTQueryWithOutput.cpp Resolved
# Conflicts:
#	src/Parsers/ASTDropQuery.cpp
#	src/Parsers/ASTUndropQuery.cpp
`resetOutputASTIfExist` now also clears the `APPEND` / `TRUNCATE` / `AND STDOUT`
flags: they are part of the tree hash, and callers (e.g. the query result cache)
use this function to normalize the AST before hashing.

`readOutputOptionsJSON` now appends the output-option children in the canonical
order of `output_option_members` (`out_file`, `compression`, `compression_level`,
`format_ast`, `settings_ast`), so an AST restored from `clickhouse_json` hashes
the same as a freshly parsed one when `COMPRESSION` / `LEVEL` are present.
When a `CREATE` query declares a `PRIMARY KEY` inside the column list and has
no explicit `ENGINE` clause, the parser synthesizes the storage definition
while normalizing the primary key into it, and appended it to `children` after
the `COMMENT` child. A fresh parse of the formatted query - which spells the
storage-level `PRIMARY KEY` - puts the storage before the comment, so the tree
hash did not survive a format+parse round trip and the debug build reported the
`Inconsistent AST formatting` logical error.

Found by the AST fuzzer:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114171&sha=34700cc2c0361954c1223a35e5c24908d8d38b57&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

The regression cases are covered in `FormatRoundTripHashesEqual` in
`gtest_tree_hash_completeness.cpp` (added in the previous commit).
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 709.92 MiB 706.98 MiB -2.94 MiB (-0.41%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

106 object files changed (+104.01 KiB total), 1 added.

Object file Master PR Δ
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTWatchQuery.cpp.o new 307.54 KiB +307.54 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTShowIndexesQuery.cpp.o 51.04 KiB 303.97 KiB +252.94 KiB (+495.61%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserWatchQuery.cpp.o 80.36 KiB 39.48 KiB -40.89 KiB (-50.88%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTCreateQuery.cpp.o 481.57 KiB 515.27 KiB +33.70 KiB (+7.00%)
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/attachInformationSchemaTables.cpp.o 94.76 KiB 63.93 KiB -30.82 KiB (-32.53%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserDropIndexQuery.cpp.o 54.37 KiB 25.21 KiB -29.16 KiB (-53.64%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDropIndexQuery.cpp.o 63.73 KiB 35.48 KiB -28.25 KiB (-44.33%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserHypotheticalIndexQuery.cpp.o 74.09 KiB 48.02 KiB -26.07 KiB (-35.19%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserCreateIndexQuery.cpp.o 77.23 KiB 51.39 KiB -25.85 KiB (-33.47%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserDeleteQuery.cpp.o 65.73 KiB 41.50 KiB -24.24 KiB (-36.87%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTQueryWithTableAndOutput.cpp.o 37.05 KiB 60.98 KiB +23.93 KiB (+64.57%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserOptimizeQuery.cpp.o 94.79 KiB 71.86 KiB -22.93 KiB (-24.19%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserUpdateQuery.cpp.o 75.14 KiB 52.28 KiB -22.86 KiB (-30.43%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTAlterQuery.cpp.o 532.45 KiB 551.34 KiB +18.89 KiB (+3.55%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterCreateIndexQuery.cpp.o 71.68 KiB 54.16 KiB -17.52 KiB (-24.44%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserDropQuery.cpp.o 83.99 KiB 66.85 KiB -17.14 KiB (-20.41%)
src/CMakeFiles/dbms.dir/Storages/TimeSeries/createTimeSeriesInnerTable.cpp.o 76.52 KiB 59.76 KiB -16.77 KiB (-21.91%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTDropQuery.cpp.o 345.37 KiB 361.73 KiB +16.36 KiB (+4.74%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDropQuery.cpp.o 412.48 KiB 396.16 KiB -16.32 KiB (-3.96%)
src/CMakeFiles/dbms.dir/Databases/DatabaseOrdinary.cpp.o 732.12 KiB 716.11 KiB -16.01 KiB (-2.19%)

737 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

827 translation units recompiled, 5315 s compile time in total, 826 of them have a recent master baseline.

Job report

A `PRIMARY KEY` declared in the column list of a view was normalized into a
synthesized storage definition. A plain view has no storage, and a materialized
view with `TO [db].[table]` must not have one - the same rule that already
rejects an explicit `ENGINE` - so formatting printed the synthesized node as a
table-level `PRIMARY KEY` that no longer parsed back. In a debug build this
raised `Inconsistent AST formatting`, and such a view could not have been loaded
from its own metadata after a restart.

Found by the AST fuzzer in the stress test:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114171&sha=2394a81226a152106d56f16cf586345726fc9434&name_0=PR&name_1=Stress%20test%20%28amd_debug%29
#114171
`ASTCheckTableQuery::partition` / `part_name`, `ASTWatchQuery::limit_length` /
`is_watch_events` and `ASTOptimizeQuery::deduplicate_by_columns` are kept outside
`children` and were not hashed at all, so `CHECK TABLE t PARTITION 1` hashed the
same as a plain `CHECK TABLE t`, `WATCH t LIMIT 5` the same as `WATCH t`, and
`OPTIMIZE TABLE t DEDUPLICATE BY a` the same as `... BY b` - which also made the
clone regression vacuous for those roots. Every one of them is printed, so they
survive a format+parse round trip; the new `MemberOnlyClausesAreSignificant`
gtest checks both directions.

`ASTCreateQuery::has_uuid_clause` stays out of the hash on purpose, and the
reason is now recorded next to the member: formatting prints the `UUID` clause
only for a non-`Nil` value, and `SHOW CREATE`, `system.tables` and backups zero
`uuid` for display, so a hash that depended on the flag would differ from the
hash of the reparsed formatted query and
`ATTACH TABLE t UUID '00000000-0000-0000-0000-000000000000'` would raise
`Inconsistent AST formatting` in a debug build. The colliding pair never both
execute: `ATTACH` rejects an explicit `Nil` clause, and for `CREATE` the clause
carries no meaning. `ExplicitNilUuidClauseIsNormalizedAway` pins that down.
Master added the `subscribe_for_updates` and `unordered` members to
`ASTStreamSettings`; both carry meaning, are printed, and are not part of
`getID`, so hash them and update the expected struct size the `static_assert`
guards.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed fixes for the three red stress jobs and both AI-review Majors.

All three stress failures had one root cause, and it was a real bug this PR is well placed to fix: a PRIMARY KEY declared in the column list of a view was normalized into a synthesized storage definition. A plain view has no storage, and a materialized view with TO [db].[table] must not have one - the same rule that already rejects an explicit ENGINE - so formatting printed the synthesized node as a table-level PRIMARY KEY that no longer parsed back:

CREATE MATERIALIZED VIEW v TO t (`a` UInt8 PRIMARY KEY) AS SELECT 1 AS a
-->  CREATE MATERIALIZED VIEW v TO t (`a` UInt8) PRIMARY KEY tuple(a) AS SELECT 1 AS a
-->  Code: 62. When creating a materialized view you can't declare both 'TO [db].[table]' and 'ENGINE'

That is the Inconsistent AST formatting in Stress test (amd_debug) / (arm_debug), and the arm_msan Cannot start clickhouse-server is the same bug one step later: the fuzzer had created such a view, so its metadata file could not be parsed on startup (Syntax error (in file store/.../v_window_partition__fuzz_4.sql) ... (PRIMARY)). The parser now rejects it, with regressions in 04836_tree_hash_ast_identity and a new ViewsRejectAPrimaryKeyTheyCannotFormat gtest. A materialized view with its own inner table still accepts it - there the storage definition is real.

Also in this push: the member-only CHECK / WATCH / OPTIMIZE clauses are now hashed (see the review thread), has_uuid_clause deliberately stays out of the hash with the reason recorded next to the member and pinned by a test (see the other thread), master is merged, and the two ASTStreamSettings modifiers master added (subscribe_for_updates, unordered) are hashed too.

All 211 parser/format/tree-hash gtests pass locally.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 6336358: the parser-rejection coverage remains in TreeHashCompleteness.ViewsRejectAPrimaryKeyTheyCannotFormat; removing those expected-error statements from the stateless query test prevents the functional harness from stopping at the first expected SYNTAX_ERROR.

Comment thread src/Parsers/ASTCreateQuery.cpp Resolved
Comment thread src/Parsers/ASTDropQuery.cpp Resolved
Comment thread src/Parsers/ASTShowColumnsQuery.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed all three active review threads in 680f374ff85c: the remaining member-only semantic state is included in the CREATE, DROP, and SHOW tree hashes; ASTShowIndexesQuery::getID is corrected; and ASTShowColumnsQuery JSON restores the parser child shape. Focused regressions were added. Local parser test execution was blocked before compilation by a concurrent shared-build CMake regeneration that failed while renaming the generated licenses source.

The table now describes the merged tree: 1337627 bytes for the default build
against 1234716 on the `master` this merged, so the change costs 102911 bytes
uncompressed and 12629 gzipped. Every configuration stays under its ceiling.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 0ebb445d6776 after merging current master. Both AI-review blockers are addressed, and so are the three red jobs.

  1. Stateless tests (amd_debug, flaky check) - Inconsistent AST formatting on 04247_attach_table_storage_clauses_without_engine_error, and the server death that followed it. Real, and caused by this change: a short ATTACH TABLE t TO INNER UUID '...' builds no targets, which is what formatQueryImpl prints the clause from, so only has_inner_uuid_clause survived - and that flag is now part of the tree hash, so the formatted query hashed differently from the original. ParserCreateTableQuery now rejects the clause on the short ATTACH form, which never produced a formattable AST. The query was already an error, so only the side reporting it moves, from the server to the client; cases 14 and 15 of 04247 become clientError.

  2. Integration tests - test_wasm_parser[everything]: the standalone WebAssembly parser is over its byte ceiling. Real. All four configurations were rebuilt and re-measured, the table in utils/wasm-parser/README.md is from that build, and each MAX_SIZE_* is again about 8% above its row. On the same wasi-sdk 33 toolchain the default build is 1234716 bytes on the master this merged and 1337627 bytes here, so this change costs 102911 bytes uncompressed and 12629 gzipped. -DENABLE_DCL=OFF was over its ceiling too - CI only builds the two extreme configurations, so it was not asserted.

  3. Both review blockers, in 8ea33eda7e37: readJSON now enforces the parser's POPULATE / EMPTY shape rules, and forEachPointerToChild names the remaining direct children (watermark_function, lateness_function, sql_security, refresh_strategy). See the two threads for details.

Finish Workflow / new_tests_check.py reported that no per-arch Bugfix validation job validated the fix, but all four of those jobs were DROPPED or SKIPPED in that run - nothing ran to validate. The changed 04247 expectations do fail on master.

Verified locally: 25/25 TreeHashCompleteness gtests pass; 04247_attach_table_storage_clauses_without_engine_error, 04836_tree_hash_ast_identity, 04494_ast_json_create_system_identifier_validation, 01153_attach_mv_uuid, 04201_refreshable_mv_to_inner_uuid_rejected, 04272_create_table_to_inner_uuid_without_engine, 04613_ast_json_create_variant_clause_ownership and 04614_ast_json_create_inner_uuid_target_shape all pass against a local server built from this branch; and all four WebAssembly configurations build and stay under their ceilings.

Comment thread src/Parsers/ASTCreateQuery.cpp Resolved
Comment thread src/Parsers/ASTDropQuery.cpp Resolved
Comment thread src/Parsers/ASTStreamSettings.cpp Resolved
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Aug 22, 2026
…ape"

This reverts commit 10b0d3b.

PR ClickHouse#114171 already closes the same hole in a stronger form: it rejects the
key's presence rather than only a true value, and stops writeJSON emitting
the field at all, so there is no forgeable input left. Its hunks touch these
exact lines and conflict only with this commit, and its removal of the field
would silently void the test arm added here (the arm injects into a needle
that leaves the payload).

The URL delegate engine check this branch is about does not depend on the
revert: attach_short_syntax remains a sound provenance signal for every
parsed query, which is the only shape reachable without the default-off
enable_json_ast_dialect setting.
alexey-milovidov and others added 2 commits August 24, 2026 23:04
- `ASTColumns::readJSON` rejects a column-level `primary_key_specifier` in a
  `CREATE` column list: the parser always normalizes it into the storage
  definition (or rejects it for view shapes) and clears the flag, while
  execution ignores it and formatting prints it, so a JSON payload carrying
  it would execute one definition and persist another.
- `ASTDropQuery::readJSON` enforces the parser's cardinality rule on
  `database_and_tables`: a multi-entry list is only valid for `DROP`, so a
  JSON payload can no longer execute a multi-table `DETACH` or `TRUNCATE`
  that SQL cannot express.
- `ASTStreamSettings::readJSON` rejects orphaned `watermark_expression` /
  `watermark_idle_timeout_ms` without `watermark_column` instead of silently
  dropping them.

Test: `TreeHashCompleteness.JSONRejectsColumnPrimaryKeyMultiTargetDetachAndOrphanedWatermark`.

Co-Authored-By: Claude Fable 5 <[email protected]>
res->set(res->command_list, command_list->clone());

cloneOutputOptions(*res);
/// `ParserAlterQuery` adds the command list child first, then the database/table, and

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.

ParserAlterQuery appends command_list before the table target (src/Parsers/ParserAlterQuery.cpp:1252-1264), but readJSON pushes database / table first and only then command_list. Because getTreeHash includes children order, clickhouse_json still changes the AST identity of every ALTER on round-trip: ALTER TABLE t ADD COLUMN x UInt64 parses as [command_list, table], while the JSON path rebuilds [table, command_list].

This PR is explicitly tightening ALTER hash completeness, so I think readJSON needs to rebuild children in the parser's order and add a focused hashOfJSONRoundTrip("ALTER TABLE t ADD COLUMN x UInt64") regression.

/// multiple tables currently"), yet `InterpreterDropQuery` would happily execute each entry,
/// so a JSON payload could perform a multi-table DETACH / TRUNCATE that SQL cannot express
/// (and whose formatted SQL does not parse back). Enforce the parser's cardinality rule.
if (child->children.size() > 1 && kind != Kind::Drop)

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.

ParserDropQuery only keeps database_and_tables on the final AST for multi-table DROP: it rewrites a single-entry list to the single-table form and it rejects multi-entry DETACH / TRUNCATE (src/Parsers/ParserDropQuery.cpp:119-120, 185-186). readJSON enforces only the size > 1 => kind == Drop half, so it still accepts an empty list and a single-entry list for any kind.

That means clickhouse_json can still build final DropQuery shapes the SQL parser never returns. A single-entry DETACH / TRUNCATE list formats as valid SQL but reparses to the canonical single-table AST with a different tree hash, and an empty list is worse: it formats as DROP TABLE with no target. I think database_and_tables should be accepted only for kind == Drop && size > 1, with the single-entry case canonicalized or rejected.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Aug 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 26, 2026
Merged via the queue into master with commit 0453aba Aug 26, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the tree-hash-completeness branch August 26, 2026 21:00
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
@alexey-milovidov alexey-milovidov mentioned this pull request Aug 27, 2026
1 task done
@alexey-milovidov alexey-milovidov mentioned this pull request Aug 27, 2026
1 task done
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
Conflicts resolved by keeping the `WINDOW VIEW` / `WATCH` removal:
- `ASTCreateQuery` clone/tree-hash/JSON: took master's parser-order clone, `updateTreeHashImpl` and `attach_short_syntax` rejection, minus the removed `is_window_view` / watermark / lateness state; kept the fail-closed rejection of legacy window-view JSON payloads.
- Deleted `ASTWatchQuery.h`/`ASTWatchQuery.cpp` (master extended them for AST JSON support in #114171) and dropped the `WatchQuery` factory entry in `ASTFromJSON.cpp`.
- Adapted `gtest_tree_hash_completeness.cpp`: removed `WATCH` / `CREATE WINDOW VIEW` cases; the child-pointer test now exercises `sql_security` and `comment`.
- Regenerated docs artifacts from master's versions minus the window-view settings and the `windowID` section.
- Deleted the re-added `test_window_view_attach_wrapped_interval` integration test.
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 11, 2026
`CREATE TABLE t ENGINE = TimeSeries <kind> INNER UUID '00000000-0000-0000-0000-000000000000'`
made `ParserViewTargets` create an `ASTViewTargets` and then drop the Nil UUID
(`ASTViewTargets::setInnerUUID` only records a non-Nil one), so the query carried an
empty `ViewTargets` child that formatting cannot print. The debug round-trip check in
`executeQuery` then threw `Inconsistent AST formatting` and aborted the server
(found by La Casa Del Dolor, STID 1941-1bfa). In release builds the clause was a
silent no-op.

Reject a Nil `<kind> INNER UUID` at parse time with BAD_ARGUMENTS, the same way
`TO INNER UUID` and `ATTACH ... UUID` already reject Nil since ClickHouse#114171. Server-written
metadata never contains such a clause (`ASTViewTargets::formatTarget` prints
`INNER UUID` only for a non-Nil value), so stored tables are unaffected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants