Repository navigation
Reject ATTACH TABLE with non-engine storage clauses (narrower guard, re-land of #104800) - #105068
Conversation
Re-land of ClickHouse#104800 with a narrower guard that does not break `ATTACH TABLE t SETTINGS log_comment = 'foo';`. PR ClickHouse#104800 was reverted in ClickHouse#105032 because it rejected that pattern, which internal CI relies on (reported by @Algunenano on ClickHouse#104791). `InterpreterSetQuery::applySettingsFromQuery` runs in `executeQueryImpl` before `InterpreterCreateQuery::createTable` and hoists session settings out of `create.storage->settings` into the context, resetting `storage->settings` to `nullptr` when nothing engine-specific is left. The reverted guard fired only on the existence of an `ASTStorage` without an `engine`, so by the time it ran the storage object had already been emptied — rejecting the legitimate `log_comment` shape. The narrower guard checks the individual non-engine fields (`partition_by`, `primary_key`, `order_by`, `sample_by`, `ttl_table`, `unique_key`, `settings`) so it only rejects when there is something the short-`ATTACH` path would actually drop: ATTACH TABLE t; OK (short ATTACH) ATTACH TABLE t SETTINGS log_comment = 'foo'; OK (session bind) ATTACH TABLE t SETTINGS index_granularity = 100; BAD_ARGUMENTS ATTACH TABLE t SETTINGS max_part_loading_threads = 16; BAD_ARGUMENTS ATTACH TABLE t ORDER BY id; BAD_ARGUMENTS ATTACH TABLE t PARTITION BY id; BAD_ARGUMENTS Regression test `04247_attach_table_storage_clauses_without_engine_error` covers all six cases. Closes ClickHouse#104791. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Pre-PR validation gate(a) Deterministic repro? Yes. Regression test
(b) Root cause explained? Yes. (c) Fix matches root cause? Yes. The narrower guard checks the individual non-engine storage fields ( (d) Test intent preserved? Yes. The test still catches the original (e) Both directions demonstrated? Yes. Built the branch locally with the fix; (f) Fix is general? Yes. The guard rejects all six bug-class shapes ( |
|
Workflow [PR], commit [a7ce648] Summary: ❌
AI ReviewSummaryThis PR closes the short- Final VerdictStatus: ✅ Approve |
| if (has_non_engine_storage_clauses) | ||
| { | ||
| throw Exception(ErrorCodes::BAD_ARGUMENTS, | ||
| "ATTACH TABLE without ENGINE cannot specify storage clauses (ORDER BY, PARTITION BY, PRIMARY KEY, " |
There was a problem hiding this comment.
@groeneai Please simplify this error message. No need to say they would be ignored (or that session settings work), just say that ATTACH applies the table definition from stored metadata and can't be changed in the query itself. Keep the recommendation for the workaround, that's really good.
Also, please avoid using —. That's not a standard way of communicating in the project or in the error messages. Use plain and easy to understand English please. Make a note of this for the future.
There was a problem hiding this comment.
Thanks for the review @Algunenano. Pushed 6b4551c:
- Simplified the error message to the core point you suggested. Kept the workaround recommendation (
ATTACH TABLE {0};andALTER TABLE {0} MODIFY SETTING ...). Dropped thewould be ignoredandsession settings workwording. - Replaced the em-dash in the error string. Also removed the two em-dashes from the comment block above the guard and from the regression test header comment.
- Noted for future ClickHouse contributions: plain ASCII punctuation only in error messages, code comments, PR descriptions and replies. No em-dash.
Behavior is unchanged, the regression test only asserts BAD_ARGUMENTS so it still passes. New error text:
ATTACH applies the table definition from stored metadata and can't be changed in the query itself. Use 'ATTACH TABLE {0};' to re-attach with stored metadata, or 'ALTER TABLE {0} MODIFY SETTING ...' (or 'MODIFY ORDER BY ...') after ATTACH to change settings.
@Algunenano asked to drop the wording about silent ignoring and session settings and just say that ATTACH applies the table definition from stored metadata. The recommendation for the workaround stays. Also remove the em-dash from the error string and from the surrounding code/test comments per the same review (use plain ASCII punctuation in error messages and comments). Behavior is unchanged: the guard still raises `BAD_ARGUMENTS` in exactly the same cases. Regression test `04247_attach_table_storage_clauses_without_engine_error` only asserts `{ serverError BAD_ARGUMENTS }`, not the message text, so it keeps passing. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
@groeneai It seems that we only cover the fields under create.storage, but not the ones under create itself. For example, |
@Algunenano pointed out that the previous guard only checked `create.storage` sub-fields (`partition_by`, `primary_key`, `order_by`, `sample_by`, `ttl_table`, `unique_key`, `settings`). For an `ATTACH` query the parser also populates top-level `ASTCreateQuery` fields that the short `ATTACH` path silently drops by overwriting `create` with the stored table metadata. Example: `ATTACH TABLE t COMMENT 'x';` parsed, ran without error, and silently dropped the user-supplied comment. Same shape with `EMPTY`, `CLONE`, and for views `REFRESH`, `TO target`, `AS SELECT`. The guard now also rejects `BAD_ARGUMENTS` when any of these are populated at the point `createTable` runs and the query is going to take the short `ATTACH` path: - `create.comment` (top-level `COMMENT`) - `create.refresh_strategy` (`REFRESH` on a materialized view) - `create.sql_security` (`SQL SECURITY` on a view) - `create.select` (`AS SELECT` on a view) - `create.targets` (`TO target` on a materialized view, `INNER UUID`, `DATA/TAGS/METRICS` on `TimeSeries`) - `create.as_table_function` (`AS func(...)`) - `create.aliases_list` (`(a, b)` view aliases) - `create.is_create_empty` (`EMPTY`) - `create.is_clone_as` (`CLONE`) - `create.as_database`, `create.as_table` (`AS [db.]table`) The legitimate cases stay legitimate: `ATTACH TABLE t;`, `ATTACH TABLE t SETTINGS log_comment = 'foo';` (session settings hoisted out by `InterpreterSetQuery::applySettingsFromQuery`), `ATTACH TABLE t AS REPLICATED;`, `ATTACH TABLE t FROM '/path';`. Regression test extended with cases 8-13: `ATTACH TABLE t COMMENT`, `ATTACH TABLE t EMPTY AS SELECT 1`, `ATTACH TABLE t CLONE AS source`, `ATTACH MATERIALIZED VIEW t REFRESH ... TO ... AS SELECT ...`, `ATTACH MATERIALIZED VIEW t TO different_target AS SELECT ...`, and `ATTACH MATERIALIZED VIEW t TO target AS different_SELECT`. All previously silently succeeded, now all reject with `BAD_ARGUMENTS`. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Good catch @Algunenano, thanks. Pushed 60e1757 that broadens the guard to cover the top-level Audit of top-level fields the parser may populate for
|
| Field | User syntax that sets it | Behavior before this patch |
|---|---|---|
create.comment |
ATTACH TABLE t COMMENT 'x' |
silently dropped |
create.refresh_strategy |
ATTACH MATERIALIZED VIEW t REFRESH ... |
silently dropped |
create.sql_security |
ATTACH VIEW t SQL SECURITY DEFINER ... |
silently dropped |
create.select |
ATTACH MATERIALIZED VIEW t AS SELECT ... |
silently dropped |
create.targets |
ATTACH MATERIALIZED VIEW t TO target ..., TimeSeries DATA/TAGS/METRICS, TO INNER UUID |
silently dropped |
create.as_table_function |
ATTACH TABLE t AS func(...) (gated, rejected at parse for plain table) |
silently dropped if it slips through |
create.aliases_list |
view aliases (a, b) |
silently dropped |
create.is_create_empty |
ATTACH TABLE t EMPTY AS ... |
silently dropped |
create.is_clone_as |
ATTACH TABLE t CLONE AS source |
silently dropped |
create.as_database, create.as_table |
ATTACH TABLE t AS [db.]source (gated, rejected at parse for plain table) |
silently dropped if it slips through |
For plain ATTACH TABLE t AS ... the parser specifically only accepts NOT REPLICATED / REPLICATED after AS, so as_table_function / as_database / as_table would normally SYNTAX_ERROR. I check them anyway to stay safe under future parser changes.
The fields I deliberately do not touch because they are legitimate ATTACH flags:
create.attach_as_replicated(ATTACH TABLE t AS REPLICATED/AS NOT REPLICATED)create.attach_from_path/create.has_attach_from_path(ATTACH TABLE t FROM '/path')create.if_not_existscreate.is_temporarycreate.has_uuid,create.uuidcreate.cluster
Verified locally
| Query | Before this patch | After this patch |
|---|---|---|
ATTACH TABLE t COMMENT 'x'; |
OK (comment dropped) | BAD_ARGUMENTS |
ATTACH TABLE t EMPTY AS SELECT 1; |
OK (EMPTY dropped) |
BAD_ARGUMENTS |
ATTACH TABLE t CLONE AS source; |
OK (CLONE dropped) |
BAD_ARGUMENTS |
ATTACH MATERIALIZED VIEW t REFRESH EVERY 1 YEAR TO target AS SELECT ...; |
OK (all dropped) | BAD_ARGUMENTS |
ATTACH MATERIALIZED VIEW t TO different_target AS SELECT ...; |
OK (TO dropped) |
BAD_ARGUMENTS |
ATTACH TABLE t; |
OK | OK |
ATTACH TABLE t SETTINGS log_comment = 'foo'; |
OK | OK |
ATTACH TABLE t AS NOT REPLICATED; |
OK | OK |
Regression test extended with the new cases (8 through 13). The full test passes 50/50 with full randomization. Adjacent ATTACH-related tests (01601_detach_permanently, 01516_create_table_primary_key, 01153_attach_mv_uuid, 01073_attach_if_not_exists, 01188_attach_table_from_path, 01015_attach_part, 03167_attach_as_replicated_errors, 04239_detach_table_on_temporary_table_103475, 00180_attach_materialized_view, 01107_atomic_db_detach_attach) all pass.
Pre-PR validation gate (TASK.md Phase 4 Step 9)(a) Deterministic repro? Yes. (b) Root cause explained? Yes. (c) Fix matches root cause? Yes. The guard now enumerates the top-level fields of (d) Test intent preserved? Yes. Cases 1-7 of (e) Both directions demonstrated? Yes. Verified on debug build: pre-patch the new cases run without error; post-patch they all throw (f) Fix is general? Yes. Audited every parse-settable field on Session: cron:clickhouse-ci-task-worker:20260519-173000 |
Algunenano
left a comment
There was a problem hiding this comment.
@groeneai Some minor issues
Per @Algunenano on PR ClickHouse#105068: 1. The new outer `if` was identical to the existing stub-ATTACH block below it (same `create.attach`/`columns_list`/`storage->engine` condition). Moved the `has_dropped_clauses` check inside the existing block instead of having two `if` statements with the same predicate. Comment shortened. 2. Added `create.uuid != UUIDHelpers::Nil` to the list of fields the short-ATTACH path silently drops. `ATTACH TABLE t UUID '...';` without other clauses would have its user-supplied UUID overwritten by the stored UUID; now rejected with `BAD_ARGUMENTS`. Regression test extended with case 11 covering the UUID case; the existing MV cases are renumbered 12-14.
|
@Algunenano addressed both minor issues in f72ea11:
Verification:
Session: |
|
Pre-PR validation gate for f72ea11: (a) Deterministic repro? Yes. (b) Root cause explained? The short-ATTACH path at line 1571 reads stored metadata via (c) Fix matches root cause? Yes. Added (d) Test intent preserved? / New tests added? Yes. New regression case 11 ( (e) Demonstrated in both directions? Yes. Without the (f) Fix is general, not a narrow patch? Same bug class as the rest of the guard (silent-drop in short ATTACH). The fix covers the full UUID surface in Session: |
|
@groeneai More corner cases: |
Two more silent-drop corner cases on top of ClickHouse#105068, both raised by @Algunenano on the broader-guard commit: 1. `ATTACH TABLE t FROM '/path';` short-attach path drops the user FROM clause when `create = create_query;` replaces the parsed AST with stored metadata. The guard now rejects it via the existing `create.has_attach_from_path` flag. The legitimate long form `ATTACH TABLE t (cols) FROM '/path' ENGINE = ...;` has a columns list and so is not affected. 2. `ATTACH TABLE t UUID '00000000-0000-0000-0000-000000000000';` was silently dropped because `ParserCompoundIdentifier` stores UUID by value and the previous `create.uuid != UUIDHelpers::Nil` check treated explicit `Nil` as "no clause". Fix: track parser-level clause presence on `ASTTableIdentifier::has_uuid` and propagate into a new `ASTCreateQuery::has_uuid_clause` field. The existing `has_uuid` field keeps its value-based semantic for callers that gate on a non-`Nil` UUID (DatabaseReplicated macro expansion, `TableZnodeInfo::resolve`, etc.). Regression test 04247 extended with two cases (12 explicit Nil UUID, 13 `FROM '/path'`); MV cases renumbered 14-16. Verified 30/30 passes locally, adjacent ATTACH tests still pass.
|
@Algunenano Pushed Corner case 1:
|
Pre-PR validation gate for
|
|
@groeneai Please check the new AI review comments. This PR is going to take 100 commits at this point 😄 |
ParserCreateTableQuery parses TO INNER UUID into a local variable before the short-ATTACH early return, but the short-ATTACH branch does not persist it into the query AST. Only the non-short branch did, via view_targets->setInnerUUID. So an ATTACH TABLE t TO INNER UUID '...' silently dropped the user-supplied clause via create = create_query (short-ATTACH overwrites with stored metadata). Add has_inner_uuid_clause flag to ASTCreateQuery (mirroring has_uuid_clause), set it in both parser branches when to_inner_uuid is parsed, and check it in the narrower guard in InterpreterCreateQuery. Test cases 14, 15 added (non-Nil and Nil values) to cover the short-ATTACH shape. The non-short branch is already covered by the existing create.targets != nullptr check in the guard.
|
Addressed the third corner case from the AI review at #105068 (comment) ( Root cause
FixFollowing the same pattern used for
The non-short branch is already covered by the existing Test extension
Verification
Separate finding (not in this PR)While exercising |
Pre-PR validation gate (for commit
|
`ParserCreateDictionaryQuery::parseImpl` previously copied `dict_id->uuid` to `query->uuid` but did not propagate `dict_id->has_uuid` to `query->has_uuid_clause`. Since the narrower ATTACH guard in `InterpreterCreateQuery::createTable` switched from the value-based `create.uuid != UUIDHelpers::Nil` check to `create.has_uuid_clause` (in 1e7c952), the dictionary path bypassed the guard. `ATTACH DICTIONARY d UUID '...'` (with any value) silently overwrote the user-supplied UUID via `create = create_query`. `ParserCreateViewQuery` and `ParserCreateWindowViewQuery` had the same propagation gap. The short ATTACH UUID-only shape doesn't currently parse for views, so the propagation there is defensive consistency rather than a current exploit, matching the bot's "and other table_id-based parser branches" review note. Regression test cases 16-17 in `04247_attach_table_storage_clauses_without_engine_error.sql` cover both non-`Nil` and explicit `Nil` UUID on `ATTACH DICTIONARY`. Addresses inline review comment on PR ClickHouse#105068.
Pre-PR validation gate (for commit
|
LLVM Coverage Report
Changed lines: 96.94% (95/98) · Uncovered code |
94976df
…1-narrower-attach-table-storage-guard Reject ATTACH TABLE with non-engine storage clauses (narrower guard, re-land of ClickHouse#104800)
Re-land of #104800 with a narrower guard that does not break legitimate session-settings
ATTACH.PR #104800 was merged then reverted in #105032 because it rejected
ATTACH TABLE t SETTINGS log_comment = 'foo';— a legitimate pattern internal CI relies on (per @Algunenano in #104791). This re-land fixes the same silent-drop bug from #104791 but only rejectsATTACHqueries that actually carry non-engine storage clauses that would be silently dropped.Background
ParserCreateQuery.cppallowsSETTINGS(andORDER BY,PARTITION BY, etc.) withoutENGINEfor tables (#73120) so thatCREATE TABLE t (...) SETTINGS ...works underdefault_table_engine. ForATTACHthe same syntax used to be parsed without error and then silently dropped: the short-ATTACHpath atInterpreterCreateQuery.cpp:1571reads the stored metadata and overwritescreate.storage/create.columns_list, discarding whatever the user typed.Why the broad guard from #104800 broke CI
InterpreterSetQuery::applySettingsFromQueryruns inexecuteQueryImplbeforeInterpreterCreateQuery::createTable. ForATTACH TABLE t SETTINGS log_comment = 'foo';it does what it does forCREATE: it walkscreate.storage->settings, splits session settings (anything present in the per-query settings registry but not in the storage's builtin-setting list) from engine settings, applies the session settings to the context, and resetsstorage->settingstonullptrif nothing engine-specific is left. The user-visible result is thatlog_commenttakes effect and the table is re-attached using stored metadata.The reverted guard tripped on this case because it only checked that
create.storageexisted and had noengine. By the time the guard ran, the storage object's only meaningful field had already been hoisted out byapplySettingsFromQuery, so rejecting was wrong.The narrower guard
Check the non-engine storage fields directly instead of just looking at the storage object. The guard now fires only when at least one of
partition_by,primary_key,order_by,sample_by,ttl_table,unique_key, orsettingsis still populated at the pointcreateTableruns — i.e. the user supplied a storage clause that survived the session-settings hoisting and would otherwise be silently dropped.ATTACH TABLE t;ATTACH TABLE t SETTINGS log_comment = 'foo';applySettingsFromQueryhoistslog_commentto context and clearsstorage->settingsATTACH TABLE t SETTINGS index_granularity = 100;BAD_ARGUMENTSindex_granularityis aMergeTreebuiltin → stays instorage->settingsATTACH TABLE t SETTINGS max_part_loading_threads = 16;BAD_ARGUMENTSstorage->settingsATTACH TABLE t SETTINGS log_comment = 'foo', index_granularity = 100;BAD_ARGUMENTSlog_commentis hoisted,index_granularityremains instorage->settingsATTACH TABLE t ORDER BY id;/... PARTITION BY id;BAD_ARGUMENTSstorage->order_by/storage->partition_bysetThe guard still fires before
database->shouldReplicateQuery(...)andexecuteQueryOnCluster(...), so distributed /ReplicatedATTACHis rejected at the initiator instead of silently dropping on each replica.Tests
04247_attach_table_storage_clauses_without_engine_errorcovers all six rows of the table above.Reverted PR
ATTACH TABLEwith storage clauses but noENGINE#104800 (merged, then reverted via Revert "RejectATTACH TABLEwith storage clauses but noENGINE" #105032)ATTACH TABLE ... SETTINGSsilently ignores settings when ENGINE not specified #104791Closes #104791.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ATTACH TABLE name <clauses>;queries that supply storage clauses (ORDER BY,PARTITION BY,PRIMARY KEY,SAMPLE BY,TTL,UNIQUE KEY, or engineSETTINGS) without anENGINEnow throwBAD_ARGUMENTSinstead of silently re-attaching the table with its stored definition and discarding the user-supplied clauses. Query-level sessionSETTINGS(such aslog_comment) are still applied. UseATTACH TABLE t;to re-attach with stored metadata, orALTER TABLE t MODIFY SETTING ...afterATTACHto change settings.Version info
26.6.1.88