Skip to content

Reject a repeated constraint name, and arrayJoin in any ADD/MODIFY CONSTRAINT - #121235

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/alter-constraint-repeated-name-screen
Sep 28, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/alter-constraint-repeated-name-screen

Conversation

@groeneai

@groeneai groeneai commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117267

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

CREATE TABLE and full-definition ATTACH TABLE now refuse a CONSTRAINT name declared more than once, and ALTER TABLE ... ADD CONSTRAINT / MODIFY CONSTRAINT now refuse an expression containing arrayJoin even 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 CONSTRAINT erases and MODIFY CONSTRAINT replaces only the first declaration of a name. That multiplicity also defeated the arrayJoin screen of #117267, which followed the table's constraint names in a NameSet and screened a declaration only when apply would really install it:

CREATE TABLE t (arr Array(UInt8), n UInt8, CONSTRAINT c CHECK n > 0, CONSTRAINT c CHECK n < 10)
ENGINE = MergeTree ORDER BY n;

ALTER TABLE t DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c CHECK arrayJoin(arr) > 0;

was accepted and stored the row-count-changing CHECK that screen exists to reject, after which INSERT INTO t VALUES ([1, 2], 5) failed although the row satisfies it.

Two rejections now, both Code: 80, INCORRECT_QUERY:

  • CREATE, a full-definition ATTACH, and the AS src / CLONE AS src copy refuse a name declared more than once.
  • ADD CONSTRAINT / MODIFY CONSTRAINT refuse an arrayJoin wherever the expression is stated, so the name tracking is gone and the answer no longer depends on the name being taken. This reverses Reject a CHECK constraint containing arrayJoin #117267's acceptance of ADD CONSTRAINT IF NOT EXISTS <taken name> and MODIFY CONSTRAINT IF EXISTS <absent name> carrying an arrayJoin as 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

  • Merged into: 26.10.1.913-master (included in 26.10 and later)

groeneai and others added 2 commits September 20, 2026 20:04
…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
gate and 9 by my own cold reviews, 10 distinct after merging the overlap. The fifth round raised none on the
shipped head. The branch is a single amended commit, so the items below are cited as fixed in this PR rather
than against per-round SHAs.

# Sev Finding Verdict Evidence / action
1 ⚠️ The accepted DROP CONSTRAINT c, ADD CONSTRAINT IF NOT EXISTS c CHECK arrayJoin(arr) > 0 arm never proved the DROP was applied (05071_alter_constraint_array_join_no_op.sql) AGREE, fixed in this PR The inserted k = 1 satisfied both original constraints, so the assertions also held on a table where the ALTER had been skipped; the insert now uses k = 0, which passes the surviving c CHECK k < 1000 and fails the dropped c CHECK k > 0, with a negative control refusing it at Code: 469 ... Expression: (k > 0).
2 ⚠️ The description and commit message overclaimed the insert-time consequence, first as "every INSERT fails, the table is write-dead", then as "the table took no ordinary insert" AGREE, fixed in this PR CheckConstraintsTransform throws UNSUPPORTED_METHOD only when the constraint result's size differs from the block's row count, so VALUES ([1, 2], 5) is refused (2 values, 1 row) while VALUES ([1], 5) is accepted; both texts now state the measured behavior, and the defect is unchanged, VALUES ([1, 2], 5) being valid input rejected.
3 💡 No test pinned the new conditional push_back, so a phantom name entry could be reintroduced silently AGREE, added in this PR Making it unconditional again leaves every assertion in the repo green, yet it would make ADD CONSTRAINT IF NOT EXISTS c CHECK k < 1000, DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c CHECK arrayJoin(arr) > 0 (accepted today, installs nothing) throw and lose the user's DROP; that statement is now pinned and reddens at Code: 80 under a mutation build.
4 💡 Nor did any test pin the other direction of the same line: deleting the push_back entirely AGREE, added in this PR Removing it left the whole file green while letting ADD CONSTRAINT IF NOT EXISTS d CHECK k < 1000, MODIFY CONSTRAINT IF EXISTS d CHECK arrayJoin(arr) > 0 through unscreened, which is the defect this PR closes, so that direction is pinned too, again behind a mutation build.
5 ⚠️ A tracker entry was added for an ADD CONSTRAINT of a name that is already taken and carries no IF NOT EXISTS, which apply() refuses without storing anything (src/Storages/AlterCommands.cpp) AGREE, fixed in this PR The phantom entry survived erase-one, so ADD CONSTRAINT c CHECK k > 0, DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c CHECK arrayJoin(arr) > 0 over a singly-declared c reported the third leg's arrayJoin instead of the duplicate name master reports; nothing user-reachable regressed and the direction was one-way, but an entry is now added only when the name is still free, pinned by an arm green on master and reddening on the phantom version.
6 ⚠️ installs is true for an already-taken name without IF NOT EXISTS, so the arrayJoin screen pre-empts the duplicate-name error although nothing can be installed DISAGREE This is the screen half of the line in row 5 and is not introduced here: with if_not_exists == false the && short-circuits before the tracker is consulted, so the predicate reads alike in the previous NameSet version and the Names version, re-measured as Code: 80 on base, phantom and final binaries, nine of nine. Gating the screen on the name being free would stop screening ADD CONSTRAINT <taken name> altogether, turning a fail-closed screen fail-open while duplicate constraint names are reachable from CREATE.
7 💡 No arm for DROP CONSTRAINT c, DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c ... staying accepted DISAGREE Erase-one is already discriminated as a pair: the pre-existing singly-named DROP c, ADD IF NOT EXISTS c arm requires DROP to erase, and the repeated-name arms require it to erase only one; a third arm would need a third CREATE, because the table has one c left by then.
8 ⚠️ Row (i) of the pre-PR validation comment stated the invariant as "a declaration is screened exactly when the statement installs it", and two of its other rows had gone stale against the amended tree AGREE, corrected before posting The "exactly when" is false in one direction, because ADD CONSTRAINT <taken name> without IF NOT EXISTS screens a declaration that is then refused for the duplicate name; the row now states the direction that does hold and names that one shape as unchanged master behavior, and the stale arm count and superseded Build ID are corrected against the recorded measurements.

Three further nits were folded into the same amends: a stale scenario count in the commit message; a
"nothing else changes" clause in the description that row 5 contradicts; and an earlier instance of row 8's
staleness.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-self-slot-58:20260920-201200

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no settings and no server: two clickhouse local statements (the CREATE and the ALTER in the description) exit 0 on base and 80 with the fix.
b Root cause explained? Yes: AlterCommands::validate tracked constraint names in a NameSet, which cannot represent a name declared twice, while apply()'s DROP/MODIFY legs are first-match, so after the DROP leg the tracker says the name is free although the table still has it.
c Fix matches root cause? Yes: the structure that lost the multiplicity becomes a Names list with erase-one semantics, in the function that owns the "will this install?" question; no widened bound, no guard at the failure site, and the insert-time check is untouched.
d Test intent preserved / new tests added? Yes: the new scenarios are appended to 05071_alter_constraint_array_join_no_op, the test #117267 created for this exact rule, whose existing assertions are unchanged and still pass: one statement per direction of the defect, both reddening on base, plus arms pinning which commands take the name for the rest of the statement, each shown to redden under a mutation of the line it pins, and an insert of k = 0 that holds only if the DROP really applied.
e Both directions demonstrated? Yes, twice: a 9-arm matrix on Build-ID-verified base and fix binaries, and the runner on Build-ID-verified servers, where 05071 FAILs on base (750c25f4...) quoting exactly the two repeated-name statements and passes on the shipped fix (cd9d1316...).
f Fix is general across code paths? Yes, measured: both ALTER-side call sites of checkExpressionsPreserveRowCount are fixed and they are the only two; ADD/MODIFY/DROP CONSTRAINT are the only constraint commands; validate has exactly one caller, so Replicated/ON CLUSTER inherit it; the CREATE site has no tracker and is verified unchanged; the sibling NameSet trackers stay correct because ColumnsDescription::add rejects a duplicate column name.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: multiplicity 1, 2 and 3; MODIFY IF EXISTS and ADD IF NOT EXISTS; both command orders; the same name and a different name; an ordinary expression that must stay accepted and installed. Type wrappers are not a dimension: the tracker compares String names and never reads the expression.
h Backward compatible? (maintainer-approved exception only) Yes, measured: a table that got the declaration in through the bypass still loads, still SELECTs (also with optimize_using_constraints=1), and ALTER TABLE ... DROP CONSTRAINT c still recovers it; no setting added or changed, so SettingsChangesHistory.cpp is not owed, and no format or serialization change. The deliberate tightening is stated in the description.
i Invariants and contracts preserved? Yes: every declaration apply() would install is screened, and a command that installs nothing because its name is taken or absent is not screened for it. Deliberately not an "exactly when": ADD CONSTRAINT <taken name> without IF NOT EXISTS is screened although apply() then refuses it for the duplicate name, which is unchanged master behavior from #117267 that leaves the statement rejected either way. validate stays const and still throws before apply(), so a rejected ALTER leaves the table untouched (asserted by SHOW CREATE after each Code: 80), and the tracker is function-local.

Session id: cron:clickhouse-impl-self-slot-57:20260920-141800

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0766818]

Summary: ✅


AI Review

Summary

This PR fixes the local single-node holes around duplicate constraint names and arrayJoin inside ADD / MODIFY CONSTRAINT, but it still tightens replay paths that newer secondaries execute for older initiators. Because those replay-only paths can now reject DDL that current releases still commit, the change is not safe for rolling upgrades yet.

Findings
  • ❌ Blockers
    • [src/Interpreters/InterpreterCreateQuery.cpp:1213] checkNamesAreUnique() is gated only by isFreshTableDefinition(). That still returns true for full-definition ATTACH replays (attach outranks secondary in getLoadingStrictnessLevel()), for Shared Catalog internal replays, and for Keeper-recovered stored definitions that arrive as plain CREATE. An older initiator can therefore commit metadata with duplicate constraint names, while an upgraded secondary now throws during replay and retries the DDL forever. Suggested fix: exempt replay-only create paths the same way nearby validators do (is_ddl_replay, isRecoveryFromStoredMetadata(), shared-catalog replay), or move the duplicate-name validation to an initiator-only path.
    • [src/Storages/AlterCommands.cpp:2133] AlterCommands::validate() now rejects ADD CONSTRAINT IF NOT EXISTS <taken> and MODIFY CONSTRAINT IF EXISTS <absent> with arrayJoin before replay-specific exemptions in checkAlterIsPossible() can run. Older versions still accept those exact shapes as no-ops, so a mixed-version replicated/shared-catalog rollout can wedge the DDL queue on statements that do not change metadata at all. Suggested fix: keep the stricter behavior for user execution, but preserve the pre-PR no-op semantics on replay paths (or otherwise gate this compatibility break behind an initiator-only / compatibility check).
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    • Add a replay-compatibility path for the new duplicate-name rejection on create/attach replays.
    • Avoid tightening no-op ALTER ... ADD/MODIFY CONSTRAINT replays on newer secondaries.

LLVM Coverage Report

Measured on commit 0766818.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 20/21 (95.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 20, 2026
Comment thread src/Storages/AlterCommands.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 06b0822

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, 4/8) / test_storage_nats/test_nats_jetstream_credentials_rotation.py::test_jetstream_unacked_messages_survive_rotation Code: 665 ... Cannot connect to Nats last error: (unix/sock.c:56): poll error: 4, i.e. a poll interrupted by a signal (EINTR) treated as a socket error. 1 failed of 936 in the shard; CIDB shows it across 38 distinct pull requests and 4 master commits in 30 days, so it is not reachable from this diff #120202 (external, open)
Build profile diff infra, not reachable from this diff: the job aborts before it emits any leaf, with RuntimeError: CI logs cluster query failed after requests.exceptions.ReadTimeout on t6h0zvqlgy.us-east-2.aws.clickhouse-staging.com (job 106178409448) #121048 (external, open); #118708 (ours, open)

PR is the praktika rollup and carries no failure of its own: it is red only because the two
leaves above are. Mergeable Check, Finish Workflow and CH Inc sync are green on this head.

Measured on this head: 176 contexts, 153 SUCCESS / 20 SKIPPED / 3 FAILURE.

Session id: cron:our-pr-ci-monitor:20260921-050309

@PedroTadim PedroTadim self-assigned this Sep 21, 2026
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]>
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai for this case CREATE TABLE t (arr Array(UInt8), n UInt8, CONSTRAINT c CHECK n > 0, CONSTRAINT c CHECK n < 10) ENGINE = MergeTree ORDER BY n; the create table should fail. It makes no sense for the table to have two constraints with the same name.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai for the alter case, simply reject if the alter constraint add or modify has an array join on it

@groeneai

Copy link
Copy Markdown
Collaborator Author

Both of these are implemented.

1. CREATE TABLE rejects a repeated constraint name. Code: 44, Constraint c is declared more than once, the same error code ALTER TABLE ... ADD CONSTRAINT already returns for a name the table has. The check runs under the isFreshTableDefinition gate that the arrayJoin screen next to it already uses, so a definition stated now is screened (explicit column list, full-definition ATTACH, AS src / CLONE AS src) while a replay of stored metadata is not. I measured that boundary rather than assuming it: a table stored by a build without the check still attaches, both of its declarations are still enforced, and each is still droppable one at a time. Without that gate an upgraded server would refuse to start on such a table.

2. ADD/MODIFY CONSTRAINT is screened wherever the expression is stated, no longer only when apply would really install the declaration. That removes the name tracking from this PR entirely, and AlterCommands::validate goes from 41 lines to 5.

One consequence is yours to rule on. #117267 screened only declarations that would really be installed, so ADD CONSTRAINT IF NOT EXISTS <taken name> and MODIFY CONSTRAINT IF EXISTS <absent name> carrying an arrayJoin were accepted as no-ops, and 05071_alter_constraint_array_join_no_op.sql pinned that on purpose. Rejecting them unconditionally is what closes the hole on already-stored tables, but it reverses that choice, so I rewrote the test and renamed it instead of leaving a file whose name asserts the opposite of its content. If the no-op acceptance was load-bearing, say so and I will narrow the screen back.

The changelog category is therefore no longer Not for changelog: refusing a CREATE that released versions accept is user-visible. I updated the body.

On the review bot's point about the fixture: the new 05071 no longer sets duplicate names up through CREATE at all, it asserts the rejection, and the legacy/stored-metadata route it asked for is now covered by 05234_constraint_repeated_name_legacy_metadata.sh, which attaches a hand-written definition and proves both declarations are enforced and the DROP ... MODIFY IF EXISTS bypass is refused there too.

One thing I deliberately left alone: neither this check nor #117267's is skipped on Replicated-database DDL replay, since attach outranks secondary in getLoadingStrictnessLevel and only registerStorageMergeTree guards its own checks with is_ddl_replay. So in a mixed-version window an older initiator can commit a statement an upgraded secondary refuses. That is pre-existing and symmetric with the sibling screen; extending an is_ddl_replay guard to both is small if you want it in this PR.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai this CREATE TABLE t (arr Array(UInt8), n UInt8, CONSTRAINT c CHECK n > 0, CONSTRAINT c CHECK n < 10) ENGINE = MergeTree ORDER BY n; is accepted in the latest build and it shouldn't. I see an arrayJoin in ALTER TABLE t DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c CHECK arrayJoin(arr) > 0; and it should also be rejected

…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.
@groeneai groeneai changed the title Do not let a repeated constraint name bypass the arrayJoin check in ALTER Reject a repeated constraint name, and screen arrayJoin in every ALTER that states one Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed as 4cae111.

Correcting one thing I said above, because I checked it properly afterwards: the is_ddl_replay guard is not confined to registerStorageMergeTree. Three sites use it, and one of them sits on this very path, MergeTreeData::checkAlterIsPossible (MergeTreeData.cpp:5664), next to StorageFactory.cpp:58, and AlterCommands.cpp:1189 already carries the Shared Catalog half of the same marker. So it is the house idiom here rather than an exception, which makes its absence on the interpreter-level constraint screens look more like an oversight in #117267 than a decision.

It is not free either, which is why I would rather you picked: guarding the ALTER screen on replay means a secondary accepts and stores the row-count-changing CHECK that the screen exists to reject, so the constraint reaches replicated metadata through a different door. Guarding only the CREATE-side uniqueness check carries no such cost. Tell me which of the two you want and I will add it here.

@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The CREATE side landed after you tested it: one commit, 4cae111, pushed at 14:14 UTC, after your 14:00 UTC comment. No build of this PR before it carries the check at all (ConstraintsDescription::checkNamesAreUnique does not exist anywhere in the tree before that commit), so a repeated name being accepted is what that head does.

Both of your statements, measured on a binary built from 4cae111 (build id d50e6b2f):

CREATE TABLE t (arr Array(UInt8), n UInt8, CONSTRAINT c CHECK n > 0, CONSTRAINT c CHECK n < 10) ENGINE = MergeTree ORDER BY n;
Code: 44. DB::Exception: Constraint `c` is declared more than once. (ILLEGAL_COLUMN)

ALTER TABLE t DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c CHECK arrayJoin(arr) > 0;
Code: 80. DB::Exception: Constraint `c` cannot contain arrayJoin, because it changes the number of rows. (INCORRECT_QUERY)

Code 44 is what ADD CONSTRAINT already throws for a name that is taken (AlterCommands.cpp:1069).

The ALTER is now rejected whatever the name does: ADD/MODIFY CONSTRAINT is screened wherever the expression is stated, so a taken name, an absent name, IF EXISTS, IF NOT EXISTS, and a DROP of the same name in the same statement no longer change the answer. The test that used to pin those shapes as accepted no-ops now asserts rejection instead.

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 ALTER above is rejected on it too; 05234 pins that path.

Please retest at 4cae111.

if (isFreshTableDefinition(mode, create.attach_short_syntax))
{
properties.constraints.checkExpressionsPreserveRowCount();
properties.constraints.checkNamesAreUnique();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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)

@PedroTadim

Copy link
Copy Markdown
Member

Code: 44. DB::Exception: Constraint c is declared more than once. (ILLEGAL_COLUMN) I think this should be an INCORRECT_QUERY error.

`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`.
@groeneai groeneai changed the title Reject a repeated constraint name, and screen arrayJoin in every ALTER that states one Reject a repeated constraint name, and arrayJoin in any ADD/MODIFY CONSTRAINT Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both done, pushed as f180dbe.

CREATE TABLE t (arr Array(UInt8), n UInt8, CONSTRAINT c CHECK n > 0, CONSTRAINT c CHECK n < 10) ENGINE = MergeTree ORDER BY n;
Code: 80. DB::Exception: Constraint `c` is declared more than once. (INCORRECT_QUERY)

INCORRECT_QUERY is also what the sibling screen in the same class, checkExpressionsPreserveRowCount, throws, so both ways a stated constraint definition can be refused now report one code and 05071 no longer names two. With the old code still expected that test fails, so it asserts the code and not merely the rejection.

ALTER TABLE ... ADD CONSTRAINT c on a name the table already has still returns Code: 44, ILLEGAL_COLUMN (AlterCommands.cpp:1069); that path is untouched here. Tell me if you want it aligned too and I will do it in this PR.

New title: Reject a repeated constraint name, and arrayJoin in any ADD/MODIFY CONSTRAINT. The description now leads with both rejections instead of only the arrayJoin hole, and the category is Backward Incompatible Change, since each of them refuses DDL that released versions accept.

@alexey-milovidov alexey-milovidov mentioned this pull request Sep 21, 2026
1 task done
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai what about projections, indexes, columns defaults, columns materialized values, column aliases? Are those fine with array joins?

@groeneai

Copy link
Copy Markdown
Collaborator Author

I measured all five on this PR's head (debug build of f180dbe), at CREATE and again through ALTER:

Carrier arrayJoin at DDL Error
Skip index (minmax, set, bloom_filter) rejected Code: 80 ... Secondary index 'idx' cannot contain array joins (INCORRECT_QUERY)
Column DEFAULT rejected Code: 116 ... Unsupported default value that requires ARRAY JOIN action (THERE_IS_NO_DEFAULT_VALUE)
Column MATERIALIZED rejected same, 116
Column ALIAS rejected same, 116
Projection accepted nothing at DDL time

For the columns the rejection also covers ADD COLUMN and MODIFY COLUMN (ColumnsDescription.cpp:1526), and for indexes both CREATE and ALTER TABLE ... ADD INDEX (MergeTreeIndices.cpp:546).

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

ProjectionsDescription.cpp:220, and ALTER TABLE ... ADD PROJECTION reaches it the same way. On an already populated table, ADD PROJECTION plus MATERIALIZE PROJECTION are both accepted and the mutation then never finishes (is_done = 0, empty latest_fail_reason). The non-aggregate form is accepted too and inserts do succeed, but the projection part then holds arr Array(UInt8) and n, that is the unexpanded array rather than the declared expression: 2 rows stored for 4 array elements.

That gap is already reported as #117268, with #117269 for the Distributed sharding key, and it already has an open fix in #117791, which rejects arrayJoin in projections and sharding keys in both CREATE and ALTER. So I am not duplicating it here; this PR stays on constraint names and constraint expressions.

For completeness, the neighbouring carriers reject it too, with two more codes: sorting and primary keys and partition keys give Code: 44 ... key cannot contain array joins (ILLEGAL_COLUMN), and TTL gives Code: 450 (BAD_TTL_EXPRESSION).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f180dbe

Every failure below has an owner: a fixing PR, mine or external. Both reds on this head are
CI-side timeouts, neither is produced by this diff.

Check / test Reason Owner / fixing PR
Build profile diff infra: the CI logs cluster read timed out at 60 s on the compare_symbols query, retried 6 times, and this branch still carried the job script that turns that into a hard failure #121048 (external, merged), merged master @ 07668185ebe1 to pick it up
Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1 perf harness: Select historical data timed out at read timeout=10, so the learned thresholds were never fetched and every bar fell to the 0.15 floor; the learned bar for this query is 0.65, against which the measured 0.343 is silent #121189 (mine, open)

Details, so the numbers are checkable:

  • Build profile diff failed inside compare_symbols, and the traceback frames it names, 234, 1447, 1600, 1623 and 1683, are the line numbers of the job script on this branch, whose file is exactly 1683 lines. Master's copy is 1734 lines and no longer contains that RuntimeError at all, because CI: "Build profile diff" is green when the CI logs cluster does not answer #121048 landed at 16:14Z and turns an unanswering cluster into a green check. praktika ran this branch's copy of ci/, not master's, so the merge above is what picks the fix up.
  • The perf row is client_time 0.0146 s to 0.0196 s, a 5 ms shift on a 15 ms query. This diff only screens duplicate constraint names in ALTER and CREATE, so it does not touch the read-in-order path; the same query on the same shard has been flagged on several unrelated pull requests today, always with the threshold fetch timed out.

Session id: cron:our-pr-ci-monitor:20260921-220150

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 07668185e with master f16ef1991 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

811 translation units recompiled, 6045 s compile time in total, 811 of them have a recent master baseline.

Job report

@PedroTadim

Copy link
Copy Markdown
Member

@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

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 can't you move the ATTACH statements to the sql test and remove this test file?

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.

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.

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov , the CI is green

@PedroTadim

Copy link
Copy Markdown
Member

Ok, I am merging to complement #117267

@PedroTadim
PedroTadim added this pull request to the merge queue Sep 28, 2026
Merged via the queue into ClickHouse:master with commit 0ba5255 Sep 28, 2026
176 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 28, 2026
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 comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-backward-incompatible Pull request with backwards incompatible changes 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