Repository navigation
Screen every stated constraint definition for arrayJoin, with one walk instead of six - #117799
Conversation
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
|
Workflow [PR], commit [8fc7c2c] Summary: ✅
AI ReviewSummaryThis PR closes the Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 8fc7c2c.
Changed lines: Changed C/C++ lines covered: 119/125 (95.20%) · Uncovered code |
|
The rejection is well-placed and avoids the two wedge classes that bit the sibling One residual: |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units890 translation units recompiled, 6013 s compile time in total, 890 of them have a recent master baseline. |
|
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 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-armedlands the constraint with no error. Unlike the The in-code justification for walking into subqueries is not accurate. The comment on Minor: |
| /// 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) |
There was a problem hiding this comment.
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 {}
There was a problem hiding this comment.
🕵 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 whatRowPolicydid), sounnestandUNNESTcount 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_udfswalks the body of a SQL UDF the expression calls. OnlyRowPolicypasses 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 wrappingarrayJoinis rejected in bothCREATE ... CONSTRAINTandADD CONSTRAINTwithout 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.
There was a problem hiding this comment.
🕵 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.
`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]>
|
🕵 All three follow-ups are in, along with the four inline findings. Full-definition The in-code justification. You are right that the premise was overstated: a subquery in a
|
`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.
|
Isn't it a duplicate of #117267? |
…n-check-constraint-117022 # Conflicts: # src/Processors/QueryPlan/numbersLikeUtils.cpp # src/Storages/ConstraintsDescription.h
arrayJoin in a CHECK constraintarrayJoin, with one walk instead of six
|
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 merged implementation's own copies are removed in the merge commit: The one behaviour dropped is the UDF descent in the merged constraint walk, which is dead code there: Locally, |
Algunenano
left a comment
There was a problem hiding this comment.
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]>
…n-check-constraint-117022
…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]>
|
🕵 @groeneai, the only red on this pull request before the latest push was
This branch has since merged |
|
Both are owned, and neither needs a new pull request from me. 1. The producer is a background replicated mutation, not a merge: #100330 ("Fix vertical merge nested default corruption") drops the 2.
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 (
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 |
|
🕵 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 The run on |
`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]>
A
CHECKconstraint is evaluated per block and its result column is read by block row, so anarrayJoininside 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:#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
ALTERguard, the walk and the transform backstop it merged are replaced by the wider versions below, and its test05074_check_constraint_array_join_rejectedis 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 onisFreshTableDefinition. That coversCREATE, a full-definitionATTACH, and theAS src/CLONE AS srccopy 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, andRESTOREandReplicateddatabase replay still accept it.An
ASSUMEconstraint is screened as well.ConstraintsDescription::getExpressionsdoes 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
ALTERis screened only when it really installs a declaration.ADD CONSTRAINT IF NOT EXISTSof a name that is taken andMODIFY CONSTRAINT IF EXISTSof 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, becauseapplyruns 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
WhereConstraintsOptimizerandConvertQueryToCNFPass::optimizeWithConstraintsread the constraints of the table without re-checking anything: a storedCHECKorASSUME arrayJoin(arr) > 0matchedWHERE arrayJoin(arr) > 0and removed the filter, answering a query over the exploded rows with the base rows.ConstraintsDescription::filterConstraintsForOptimizationnow leaves such a constraint out of the three derived views the optimizer reads - the CNF data, the atomic data behind theComparisonGraph, and the query-tree data - soAddIndexConstraintsOptimizerandSubstituteColumnOptimizerare covered as well. The optimization is skipped rather than the query refused, so that such a table stays readable, andCheckConstraintsTransformstill sees every constraint, so an insert into it is still reported.One walk looking for
arrayJoin, not six.TreeRewriter::hasArrayJoin,astContainsArrayJoinFunctioninsrc/Parsers/ASTSelectQuery.cpp,InterpreterSelectQuery::selectListHasArrayJoinFunction,QueryOracleChecker::hasArrayJoinFunctionandRowPolicy'sexpressionContainsArrayJoineach looked forarrayJoinin an AST in its own way. They are one function now -expressionContainsArrayJoininsrc/Interpreters/ExpressionContainsArrayJoin.cpp- taking the strictest behaviour of each: the name resolved withgetFunctionCanonicalNameIfAny, so the case-insensitive aliasunnestcounts without a spelling being hardcoded (three of them missed it, including the limit pushdown guard innumbersLikeUtils); 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-queryclonecalls it made only in order to walk them.The transform backstop is checked before the
Nullableunwrapping 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 - see04489_constraint_comparison_wrong_arity) is only reported when a row is inserted, and building it at DDL time would move that report to theCREATE.The walk stops at a nested query, whose
arrayJoinmultiplies the rows of that query and hands the enclosing expression whatever shape the query returns, soCHECK k IN (SELECT arrayJoin([1, 2, 3]))works today and keeps working.Related: #117267
Related: #117022
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
arrayJoinin a table constraint is now also rejected when the definition is copied byCREATE TABLE ... AS srcorCLONE AS src, stated by a full-definitionATTACH, or declared asASSUME. 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 aWHEREthat the constraint did not really imply and answer a query over thearrayJoin-expanded rows with the base rows.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117799]
Version info
26.9.1.1334(included in26.9and later)