Skip to content

Reject CREATE TABLE ... CLONE AS SELECT / table function - #105004

Merged
alexey-milovidov merged 30 commits into
ClickHouse:masterfrom
tuanpach:fix-clone-as-select
Sep 12, 2026
Merged

alexey-milovidov merged 30 commits into
ClickHouse:masterfrom
tuanpach:fix-clone-as-select

Conversation

@tuanpach

@tuanpach tuanpach commented May 15, 2026 •

Copy link
Copy Markdown
Member

The CREATE TABLE ... CLONE AS <source> clause is intended to clone a real on-disk source table — the partition-attach step performed after table creation needs actual partitions to copy. The parser, however, also accepted CREATE TABLE t CLONE AS SELECT ... and CREATE TABLE t CLONE AS <table_function>. Neither shape has partitions to attach, so the CLONE keyword was silently ignored and the table was created as a plain CREATE ... AS SELECT with an inferred schema and ORDER BY tuple().

This PR rejects both shapes early in getTablePropertiesAndNormalizeCreateQuery with BAD_ARGUMENTS, so the user gets a clear error instead of silent misbehavior. It also fixes a related defect in ASTCreateQuery::formatQueryImpl: the if (select) branch did not call add_clone_if_needed, so an AST format round-trip silently dropped CLONE from CLONE AS SELECT. The randomized-settings injection in clickhouse-test round-trips queries through this formatter, which is how the gap surfaced.

Closes: #104994

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 CREATE TABLE ... CLONE AS SELECT ... and CREATE TABLE ... CLONE AS <table_function> silently ignoring the CLONE keyword and creating a plain CREATE ... AS SELECT instead. These shapes are now rejected with BAD_ARGUMENTS.

Documentation entry for user-facing changes

  • Documentation is unchanged: this is a bug fix that brings behavior in line with the existing CLONE AS documentation, which only describes the CLONE AS <table> form.

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

@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [55aeb12]

Summary: ✅


AI Review

Summary

This PR closes the silent misbehavior around CREATE / full ATTACH ... CLONE AS with a non-table source by rejecting the AS SELECT and AS <table_function> forms in the interpreter, restores lossless formatting for CLONE AS SELECT, and now rejects parser-impossible is_clone_as JSON shapes in ASTCreateQuery::readJSON. I re-checked the current PR head against the full prior discussion, including the previously unresolved bot thread, and did not find any remaining correctness, compatibility, or coverage gaps in the changed surface.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 55aeb12.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.10% -0.10%

Changed lines: Changed C/C++ lines covered: 25/25 (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 May 15, 2026
The parser accepted CREATE TABLE t CLONE AS SELECT ... and CREATE TABLE t
CLONE AS <table_function>, but neither shape has partitions to attach, so
the CLONE keyword was silently ignored and the table was created as a
plain CREATE ... AS SELECT. Reject these shapes in
getTablePropertiesAndNormalizeCreateQuery with BAD_ARGUMENTS. The check
is gated to fresh user CREATE only — pre-fix the AS-table-function shape
was persisted into .sql metadata, and rejecting on ATTACH would break
loading of any such legacy table on upgrade.

Also fix ASTCreateQuery::formatQueryImpl: the `if (select)` branch did
not emit CLONE, so an AST round-trip silently dropped the keyword. The
randomized-settings injection in clickhouse-test round-trips queries
through this formatter, which is how the gap surfaced.

Fixes ClickHouse#104994
@tuanpach
tuanpach force-pushed the fix-clone-as-select branch from ae90c08 to 5fb381c Compare May 15, 2026 14:11
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@SmitaRKulkarni SmitaRKulkarni self-assigned this Jun 9, 2026

@SmitaRKulkarni SmitaRKulkarni left a comment

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.

LGTM

The guard added in `getTablePropertiesAndNormalizeCreateQuery` only fired
for a fresh `CREATE` (`mode <= CREATE`). A user-supplied full `ATTACH`
definition — one that carries an explicit column list (and an engine for
the `SELECT` form) — is not the short-attach path: `attach_short_syntax`
is false, so it goes through the create-like path with `mode == ATTACH`
and bypassed the guard. `isCreateQueryWithImmediateInsertSelect` returns
false for `attach` and the clone partition-attach path requires
`as_table_saved`, so `CLONE AS SELECT` / `CLONE AS table_function` were
silently ignored for such `ATTACH` queries, exactly as they were for
`CREATE` before this fix.

Extend the guard to also reject `is_clone_as && as_table.empty()` for a
user-supplied full `ATTACH` (`mode == ATTACH && !attach_short_syntax`),
while leaving short `ATTACH` (`ATTACH TABLE t;`) and `SECONDARY_CREATE`
(`DatabaseReplicated` internal queries, `RESTORE`) permissive so
previously-validated metadata that persisted these forms still loads.
Server startup is unaffected: it loads tables via `createTableFromAST`,
which never calls this function.

Adds full-`ATTACH` regression cases to
`04238_clone_as_select_rejected`.

Addresses review feedback on ClickHouse#105004

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Addressed the AI review's "Request changes" verdict (full ATTACH case) in commit 8d1f677.

The guard in getTablePropertiesAndNormalizeCreateQuery previously fired only for a fresh CREATE (mode <= CREATE). A user-supplied full ATTACH definition (explicit column list, plus an engine for the SELECT form) is not the short-attach path — attach_short_syntax is false, so it goes through the create-like path with mode == ATTACH and bypassed the guard, silently dropping CLONE.

The guard now also rejects is_clone_as && as_table.empty() for a full user ATTACH (mode == ATTACH && !attach_short_syntax), while leaving short ATTACH (ATTACH TABLE t;) and SECONDARY_CREATE (DatabaseReplicated / RESTORE) permissive so previously-validated metadata still loads. Server startup is unaffected: tables are loaded via createTableFromAST, which never calls this function.

Added regression cases to 04238_clone_as_select_rejected for full-ATTACH ... CLONE AS SELECT and full-ATTACH ... CLONE AS <table function>; both now return BAD_ARGUMENTS. Verified locally with an ASan build.

@alexey-milovidov

Copy link
Copy Markdown
Member

The only red check is AST fuzzer (amd_debug) — Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa). It is a pre-existing, unrelated fuzzer flake, not a regression from this PR.

The failing query is a fuzzer-mutated CREATE TABLE dist_t0__fuzz_47 (a Decimal(22, 3), b Array(Array(Array(Array(Array(intDiv(less(1048575, '6ba7b810-…'), LowCardinality(UInt8)))))))) ENGINE = Distributed(…). It contains no CLONE and no SELECT, so none of this PR's code (the getTablePropertiesAndNormalizeCreateQuery guard, or the ASTCreateQuery::formatQueryImpl CLONE-emitting branch) is exercised. The divergence is entirely in the fuzzer's nonsense nested type: the token 1048575 round-trips as DataType_1048575 on the original AST but as Literal_UInt64_1048575 after re-parsing — a general numeric-token-in-type-position artifact.

This signature has failed 279 times over the last 6 months across ~249 unrelated PRs (e.g. #105714, #106215, #107125, #88234, #86768, #108055, #79091, #109107, #108414). It was tracked by the now-closed #106358 (exact STID 1941-1bfa), and the same "original AST" family remains open as #108372.

All other checks are green and the PR is approved.

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Dear @SmitaRKulkarni, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (1d15911) to clear the only red check on 54ff1dd2.

Integration tests (amd_tsan, 5/6) — test_keeper_snapshot_on_exit/test.py::test_snapshot_on_exit crashed with Logical error: 'response_bytes_in_all_queues.load() == 0' in Keeper on shutdown. Unrelated to this PR (nothing here touches Keeper); it is exactly what #112668 ("Fix Keeper logical error response_bytes_in_all_queues.load() == 0 on shutdown") fixes. That PR merged into master on 2026-08-04, i.e. after the previous merge base, so merging master pulls the fix in.

The merge is clean and needed no code changes; both changed translation units (InterpreterCreateQuery.cpp, ASTCreateQuery.cpp) still compile against current master. The PR is approved (@SmitaRKulkarni) with an ✅ Approve AI-review verdict and no unresolved review threads — it just needs the fresh CI run to finish and a maintainer merge.

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Dear @SmitaRKulkarni, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the unrelated stress-test failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105004&sha=5fb11a63606e551ca261911c6db55867bb8a450c&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29. Both failing stress jobs hit checkEqualRangeEndAssumeSorted (Equal values are not contiguous within the range assumed to be sorted); this PR only changes CREATE ... CLONE AS validation/formatting. The failure family is tracked in #115455. Please provide a fix in a separate PR, or link one already in progress.

@groeneai

Copy link
Copy Markdown
Collaborator

Both failing stress jobs are the same trunk defect, and a fix PR is already open: #113242.

check STID fuzzed declared type (from the stack)
Stress test (amd_tsan) 2508-348f Int16
Stress test (arm_debug) 2508-3775 Decimal256

Aborting queries, read from fatal.log (query_log only holds the pre-fuzz text):

SELECT 1023 > 0, count() FROM (SELECT DISTINCT s FROM merge_distinct__fuzz_3 ORDER BY s ASC LIMIT 100)
SETTINGS max_threads = 1, distributed_aggregation_memory_efficient = 0, optimize_distinct_in_order = 1

SELECT count() FROM (SELECT DISTINCT s FROM merge_distinct__fuzz_2 ORDER BY s ASC NULLS LAST LIMIT 100)
SETTINGS max_threads = 1, distributed_aggregation_memory_efficient = 1, optimize_distinct_in_order = 1

Both carry log_comment = 04870_distinct_merge_over_distributed.sql, so the fixture is my own test from #114677. The server-side AST fuzzer re-declares its Merge table with a mutated column type while the Distributed child keeps String.

Root cause: ReadFromMerge::convertAndFilterSourceStream applies the child to declared-type cast above the child's own sort, while getQueryProcessingStage has already told the initiator to only merge pre-sorted streams. An order-breaking cast then reinterprets values after they were sorted. #113242 returns FetchColumns when conversionPreservesOrder is false.

Verified both directions locally, master adae6c4db92826f vs #113242 head efedd7374f6d7d7, build ids asserted distinct. Both queries above abort on master and return 21 on the fix. Release-visible without DISTINCT, SELECT s FROM merge_distinct__fuzz_int16 ORDER BY s DESC LIMIT 6 returns [9,9,9,9,9,9] on master and [20,20,20,20,20,20] on the fix; correct max is 20. Three controls each stay OK on master, isolating the cast: declared column left as String, optimize_distinct_in_order = 0, and Merge over a local MergeTree.

Not caused by this PR: 30d CIDB gives 22 rows / 22 distinct PRs for 2508-348f and 4 / 4 for 2508-3775, with 0 true-master rows in either and one hit per PR.

#113242 is sequenced behind #113735, which currently has CHANGES_REQUESTED from @ novikd. That ruling is the unblock.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (81911ce123f4) — the branch was 9 days behind. The plain merge exploded into ~300 spurious conflicts because the branch history has two merge bases (criss-cross via the earlier master merges); resolved with a single-base git merge-tree --write-tree --merge-base=a4efc96a3f8c merge, and verified the resulting diff vs master is exactly the PR's own 6 files. Both changed translation units compile against current master.

The only red on 8574117790c4 was Stress test (arm_release) — Logical error: 'Column x UInt8 query tree node does not have valid source node' in ColumnNode::getColumnSource via ReadFromMerge::applyFilters → StorageDistributed::read (AST fuzzer, Merge over Distributed). Unrelated to this PR (which only touches CLONE AS validation in InterpreterCreateQuery and ASTCreateQuery formatting): it is the known issue #111253, with the fix already in progress in #111327.

Status unchanged otherwise: approved by @SmitaRKulkarni, AI review ✅, zero unresolved review threads. Ready for a maintainer to merge once CI is green.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (7c21191c8bd1) — clean merge this time (single merge base). Both reds on 81911ce123f4 were Stress test (arm_tsan / arm_msan) failing with the AST-fuzzer Logical error: 'Not-ready Set is passed as the second argument for function 'globalIn'/'globalNotIn'' — unrelated to this parser/InterpreterCreateQuery change, tracked in #107619; the fix (#115083) merged into master on 2026-08-30, so this merge pulls it in and should clear the red. Both changed translation units verified with -fsyntax-only against the merged tree. Status unchanged otherwise: approved by @SmitaRKulkarni, AI review positive, zero unresolved review threads — awaiting a maintainer to merge after fresh CI.

Comment thread src/Parsers/ASTCreateQuery.cpp Resolved
@abashkeev abashkeev added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 2026
…dJSON`

The AI review pointed out that `ASTCreateQuery::readJSON` never constrained
`is_clone_as`, so a crafted `clickhouse_json` payload could put the flag on a
view / dictionary form or on a source-less table. Since this pull request makes
`formatQueryImpl` emit `CLONE` for the `AS SELECT` shape as well, such a payload
now formats into DDL that the SQL parser cannot read back, for example
`CREATE VIEW v CLONE AS SELECT 1`.

`CLONE` is set only by `ParserCreateTableQuery`, only for tables, and only in
front of an `AS <source>`; it is also mutually exclusive with `EMPTY`. Validate
exactly that at the JSON boundary, alongside the existing `POPULATE` / `EMPTY`
shape checks, and cover it with `05054_ast_json_clone_as_shape`.
The `05054` slot filled up with other tests on master in the meantime.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed 55aeb124a97d:

  1. Addressed the outstanding AI review thread (discussion_r3948390584) — ASTCreateQuery::readJSON now rejects the parser-impossible is_clone_as shapes (on a view / materialized view / dictionary, on a source-less table, and together with is_create_empty), alongside the existing POPULATE / EMPTY shape checks. New focused test tests/queries/0_stateless/05136_ast_json_clone_as_shape.sql.
  2. Merged master (the branch was 3861 commits behind).
  3. Renumbered the new test to 05136 because the 05054 slot filled up on master in the meantime.

Verified locally with a freshly built RelWithDebInfo binary: 04238_clone_as_select_rejected, 04307_ast_json_roundtrip_lossless and 05136_ast_json_clone_as_shape all match their references. Style check is clean.

The single red on the previous head 2da8845d95bf was unrelated

Upgrade check (amd_release) — Error message in clickhouse-server.log:

<Error> MutatePlainMergeTreeTask: Code: 16. DB::Exception: Unexpected const virtual column: _table:
While executing MergeTreeSequentialSource. (NO_SUCH_COLUMN_IN_TABLE)

This is a mutation / virtual-column path that this pull request does not touch (it only changes InterpreterCreateQuery::getTablePropertiesAndNormalizeCreateQuery, ASTCreateQuery::formatQueryImpl and ASTCreateQuery::readJSON). It is tracked by an open issue and a fix is already in progress:

Since the fix has not landed on master yet, this red may recur on the fresh CI run until #117724 merges.

Status otherwise unchanged: approved by @SmitaRKulkarni, AI review clean, no other unresolved review threads. This is a fork branch, so the final merge is a maintainer's call — I am not self-merging.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit ddf4d12 Sep 12, 2026
175 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@tuanpach @SmitaRKulkarni @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). 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.

CLONE AS SELECT silently ignores CLONE keyword instead of throwing error

7 participants