Skip to content

Screen every stated constraint definition for arrayJoin, with one walk instead of six - #117799

Merged
alexey-milovidov merged 12 commits into
masterfrom
reject-array-join-in-check-constraint-117022
Sep 13, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
reject-array-join-in-check-constraint-117022

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

A CHECK constraint is evaluated per block and its result column is read by block row, so an arrayJoin inside it checks a row against another row's value, and with an empty array the column is shorter than the block and the read goes past its end - a violating row passes and the diagnostics name the wrong row:

CREATE TABLE t (k UInt32, arr Array(UInt32), CONSTRAINT c CHECK arrayJoin(arr) > 0) ENGINE = MergeTree ORDER BY k;
INSERT INTO t VALUES (1, []);   -- accepted, although the constraint has nothing to evaluate

#117267 fixed that and is merged. This pull request was written against the same issue, and it is reconciled onto that fix now rather than repeating it: the screen, the ALTER guard, the walk and the transform backstop it merged are replaced by the wider versions below, and its test 05074_check_constraint_array_join_rejected is kept as it is.

Every definition the user states is screened, not only an explicit column list. The screen sits at one point in InterpreterCreateQuery::getTableProperties, where the definition is normalized and formatted back into the query, gated on isFreshTableDefinition. That covers CREATE, a full-definition ATTACH, and the AS src / CLONE AS src copy of the constraints of another table - which a version without this check may have stored. Loading existing metadata is unaffected, so a table stored before the check still attaches, and RESTORE and Replicated database replay still accept it.

An ASSUME constraint is screened as well. ConstraintsDescription::getExpressions does not evaluate it per block, but the constraint optimizer substitutes its atoms into queries, and it has no more business changing the number of rows.

An ALTER is screened only when it really installs a declaration. ADD CONSTRAINT IF NOT EXISTS of a name that is taken and MODIFY CONSTRAINT IF EXISTS of a name that is not there install nothing, so they keep meaning what they meant before. The names are followed through the adds and drops of the same statement, because apply runs its commands one after another.

A stored constraint that changes the number of rows is not trusted by the query-time optimizer either. The screen above closes the DDL path, but metadata stored by a version without it still loads, and WhereConstraintsOptimizer and ConvertQueryToCNFPass::optimizeWithConstraints read the constraints of the table without re-checking anything: a stored CHECK or ASSUME arrayJoin(arr) > 0 matched WHERE arrayJoin(arr) > 0 and removed the filter, answering a query over the exploded rows with the base rows. ConstraintsDescription::filterConstraintsForOptimization now leaves such a constraint out of the three derived views the optimizer reads - the CNF data, the atomic data behind the ComparisonGraph, and the query-tree data - so AddIndexConstraintsOptimizer and SubstituteColumnOptimizer are covered as well. The optimization is skipped rather than the query refused, so that such a table stays readable, and CheckConstraintsTransform still sees every constraint, so an insert into it is still reported.

One walk looking for arrayJoin, not six. TreeRewriter::hasArrayJoin, astContainsArrayJoinFunction in src/Parsers/ASTSelectQuery.cpp, InterpreterSelectQuery::selectListHasArrayJoinFunction, QueryOracleChecker::hasArrayJoinFunction and RowPolicy's expressionContainsArrayJoin each looked for arrayJoin in an AST in its own way. They are one function now - expressionContainsArrayJoin in src/Interpreters/ExpressionContainsArrayJoin.cpp - taking the strictest behaviour of each: the name resolved with getFunctionCanonicalNameIfAny, so the case-insensitive alias unnest counts without a spelling being hardcoded (three of them missed it, including the limit pushdown guard in numbersLikeUtils); nested queries not descended into (the oracle checker did, which only made it skip a query it could have checked); and the body of a SQL UDF the expression calls walked as well, with a memory-tracked set of visited names, so an expression that is stored as written and has its UDFs inlined only when it is evaluated - a row policy filter - is covered. The oracle checker also loses three whole-query clone calls it made only in order to walk them.

The transform backstop is checked before the Nullable unwrapping rather than after it, so a nullable result of the wrong size is reported too.

The screen reads the constraint AST rather than building its expression: a constraint that cannot be built at all (a bare subquery - see 03594_constraint_subqery_logical_error - or a wrong arity - see 04489_constraint_comparison_wrong_arity) is only reported when a row is inserted, and building it at DDL time would move that report to the CREATE.

The walk stops at a nested query, whose arrayJoin multiplies the rows of that query and hands the enclosing expression whatever shape the query returns, so CHECK k IN (SELECT arrayJoin([1, 2, 3])) works today and keeps working.

Related: #117267
Related: #117022

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 to CHANGELOG.md):

arrayJoin in a table constraint is now also rejected when the definition is copied by CREATE TABLE ... AS src or CLONE AS src, stated by a full-definition ATTACH, or declared as ASSUME. It changes the number of rows, so the constraint was checked against the wrong rows. A constraint containing it that is already stored in the metadata of a table is no longer used by the query-time constraint optimizer, which could remove a WHERE that the constraint did not really imply and answer a query over the arrayJoin-expanded rows with the base rows.

🤖 Generated with Claude Code


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

Version info

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

A `CHECK` constraint is evaluated per block and its result column is read by block row, so an
`arrayJoin` inside it checks a row against another row's value, and with an empty array the
column is shorter than the block and the read goes past its end - a violating row passes and
the diagnostics name the wrong row. `arrayJoin` is already rejected at DDL time for sorting
keys, partition keys, secondary indexes and column expressions; a `CHECK` constraint is
rejected the same way now, in `CREATE` and in `ALTER TABLE ... ADD CONSTRAINT`.

The check reads the constraint AST rather than building its expression: a constraint that
cannot be built at all (a 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`. Loading existing metadata
is unaffected, so a table stored before this check still attaches.

Closes: #117022
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8fc7c2c]

Summary: ✅


AI Review

Summary

This PR closes the arrayJoin-in-constraint bug beyond the original DDL check: fresh constraint definitions are screened across CREATE, full-definition ATTACH, CREATE ... AS, CLONE AS, and effective ALTER ... ADD/MODIFY CONSTRAINT; legacy stored constraints are excluded from the query-time constraint optimizers; and CheckConstraintsTransform now rejects row-count mismatches before it can read past the end of a block column. The implementation matches the stated contract on the current head, and the added stateless coverage exercises the new DDL surfaces, the legacy-metadata backstop, and the optimizer behavior under both analyzers.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 8fc7c2c.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 81.40% 81.30% -0.10%

Changed lines: Changed C/C++ lines covered: 119/125 (95.20%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/ConstraintsDescription.cpp Resolved
@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

The rejection is well-placed and avoids the two wedge classes that bit the sibling arrayJoin-in-TTL work: the screen fires only when authoring DDL (AlterCommands::validate gated on ADD_CONSTRAINT, and getConstraintsDescription(..., validate = mode <= LoadingStrictnessLevel::CREATE) with validate defaulting to false), so a legacy table with an arrayJoin CHECK still attaches on startup / short-syntax ATTACH / Replicated-DB replay / RESTORE, and unrelated ALTERs that re-derive constraints via the three-argument getConstraintsDescription in DatabasesCommon.cpp do not fire the check. astContainsArrayJoin recurses over all children, so lambdas, aliases, untuple, and SQL-UDF-expanded bodies are all covered.

One residual: CREATE TABLE t2 AS legacy_t copies the constraint into a brand-new table without screening it. In getTablePropertiesAndNormalizeCreateQuery the as_table branch does properties.constraints = as_storage_metadata->getConstraints(); with no validation call, while the validating call sites are only the explicit-columns_list branch and the use_legacy_to_time rewrite branch. So on a post-fix server a legacy table that carries an arrayJoin CHECK (attached as intended) can be templated with CREATE TABLE t2 AS legacy_t (and ... CLONE AS) to mint a fresh table — with metadata written post-fix — that still holds the out-of-bounds-read constraint, at pure defaults and with no error. It is contained (the hazard equals the legacy template's own), but it does re-open the one CREATE form that re-derives from a live table, so screening the as_table constraint copy would close it.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8fc7c2c32 with master 3476b12ea (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

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

Job report

@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

Three follow-ups after looking at the head more closely, one of which is a residual that survives the current fix at pure defaults.

Full-definition ATTACH still mints fresh broken metadata (residual, distinct from the CREATE ... AS copy above). Both validation call sites gate on validate = mode <= LoadingStrictnessLevel::CREATE, but mode = getLoadingStrictnessLevel(create.attach, ...) returns ATTACH for any ATTACH query — including a full-definition ATTACH TABLE t (...) ENGINE = ... on a name that does not exist on disk, which is fresh user input that writes brand-new metadata, not a replay of an existing table. So on a post-fix server:

ATTACH TABLE t (k UInt32, arr Array(UInt32), CONSTRAINT c CHECK arrayJoin(arr) > 0)
ENGINE = MergeTree ORDER BY k;
INSERT INTO t VALUES (1, [1, 2, 3]);  -- the #117022 out-of-bounds read, re-armed

lands the constraint with no error. Unlike the CREATE TABLE t2 AS legacy_t residual, this needs no pre-existing legacy template — a two-statement script reconstructs the exact #117022 hazard on a clean post-fix server. The legacy case you correctly exempt is attach_short_syntax / metadata-exists replay; a full-definition ATTACH of a non-existent table is fresh definition input and should be screened the same as CREATE (this is the isFreshTableDefinition distinction from the #117791 thread).

The in-code justification for walking into subqueries is not accurate. The comment on astContainsArrayJoin says a constraint containing a subquery "is only reported when a row is inserted", but on 26.9.1.1 both CONSTRAINT c CHECK x IN (SELECT number FROM numbers(5)) and CONSTRAINT c CHECK x IN (SELECT arrayJoin([1,2,3])) create, build and enforce correctly at INSERT — the inner arrayJoin is confined to the subquery and never changes the outer block's row count, which is the only thing that breaks the constraint machinery. Recursing into ASTSubquery therefore turns a set of constraints that demonstrably work today into INCORRECT_QUERY on CREATE/ADD CONSTRAINT, and makes their SHOW CREATE dumps un-replayable. Stopping the recursion at ASTSubquery (the include is already in the file) keeps the fix targeted at the row-count-changing top-level arrayJoin that #117022 is actually about. (The review bot flagged the false-positive; the point here is that the code comment's premise is what's wrong.)

Minor: ASSUME constraints escape the screen (checkExpressionsPreserveRowCount filters to Type::CHECK), so CONSTRAINT c ASSUME arrayJoin(arr) > 0 is still accepted. No insert-time hazard (getExpressions also filters to CHECK); the only reach is the default-off constraint-optimizer settings that substitute constraint atoms into queries. Below the bar, just noting it for completeness of the screen.

@Algunenano Algunenano self-assigned this Sep 3, 2026
Comment thread src/Storages/ConstraintsDescription.cpp Outdated
/// done on the AST rather than on the built expression, because a constraint that cannot be built at all
/// (a subquery, a wrong arity) is only reported when a row is inserted, and building it here would move
/// that report to the DDL.
bool astContainsArrayJoin(const IAST & ast)

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.

There is a astContainsArrayJoinFunction in src/Processors/QueryPlan/numbersLikeUtils.cpp and hasArrayJoinFunction under src/Interpreters/QueryOracleChecker.cpp, both with slightly different implementations (one not considering "unnest").

We need to unify things.

Also, please don't nest if-if or for-if without braces. It makes the code harder to read for not reason. IMO we should only avoid {} when we are doing single statements and not nest statements that skip {}

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.

🕵 Unified. src/Functions/astContainsArrayJoin.{h,cpp} holds the single walk, and the copies are gone: numbersLikeUtils::astContainsArrayJoinFunction, QueryOracleChecker::hasArrayJoinFunction, TreeRewriter::hasArrayJoin, InterpreterSelectQuery::selectListHasArrayJoinFunction, RowPolicy's expressionContainsArrayJoin and the one this pull request added.

The shared one takes the strictest behaviour of each:

  • the name is resolved with getFunctionCanonicalNameIfAny (which is what RowPolicy did), so unnest and UNNEST count without a spelling being hardcoded - three of the walks missed the alias entirely;
  • a nested query is not descended into, which is what three of them already did, and what answers Screen every stated constraint definition for arrayJoin, with one walk instead of six #117799 (comment);
  • descend_into_sql_udfs walks the body of a SQL UDF the expression calls. Only RowPolicy passes it: a filter is stored as written and has its UDFs inlined at read time, while a table definition has them substituted before it is checked (I confirmed a UDF wrapping arrayJoin is rejected in both CREATE ... CONSTRAINT and ADD CONSTRAINT without it).

It lives in src/Functions because the canonical name comes from FunctionFactory, which src/Parsers cannot reach. The oracle checker also loses three whole-query clone calls it made only in order to walk them.

Braces added.

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.

🕵 One follow-up here, after merging master: the unification landed there in the meantime as src/Interpreters/ExpressionContainsArrayJoin.h (expressionContainsArrayJoin), so this branch's src/Functions/astContainsArrayJoin.h was a second copy of the same walk.

The branch's copy is gone and its implementation is folded into master's one - canonical function names via getFunctionCanonicalNameIfAny (so unnest and UNNEST count), a nested query not descended into, SQL UDF bodies walked with a memory-tracked set of visited names so a cycle among them cannot recurse forever - plus an IAST & overload, which lets the callers that hold a reference stop cloning a whole query only in order to walk it.

The two remaining copies are gone as well: astContainsArrayJoinFunction in src/Parsers/ASTSelectQuery.cpp (it compared the spelling, so it missed unnest) and QueryOracleChecker::hasArrayJoinFunction. Everything now goes through the one function: RowPolicy, TTLDescription, ConstraintsDescription, TreeRewriter, InterpreterSelectQuery, ExpressionAnalyzer's LIMIT AFTER/UNTIL guard, numbersLikeUtils and the oracle checker.

That also fixes the one real red on this pull request, Build (arm_fuzzers): undefined symbol: DB::astContainsArrayJoin(DB::IAST const&, bool), because the fuzzers' link set did not include the branch's src/Functions object.

@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 2026
alexey-milovidov and others added 3 commits September 4, 2026 13:11
`arrayJoin` is the one function that changes the number of rows, and five places walked an AST
looking for it, each in its own way: `TreeRewriter::hasArrayJoin`,
`numbersLikeUtils::astContainsArrayJoinFunction`,
`InterpreterSelectQuery::selectListHasArrayJoinFunction` (whose comment says it mirrors the previous
one), `QueryOracleChecker::hasArrayJoinFunction`, `RowPolicy`'s `expressionContainsArrayJoin`, and
the one this pull request added made six.

They are one function now, `astContainsArrayJoin`, taking the strictest behaviour of each:

- the name is resolved with `getFunctionCanonicalNameIfAny`, so the case-insensitive alias `unnest`
  counts too without a spelling being hardcoded - three of the walks missed it;
- a nested query is not descended into, because its `arrayJoin` multiplies the rows of that query and
  hands the enclosing expression whatever shape the query returns. Two of the walks did descend; for
  the constraint check that rejected `CHECK x IN (SELECT arrayJoin([1, 2, 3]))`, which works today,
  and for `QueryOracleChecker` it skipped a query it could have compared;
- `descend_into_sql_udfs` walks the body of a SQL UDF the expression calls, for an expression that is
  stored as written and has its UDFs inlined only when it is evaluated. A row policy filter is the
  one such caller: a table definition has them substituted before it is checked.

It lives in `src/Functions` because the canonical name comes from `FunctionFactory`. The oracle
checker also loses three whole-query `clone` calls it made only in order to walk them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`MODIFY CONSTRAINT` replaces the stored declaration in place, so it states a new expression exactly
like `ADD CONSTRAINT` does, and it reached the insert-time path this pull request closes.

An `ASSUME` constraint is not evaluated per block, so it cannot read past the end of its own result
column, but the constraint optimizer substitutes its atoms into queries and it has no more business
changing the number of rows than a `CHECK` has. Screening every declaration also drops a special
case from the check.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The screen was two calls with a `mode <= LoadingStrictnessLevel::CREATE` gate, which left two fresh
definitions unscreened: a full-definition `ATTACH TABLE t UUID '...' (...) ENGINE = ...`, which runs
under `ATTACH` although it is user input rather than a replay, and `CREATE TABLE t2 AS src` /
`CLONE AS src`, which copies the constraints of another table - possibly stored by a version without
this check - into brand-new metadata.

It is one call now, at the end of `getTablePropertiesAndNormalizeCreateQuery`, where every branch has
finished filling `properties.constraints` and the definition is about to be formatted back into the
query, gated on `isFreshTableDefinition`. The `validate` parameter of `getConstraintsDescription`
goes with it.

The negative `AS src` case is not reachable from SQL on a patched server: every path that states a
fresh definition is screened, so a source table carrying such a constraint can only come from
metadata an older version stored. The test asserts instead that the copy still happens and that the
copied constraint is still enforced. `CLONE AS` gets a test of its own because a `Replicated`
database does not support it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 All three follow-ups are in, along with the four inline findings.

Full-definition ATTACH. The gate is isFreshTableDefinition(mode, create.attach_short_syntax) now, and it sits at a single point at the end of getTablePropertiesAndNormalizeCreateQuery rather than at each call that builds constraints, so the explicit column list, AS src, CLONE AS src and a full-definition ATTACH are all screened by the same line. Your two-statement repro is a test case in 05069_reject_array_join_in_check_constraint.sql.

The in-code justification. You are right that the premise was overstated: a subquery in a CHECK builds and enforces fine, and only the bare CHECK (SELECT 1) form of 03594_constraint_subqery_logical_error fails at insert time. The comment says that now (and names the two tests it is about), and the walk stops at a nested query, so CHECK x IN (SELECT arrayJoin([1, 2, 3])) is accepted again - with a regression test. Stopping there also made the check agree with the three arrayJoin AST walks that already existed, which is what @Algunenano asked for in #117799 (comment); all six copies are one function now, astContainsArrayJoin in src/Functions/astContainsArrayJoin.cpp.

ASSUME. Screened as well. It is not evaluated per block, so it cannot read past the end of its own result column, but the constraint optimizer substitutes its atoms into queries and it has no more business changing the number of rows than a CHECK has - and dropping the type filter removes a special case rather than adding one.

CREATE TABLE t2 AS legacy_t. Screened too. Worth noting what the test can assert: with every fresh-definition path screened, a source table carrying such a constraint can only come from metadata an older version stored, so the negative case is not reachable from SQL on a patched server. The test asserts that the copy still happens and that the copied constraint is still enforced; CLONE AS is in 05070_clone_as_copies_constraints.sql, separate because a Replicated database does not support it.

`AlterCommands::validate` screened the declaration of every `ADD CONSTRAINT` and
`MODIFY CONSTRAINT`, including one that `apply()` then installs nowhere: an
`ADD CONSTRAINT IF NOT EXISTS` of a name that is already taken, and a
`MODIFY CONSTRAINT IF EXISTS` of a name that is not there, are documented no-ops, and they
started to fail on an `arrayJoin` they were never going to install. A `MODIFY CONSTRAINT`
of a missing name without `IF EXISTS` reported the `arrayJoin` rather than the missing name.

`validate` now keeps the constraint names of the table and follows them through the adds and
drops of the same `ALTER` - the way it already advances `all_columns` for a
`MODIFY COLUMN ADD ENUM VALUES` - and screens a command only when it will really install a
declaration. This is what `ADD COLUMN IF NOT EXISTS` does too: it skips the validation of
its column when the name is taken.

Test `05071_alter_constraint_array_join_no_op`.
…eading past it

Rejecting `arrayJoin` when a constraint is declared does not help a table that was stored
before that check existed: a replay of stored metadata is deliberately not screened, so such
a table still attaches, and inserting into it still scans the `arrayJoin`-expanded result and
reads the block's own columns at an index past their end - the
`Array of size 18446744073709551613 is too large` of the issue, or an abort in a debug build.

`CheckConstraintsTransform` now verifies that the result has as many values as the block has
rows, which is what reading it row by row assumes, and names the constraint and the two sizes
instead. Nothing else can make them differ: `arrayJoin` is the one action that changes the
number of rows of a block, and a constant result is expanded to the block's row count.

Test `05072_check_constraint_row_count_mismatch` writes the metadata by hand, as a version
without the declaration check would have stored it, and covers both a result longer than the
block and one shorter than it.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Isn't it a duplicate of #117267?

…n-check-constraint-117022

# Conflicts:
#	src/Processors/QueryPlan/numbersLikeUtils.cpp
#	src/Storages/ConstraintsDescription.h
@alexey-milovidov alexey-milovidov changed the title Reject arrayJoin in a CHECK constraint Screen every stated constraint definition for arrayJoin, with one walk instead of six Sep 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

It was, and #117267 is merged now, so this one is reconciled onto it rather than repeating it. What is left is the part that PR did not cover:

  • The screen sits at one point in InterpreterCreateQuery::getTableProperties, gated on isFreshTableDefinition, instead of in the create.columns_list branch. That adds the AS src / CLONE AS src copy of another table's constraints and a full-definition ATTACH - both of which state a definition that a version without the check may have stored. A replay of stored metadata stays unscreened, as before.
  • An ASSUME constraint is screened too. It is not evaluated per block, but the constraint optimizer substitutes its atoms into queries.
  • An ALTER is screened only when it really installs a declaration. ADD CONSTRAINT IF NOT EXISTS of a name that is taken and MODIFY CONSTRAINT IF EXISTS of a name that is not there install nothing, so they keep meaning what they meant before; the names are followed through the adds and drops of the same statement.
  • One arrayJoin walk, not six - astContainsArrayJoin. numbersLikeUtils's copy has meanwhile been widened to scan the whole query, and that widening is kept, now with unnest caught as well.
  • The transform backstop is checked before the Nullable unwrapping rather than after it.

The merged implementation's own copies are removed in the merge commit: assertConstraintPreservesRowCount / assertPreserveRowCount and their private walk, the mode < ATTACH screen, the ALTER guard and the later size check. Its error wording is kept verbatim, and its test 05074_check_constraint_array_join_rejected is kept and still passes.

The one behaviour dropped is the UDF descent in the merged constraint walk, which is dead code there: InterpreterCreateQuery and InterpreterAlterQuery run UserDefinedSQLFunctionVisitor::visit over the whole query before properties are built, so the declaration being screened already has its UDFs substituted. Checked against a local build rather than read off the source - with CREATE FUNCTION udf_aj AS x -> arrayJoin(x), both CREATE TABLE ... CONSTRAINT c CHECK udf_aj(arr) > 0 and ALTER TABLE ... ADD CONSTRAINT c CHECK udf_aj(arr) > 0 are still rejected. A row policy filter is the opposite case and keeps descend_into_sql_udfs = true.

Locally, 05069-05072 and 05074 pass, and so does the rest of the constraint set except five that this rig cannot run (settings-constraint tests needing the custom-settings prefixes, a MySQL port, a DistributedDDL config, and 00988, whose two replicas of one table cannot fetch from each other here - it hangs the same way with no constraints at all).

Comment thread src/Storages/ConstraintsDescription.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). labels Sep 6, 2026

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

Code cleanup looks pretty good and it's also extended to fix more issues, which is great. The AI bot is reported one unfixed pattern, let's cover it and merge

…n-check-constraint-117022

Master grew `src/Interpreters/ExpressionContainsArrayJoin.h`, which is the same single
`arrayJoin` walk this branch added as `src/Functions/astContainsArrayJoin.h`. The branch's
copy is dropped and its stricter implementation (canonical function names, a
memory-tracked set of visited SQL UDF bodies) is folded into master's, so there is still
one walk: `astContainsArrayJoinFunction` in `src/Parsers/ASTSelectQuery.cpp` and
`QueryOracleChecker::hasArrayJoinFunction` are gone as well.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…source limit

Review asked for a case proving that a top-level `WITH` definition that the query never
references does not cost the source limit, since `04320` only checks the final rows.

`max_rows_to_read = 10` is the observable: the query reads the three rows it asks for and
not a whole block. Both spellings of the function (`arrayJoin` and `unnest`), both
analyzers, plus the two shapes that do multiply the rows - a referenced alias used in
`WHERE` and a plain call in the `SELECT` list - as negative controls.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, the only red on this pull request before the latest push was Stress test (arm_asan_ubsan), and both of its failures are fleet-wide, not caused by this change - please investigate them and fix them in a separate pull request (or link the fix here if it is already in progress):

This branch has since merged master, so the next run will tell whether either of them reproduces here.

@groeneai

groeneai commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

Both are owned, and neither needs a new pull request from me.

1. offsets_column has data inconsistent with nested_column (STID 2632-3cfc): the fix already in progress is #100330.

The producer is a background replicated mutation, not a merge: MergeTreeBackgroundExecutor -> ReplicatedMergeMutateTaskBase::executeImpl -> MutateAllPartColumnsTask::executeStep -> PartMergerWriter::mutateOriginalPartAndPrepareProjections (MutateTask.cpp:2166) -> MaterializingTransform -> ColumnArray::convertToFullColumnIfConst.

#100330 ("Fix vertical merge nested default corruption") drops the hasDefault early exit in fillMissingColumns and adds reconcileEvaluatedDefaultWithSharedOffsets(), gated on MergeTreeReaderSettings::reconcile_missing_defaults_with_shared_offsets, which is set in createForMergeMutation. This route reaches that factory through MutationsInterpreter::Source::read -> createReadFromPartStep(MergeTreeSequentialSourceType::Mutation, ...) -> MergeTreeSequentialSource.cpp:192, so despite the "vertical merge" title the gate is on for exactly the stack above. The mechanism is the shared ArraySizes stream of a Nested group: after DROP COLUMN n.y plus ADD COLUMN n.y ... DEFAULT, the compact reader borrows the sibling's offsets and leaves the column to evaluateMissingDefaults, which has no offsets context, so it arrives with a last offset of 22 and zero elements. The assertion text appears nowhere in that title, which is why searching the message does not surface it.

2. Cannot start clickhouse-server: in this run it is the same event as (1), not a second failure.

fatal.log carries a single signature, on a single part (4735b0d6-...::0_0_4_1_6) with the same Data size: 0, last offset: 22: one abort at 10:29:13 during the workload, then eleven more between 10:32:18 and 10:39:34, roughly 43 s apart, one per restart, alongside three core.MergeMutate.* dumps. The mutation entry is persisted, so every restart re-runs it and re-aborts, which is what the "11 start attempts" counts. This row goes away with #100330.

Fleet-wide that row is a harness give-up label rather than a signature, though since #117094 it is a precise one: it is emitted only on the branch where the daemon is no longer running, so "after N start attempts" means the process exited, while a live but slow-loading server takes the separate "did not become ready" path. On true trunk (head_ref = 'master' AND pull_request_number = 0) it is 10 runs in 14 days, and all 10 attribute:

runs cause owner
5 marks-file family, STID 4777-5873 (Cannot append mark after final / Number of marks A is not divisible by number of columns in mark B) merged #119188 removed the trigger; that family has produced no row since
3 ATTACH ... AS timeSeriesSelector(db.ts_src_ren, ...) fails Code: 60 once the target is renamed, 11 exits the fixture left master with #119281; the fix is written and holds for the sequencing question at #116629 (comment) so that it cannot conflict with #119282
1 Filesystem database whose user_files directory no longer exists, Code: 36 #118684 (mine, open)
1 persisted CONSTRAINT ... CHECK (SELECT id FROM t1) GLOBAL IN (test_2.conversation) after t1 was dropped, Code: 60 #112992 (mine, open) rejects that table reference in a constraint's IN (the RHS is the table's own column read as db.table), so the definition is never persisted; the legal CHECK a IN (SELECT id FROM t1) form still loads after the drop

The "several times a day" rate is mostly release branches rather than master: in the same window the same row is 46 runs on 26.3, 31 on 26.6, 24 on 26.7 and 12 on 26.8, each carrying different companion signatures, against the 10 on master.

The run on afd09027 is still in flight; I will follow up here if either signature reappears on it.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you - that is a complete attribution, and it changes the picture on this pull request: the two rows are one event, a persisted mutation entry that re-aborts on every restart, so the Cannot start clickhouse-server row is a consequence of the offsets_column has data inconsistent with nested_column abort rather than a second failure, and #100330 covers it. Nothing for me to carry here.

The run on afd09027 has since finished green, with neither signature reappearing.

`shouldPushdownLimit` classifies an unreferenced top-level
`WITH arrayJoin(...) AS unused` as row-expanding under the old analyzer,
because the alias survives into the walked AST. This has been raised as a lost
optimization; record at the call site why the breadth is deliberate and free.

The verdict is consumed only through `getLimitFromQueryInfo`, whose only readers
are the `limit` hint of `ReadFromSystemNumbersStep` and
`ReadFromSystemPrimesStep`, and the outer `LIMIT` reaches those sources through
the plan regardless. Measured with a control binary in which the guard refuses
every pushdown: identical rows, identical `EXPLAIN PIPELINE`, and identical
`SelectedRows`/`SelectedBytes`. So refusing the hint cannot make a bounded query
read more rows, while a missed `arrayJoin` would be a correctness bug.

No behaviour change - comment only.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into master with commit f78b9ed Sep 13, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the reject-array-join-in-check-constraint-117022 branch September 13, 2026 02:35
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.

5 participants