Repository navigation
Reject a repeated constraint name, and arrayJoin in any ADD/MODIFY CONSTRAINT - #121235
PedroTadim merged 6 commits into
Conversation
…idate
A constraint name may be declared more than once. `AlterCommands::validate`
screens a constraint declaration with `checkExpressionsPreserveRowCount` only
when `apply()` will really install it, and to know that it follows the table's
constraint names through the commands of the same `ALTER`. It followed them in a
`NameSet`, which stores a name once, while `apply()` works one declaration at a
time: `DROP CONSTRAINT` erases the first matching declaration and
`MODIFY CONSTRAINT` replaces the first one in place.
So on a table that declares `c` twice,
ALTER TABLE t DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c CHECK arrayJoin(arr) > 0;
left a `c` installed while the set no longer held the name at all: the `MODIFY`
leg was read as a no-op and its declaration went in unscreened. An INSERT into
that table then failed with UNSUPPORTED_METHOD even when every array element
satisfies the constraint, because the constraint is checked row by row and
`arrayJoin` returns one value per element: a block is refused outright whenever
its element count differs from its row count, and only a block where the two
happen to be equal is checked at all. The same emptied set made
ALTER TABLE t DROP CONSTRAINT c, ADD CONSTRAINT IF NOT EXISTS c CHECK arrayJoin(arr) > 0;
throw although `apply()` installs nothing there, discarding the user's DROP as
well.
Keep one entry per stored declaration in a `Names` list, test presence with
`std::find`, and erase one entry on `DROP CONSTRAINT`, so the tracker mirrors
what `apply()` does. `ADD CONSTRAINT` adds an entry only when the name is still
free, because `apply()` stores nothing for a name that is taken: it keeps the
declaration it has when `IF NOT EXISTS` is given, and refuses the command
otherwise. With a set an unconditional insert was correct, since inserting a
name that was already present changed nothing; with a list it would leave a
phantom entry that a later `DROP` would not account for, and a statement whose
`ADD` is refused would report a later leg's `arrayJoin` instead of the duplicate
name it fails on.
Two alternatives were rejected. Simulating the constraint AST list answers the
same question with a duplicate of `apply()`'s body, which then has to be kept in
step with it. Screening the constraints of the resulting metadata after
`apply()` would also screen declarations the statement did not state: metadata
stored by a version without the check deliberately still loads, so an unrelated
`ALTER TABLE t ADD COLUMN x` on such a table would start failing.
The screen and the name tracker are from ClickHouse#117267, and its own test
05071_alter_constraint_array_join_no_op covers this rule, so the new scenarios
are appended there: one per direction of the defect, and three more pinning
which commands take the name for the rest of the statement: a no-op `ADD` does
not, an `ADD` that installs does, and an `ADD` that is refused does not either.
Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the sentence narrating why the tracker is a list rather than a set; the declaration-multiplicity property it justifies stays.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex) over 5 rounds: 17 findings raised, 8 by the
Three further nits were folded into the same amends: a stale scenario count in the commit message; a Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20260920-201200 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260920-141800 |
|
Workflow [PR], commit [0766818] Summary: ✅
AI ReviewSummaryThis PR fixes the local single-node holes around duplicate constraint names and Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 0766818.
Changed lines: Changed C/C++ lines covered: 20/21 (95.24%) · Uncovered code |
CI finish ledger - 06b0822Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Measured on this head: 176 contexts, 153 SUCCESS / 20 SKIPPED / 3 FAILURE. Session id: cron:our-pr-ci-monitor:20260921-050309 |
Brings the branch up to date with origin/master (88dea5e). Master had three commits touching AlterCommands.cpp in that range, so that file was auto-merged; the result is conflict-free and the branch's diff against master is unchanged: the same three files at +54/-7. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
@groeneai for this case |
|
@groeneai for the alter case, simply reject if the alter constraint add or modify has an array join on it |
|
Both of these are implemented. 1. 2. One consequence is yours to rule on. #117267 screened only declarations that would really be installed, so The changelog category is therefore no longer On the review bot's point about the fixture: the new One thing I deliberately left alone: neither this check nor #117267's is skipped on |
|
@groeneai this |
…LTER` that states one `CREATE TABLE t (n UInt8, CONSTRAINT c CHECK n > 0, CONSTRAINT c CHECK n < 10)` was accepted, while `DROP CONSTRAINT` erases and `MODIFY CONSTRAINT` replaces the first declaration of a name, so a second declaration of it was reachable only once the first one had been dropped. `ConstraintsDescription::checkNamesAreUnique` now refuses it, under the same `isFreshTableDefinition` gate as the `arrayJoin` screen next to it: a definition the user states now is screened (an explicit column list, a full-definition `ATTACH`, the `AS src` / `CLONE AS src` copy), a replay of stored metadata is not, so a table stored by an earlier version still attaches and each of its declarations stays enforced. `AlterCommands::validate` screened a constraint expression only when `apply` would really install the declaration, which made the answer depend on whether the name was taken, and a repeated name defeated the `NameSet` that followed it: `DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c CHECK arrayJoin(arr) > 0` stored the row-count-changing `CHECK` that ClickHouse#117267 exists to reject, while the plain `MODIFY CONSTRAINT c CHECK arrayJoin(arr) > 0` was refused. `ADD`/`MODIFY CONSTRAINT` is now screened wherever the expression is stated, so the name tracking goes away entirely and a no-op `ADD CONSTRAINT IF NOT EXISTS <taken name>` or `MODIFY CONSTRAINT IF EXISTS <absent name>` carrying an `arrayJoin` is refused rather than quietly accepted. `05071_alter_constraint_array_join_no_op` is renamed and rewritten: its premise, that the two no-op forms stay no-ops, is the one this reverses. `05234_constraint_repeated_name_legacy_metadata.sh` attaches a hand-written definition carrying the repeated name, the way a table stored before the check looks, and pins what that table keeps doing: it loads, each of its declarations is enforced, each is droppable one at a time, and the `DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c` bypass is refused on it too. Both parts requested by PedroTadim in the review of ClickHouse#121235.
arrayJoin check in ALTERarrayJoin in every ALTER that states one
|
Pushed as 4cae111. Correcting one thing I said above, because I checked it properly afterwards: the It is not free either, which is why I would rather you picked: guarding the |
|
The Both of your statements, measured on a binary built from 4cae111 (build id Code 44 is what The A table whose duplicate names were stored by an older version still attaches, because the uniqueness check runs on a fresh definition and not on a metadata replay. Both of its declarations stay enforced, and the Please retest at 4cae111. |
| if (isFreshTableDefinition(mode, create.attach_short_syntax)) | ||
| { | ||
| properties.constraints.checkExpressionsPreserveRowCount(); | ||
| properties.constraints.checkNamesAreUnique(); |
There was a problem hiding this comment.
This new uniqueness check is only gated by isFreshTableDefinition(), but a full-definition ATTACH on a Replicated database still reaches this branch on secondaries because attach outranks secondary in getLoadingStrictnessLevel(). An older initiator can therefore commit CREATE / full-definition ATTACH metadata that repeats a constraint name, while an upgraded secondary now throws here and retries the queue entry forever.
The nearby CREATE-time validators already handle the same mixed-version problem by also skipping is_ddl_replay / shared-catalog replays. checkNamesAreUnique() needs the same compatibility guard, otherwise this backward-incompatible check is not safe to roll out.
There was a problem hiding this comment.
The mechanism is right: getLoadingStrictnessLevel returns ATTACH before it can return SECONDARY_CREATE (LoadingStrictnessLevel.cpp:23-27), so a full-definition ATTACH on a secondary does satisfy isFreshTableDefinition.
Two facts make this an owner decision rather than an edit here. InterpreterCreateQuery.cpp has no is_ddl_replay at all (git grep is_ddl_replay -- src finds only MergeTreeData, registerStorageMergeTree, StorageFactory), so adopting the guard means introducing the concept in this file. And checkExpressionsPreserveRowCount, on the line above, carries the identical exposure under the identical single gate and was merged that way by #117267: guarding only the new call makes the pair inconsistent, guarding both reverses a merged decision.
Both options are already on the PR with the reviewers, one line each: #121235 (comment)
| constraint_names.erase(command.constraint_name); | ||
| /// just like `ADD CONSTRAINT` does. Screened wherever the expression is stated, whether or not | ||
| /// `apply()` goes on to install it, so that the answer does not depend on the name being taken. | ||
| if ((command.type == AlterCommand::ADD_CONSTRAINT || command.type == AlterCommand::MODIFY_CONSTRAINT) |
There was a problem hiding this comment.
This unconditional screen now runs on replicated/shared-catalog replays too, because InterpreterAlterQuery calls alter_commands->validate() before table->checkAlterIsPossible() can apply its is_ddl_replay / shared-catalog exemptions. Older versions still accept ADD CONSTRAINT IF NOT EXISTS <taken> CHECK arrayJoin(...) and MODIFY CONSTRAINT IF EXISTS <absent> CHECK arrayJoin(...) as no-ops, so a mixed-version rollout will wedge the DDL queue on statements that do not change metadata at all.
We need a replay-compatibility path for these no-op shapes instead of tightening them only on newer secondaries.
There was a problem hiding this comment.
The ordering is right: validate() at InterpreterAlterQuery.cpp:366 runs before checkAlterIsPossible() at :373, so an is_ddl_replay exemption cannot reach this screen.
The delta is narrower than the finding states. Before this PR the screen already ran here unconditionally for any command that would really install a declaration, so a replay of an installing ADD CONSTRAINT ... arrayJoin(...) already threw. What this PR adds is the two no-op shapes, ADD CONSTRAINT IF NOT EXISTS <taken name> and MODIFY CONSTRAINT IF EXISTS <absent name>, which #117267 accepted deliberately. That is the cost of dropping the name tracking, and it is stated in the description.
Where the guard should go, if anywhere, is the same open question as the sibling thread: #121235 (comment)
|
|
`checkNamesAreUnique` threw `ILLEGAL_COLUMN`, the code `ALTER TABLE ... ADD CONSTRAINT` returns for a name the table already has (`AlterCommands.cpp:1069`). Requested in review: `INCORRECT_QUERY`, which is what the sibling screen in the same class, `checkExpressionsPreserveRowCount`, already throws. So both ways a stated constraint definition can be refused now report one code, and 05071 no longer has to name two. The pre-existing `ADD CONSTRAINT` path is untouched and still returns `ILLEGAL_COLUMN`.
arrayJoin in every ALTER that states onearrayJoin in any ADD/MODIFY CONSTRAINT
|
Both done, pushed as f180dbe.
New title: |
|
@groeneai what about projections, indexes, columns defaults, columns materialized values, column aliases? Are those fine with array joins? |
|
I measured all five on this PR's head (debug build of
For the columns the rejection also covers Projections are the one carrier that still takes it, and it lands in the same write-dead state as the constraint hole: CREATE TABLE t (arr Array(UInt8), n UInt8,
PROJECTION p (SELECT arrayJoin(arr) AS x, count() GROUP BY x))
ENGINE = MergeTree ORDER BY n; -- accepted
INSERT INTO t VALUES ([1,2,3], 5);
-- Logical error: 'Projection cannot increase the number of rows in a block. It's a bug'
SELECT count() FROM t; -- 0
That gap is already reported as #117268, with #117269 for the For completeness, the neighbouring carriers reject it too, with two more codes: sorting and primary keys and partition keys give |
…traint-repeated-name-screen
CI finish ledger - f180dbeEvery failure below has an owner: a fixing PR, mine or external. Both reds on this head are
Details, so the numbers are checkable:
Session id: cron:our-pr-ci-monitor:20260921-220150 |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units811 translation units recompiled, 6045 s compile time in total, 811 of them have a recent master baseline. |
|
@alexey-milovidov give the final review. The PR seems good to me |
| # The metadata is written by hand here, which is what a table created before the check looks like. | ||
|
|
||
| # Creation of a database with the Ordinary engine emits a warning. | ||
| CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=fatal |
There was a problem hiding this comment.
@groeneai can't you move the ATTACH statements to the sql test and remove this test file?
There was a problem hiding this comment.
An ATTACH that carries the definition is user input, so it goes through the same screen as CREATE and is rejected; 05071_alter_constraint_array_join_always_rejected.sql already asserts that (ATTACH TABLE ... (k UInt32, CONSTRAINT c CHECK k > 0, CONSTRAINT c CHECK k < 1000) ... -- { serverError INCORRECT_QUERY }). This file needs the opposite: a definition the server never validated, which only a replay of stored metadata gives, and writing that metadata needs a shell. 05099_ttl_array_join_stored_metadata.sh and 05182_legacy_array_join_constraint_not_used_by_optimizer.sh in master build their tables the same way for the same reason.
There is no other route to a table holding the same constraint name twice once this PR is in. Measured on master 26.10.1.1 today: CREATE accepts it (the hole being closed), ALTER TABLE t ADD CONSTRAINT c ... on a taken name gives Code: 44. Cannot add constraint c: constraint with this name already exists. (ILLEGAL_COLUMN) (AlterCommands.cpp:1135), two ADDs of one name in a single ALTER give the same, and ADD CONSTRAINT IF NOT EXISTS is a no-op.
The repeated name is also the only state in which the bypass persists anything. With one declaration of c, every shape the old check skipped installs nothing, and 05071 covers those. With two, DROP CONSTRAINT c removes one declaration but frees the name in the set the old check tracked, so MODIFY CONSTRAINT IF EXISTS c CHECK arrayJoin(arr) > 0 was unscreened and still found the surviving declaration to replace. That is how the arrayJoin constraint got stored and the table stopped accepting inserts, so this file is the regression test for the bug in the title.
If the size is what bothers you, I can cut it to the two arms the fix owns, the table still attaching and the ALTER being refused with nothing stored, and drop the two that only show how a repeated name behaves.
|
@alexey-milovidov , the CI is green |
|
Ok, I am merging to complement #117267 |
Related: #117267
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
CREATE TABLEand full-definitionATTACH TABLEnow refuse aCONSTRAINTname declared more than once, andALTER TABLE ... ADD CONSTRAINT/MODIFY CONSTRAINTnow refuse an expression containingarrayJoineven when the command would install nothing. A table already stored with a repeated constraint name still attaches and keeps enforcing each of its declarations.Description
A constraint name could be declared more than once, while
DROP CONSTRAINTerases andMODIFY CONSTRAINTreplaces only the first declaration of a name. That multiplicity also defeated thearrayJoinscreen of #117267, which followed the table's constraint names in aNameSetand screened a declaration only whenapplywould really install it:was accepted and stored the row-count-changing
CHECKthat screen exists to reject, after whichINSERT INTO t VALUES ([1, 2], 5)failed although the row satisfies it.Two rejections now, both
Code: 80, INCORRECT_QUERY:CREATE, a full-definitionATTACH, and theAS src/CLONE AS srccopy refuse a name declared more than once.ADD CONSTRAINT/MODIFY CONSTRAINTrefuse anarrayJoinwherever the expression is stated, so the name tracking is gone and the answer no longer depends on the name being taken. This reverses Reject aCHECKconstraint containingarrayJoin#117267's acceptance ofADD CONSTRAINT IF NOT EXISTS <taken name>andMODIFY CONSTRAINT IF EXISTS <absent name>carrying anarrayJoinas no-ops; the test that pinned that is rewritten here.Neither rejection applies to a replay of stored metadata, so a table written by an earlier version still attaches, still enforces each of its declarations, and can still have them dropped one at a time (
05234_constraint_repeated_name_legacy_metadata.sh).Both rejections, and the error code, were requested in review.
Workflow [PR]
Sync PR [sync-upstream/pr/121235]
Version info
26.10.1.913-master(included in26.10and later)