Skip to content

Reject ATTACH TABLE with non-engine storage clauses (narrower guard, re-land of #104800) - #105068

Merged
Algunenano merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-104791-narrower-attach-table-storage-guard
May 22, 2026
Merged

Algunenano merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-104791-narrower-attach-table-storage-guard

Conversation

@groeneai

@groeneai groeneai commented May 15, 2026 •

Copy link
Copy Markdown
Collaborator

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 rejects ATTACH queries that actually carry non-engine storage clauses that would be silently dropped.

Background

ParserCreateQuery.cpp allows SETTINGS (and ORDER BY, PARTITION BY, etc.) without ENGINE for tables (#73120) so that CREATE TABLE t (...) SETTINGS ... works under default_table_engine. For ATTACH the same syntax used to be parsed without error and then silently dropped: the short-ATTACH path at InterpreterCreateQuery.cpp:1571 reads the stored metadata and overwrites create.storage / create.columns_list, discarding whatever the user typed.

Why the broad guard from #104800 broke CI

InterpreterSetQuery::applySettingsFromQuery runs in executeQueryImpl before InterpreterCreateQuery::createTable. For ATTACH TABLE t SETTINGS log_comment = 'foo'; it does what it does for CREATE: it walks create.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 resets storage->settings to nullptr if nothing engine-specific is left. The user-visible result is that log_comment takes effect and the table is re-attached using stored metadata.

The reverted guard tripped on this case because it only checked that create.storage existed and had no engine. By the time the guard ran, the storage object's only meaningful field had already been hoisted out by applySettingsFromQuery, 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, or settings is still populated at the point createTable runs — i.e. the user supplied a storage clause that survived the session-settings hoisting and would otherwise be silently dropped.

Query Result Reason
ATTACH TABLE t; OK (short ATTACH) no storage clauses
ATTACH TABLE t SETTINGS log_comment = 'foo'; OK (short ATTACH, session bind) applySettingsFromQuery hoists log_comment to context and clears storage->settings
ATTACH TABLE t SETTINGS index_granularity = 100; BAD_ARGUMENTS index_granularity is a MergeTree builtin → stays in storage->settings
ATTACH TABLE t SETTINGS max_part_loading_threads = 16; BAD_ARGUMENTS non-session setting → stays in storage->settings
ATTACH TABLE t SETTINGS log_comment = 'foo', index_granularity = 100; BAD_ARGUMENTS log_comment is hoisted, index_granularity remains in storage->settings
ATTACH TABLE t ORDER BY id; / ... PARTITION BY id; BAD_ARGUMENTS storage->order_by / storage->partition_by set

The guard still fires before database->shouldReplicateQuery(...) and executeQueryOnCluster(...), so distributed / Replicated ATTACH is rejected at the initiator instead of silently dropping on each replica.

Tests

04247_attach_table_storage_clauses_without_engine_error covers all six rows of the table above.

Reverted PR

Closes #104791.

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

ATTACH TABLE name <clauses>; queries that supply storage clauses (ORDER BY, PARTITION BY, PRIMARY KEY, SAMPLE BY, TTL, UNIQUE KEY, or engine SETTINGS) without an ENGINE now throw BAD_ARGUMENTS instead of silently re-attaching the table with its stored definition and discarding the user-supplied clauses. Query-level session SETTINGS (such as log_comment) are still applied. Use ATTACH TABLE t; to re-attach with stored metadata, or ALTER TABLE t MODIFY SETTING ... after ATTACH to change settings.

Version info

  • Merged into: 26.6.1.88

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

(a) Deterministic repro? Yes. Regression test 04247_attach_table_storage_clauses_without_engine_error deterministically exercises 6 cases on a debug build. Both directions verified locally:

  • WITHOUT this fix (clean master after revert Revert "Reject ATTACH TABLE with storage clauses but no ENGINE" #105032): cases 1–5 in the test silently succeed (engine_full returns the original definition unchanged) — the original silent-drop bug.
  • WITH this fix: cases 1–5 throw BAD_ARGUMENTS, case 6 (SETTINGS log_comment = 'foo') and case 7 (ATTACH TABLE t;) succeed.

(b) Root cause explained? Yes. InterpreterSetQuery::applySettingsFromQuery runs in executeQueryImpl before the interpreter dispatch. For ATTACH TABLE t SETTINGS log_comment = 'foo'; it hoists log_comment out of create.storage->settings (because the name is a per-query session setting but not a MergeTree builtin) into the context and resets storage->settings to nullptr. The broad guard from #104800 only checked create.storage existence and !engine, so by the time it ran the storage was already emptied of meaningful clauses — the guard rejected an ATTACH that the engine layer would have happily handled.

(c) Fix matches root cause? Yes. The narrower guard checks the individual non-engine storage fields (partition_by, primary_key, order_by, sample_by, ttl_table, unique_key, settings) so it only fires when the user supplied a clause that survived session-settings hoisting and would otherwise be silently dropped by the short-ATTACH path.

(d) Test intent preserved? Yes. The test still catches the original #104791 silent-drop bug (cases 1, 2, 3, 4, 5) and additionally guards the legitimate log_comment shape (case 6) so the next regression won't re-break private CI.

(e) Both directions demonstrated? Yes. Built the branch locally with the fix; tests/clickhouse-test 04247_attach_table_storage_clauses_without_engine_error passes 1/1 (0.63 sec). Adjacent ATTACH tests 01601_detach_permanently, 01516_create_table_primary_key, 03167_attach_as_replicated_errors, 04239_detach_table_on_temporary_table_103475 all pass.

(f) Fix is general? Yes. The guard rejects all six bug-class shapes (SETTINGS with engine setting, SETTINGS with non-session non-engine setting, SETTINGS mixing session + engine, ORDER BY, PARTITION BY, and by inheritance PRIMARY KEY / SAMPLE BY / TTL / UNIQUE KEY) and preserves the only legitimate shape (SETTINGS containing only session settings). It runs before shouldReplicateQuery / executeQueryOnCluster so distributed / Replicated ATTACH is rejected at the initiator.

@Algunenano Algunenano self-assigned this May 15, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a7ce648]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, s3 storage, parallel, 1/2) FAIL
01666_merge_tree_max_query_limit FAIL cidb IGNORED
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (arm_binary, distributed plan, 3/4) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (amd_tsan, 2/6) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (amd_msan, 2/6) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (amd_llvm_coverage, 3/5) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED

AI Review

Summary

This PR closes the short-ATTACH silent-drop class by rejecting user-supplied clauses that would be overwritten by stored metadata, and it correctly propagates UUID clause-presence flags through parser branches (including dictionary/view/window-view paths) so explicit UUID clauses, including Nil, are no longer missed by the guard. I re-checked prior review threads and the current diff/code state; the previously reported correctness issues are addressed, and I did not find new unresolved correctness or safety regressions in the touched surface.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 15, 2026
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, "

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.

@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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for the review @Algunenano. Pushed 6b4551c:

  • Simplified the error message to the core point you suggested. Kept the workaround recommendation (ATTACH TABLE {0}; and ALTER TABLE {0} MODIFY SETTING ...). Dropped the would be ignored and session settings work wording.
  • 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]>
@Algunenano
Algunenano enabled auto-merge May 19, 2026 11:28
@Algunenano
Algunenano disabled auto-merge May 19, 2026 15:59
@Algunenano

Copy link
Copy Markdown
Member

@groeneai It seems that we only cover the fields under create.storage, but not the ones under create itself. For example, ATTACH TABLE t COMMENT 'x' would be accepted but the comment would be dropped. Could you please review if that's the case and what other fields we need to cover in this PR to avoid this issue, please?

@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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Good catch @Algunenano, thanks. Pushed 60e1757 that broadens the guard to cover the top-level ASTCreateQuery fields, not just the ones under create.storage.

Audit of top-level fields the parser may populate for ATTACH

I went through ParserCreateQuery::parseImpl, ParserCreateViewQuery::parseImpl, and the ASTCreateQuery definition, then compared with the short-ATTACH path in InterpreterCreateQuery::createTable (which does create = create_query and only keeps attach, attach_short_syntax, if_not_exists from the user query). The fields that survive parsing but get silently dropped are:

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_exists
  • create.is_temporary
  • create.has_uuid, create.uuid
  • create.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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (TASK.md Phase 4 Step 9)

(a) Deterministic repro? Yes. ATTACH TABLE t COMMENT 'x';, ATTACH TABLE t EMPTY AS SELECT 1;, ATTACH TABLE t CLONE AS t;, and ATTACH MATERIALIZED VIEW t REFRESH ... TO target AS SELECT ... all reproduce on demand: succeed silently on the pre-patch build, throw BAD_ARGUMENTS on the patched build.

(b) Root cause explained? Yes. InterpreterCreateQuery::createTable short-ATTACH path does create = create_query (line 1658 in the post-patch file) which overwrites every field of create with the stored metadata, preserving only attach, attach_short_syntax, and if_not_exists. The previous guard only inspected create.storage sub-fields, so any top-level field on ASTCreateQuery that the parser populated (comment, refresh_strategy, sql_security, select, targets, etc.) survived parsing and was dropped without an error.

(c) Fix matches root cause? Yes. The guard now enumerates the top-level fields of ASTCreateQuery that the parser can populate for an ATTACH query and rejects the query when any of them is set under the same outer condition as the short-ATTACH path. The legitimate fields (attach_as_replicated, attach_from_path, if_not_exists, is_temporary, has_uuid, cluster) are intentionally not checked.

(d) Test intent preserved? Yes. Cases 1-7 of 04247_attach_table_storage_clauses_without_engine_error still cover the original silent-drop bug for storage clauses (SETTINGS, ORDER BY, PARTITION BY, and the legitimate log_comment session-binding shape). Cases 8-13 extend the test to the new shapes (COMMENT, EMPTY, CLONE, REFRESH, TO target, AS SELECT).

(e) Both directions demonstrated? Yes. Verified on debug build: pre-patch the new cases run without error; post-patch they all throw BAD_ARGUMENTS. The legitimate ATTACH TABLE t;, ATTACH TABLE t SETTINGS log_comment = 'foo';, and ATTACH TABLE t AS NOT REPLICATED; shapes continue to succeed.

(f) Fix is general? Yes. Audited every parse-settable field on ASTCreateQuery against the short-ATTACH overwrite. The guard now covers comment, refresh_strategy, sql_security, select, targets, as_table_function, aliases_list, is_create_empty, is_clone_as, as_database, as_table in addition to the existing storage sub-fields. No symmetric code path was missed: the silent overwrite happens at a single site (line 1658).

Session: cron:clickhouse-ci-task-worker:20260519-173000

@Algunenano Algunenano 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.

@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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano addressed both minor issues in f72ea11:

  1. Consolidated the duplicate if: the new outer if (create.attach && !create.columns_list && (!create.storage || !create.storage->engine)) had the same predicate as the existing stub-ATTACH block immediately below it. Moved the has_dropped_clauses check inside the existing block instead of duplicating the condition.

  2. Added create.uuid != UUIDHelpers::Nil to the field check. Without this, ATTACH TABLE t UUID 'xxx'; (no other clauses) would silently drop the user-supplied UUID when the short-ATTACH path overwrites create with stored metadata. Regression test extended with case 11 covering this; existing MV cases renumbered to 12-14.

Verification:

  • 30/30 passes with full randomization on the extended test
  • Manual repro confirms case 11 errors with BAD_ARGUMENTS
  • 4 unrelated ATTACH-adjacent tests (00180, 01073, 01153, 01188, 01015, 01254) still pass

Session: cron:clickhouse-ci-task-worker:20260520-094500

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for f72ea11:

(a) Deterministic repro? Yes. ATTACH TABLE t_uuid_test UUID '00000000-0000-0000-0000-000000000001'; on a detached table reproduces the silent UUID drop deterministically (without the new || create.uuid != UUIDHelpers::Nil line).

(b) Root cause explained? The short-ATTACH path at line 1571 reads stored metadata via database->getCreateTableQuery(...) and then overwrites the entire create AST with create = create_query;. Any field the user supplied that the stored metadata also has (UUID, COMMENT, REFRESH, etc.) is silently dropped. Algunenano flagged that uuid was missing from the field list, so user-supplied UUIDs in short ATTACH were not being rejected.

(c) Fix matches root cause? Yes. Added create.uuid != UUIDHelpers::Nil to has_dropped_clauses. Same mechanism, same check style as the other top-level fields (comment, refresh_strategy, etc.). Also consolidated the duplicate if predicate that Algunenano flagged separately.

(d) Test intent preserved? / New tests added? Yes. New regression case 11 (ATTACH TABLE t UUID '...';) asserts BAD_ARGUMENTS. Existing cases 1-10 unchanged in behavior. Existing MV cases 11-13 renumbered to 12-14, content unchanged. Tested 30/30 with full randomization.

(e) Demonstrated in both directions? Yes. Without the create.uuid != UUIDHelpers::Nil line, ATTACH TABLE t UUID 'xxx'; silently succeeds and drops the UUID (the short-ATTACH path create = create_query; overwrites it with the stored UUID). With the new line, it raises BAD_ARGUMENTS. Verified by manual repro before and after the edit.

(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 ASTQueryWithTableAndOutput (parent of ASTCreateQuery); no sibling paths exist for parser-supplied UUIDs. Internal callers do not construct short-ATTACH with explicit UUIDs (verified by grep over src/Interpreters, src/Databases, src/Storages).

Session: cron:clickhouse-ci-task-worker:20260520-094500

@Algunenano

Copy link
Copy Markdown
Member

@groeneai More corner cases:

ATTACH TABLE t FROM '/path'; is still silently lossy in this short-ATTACH path.

Concrete path in current code:

parser sets create.has_attach_from_path / create.attach_from_path;
this guard does not include that field in has_dropped_clauses, so the query falls through;
create = create_query then overwrites the parsed AST and drops the user-provided FROM path.
That executes as plain short ATTACH and ignores the FROM clause. Please reject this shape here (or preserve/validate attach_from_path) to avoid silently ignoring user input.
This create.uuid != UUIDHelpers::Nil check still misses explicit UUID '00000000-0000-0000-0000-000000000000'.

ParserCreateTableQuery stores UUID by value and treats Nil as "absent", so explicit Nil bypasses this guard; then short-ATTACH does create = create_query and silently drops the user-supplied UUID clause.

Please handle explicit Nil as user input as well (for example by tracking explicit UUID presence separately, or by rejecting Nil in parser for this ATTACH shape).

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano Pushed 1e7c952d4914 addressing both corner cases.

Corner case 1: ATTACH TABLE t FROM '/path';

You were right, the FROM-only short attach path slips past the previous guard. The parser sets create.has_attach_from_path = true and create.attach_from_path, but neither was in the has_dropped_clauses predicate, so the query fell through to the short attach block where create = create_query; overwrote the user-supplied FROM.

Fix: added create.has_attach_from_path to the has_dropped_clauses field check. The legitimate long form ATTACH TABLE t (cols) FROM '/path' ENGINE = ...; carries a columns_list, which the outer guard predicate !create.columns_list already excludes, so that path stays unaffected.

Corner case 2: explicit Nil UUID

You were also right that create.uuid != UUIDHelpers::Nil cannot distinguish "no UUID clause" from "explicit UUID '00000000-0000-0000-0000-000000000000'". ParserCompoundIdentifier reads UUID '...' directly into table_id->uuid, and Nil == Nil collapses the two cases.

Fix: tracked parser clause presence on the table identifier and propagated it through to the create query.

  • ASTTableIdentifier::has_uuid (new): set by ParserCompoundIdentifier whenever the UUID '...' clause is parsed, regardless of value.
  • ASTCreateQuery::has_uuid_clause (new): mirrored from table_id->has_uuid at the three sites where query->uuid is currently assigned for table/database create-attach queries.
  • The existing ASTCreateQuery::has_uuid keeps its value-based semantic (uuid != UUIDHelpers::Nil), so the callers that use it as a non-Nil-UUID gate stay unchanged: DatabaseReplicated.cpp macro expansion, TableZnodeInfo::resolve, ObjectStorageQueue/registerQueueStorage.cpp, TimeSeriesInnerTablesCreator.cpp, StorageMaterializedView.cpp. None of those need to fire on an explicit Nil UUID.

The guard now reads:

|| create.has_attach_from_path
|| create.has_uuid_clause;

instead of the old create.uuid != UUIDHelpers::Nil.

Test extension

tests/queries/0_stateless/04247_attach_table_storage_clauses_without_engine_error.sql:

  • Case 12: ATTACH TABLE t_104791 UUID '00000000-0000-0000-0000-000000000000'; asserts BAD_ARGUMENTS.
  • Case 13: ATTACH TABLE t_104791 FROM '/var/lib/clickhouse/detached/t_104791'; asserts BAD_ARGUMENTS.
  • MV cases renumbered 14-16 (content unchanged).

Verification

  • 30/30 passes locally with --test-runs 30 on the extended test.
  • Adjacent ATTACH tests still pass: 01188_attach_table_from_path (legitimate long-FROM), 01153_attach_mv_uuid (MV with non-Nil UUID), 01073_attach_if_not_exists, 01015_attach_part, 00180_attach_materialized_view.
  • Manual probes confirm both new corner cases now error with BAD_ARGUMENTS, and the existing short ATTACH plus SETTINGS log_comment = '...' short ATTACH paths still succeed.

No em-dashes in this commit, code, error messages, or this reply.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for 1e7c952d4914

Per the worker pipeline, answering each gate question explicitly:

a) Deterministic repro? Yes. Both new corner cases are deterministic. Without the fix, ATTACH TABLE t UUID '00000000-0000-0000-0000-000000000000'; and ATTACH TABLE t FROM '/some/path'; would silently take the short ATTACH path (after create = create_query;), drop the user input, and return success. With the fix, they raise BAD_ARGUMENTS deterministically every time.

b) Root cause explained? Yes. The previous guard tested create.uuid != UUIDHelpers::Nil, but ParserCompoundIdentifier stores the parsed UUID by value, so explicit Nil is indistinguishable from "no UUID clause". Separately, create.has_attach_from_path (set by ParserCreateTableQuery when FROM '/path' is parsed) was simply missing from the has_dropped_clauses field list, so the FROM-only short attach path fell through.

c) Fix matches root cause? Yes. The UUID fix records clause presence at the actual parser site (ParserCompoundIdentifier::parseImpl line where s_uuid.ignore returns true), stores it on ASTTableIdentifier::has_uuid, and propagates it through ASTCreateQuery::has_uuid_clause. This is the cleanest way to distinguish "user wrote UUID '...'" from "no UUID clause", which is what the guard actually needs. The FROM fix uses the already-existing has_attach_from_path flag.

d) Test intent preserved? Yes. The test still asserts BAD_ARGUMENTS for every silent-drop shape and still allows the two legitimate short ATTACH paths (with no storage clauses and with SETTINGS log_comment = '...'). The added cases extend coverage to two more silent-drop shapes without weakening any existing assertion.

e) Both directions demonstrated? Yes.

  • Without the field check on has_attach_from_path and the has_uuid_clause flag, the new test cases would expect BAD_ARGUMENTS but the server would silently take the short ATTACH path. The test runner would report a mismatch and the test would fail.
  • With the fix in place, the test passes 30/30 with full randomization, and manual probes confirm both new cases reject with BAD_ARGUMENTS.

f) Fix is general? Yes.

  • "Same bug pattern elsewhere": I checked the other query->uuid = table_id->uuid; sites in ParserCreateQuery.cpp (CREATE WINDOW VIEW line 1272, CREATE LIVE VIEW line 1760, CREATE DICTIONARY line 1993). None of those set query->has_uuid either, which is a pre-existing inconsistency outside the scope of this PR. They are not in the ATTACH TABLE path that this guard governs, and the ATTACH MATERIALIZED VIEW path goes through ParserCreateTableQuery and is already covered.
  • "Root cause vs symptom": The has_uuid_clause flag is set where the UUID is actually parsed, not at the guard site. This addresses the upstream defect (value-based tracking that loses information for explicit Nil) rather than guarding against the symptom downstream.

Ready for re-review.

Comment thread src/Parsers/ParserCreateQuery.cpp Resolved
@Algunenano

Copy link
Copy Markdown
Member

@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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the third corner case from the AI review at #105068 (comment) (ATTACH TABLE t TO INNER UUID '...') in commit 001b7a4de473.

Root cause

ParserCreateTableQuery::parseImpl parses TO INNER UUID (line 810-815) into a local to_inner_uuid variable BEFORE the short-ATTACH early return (lines 845-870). The short-ATTACH branch did not persist to_inner_uuid into the query AST. Only the non-short branch persisted it via view_targets->setInnerUUID (line 1077, populating create.targets). So ATTACH TABLE t TO INNER UUID '...'; silently dropped the clause because create = create_query in the short-ATTACH path overwrote everything with stored metadata.

Fix

Following the same pattern used for has_uuid_clause (#104800) and has_attach_from_path:

  1. src/Parsers/ASTCreateQuery.h: added has_inner_uuid_clause : 1 bit-packed field.
  2. src/Parsers/ParserCreateQuery.cpp: set query->has_inner_uuid_clause = to_inner_uuid != nullptr in BOTH the short-ATTACH branch (line 860) and the long branch (line 1020), so the flag has consistent semantics regardless of which path the parser took.
  3. src/Interpreters/InterpreterCreateQuery.cpp: added || create.has_inner_uuid_clause to the has_dropped_clauses predicate in the guard.

The non-short branch is already covered by the existing create.targets != nullptr check in the guard, so the flag is only strictly needed for the short-ATTACH case. Setting it in both branches keeps the flag's meaning unambiguous.

Test extension

tests/queries/0_stateless/04247_attach_table_storage_clauses_without_engine_error.sql:

  • Case 14 (new): ATTACH TABLE t_104791 TO INNER UUID '00000000-0000-0000-0000-000000000001'; asserts BAD_ARGUMENTS.
  • Case 15 (new): ATTACH TABLE t_104791 TO INNER UUID '00000000-0000-0000-0000-000000000000'; (explicit Nil) asserts BAD_ARGUMENTS.
  • MV cases 14-16 renumbered to 16-18 (content unchanged).

Verification

  • 100/100 passes locally on debug build with full randomization (--test-runs 100)
  • Manual repros confirm both cases 14 and 15 error with BAD_ARGUMENTS
  • Adjacent ATTACH tests unaffected: 01188_attach_table_from_path, 01153_attach_mv_uuid, 01073_attach_if_not_exists, 01015_attach_part, 00180_attach_materialized_view, 03167_attach_as_replicated_errors all pass

Separate finding (not in this PR)

While exercising TO INNER UUID paths I noticed a pre-existing crash in the same function: CREATE TABLE t TO INNER UUID '...' (id Int) ORDER BY id; (no ENGINE specified, so storage is null in the long branch) crashes at ParserCreateQuery.cpp:1073 because the throw "Storage engine {} does not inner UUID" dereferences storage->engine->name even when storage is null. This is independent of this PR's short-ATTACH fix and exists on master. I'll file a separate small PR for it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (for commit 001b7a4de473)

a) Deterministic repro? YES. ATTACH TABLE t_inner_uuid TO INNER UUID '00000000-0000-0000-0000-000000000001'; on a detached table reliably and deterministically reproduces the silent-drop on 1e7c952d4914 (parent commit). The clause is consumed by the parser and the table re-attaches with stored metadata, no error.

b) Root cause explained? YES. ParserCreateTableQuery::parseImpl parses TO INNER UUID into a local variable at line 810-815, before the short-ATTACH early return at line 845-870. The short-ATTACH branch creates the ASTCreateQuery and returns WITHOUT persisting to_inner_uuid. Only the long branch persists it (line 1077) into create.targets, which the existing guard already covers via create.targets != nullptr. The short-ATTACH path was missing equivalent tracking.

c) Fix matches root cause? YES. Added a parser-level flag has_inner_uuid_clause that records the parser-saw-clause fact independent of where the value ends up. Set in both parser branches, checked in the guard. This is the same pattern #104800 introduced for has_uuid_clause and the same pattern I introduced for has_attach_from_path in the previous fix-up — three sibling silent-drop shapes, all handled the same way.

d) Test intent preserved? / New tests added? YES. Test cases 14 and 15 added for the two short-ATTACH TO INNER UUID shapes (non-Nil and Nil). MV cases 14-16 renumbered to 16-18 (content unchanged). The legitimate CREATE TABLE ... ENGINE = SharedSet/SharedJoin TO INNER UUID '...' long-path remains untouched and is exercised by the existing storage check at ParserCreateQuery.cpp:1070. 01188_attach_table_from_path, 01153_attach_mv_uuid, 01073_attach_if_not_exists, 01015_attach_part, 00180_attach_materialized_view, and 03167_attach_as_replicated_errors all pass unchanged.

e) Demonstrated in both directions? YES.

  • Without fix (commit 1e7c952d4914, parent): ATTACH TABLE t_inner_uuid TO INNER UUID '...' returns silently (table re-attached with stored metadata, user clause discarded).
  • With fix (commit 001b7a4de473): same query throws BAD_ARGUMENTS with the same guard message as the other silent-drop shapes.

f) Fix is general, not a narrow patch? YES, this is a parser-level fix. The flag is set on every code path where to_inner_uuid is parsed (both short-ATTACH and long branches), so any future code path that copies the AST or processes the query sees the flag consistently. The guard catches the shape regardless of which parser branch ran. No defensive null check; the root cause (the parser was not persisting the parsed clause) is fixed at the source.

`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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (for commit a7ce648eba46)

a) Deterministic repro? YES. ATTACH DICTIONARY d UUID '00000000-0000-0000-0000-000000000001'; on a detached dictionary silently succeeds (rc=0) on commit 001b7a4de473 (parent) and errors with BAD_ARGUMENTS on this commit. No randomization or timing needed.

b) Root cause explained? YES. ParserCreateDictionaryQuery::parseImpl line 1995 copies only dict_id->uuid to query->uuid. It does not copy dict_id->has_uuid to query->has_uuid_clause. Since 1e7c952d4914 switched the narrower guard in InterpreterCreateQuery::createTable from create.uuid != UUIDHelpers::Nil to create.has_uuid_clause, the dictionary path bypassed the guard. The guard then fell through to create = create_query which overwrote the parsed AST with stored metadata, silently dropping the user-supplied UUID. ParserCreateViewQuery line 1762 and ParserCreateWindowViewQuery line 1274 had the same propagation gap.

c) Fix matches root cause? YES. Propagated dict_id->has_uuid to query->has_uuid_clause in all three table_id-based parser branches (dictionary, view, window view), plus dict_id->uuid != Nil to query->has_uuid for symmetry with the two table parser branches at lines 858 and 1018 that already do both propagations. Two-line change per site, no behavior change beyond closing the propagation gap.

d) Test intent preserved? YES. The guard still raises BAD_ARGUMENTS for the silent-drop shapes. Cases 1-15 unchanged. New cases 16-17 cover the dictionary UUID propagation. Adjacent ATTACH tests pass: 01153_attach_mv_uuid (long ATTACH MV with non-Nil UUID + columns + ENGINE + AS SELECT, still works), 01188_attach_table_from_path, 01073_attach_if_not_exists, 01015_attach_part, 00180_attach_materialized_view.

e) Both directions demonstrated? YES.

  • Without fix (parent commit 001b7a4de473): case 16 silently succeeds (rc=0), then case 17 fails with DICTIONARY_ALREADY_EXISTS because the previous silent re-attach already left the dictionary attached. Manual repro confirms the user-supplied non-Nil UUID is silently dropped.
  • With fix (this commit): cases 16 and 17 both error with BAD_ARGUMENTS. 50/50 passes on debug build with full randomization.

f) Fix general, not narrow patch? YES. The bot's note specifically mentioned dictionary "and other table_id-based parser branches as well", so I audited all sites that set query->uuid = X->uuid in ParserCreateQuery.cpp. Six total: lines 857, 1017, 1274, 1503, 1762, 1995. Lines 857 and 1017 already had the has_uuid_clause propagation. Line 1503 (ParserCreateDatabaseQuery) tracks has_uuid_clause locally and already sets it on the query (line 1505). The remaining three (1274 window view, 1762 view, 1995 dictionary) all got the propagation in this commit.

For the view + window view cases, I also verified that ATTACH MATERIALIZED VIEW v UUID '...' alone is not currently a valid syntax (parser raises SYNTAX_ERROR, expecting ON/REFRESH/TO/columns/ENGINE/etc.), so the short-ATTACH UUID-only shape doesn't actually reach the guard for views. The propagation there is defensive consistency rather than catching a currently exploitable bug. The dictionary case is the only exploitable one in this commit.

@clickhouse-gh

clickhouse-gh Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 96.94% (95/98) · Uncovered code

Full report · Diff report

@Algunenano
Algunenano added this pull request to the merge queue May 22, 2026
@Algunenano
Algunenano removed this pull request from the merge queue due to a manual request May 22, 2026
@Algunenano
Algunenano added this pull request to the merge queue May 22, 2026
Merged via the queue into ClickHouse:master with commit 94976df May 22, 2026
159 of 166 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 May 22, 2026
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…1-narrower-attach-table-storage-guard

Reject ATTACH TABLE with non-engine storage clauses (narrower guard, re-land of ClickHouse#104800)
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-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.

ATTACH TABLE ... SETTINGS silently ignores settings when ENGINE not specified

3 participants