Skip to content

Reject a PRIMARY KEY that a table created from a table function cannot format back - #116645

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:reject-primary-key-a-table-function-cannot-format
Aug 28, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:reject-primary-key-a-table-function-cannot-format

Conversation

@groeneai

@groeneai groeneai commented Aug 27, 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):

A PRIMARY KEY in the column list of CREATE TABLE ... AS <table function> was accepted, and the table metadata was then written in a form the server could not parse back, so the database failed to load with Code: 62 SYNTAX_ERROR on the next start. Such a statement is now rejected, as it already is for views.

Description

Found by the AST fuzzer in the stress test, Stress test (amd_debug), STID 1941-26fa:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113077&sha=8ed17407ce766eefd63ecefecaac7a9f0f8f2063&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

CREATE TABLE t (x UInt64 PRIMARY KEY) AS numbers(5) is accepted on every release I tested (25.8 LTS through master), the PRIMARY KEY is ignored at execution, and the metadata written is unparseable, so the server does not come back up:

$ clickhouse client -q "CREATE TABLE d.t (x UInt64 PRIMARY KEY) AS numbers(5)"   # accepted
$ cat store/591/.../t.sql
ATTACH TABLE _ UUID '...' (`x` UInt64) AS numbers(5)
PRIMARY KEY tuple(x)
$ # restart, 26.8.1.2016 official build: server exits 62
<Error> Application: Caught exception while loading metadata: Code: 62 ...
  Syntax error (in file .../t.sql): failed at position 93 (PRIMARY) (line 5, col 1)

Root cause: the parser normalizes a column-list PRIMARY KEY into a synthesized storage definition without checking as_table_function (ParserCreateQuery.cpp:1088-1122), so the AST carries both. A table built from a table function has no storage definition of its own, which is the same rule that already rejects an explicit ENGINE (:1020), so formatting prints it after AS numbers(5), where the grammar has no production for it. Debug builds report Inconsistent AST formatting.

I reject the statement at parse time, mirroring the existing guard for views (390df2a54779c2e), and add the same mutual-exclusion check to the JSON AST reader, where a payload carrying both members reached the same unparseable metadata.

Test shape follows 633635892484d83, which removed the stateless arms 390df2a54779c2e added, leaving the gtest_tree_hash_completeness.cpp case. Both new arm sets fail without their guard.

Residuals, not addressed here: metadata already persisted this way stays unreadable, and CREATE WINDOW VIEW wv (x UInt64 PRIMARY KEY) AS SELECT ... has a different root cause (the clause is dropped silently). If #101177 lands, making storage plus as_table_function legal, both guards need revisiting.


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

Version info

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

…t format back

A PRIMARY KEY declared in the column list of CREATE TABLE ... AS <table function>
was normalized into a synthesized storage definition, leaving as_table_function and
storage both set on the ASTCreateQuery. A table built from a table function has no
storage definition of its own, which is the same rule that already rejects an
explicit ENGINE, so formatting printed the synthesized node after the table
function, where the grammar has no production for it.

Two consequences followed. In debug and sanitizer builds the format-and-reparse
check raised 'Inconsistent AST formatting', which is how the AST fuzzer surfaced
this. In release builds nothing on the CREATE path rejected the combination, so the
table was created and DatabaseOnDisk wrote its metadata through the same formatter;
on the next start the database failed to load with Code: 62 SYNTAX_ERROR and the
server did not come up. Measured on 26.8.1.2016 (official build), and the formatter
emits the same unparseable text on every release back to 25.8 LTS.

Reject the statement at parse time instead, mirroring the guard
ParserCreateViewQuery already carries for views (390df2a). The same
mutual-exclusion check is added to ASTCreateQuery::readJSON, where a
clickhouse_json payload carrying both members reached the identical unparseable
metadata and, unlike the SQL path, did so silently even in a debug build.

Tests go in gtest_tree_hash_completeness.cpp next to the view case. The stateless
arms that 390df2a added were removed again by 6336358, leaving the
gtest as the convention for this defect class.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding; 1 full pass,
no fix round needed).

# Sev Finding Verdict Evidence / action
1 💡 The commit message omits the CI report URL and the corresponding pull request link AGREE in part The report URL, the check name and the STID are now in the description. The commit message is left as it is: the finding itself says not to amend, and the repository rulebook asks for new commits rather than an amend, so the existing message cannot be changed. I also did not link the carrier pull request: it is one of 22 mutually unrelated ones that inherited this trunk failure within four hours, and linking such a pull request only makes them look connected, so I linked the CI report instead.

Also noted, not blocking: my own commit message does not wrap identifiers in inline code
blocks, which the repository rulebook asks for. I am not spending a round on it while the
defect is live on master.

Session id: cron:clickhouse-review-slot-11:20260827-043500

@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8977ecc]

Summary: ✅


AI Review

Summary

This PR closes the parser/formatter hole where a column-list PRIMARY KEY on CREATE or ATTACH TABLE ... AS <table function> was normalized into storage, then formatted after AS <table function> and made stored metadata unreadable on reload. I did not find actionable correctness, metadata, or test-coverage issues in the current patch.

Final Verdict

✅ Approve. The SQL-side guard in src/Parsers/ParserCreateQuery.cpp and the AST-JSON guard in src/Parsers/ASTCreateQuery.cpp cover the two reachable constructors of the broken storage + as_table_function state, and the added tests in src/Parsers/tests/gtest_tree_hash_completeness.cpp exercise both surfaces.

LLVM Coverage Report

Measured on commit 8977ecc.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.80% +0.10%

Changed lines: Changed C/C++ lines covered: 36/36 (100.00%) · 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 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One plain-SQL statement, no fuzzer, no randomization, no restart needed for the parse half: SELECT formatQuerySingleLine('CREATE TABLE t (x UInt64 PRIMARY KEY) AS numbers(5)') emits CREATE TABLE t (\x` UInt64) AS numbers(5) PRIMARY KEY tuple(x), and feeding that back gives Code: 62 SYNTAX_ERROR ... failed at position 43 (PRIMARY)`.
b Root cause explained? ParserCreateTableQuery::parseImpl moves a column-list PRIMARY KEY into a synthesized ASTStorage without checking as_table_function (ParserCreateQuery.cpp:1088-1122), so the AST holds both members. ASTCreateQuery::formatImpl prints as_table_function at :1140-1154 and storage at :1187-1188, emitting ... AS numbers(5) PRIMARY KEY tuple(x). The grammar has no production for that: parse_storage() runs before AS (:957), a parsed storage clause requires a SELECT after AS (:976-979), and the table-function branch is allowed only when none was parsed (:982-985, :1020).
c Fix matches root cause? Yes, and at the source: the statement is refused where the unparseable AST would otherwise be built, so neither consequence can occur. I did not delete the ostr << " PRIMARY KEY" line added by #114171, which would only re-hide the defect and reintroduce the silent-drop bug in ALTER TABLE ... ADD/MODIFY COLUMN that its comment documents.
d Test intent preserved / new tests added? Nothing weakened or removed. Two new arm sets in the existing gtest_tree_hash_completeness.cpp: TableFunctionsRejectAPrimaryKeyTheyCannotFormat (3 rejection arms plus 2 acceptance arms) and a storage + as_table_function JSON arm plus 2 single-member acceptance arms. No test in tests/queries/ and no gtest previously combined a table-function AS with a PRIMARY KEY on one statement (measured; positive control found 30 files with a table-function AS).
e Both directions demonstrated? Yes, on Build-ID verified binaries (base 8ec6246b91b577e9, fix 8679dc8d569cba5b). Base: all four defective shapes accepted, the release build persists unparseable metadata. Fix: all four rejected with Code: 62, the forged JSON payload rejected with Code: 36 and 0 metadata files written, every control still accepted. Negative controls: removing the parser guard reddens exactly the 3 EXPECT_THROW arms (0 positive-arm failures, 26 of 27 sibling tests still pass, so the mutant is narrow); removing the readJSON check reddens exactly the JSON arm.
f Fix is general across code paths? I enumerated all 11 construction sites of the invariant "as_table_function and storage are never both set". Both unguarded reachable ones are fixed (the parser normalization for both column-list spellings, and ASTCreateQuery::readJSON). The AST fuzzer's text-level producer and the restore_replace_external_table_functions_to_null LOGICAL_ERROR are fixed transitively. InterpreterCreateQuery.cpp:1489-1497, SystemLog.cpp, ASTCreateQuery::clone and the view parser are already safe or already guarded. applyTableOverride.cpp:107-121 is unguarded but unreachable (its only production caller always passes a query that already has storage and never an as_table_function), so I left it alone rather than add speculative defensive code.
g Fix generalizes across inputs (params/datatypes/wrappers)? The type-wrapper axis does not apply: the guard tests AST members, not data types, and the CI evidence confirms the shape fires with UInt64, LowCardinality(UInt64) and MultiPoint alike. Both column-list spellings (x T PRIMARY KEY and , PRIMARY KEY x) and both CREATE and ATTACH are arms. Every observed table function (numbers, format, remote, mysql, sqlite, s3, mongodb, clusterAllReplicas, VALUES) reaches the identical code path, so one arm suffices.
h Backward compatible? (maintainer-approved exception only) This rejects a statement that previously appeared to succeed, which is not a regression: the PRIMARY KEY was ignored at execution and the resulting table made the server unbootable, so anyone who ran it already has a broken database. The identical trade was accepted for views by 390df2a54779c2e. No setting or setting default changes, so no SettingsChangesHistory.cpp entry is needed, and there are no serialization-format or versioning implications. Metadata already persisted in the broken form is not repaired; that is disclosed in the description.
i Invariants and contracts preserved? The change restores the invariant in (b) on the one path that broke it and introduces no new one. It throws before any AST member is mutated, so no partially-normalized tree exists on the error path. ATTACH is covered too, and that cannot break metadata loading: metadata never contains the column-level spelling, because the parser clears that flag at ParserCreateQuery.cpp:499 so formatImpl never prints it for CREATE/ATTACH. The persisted form is the table-level one, which already fails to parse today.

Suites: unit_tests_dbms --gtest_filter='TreeHashCompleteness*' 27/27, and 50 clean repeats. Six parser-adjacent stateless files at --test-runs 50 with randomization on: 350/350. 01083_expressions_in_engine_arguments fails identically on the base binary (Code: 701 ... There is no port named https_port), so it is a limitation of my local server config rather than an effect of this change.

Session id: cron:clickhouse-impl-slot-5:20260827-034700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @alexey-milovidov, could you review this? A column-list PRIMARY KEY on CREATE TABLE ... AS <table function> was normalized into a synthesized storage definition while as_table_function stayed set, so formatting emitted the key in a position the grammar has no production for. The table was still created, its metadata was written through that same formatter, and the next start failed with Code: 62, so I reject the statement at parse time as ParserCreateViewQuery already does for views.

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 712.35 MiB 709.29 MiB -3.06 MiB (-0.43%)

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.

Compile time of recompiled translation units

8 translation units recompiled, 12 s compile time in total, 8 of them have a recent master baseline.

Job report

@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
-- accepted, PRIMARY KEY silently ignored
CREATE TABLE t (x UInt64 PRIMARY KEY) AS numbers(5);

-- the form written to metadata does not parse back:
SELECT formatQuery(formatQuery('CREATE TABLE t (x UInt64 PRIMARY KEY) AS numbers(5)'));
-- Code: 62. Syntax error: failed at position 49 ('PRIMARY') (line 5, col 1): PRIMARY KEY tuple(x)
-- On a server, the same metadata makes the database fail to load on the next start.

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3, 25.8.

CC component owner: @alexey-milovidov @vitlibar

Analysis metadata

comp-sql-syntax · Severity P2 · Finding phase_d_pr116645

  • Verified against master build 6764095e278a (aarch64)
Introducing change: not identified
  • No clean release baseline found and no lower bound established — source-build bisect is required to pin the introducing PR (not yet performed).
  • Walked 6 release(s) below the supported window: still reproduces down to 25.2.
  • Secondary components: comp-testing

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, with one correction to the target list: 26.8 is affected too, the tested-versions list above did not include it.

Measured just now on the official per-branch builds, one statement each. SELECT formatQuerySingleLine('CREATE TABLE t (x UInt64 PRIMARY KEY) AS numbers(5)') returns the unparseable CREATE TABLE t (`x` UInt64) AS numbers(5) PRIMARY KEY tuple(x) on 26.8.1.2021, 26.7.6.18, 26.6.4.30, 26.5.8.37, 26.3.25.1 and 25.8.34.11, and is rejected with PRIMARY KEY is not allowed in the column list of a table created from a table function on 26.9.1.229, whose GIT_HASH is this PR's merge commit 6764095e278a. That emitted form is what gets persisted as table metadata, so on all six branches the next server start fails with Code: 62 while loading it.

@PedroTadim could you apply v25.8-must-backport here? One version-specific label is enough: select_backport_branches in tests/ci/cherry_pick_branches.py expands it to the floor release plus every newer active branch, so it covers 25.8, 26.3, 26.5, 26.6, 26.7 and 26.8 in one go, including the 26.8 the list above missed. All six are taking merged backports this week. I am not hand-authoring release-branch PRs.

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Aug 28, 2026
alexey-milovidov added a commit that referenced this pull request Aug 28, 2026
Pulls in the fix for the fleet-wide `Inconsistent AST formatting` fuzzer
failure (issue #116732, fixed by #116645) that made the arm_debug stress test
red on this pull request.
@groeneai groeneai mentioned this pull request Aug 29, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-26fa)

5 participants