Skip to content

Fix inconsistent AST formatting for CREATE TABLE with UNIQUE KEY and TTL - #104968

Merged
murphy-4o merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ast-formatting-unique-key-ttl-104963
Jun 22, 2026
Merged

murphy-4o merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ast-formatting-unique-key-ttl-104963

Conversation

@groeneai

@groeneai groeneai commented May 14, 2026 •

Copy link
Copy Markdown
Collaborator

CREATE TABLE t0 (c0 Int PRIMARY KEY) ENGINE = MergeTree() UNIQUE KEY (c0) TTL 1 aborted the debug server with LOGICAL_ERROR: Inconsistent AST formatting.

Root cause: ParserStorage::parseImpl and ASTStorage::clone appended children (unique_key, sample_by, ttl_table) in a different order than ASTStorage::formatImpl and ASTStorage::normalizeChildrenOrder use. When normalizeChildrenOrder was not invoked on the reparse path (storage-level PRIMARY KEY, or PRIMARY KEY already hoisted out), the round-trip check in executeQueryImpl failed. The same mismatch also broke IAST::getTreeHash stability across clone.

Fix: reorder set() calls in ParserStorage::parseImpl and ASTStorage::clone to match canonical order. Regression test 04240_104963_unique_key_ttl_ast_format (local-disk-Atomic-only — UNIQUE KEY returns SUPPORT_IS_DISABLED elsewhere).

Categorised as CI Fix because the user-visible abort only fires under #ifndef NDEBUG (debug builds), so Bugfix validation (functional tests) (which downloads a RelWithDebInfo + NDEBUG master binary) cannot reproduce it. The getTreeHash stability part is release-visible. Sibling AST-formatting fixes #100136 / #96894 use the same category for the same reason.

Closes #104963

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Not applicable (CI Fix).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.1100

`ParserStorage::parseImpl` appended children in the order
(engine, partition_by, primary_key, order_by, sample_by, ttl_table,
unique_key, settings), but `ASTStorage::normalizeChildrenOrder` and
`ASTStorage::formatImpl` use the canonical order (engine, partition_by,
primary_key, order_by, unique_key, sample_by, ttl_table, settings).

When a `CREATE TABLE` carried both a `UNIQUE KEY` and a `TTL` clause and
the original AST happened to be normalized (e.g., an inline column-level
`PRIMARY KEY` triggered `normalizeChildrenOrder` in
`ParserCreateTableQuery::parseImpl`), the formatter emitted the clauses
in canonical order but the reparse path landed back in
`ParserStorage::parseImpl` where the inline PK was already hoisted, so
`normalizeChildrenOrder` was not invoked.  The reparsed AST therefore
had `unique_key` and `ttl_table` swapped relative to the original, and
the round-trip check in `executeQueryImpl` aborted the debug server with
`LOGICAL_ERROR: Inconsistent AST formatting`.

Reorder the `set()` calls in `ParserStorage::parseImpl` to match the
canonical order so re-parses produce identical child order, and add a
regression test covering the three shapes that exercise the affected
paths: inline `PRIMARY KEY` + `UNIQUE KEY` + `TTL`, storage-level
`PRIMARY KEY` + `UNIQUE KEY` + `TTL`, and the full clause combination
with `PARTITION BY`, `SAMPLE BY` added.

Closes ClickHouse#104963

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @alexey-milovidov @PedroTadim — could you review this? It fixes the AST round-trip mismatch in #104963: ParserStorage::parseImpl was appending storage children (unique_key after sample_by/ttl_table) in a different order than ASTStorage::normalizeChildrenOrder and ASTStorage::formatImpl use, so when the original AST was normalized by the inline-PK path the reparse produced swapped children and executeQueryImpl aborted with Inconsistent AST formatting. The fix reorders the set() calls to match the canonical order; new regression test 04240_104963_unique_key_ttl_ast_format covers three shapes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session cron:clickhouse-ci-task-worker:20260514-164500)

(a) Deterministic repro: ./build/programs/clickhouse local --query "CREATE TABLE t0 (c0 Int PRIMARY KEY) ENGINE = MergeTree() UNIQUE KEY (c0) TTL 1;" aborts (exit 134) on unfixed binary, every time. With fix: clean Code: 344 ... UNIQUE KEY is an experimental feature (or Code: 36 ... TTL expression 1 does not depend on any of the columns with the setting enabled).

(b) Root cause: ParserStorage::parseImpl lines 725-733 set children via set() which appends. Set order was (engine, partition_by, primary_key, order_by, sample_by, ttl_table, unique_key, settings). ASTStorage::normalizeChildrenOrder and ASTStorage::formatImpl both use canonical order (engine, partition_by, primary_key, order_by, unique_key, sample_by, ttl_table, settings). When the original AST was normalized — e.g. because an inline column-level PRIMARY KEY triggered normalizeChildrenOrder in ParserCreateTableQuery::parseImpl — but the reparse landed back in ParserStorage::parseImpl after the inline PRIMARY KEY had been hoisted out of columns_list, normalizeChildrenOrder was not invoked, so the reparsed AST had unique_key and ttl_table swapped. Round-trip check in executeQueryImpl:1277 raised LOGICAL_ERROR: Inconsistent AST formatting.

(c) Fix matches root cause: Reordered the set() calls to canonical order. Directly addresses the mechanism — not a defensive guard.

(d) New regression test: 04240_104963_unique_key_ttl_ast_format covers three shapes (inline-PK, storage-PK, full clause combo). The issue's exact reproducer is included with { serverError BAD_ARGUMENTS }.

(e) Both directions demonstrated: Without the fix, the server SIGABRTs while tests/clickhouse-test runs the new test (Exit 134 on server). With the fix, tests/clickhouse-test --test-runs 50 reports 50/50 OK. Existing test 04046_unique_key_ddl still passes 3/3.

(f) Fix is general: The parser is the single source of children order during initial AST construction. No other code paths build ASTStorage with all four clauses; downstream consumers either start from this AST or run normalizeChildrenOrder themselves. Comment added so future fields appended to ASTStorage keep canonical order.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label May 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d1004ad]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR fixes an ASTStorage child-order invariant mismatch by making ParserStorage::parseImpl and ASTStorage::clone use the same canonical clause order as ASTStorage::formatImpl/normalizeChildrenOrder, and extends 04046_unique_key_ddl with regression coverage for UNIQUE KEY + TTL shapes that previously tripped debug round-trip consistency checks. I reviewed the current diff and prior thread discussion, and the previously reported ordering bug is fixed in the current code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 14, 2026
Comment thread src/Parsers/ParserCreateQuery.cpp Resolved
groeneai and others added 2 commits May 14, 2026 18:51
The previous commit aligned `ParserStorage::parseImpl` with the canonical
order used by `ASTStorage::formatImpl` and `normalizeChildrenOrder`
(engine, partition_by, primary_key, order_by, unique_key, sample_by,
ttl_table, settings).  `ASTStorage::clone` was missed and still appended
`sample_by`, `ttl_table`, `unique_key` in the old order.

`IAST::updateTreeHash` iterates `children` in sequence, so a divergent
clone order makes `getTreeHash` order-dependent under cloning:
parse-then-hash and parse-then-clone-then-hash would produce different
hashes for the same storage definition with all three clauses present.
Subsystems that key caches or fingerprints on tree hashes (parameterized
view cache, query plan cache, AST-based deduplication) would treat the
original and the clone as two distinct keys.

Reorder the `set()` calls in `ASTStorage::clone` to match the canonical
order and add a comment documenting the invariant so future edits stay
in sync with `formatImpl` and `normalizeChildrenOrder`.

Reported by clickhouse-gh[bot] review on PR ClickHouse#104968.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The regression test for issue ClickHouse#104963 exercises `CREATE TABLE ... UNIQUE
KEY ... TTL ...`.  `UNIQUE KEY` is an experimental MergeTree feature that
the engine currently restricts to local-disk storage in an `Atomic`
database — on s3/azure/cached_s3/shared-merge-tree/replicated-database
variants it raises `SUPPORT_IS_DISABLED: UNIQUE KEY on non-local disks is
not yet supported`.

Without skip tags, the test failed on every object-storage CI variant
(`amd_tsan, s3 storage`, `amd_debug, distributed plan, s3 storage`,
`amd_llvm_coverage, ParallelReplicas/AsyncInsert/old analyzer, s3
storage`, `arm_asan_ubsan, azure`, and `Bugfix validation (functional
tests)` which runs against MinIO/Azurite).

Add the same tag set used by the canonical UNIQUE KEY test
`04046_unique_key_ddl.sql`:
`no-ordinary-database, no-replicated-database, no-shared-merge-tree,
no-object-storage, no-s3-storage`.  The original
`LOGICAL_ERROR: Inconsistent AST formatting` reproduces on the
default local-disk MergeTree variants (amd_debug parallel, amd_tsan
parallel, amd_asan_ubsan parallel, etc.), so the regression coverage
this PR adds is preserved on every variant where the feature is
actually supported.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fix-up for PR-caused regression on 04240_104963_unique_key_ttl_ast_format — pushed d5046ee2735.

What broke: the latest commit ran on every s3 / azure / cached_s3 / Bugfix-validation variant (which runs against MinIO+Azurite). All of those raised SUPPORT_IS_DISABLED: UNIQUE KEY on non-local disks is not yet supported and bailed — the test does CREATE TABLE ... UNIQUE KEY ... TTL ... and UNIQUE KEY is currently restricted to local-disk MergeTree.

Fix: added the same tag set the canonical UNIQUE KEY test (04046_unique_key_ddl.sql) uses — no-ordinary-database, no-replicated-database, no-shared-merge-tree, no-object-storage, no-s3-storage. The original LOGICAL_ERROR: Inconsistent AST formatting still reproduces (and is now covered) on every local-disk variant (amd_debug, parallel, amd_tsan, parallel, amd_asan_ubsan, parallel, …), which is the only configuration where UNIQUE KEY is actually supported.

Diff is a single 6-line block at the top of the .sql file.

The round-trip check in `executeQueryImpl` is gated by `#ifndef NDEBUG`, so
the `LOGICAL_ERROR` from ClickHouse#104963 only fires in debug-build CI variants. The
`Bugfix validation (functional tests)` runner downloads a master
`RelWithDebInfo + NDEBUG` binary where the check is compiled out, so a
`pr-bugfix`-labelled validation cannot reproduce the master-side failure
that proves the fix. Recategorising as `CI Fix or Improvement` and
expanding the regression test comment to document why.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Following up on the Bugfix validation (functional tests) failure from the previous fix-up commit (d5046ee2735) — I investigated and re-categorised this PR as CI Fix or Improvement rather than Bug Fix. Pushed 78b88325842 with a comment in the regression test explaining why.

Root reason Bugfix validation cannot prove the fix

The original LOGICAL_ERROR: Inconsistent AST formatting fires from executeQueryImpl at src/Interpreters/executeQuery.cpp:1277. That check is wrapped in #ifndef NDEBUG:

out_ast = parseQuery(parser, ...);

#ifndef NDEBUG
try
{
    /// Verify that AST formatting is consistent:
    /// If you format AST, parse it back, you get the same AST, ...

So the failure is debug-build-only. The Bugfix validation (functional tests) runner downloads master/amd64/clickhouse from clickhouse-builds.s3.us-east-1.amazonaws.com — I verified this binary is BUILD_TYPE=RelWithDebInfo with -DNDEBUG set in CXX_FLAGS:

$ /tmp/master_binary local -q "SELECT value FROM system.build_options
                                WHERE name = 'BUILD_TYPE'"
RelWithDebInfo

$ /tmp/master_binary local --allow_experimental_unique_key=1 -q \
    "CREATE TABLE t (c0 Int PRIMARY KEY, ts DateTime)
     ENGINE = MergeTree() UNIQUE KEY (c0) TTL ts + INTERVAL 1 DAY"
# exit 0 — succeeds silently on master release binary

The debug-only round-trip check is compiled out in this binary, so no pr-bugfix-labelled test can reproduce the failure on the master half of bugfix validation, regardless of how the test is structured (CREATE TABLE, EXPLAIN AST, formatQuery, clickhouse-format, etc.). I tried each shape locally against the master binary — every one of them accepts the statement silently.

Sibling AST-formatting fixes use the same lightweight category for the same reason:

The current PR remains a real correctness improvement:

  1. ParserStorage::parseImpl — fixes the debug round-trip check (CI-visible).
  2. ASTStorage::clone — fixes IAST::getTreeHash stability for clones (release-visible, but no user-facing failure mode in the issue).

What stays the same: regression test 04240_104963_unique_key_ttl_ast_format keeps its current local-disk tag set (no-ordinary-database, no-replicated-database, no-shared-merge-tree, no-object-storage, no-s3-storage, mirroring 04046_unique_key_ddl.sql) — UNIQUE KEY is local-disk-Atomic-only. On debug local-disk variants (amd_debug, amd_tsan, amd_msan, amd_asan_ubsan, arm_*) the test passes against the PR binary and would have aborted against the unpatched binary, which is the coverage that matters.

cc @evillique @alexey-milovidov @PedroTadim — the source-code fix and the test are unchanged from the previous CI-clean run on d5046ee2735 (stateless tests + bugfix-validation skip-recovery now matching). The only diff in this commit is documentation. Happy to switch back to Bug Fix if you'd prefer to add a no-bugfix-validation-style escape hatch in the bugfix-validation runner instead, but the lightweight category seems to match precedent.

Session: cron:clickhouse-ci-task-worker:20260515-004500

@clickhouse-gh clickhouse-gh Bot added pr-ci and removed pr-bugfix Pull request with bugfix, not backported by default labels May 15, 2026
@murphy-4o murphy-4o self-assigned this May 15, 2026
@murphy-4o

Copy link
Copy Markdown
Member

@groeneai please simplify the pr description

@groeneai

Copy link
Copy Markdown
Collaborator Author

@murphy-4o done — PR description trimmed to ~200 words. Kept the root cause one-paragraph, the fix one-liner, the regression test reference, and the CI Fix rationale. Dropped the long discussion of reparse paths, sibling-PR precedents, and the test-shape enumeration. Let me know if you'd like it shorter still.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai can you check the CI failures?

… WasmEdge MSan CI

Algunenano's PR ClickHouse#104971 reverts the x86v3 default; that fixed the chronic
DB::SystemLogQueue<DB::QueryLogElement>::waitFlush 180s timeout family
on Stateless tests (amd_msan, WasmEdge, *) which was the only failing
check on this PR's prior CI run (2026-05-15 02:15 UTC).

Master WasmEdge MSan SystemLog flush timeouts dropped from 33/day
(2026-05-13) to 0/day (2026-05-16+) after PR ClickHouse#104971 merged at
2026-05-15 08:57 UTC. Merging master to re-trigger CI on the post-revert
build so PR ClickHouse#104968 can be evaluated cleanly.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim sure — here is what the CI looks like on the prior head 78b8832584241d:

Only one failing check across the entire matrix: Stateless tests (amd_msan, WasmEdge, parallel, 1/2). Test 01946_profile_sleep hit the 600s job timeout. Every other check (14 builds, all AST fuzzer / BuzzHouse variants, all integration test shards, all other stateless variants) was green.

Classification (CIDB, last 30 days, 01946_profile_sleep):

  • 10 hits across 10 unrelated PRs (#97254, #100177, #100938, #101757, #104489, #104607, #104691, #104705, #104968, #104969)
  • 9 of 10 hits on the same Stateless tests (amd_msan, WasmEdge, parallel, 1/2) runner
  • 0 master hits
  • All transient: the CI's automatic randomized-settings rerun passed (Runs: 2, Failed: 0, Passed: 2)

This is the WasmEdge MSan SYSTEM FLUSH LOGS query_log 180s timeout family that @Algunenano root-caused on 2026-05-14 (x86v3 baseline ISA + __msan_chain_origin + vzeroupper overhead pushing tests over the 180s flush timeout). His revert PR #104971 merged on 2026-05-15 08:57 UTC; the master rate of this family went from 33/day (2026-05-13) to 0/day (2026-05-16 onwards).

The prior CI on this PR ran at 2026-05-15 02:15 UTC, six hours before the revert merged, so it was still on the affected build.

I just merged master into the PR branch (commit 6118cc8f) to pull in PR #104971. CI is re-running on the post-revert build; expecting the WasmEdge MSan job to clear.

The PR's source-code change is unchanged from d5046ee2: parser + clone reorder in src/Parsers/ParserCreateQuery.cpp and src/Parsers/ASTCreateQuery.cpp, plus the regression test 04240_104963_unique_key_ttl_ast_format with the appropriate no-s3-storage / no-shared-merge-tree / no-replicated-database / no-ordinary-database / no-object-storage tags. No new code changes in this CI cycle.

@murphy-4o

Copy link
Copy Markdown
Member

@groeneai

  1. don't create a new test case, merge into existing test case
  2. simplify your code comment

Per review feedback on PR ClickHouse#104968:
1. Move the UNIQUE KEY + TTL regression cases from a separate
   04240_104963_unique_key_ttl_ast_format.{sql,reference} pair into
   04046_unique_key_ddl as a new section (case 22 with sub-cases a-d).
   Both tests share the same tag set and target the same experimental
   feature, so a single canonical UNIQUE KEY DDL test is preferable.
2. Trim the multi-line clone-order comment in ASTStorage::clone down to
   the two-line invariant. The root-cause story is already in the prior
   commit message and PR description.

Source fix and child-order behaviour are unchanged from 6118cc8.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@murphy-4o thanks for the review. Both items addressed in d1004ad3c2ba:

  1. Merged into existing test. Folded the UNIQUE KEY + TTL cases from 04240_104963_unique_key_ttl_ast_format.{sql,reference} into 04046_unique_key_ddl.{sql,reference} as case 22 (sub-cases a-d). Both tests share the same tag set (no-ordinary-database, no-replicated-database, no-shared-merge-tree, no-object-storage, no-s3-storage) and target the same experimental feature, so a single canonical UNIQUE KEY DDL test is preferable. The 04240 pair is deleted.

  2. Simplified the code comment in ASTStorage::clone from the 7-line block down to the 2-line invariant:

    /// Children must be added in the canonical order used by `formatImpl` and
    /// `normalizeChildrenOrder`. `IAST::updateTreeHash` iterates `children` in sequence.

    The root-cause prose lives in the commit message and PR description.

Source-level behaviour is unchanged from 6118cc8fcf1b — this is purely a test-file consolidation plus a comment trim.

@murphy-4o
murphy-4o enabled auto-merge May 21, 2026 06:42
@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.10% -0.10%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (26/26) · Uncovered code

Full report · Diff report

@murphy-4o
murphy-4o added this pull request to the merge queue Jun 22, 2026
Merged via the queue into ClickHouse:master with commit 90e97b9 Jun 22, 2026
164 of 166 checks passed
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 pr-ci 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.

Inconsistent AST formatting with UNIQUE KEY

4 participants