Skip to content

UNIQUE KEY: DDL, metadata, and policy gates (1/N) - #104102

Merged
murphy-4o merged 10 commits into
ClickHouse:masterfrom
murphy-4o:unique-key-pr1-ddl
May 11, 2026
Merged

murphy-4o merged 10 commits into
ClickHouse:masterfrom
murphy-4o:unique-key-pr1-ddl

Conversation

@murphy-4o

@murphy-4o murphy-4o commented May 5, 2026 •

Copy link
Copy Markdown
Member

Part of #103486

First slice of a stack that introduces an experimental UNIQUE KEY clause on MergeTree-family tables, gated behind allow_experimental_unique_key. This PR ships only the public DDL surface and metadata-only policy guards. No runtime dedup, no read filtering, no write-path behaviour — those follow in later PRs.

Scope:

  • Parser / AST: new UNIQUE KEY keyword and round-trip.
  • StorageInMemoryMetadata::unique_key + accessors.
  • Storage factory / MergeTree register: experimental gate, bare-identifier-only validation, non-local-disk reject.
  • system.tables.unique_key column.
  • MergeTreeData ALTER/mutation guards: reject ADD PROJECTION, MODIFY ORDER BY, DROP|RENAME|MODIFY of a UK column, and ALTER DELETE|UPDATE|MATERIALIZE COLUMN|CLEAR COLUMN that would bypass UK dedup.
  • MergeTreeData::alterPartition blanket reject of all ALTER ... PARTITION operations on UK tables.
  • StorageMergeTree: source/destination-side reject for ATTACH/REPLACE PARTITION FROM and MOVE PARTITION TO TABLE to cover UK on either side.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry: N/A (incremental slice; user-facing changelog ships with the last PR in the stack once the full feature is reviewable).

Documentation entry for user-facing changes

  • Documentation will land with the user-facing slice.

Description

Version info

  • Merged into: 26.5.1.513

First slice of a stack that introduces an experimental UNIQUE KEY clause on MergeTree-family tables, gated behind allow_experimental_unique_key. This PR ships only the public DDL surface and metadata-only policy guards. No runtime dedup, no read filtering, no write-path behaviour — those follow in later PRs.

Scope:
- Parser / AST: new UNIQUE KEY keyword and round-trip.
- StorageInMemoryMetadata::unique_key + accessors.
- Storage factory / MergeTree register: experimental gate, bare-identifier-only validation, non-local-disk reject.
- system.tables.unique_key column.
- MergeTreeData ALTER/mutation guards: reject ADD PROJECTION, MODIFY ORDER BY, DROP|RENAME|MODIFY of a UK column, and ALTER DELETE|UPDATE|MATERIALIZE COLUMN|CLEAR COLUMN that would bypass UK dedup.
- MergeTreeData::alterPartition: blanket reject of all ALTER ... PARTITION operations on UK tables.
- StorageMergeTree: source/destination-side reject for ATTACH/REPLACE PARTITION FROM and MOVE PARTITION TO TABLE to cover UK on either side.
@clickhouse-gh

clickhouse-gh Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [52e50e6]

Summary: ✅


AI Review

Summary

This PR introduces the experimental UNIQUE KEY DDL surface for non-replicated MergeTree tables, wires metadata/AST/system table exposure, and adds guardrails that block unsupported ALTER/mutation/partition paths. I did not find any remaining correctness or safety issues in the current diff after reconciling prior review threads with the current code.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ✅
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ✅
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label May 5, 2026
Comment thread src/Core/Settings.cpp Resolved
- registerStorageMergeTree: drop the catch-all around storage policy
  resolution. The catch-all was silently swallowing exceptions; if the
  policy is unresolvable here, let the downstream MergeTree constructor
  surface the same error directly. (Style: catch_all rule.)
- MergeTreeData: lambda body opening brace on a new line. (Style: cpp
  rule about `... ) {` at end of line.)
- enableAllExperimentalSettings: register `allow_experimental_unique_key`
  so DatabaseReplicated::recoverLostReplica can recreate UK tables.
Tag 03313_unique_key_mutation_guard and 04046_unique_key_ddl with
no-object-storage and no-s3-storage so they skip under variants like
"distributed plan, s3 storage" where the default disk is cached_s3.
The UK guard correctly rejects every CREATE there (UNIQUE KEY tables
must currently reside on a local-only storage policy), so the tests
cannot run as-is in those configs.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…MODIFY SETTING

Mirror the CREATE-time check from registerStorageMergeTree.cpp into
checkAlterIsPossible so the local-only invariant is preserved across
settings-alter paths. Without this, ALTER ... MODIFY SETTING
storage_policy/disk could swap a UNIQUE KEY table onto a non-local
disk after creation and bypass the policy gate.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The guard added in a3f4c6f was nested under
`if (old_metadata.hasSettingsChanges())`, so for tables created without
a SETTINGS clause the entire block was skipped and ALTER ... MODIFY
SETTING storage_policy|disk could still bypass the gate.

Move the UK guard to right after `commands.apply(new_metadata, ...)` so
it sees the post-alter state and runs unconditionally for any UK table.
Also reject ALTER ... RESET SETTING storage_policy|disk on UK tables —
RESET would fall back to the server default which may be non-local.

The loop validates each storage_policy / disk entry in
new_metadata.settings_changes independently; a single ALTER that sets
both with one non-local and one local cannot get the non-local entry
overwritten before validation.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@murphy-4o
murphy-4o marked this pull request as ready for review May 6, 2026 01:43
…DATE test coverage

`InterpreterAlterQuery::tryRewriteToLightweightUpdate` runs before
`runCommandSegments`, so an `ALTER ... UPDATE` issued under
`alter_update_mode='lightweight'` could rewrite stored row bytes via
`updateLightweight()` without going through `MergeTreeSinkUniqueKeyCommit::run`,
producing duplicate live keys. Reject `hasUniqueKey()` at the top of
`MergeTreeData::supportsLightweightUpdate()` so the lightweight rewrite falls
back to the heavy path (which `checkMutationIsPossible` already rejects), and
under `lightweight_force` it throws directly.

Also extend test coverage: `04046_unique_key_ddl.sql` now asserts
`ALTER ... UPDATE` rejection alongside the existing `ALTER DELETE`, and
`03313_unique_key_mutation_guard.sql` adds `ALTER DELETE` / `ALTER UPDATE` (UK
column and non-UK column) plus both lightweight-update modes — closing the gap
between its docstring and reality.
@hanfei1991 hanfei1991 self-assigned this May 6, 2026

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

I tried create table t (a Int, b Int) Engine = MergeTree() Unique Key(a, a) Order by (b); with duplicated columns, and it's successful. Is it expected?

murphy-4o added 2 commits May 11, 2026 11:26
…ard message

`UNIQUE KEY (a, a)` previously created the table successfully. Add a
post-`getKeyFromAST` `NameSet` check that rejects any repeated column
with `BAD_ARGUMENTS`, plus test case 7d in `04046_unique_key_ddl.sql`.
Reword the existing expression-element guard error message and comments
from "expression-shaped" to "expression-style" per reviewer suggestion.
@murphy-4o

Copy link
Copy Markdown
Member Author

@hanfei1991 thanks for the catch on UNIQUE KEY (a, a) — that was unintentional. Fixed in 28b13d6: added a NameSet-based dedup check right after metadata.unique_key = KeyDescription::getKeyFromAST(...) in registerStorageMergeTree.cpp, which throws BAD_ARGUMENTS with UNIQUE KEY contains duplicate column \`on the first repeat. Locked in by a new test case 7d in04046_unique_key_ddl.sql`:

-- 7d. Duplicate columns in a UNIQUE KEY are rejected.
CREATE TABLE uk_t (a Int, b Int)
ENGINE = MergeTree
UNIQUE KEY (a, a)
ORDER BY (b); -- { serverError BAD_ARGUMENTS }

Verified directly against the rebuilt binary; the merge from master also went through cleanly so the conflict marker on the PR should resolve once CI re-runs.

Comment thread src/Storages/StorageFactory.cpp Resolved
…ns reference

- Switch the engine-side UK gate from a string-suffix check
  (name.ends_with("MergeTree")) to the existing StorageFeatures flag
  pattern. New supports_unique_key field defaults to false; set true on
  the eight non-replicated MergeTree variants and explicitly false on
  the Replicated block. ReplicatedMergeTreeTableMetadata does not yet
  serialize unique_key, so admitting Replicated variants would let
  replicas silently diverge. check_feature now produces the standard
  "Engine X doesn't support UNIQUE KEY clause" message with the list of
  supporting engines. Per bot review thread 3216233176.

- Add test 6a to 04046_unique_key_ddl.sql: CREATE TABLE ... ENGINE =
  ReplicatedMergeTree(...) UNIQUE KEY (id) -> { serverError BAD_ARGUMENTS }.

- Update 04046_unique_key_ddl.reference for the post-ClickHouse#92340 round-trip
  shape: user-written UNIQUE KEY (id) now formats with the parens
  preserved (and the system.tables.unique_key column likewise renders
  (id) instead of bare id). Same precedent master applied for
  PRIMARY KEY (key) in 48a0da4.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.10% +0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 87.99% (293/333) | lost baseline coverage: 9 line(s) · Uncovered code

Full report · Diff report

@murphy-4o
murphy-4o added this pull request to the merge queue May 11, 2026
Merged via the queue into ClickHouse:master with commit a097eff May 11, 2026
325 of 326 checks passed
@murphy-4o
murphy-4o deleted the unique-key-pr1-ddl branch May 11, 2026 11:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants