Skip to content

Reject a CHECK constraint containing arrayJoin - #117267

Merged
alexey-milovidov merged 6 commits into
masterfrom
fix-check-constraint-array-join
Sep 5, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
fix-check-constraint-array-join

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #117022
Related: #117014

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

Reject a CHECK constraint whose expression contains arrayJoin. Such a constraint was accepted and
then read past the end of the inserted block - surfacing as a nonsensical
Array of size 18446744073709551613 is too large, or an abort in a debug build - or blamed a
violation on the wrong row.

Description

CheckConstraintsTransform takes the result size from the constraint's result column and
cross-indexes the original chunk's columns positionally against it. arrayJoin changes the number of
rows, so:

  1. a multi-element array makes the result longer than the block - an out-of-bounds read, reported as
    TOO_LARGE_ARRAY_SIZE with (size_t)-3 as the array size;
  2. an empty array makes it shorter - the row indices shift and a genuine violation is reported against
    an innocent row, printing its column values.

arrayJoin is already rejected for skip indexes ("Secondary index cannot contain array joins"), for
keys, for mutations, for PREWHERE and for row policies for exactly this reason; the CHECK
constraint path had no guard.

Every table definition the user states is now screened: an explicit column list, a full-definition
ATTACH, the AS src / CLONE AS src copy of another table's constraints, and
ALTER TABLE ... ADD CONSTRAINT / MODIFY CONSTRAINT. A replay of stored metadata is not screened,
so a table stored before this check still attaches - which is why the transform now also refuses a
result whose size does not match the block's row count, reporting the constraint by name instead of
reading out of bounds. On the ALTER side only a command that will really install a declaration is
screened, so an ADD CONSTRAINT IF NOT EXISTS of a name that is taken and a MODIFY CONSTRAINT of a
name that is not there keep meaning what they meant before.

The declaration's AST is read rather than the built expression, because a constraint that cannot be
built at all (a bare subquery, a wrong arity) is only reported when a row is inserted, and building it
at DDL time would move that report to the CREATE. The single arrayJoin walk that four other places
each had a copy of is now one function, astContainsArrayJoin.

Tests: 05069_reject_array_join_in_check_constraint (every spelling that is rejected, and an ordinary
constraint that still accepts and still rejects a real violation, including one whose arrayJoin is
inside a subquery and therefore fine), 05070_clone_as_copies_constraints (CLONE AS keeps enforcing
a copied constraint), 05071_alter_constraint_array_join_no_op (the IF EXISTS / IF NOT EXISTS
no-ops, and the adds and drops of one multi-command ALTER), and
05072_check_constraint_row_count_mismatch (a hand-written metadata file, as a version without this
check would have stored it, attaches and reports the constraint on insert).


Workflow [PR]
Sync PR [sync-upstream/pr/117267]

Version info

  • Merged into: 26.9.1.813 (included in 26.9 and later)

`CheckConstraintsTransform` indexes the constraint's result column positionally against the rows
of the block being inserted, so an expression that changes the number of rows breaks it: a
longer result read past the end of the block's columns - reported as a nonsensical
`Array of size 18446744073709551613 is too large`, or an abort in a debug build - and a shorter
one blamed a violation on the wrong row and printed its values.

`arrayJoin` is already rejected for skip indexes, keys, mutations, `PREWHERE` and row policies
for the same reason; the `CHECK` constraint path had no such guard. A fresh `CREATE` now rejects
it, and the transform additionally refuses a result whose size does not match the block, so
metadata stored before this check fails comprehensibly instead of out of bounds.

Closes: #117022
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3f0cadb]

Summary: ✅


AI Review

Summary

This PR correctly adds a row-count backstop in CheckConstraintsTransform and rejects direct CHECK arrayJoin(...) / unnest(...) declarations, but the promised "fresh DDL rejects it" contract is still incomplete. Two DDL paths still bypass or regress that invariant, so the change is not ready to merge as-is.

Findings

⚠️ Majors

  • [src/Interpreters/InterpreterCreateQuery.cpp:928] CREATE TABLE ... AS src and CLONE AS still copy as_storage_metadata->getConstraints() verbatim in the as_table branch, without the mode < LoadingStrictnessLevel::ATTACH assertPreserveRowCount() guard that was added for explicit column lists. A table attached from pre-fix metadata can therefore still seed a brand-new table with CHECK arrayJoin(...), which violates the PR's fresh-DDL contract and leaves the new table to fail only later at insert time. Suggested fix: after copying properties.constraints in the as_table branch, run the same assertPreserveRowCount() check for fresh create/clone modes, and add a stateless regression for CREATE TABLE ... AS / CLONE AS from a legacy source table.
  • [src/Storages/AlterCommands.cpp:2092] The new assertConstraintPreservesRowCount(command.constraint_decl) runs in AlterCommands::validate(), but InterpreterAlterQuery::runCommandSegments() calls validate() before prepare() and long before apply() reaches the existing if_exists / if_not_exists short-circuits. As a result, ADD CONSTRAINT IF NOT EXISTS and MODIFY CONSTRAINT IF EXISTS now reject CHECK arrayJoin(...) even when the command is a documented no-op because the constraint already exists, is already missing, or was added/dropped earlier in the same multi-command ALTER. Suggested fix: evaluate the row-count check only after the command is known to take effect, or maintain a working constraint snapshot inside validate() the same way column validation advances all_columns; cover both IF EXISTS / IF NOT EXISTS and same-statement add/drop interactions in a regression test.
Final Verdict

⚠️ Changes requested: the direct create/alter spellings are covered now, but fresh DDL is still bypassable through CREATE ... AS / CLONE AS, and the alter-side validation regresses existing no-op IF EXISTS / IF NOT EXISTS semantics.

LLVM Coverage Report

Measured on commit 3f0cadb.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 35/43 (81.40%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
Building the constraint expression to inspect it broke two existing tests: a constraint
expression is deliberately built only at INSERT time, because it may name a table that does not
exist yet (`02841_not_ready_set_constraints`) or a function missing from the current build
(`04257_system_constraints`, `encrypt` in the fast-test build). Both must stay creatable.

The `arrayJoin` rejection is now a walk over the constraint's AST. The size check in
`CheckConstraintsTransform` stays as the backstop for anything that only becomes visible after
resolution.
Comment thread src/Storages/ConstraintsDescription.cpp Resolved
Comment thread src/Storages/ConstraintsDescription.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3f0cadbe1 with master 6113efbf0 (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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too.

…keep subquery scope allowed

Three findings from the review of the `arrayJoin` guard for `CHECK` constraints:

- The literal name match missed `unnest`, the case-insensitive alias of `arrayJoin`. The check now
  resolves the canonical function name, and also descends into SQL UDF bodies, the same way
  `checkRowPolicyFilterExpression` does.
- The walk descended into nested subqueries, rejecting constraints such as
  `CHECK x IN (SELECT arrayJoin([1, 2]))` that still produce exactly one boolean per inserted row.
  It now stops at `ASTSelectQuery`, mirroring `selectListHasArrayJoinFunction`.
- Only `CREATE TABLE` was guarded, so `ALTER TABLE ... ADD/MODIFY CONSTRAINT` was a way around the
  check. `AlterCommands::validate` now applies the same check via the new static
  `ConstraintsDescription::assertConstraintPreservesRowCount`.

The test covers all of these.
Comment thread src/Storages/AlterCommands.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 5, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 5, 2026
Merged via the queue into master with commit 5cbca3e Sep 5, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-check-constraint-array-join branch September 5, 2026 21:41
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 5, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 5, 2026
Master merged ClickHouse#117267, which rejects a `CHECK` constraint whose expression
changes the number of rows (`arrayJoin`), and it lands on the same three
statements this branch touches. The two checks answer different questions about
the same declaration and neither subsumes the other, so both are kept and
master's code is preserved verbatim.

`AlterCommands::validate`: master's unconditional
`assertConstraintPreservesRowCount` call keeps its anchor, and this branch's
metadata-changing guard follows it. Keeping them as two statements is
deliberate: this branch skips validation when the command persists no
declaration (`ADD CONSTRAINT IF NOT EXISTS` on an existing name is a no-op that
has to keep succeeding), while master's check applies to every ADD/MODIFY, and
folding one gate into the other would silently change master's behaviour.

`InterpreterCreateQuery::getTableProperties`: master inserted its
`assertPreserveRowCount()` call after the `getConstraintsDescription` line that
this branch extends with `is_fresh_definition`. Both survive; master's
`mode < LoadingStrictnessLevel::ATTACH` gate is left as written rather than
switched to this branch's narrower freshness predicate, which is a separate
question from this merge.

`ConstraintsDescription.cpp`: an add/add conflict in the include block only,
resolved by keeping both `ASTIdentifier.h` and `ASTSelectQuery.h`.

The caller set of `getConstraintsDescription` is unchanged between the old merge
base and master, so no new call site needed the freshness argument. Diff against
master is +120/-9 in `src/`, identical to the pre-merge three-dot stat, and every
removed line is one of this branch's own call sites being extended.

Merged master: 5cbca3e

Co-Authored-By: Claude Opus 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 21, 2026
…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.
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 28, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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.

CHECK constraint containing arrayJoin is accepted but causes an out-of-bounds read and wrong-row diagnostics on INSERT (sibling of #117014)

2 participants