Repository navigation
Reject arrayJoin in projections and Distributed sharding keys - #117791
alexey-milovidov merged 10 commits into
Conversation
`arrayJoin` is the one action that changes the number of rows in a block, and these three
slots are all applied positionally to the block, so nothing lines up once it appears:
- a TTL expression: `TTLDeleteAlgorithm` reads the timestamp column by block row, so a row
is judged by another row's timestamp, and with an empty array the column is shorter than
the block and the read goes past its end - rows with a future TTL are silently deleted;
- a projection: `ProjectionDataSink` rejects a block with more rows than the parent part
with a `LOGICAL_ERROR`, so every insert into the table fails and a `MATERIALIZE
PROJECTION` mutation is stuck forever;
- a `Distributed` sharding key: the shard selector is applied positionally, so the insert
either fails with "Size of selector ... doesn't match size of column" or routes a row by
an unrelated row's array element.
All three were accepted at DDL time, although `arrayJoin` is already rejected for sorting
keys, partition keys, sampling keys, secondary indexes, `MATERIALIZED`/`ALIAS`/`DEFAULT`
column expressions, mutations, `PREWHERE` and row policies. They are now rejected the same
way, in `CREATE` and in `ALTER`; loading existing metadata is unaffected, so a table stored
before this check still attaches.
Closes: #117014
Closes: #117268
Closes: #117269
|
Workflow [PR], commit [bf72b98] Summary: ✅
AI ReviewSummaryThis PR correctly switches the projection and sharding-key checks to Findings❌ Blockers
Final VerdictStatus: ❌ Block
LLVM Coverage ReportMeasured on commit bf72b98.
Changed lines: Changed C/C++ lines covered: 52/52 (100.00%) · Uncovered code |
|
Three findings from a review, one per leg. The pre-PR faces of all three linked issues reproduce on 26.9.1.1, and the two rigs below were run at pure default settings on that binary. 1. The The new check in
2. The TTL leg fires on the re-validation of existing TTLs inside The tail of 3. The TTL check screens only the timestamp expression; the The check runs on the expression built from CREATE TABLE fault (k UInt32, d DateTime, arr Array(UInt32)) ENGINE = MergeTree ORDER BY k;
INSERT INTO fault VALUES (1, now() - 3600, [1,1]), (2, now() - 3600, []), (3, now() - 3600, [0]);
SELECT count(), groupArray(k) FROM fault; -- 3 [1,2,3]
ALTER TABLE fault MODIFY TTL d + INTERVAL 1 SECOND DELETE WHERE arrayJoin(arr) = 1 SETTINGS materialize_ttl_after_modify = 0;
OPTIMIZE TABLE fault FINAL;
SELECT count(), groupArray(k) FROM fault; -- 1 [3]Row 2 has an empty array — under any sane semantics it matches nothing — and is silently deleted by row 1's second flattened element, exactly the #117014 positional-misalignment class. The control with The Adjacent but out of scope for this PR: a |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units26 translation units recompiled, 208 s compile time in total, 26 of them have a recent master baseline. |
| /// Check that sharding_key exists in the table and has numeric type. | ||
| checkShardingKeyExistsAndIsNumeric(sharding_key_, getContext(), storage_metadata.getColumns().getAllPhysical()); | ||
| checkShardingKeyExistsAndIsNumeric( | ||
| sharding_key_, getContext(), storage_metadata.getColumns().getAllPhysical(), isLoadingFromExistingMetadata(mode)); |
There was a problem hiding this comment.
isLoadingFromExistingMetadata(mode) is too narrow for this new guard. A short ATTACH TABLE, ATTACH DATABASE, replica replay under SECONDARY_CREATE, and backup RESTORE can all rebuild a previously stored Distributed definition without using FORCE_ATTACH / FORCE_RESTORE, so a legacy table whose sharding key already contains arrayJoin now stops loading on those paths even though the PR description says existing metadata should remain usable.
This needs the same "fresh definition vs stored metadata" split used elsewhere in this file (attach_short_syntax, restore, recovery), not just isLoadingFromExistingMetadata(mode).
There was a problem hiding this comment.
🕵 Fixed. The guard is now gated on isFreshTableDefinition(mode, attach_short_syntax) - the same predicate registerStorageMergeTree and the projection check use - threaded into the constructor as an explicit is_fresh_definition argument from both engine registrations (Distributed and Remote). A replayed definition is therefore accepted: a short ATTACH TABLE, the tables of an ATTACH DATABASE, a Replicated database's SECONDARY_CREATE replay and recoverLostReplica, a backup RESTORE, and server startup. TableFunctionRemote passes true (always fresh user input) and DatabaseRemote passes false (its sharding key is synthesized by the server, not stated by a user). New test 05176_distributed_array_join_sharding_key_stored_metadata.sh prepares exactly this metadata the way 05099_ttl_array_join_stored_metadata does and checks that it loads and that an unrelated ALTER of it works.
There was a problem hiding this comment.
The fresh/stored split is still incomplete here. registerStorageDistributed now passes only isFreshTableDefinition(args.mode, args.query.attach_short_syntax) into the constructor, but the same file still treats args.getLocalContext()->isRecoveryFromStoredMetadata() as an existing-metadata load at src/Storages/StorageDistributed.cpp:2730-2732. DatabaseReplicated recovery executes stored table definitions as plain CREATE with that flag set (src/Databases/DatabaseReplicated.cpp:1677-1679, 1935-1940), so mode == CREATE / attach_short_syntax == false still makes the constructor reject a legacy arrayJoin sharding key on recovery. registerStorageRemote at src/Storages/StorageDistributed.cpp:2807 has the same hole.
There was a problem hiding this comment.
The DatabaseReplicated recovery hole is still present in the current code. DatabaseReplicated and SYSTEM RESTORE DATABASE REPLICA replay stored table definitions as plain CREATE after setRecoveryFromStoredMetadata(true) (src/Databases/DatabaseReplicated.cpp:1677-1679, :1938-1940; src/Interpreters/InterpreterSystemQuery.cpp:1912-1914), but both registrations still pass only isFreshTableDefinition(args.mode, args.query.attach_short_syntax) into the constructor at src/Storages/StorageDistributed.cpp:2364 and :2807. With mode == CREATE / attach_short_syntax == false, the constructor still reaches the rejection at src/Storages/StorageDistributed.cpp:498, so a legacy arrayJoin sharding key is still rejected on that replay path.
There was a problem hiding this comment.
Not a problem at all. Our goal is to guard on newly created tables.
…n-row-count-preserving-slots-117014
Addresses the review findings on this pull request. The TTL half of the change is gone: the same check landed on master in a more complete form (`checkTTLExpressionPreservesRowCount` screens the main expression, the `DELETE WHERE` predicate and the `GROUP BY ... SET` assignments, both at DDL time and when a stored description is turned back into a runnable expression), so the hunk here was redundant. The projection and sharding key checks now use the same `expressionContainsArrayJoin` helper as the TTL and row policy checks instead of comparing the spelling of the function name. That resolves the function name to its canonical one, so the `unnest` alias is caught regardless of `normalize_function_names` (which is off for secondary queries), descends into SQL UDF bodies, which are inlined when the expression is built, and stops at a nested `ASTSelectQuery`, whose `arrayJoin` has its own scope and does not multiply the outer rows. The sharding key rejection now fires only for a definition the user supplies now - `isFreshTableDefinition`, the same split used for projections. A replayed definition (short `ATTACH TABLE`, the tables of an `ATTACH DATABASE`, a `Replicated` database's `SECONDARY_CREATE`, `RESTORE`, server startup) is read back from metadata that already exists, and rejecting it there would make the table or the whole database unloadable. For the same reason the guard no longer runs from `StorageDistributed::checkAlterIsPossible`: the sharding key is an engine argument that `ALTER` cannot change, so revalidating it as fresh user input made every unrelated `ALTER` of a table created before this check throw. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The `Distributed` sharding key rejection must not break a table whose sharding key was stored before the check existed: the key is an engine argument that `ALTER` cannot change, so rejecting a replayed definition would leave `DROP` as the only way out, and would fail the whole database load rather than the one table. The test prepares such metadata the way `05099_ttl_array_join_stored_metadata` does - `clickhouse-local` over a data directory whose stored definition is edited into the form an older server would have written - and checks that it loads, that an unrelated `ALTER` of it works, and that stating the same key now is still rejected. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
arrayJoin in TTL expressions, projections and sharding keysarrayJoin in projections and Distributed sharding keys
|
🕵 Pushed What changed
Tests — CI — the only red was |
`05175` and `05176` are taken by other pull requests that are already in flight. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Renumbered the two tests to |
…n-row-count-preserving-slots-117014
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117791&sha=a9788cfb7d9d55bb135c3203a0048a902a26fed1&name_0=PR&name_1=Stress%20test%20(amd_debug) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is The other red, |
| /// analyzer would have resolved later: the `unnest` alias (resolved by canonical name, so the | ||
| /// verdict does not depend on `normalize_function_names`) and a SQL UDF body that is inlined | ||
| /// into the projection query when it is built. `expressionContainsArrayJoin` does both. | ||
| if (expressionContainsArrayJoin(projection_definition->query)) |
There was a problem hiding this comment.
isFreshTableDefinition(mode, attach_short_syntax) is still too narrow for this new guard. DatabaseReplicated and SYSTEM RESTORE DATABASE REPLICA recreate stored tables by executing their saved CREATE under query_context->setRecoveryFromStoredMetadata(true) (src/Databases/DatabaseReplicated.cpp:1677-1679, 1935-1940), and InterpreterCreateQuery reaches this helper with mode == CREATE / attach_short_syntax == false (src/Interpreters/InterpreterCreateQuery.cpp:962-964). A table that already stored PROJECTION ... GROUP BY arrayJoin(...) before this patch will therefore still fail replica/database recovery even though the definition is not fresh user DDL.
This needs the same stored-metadata / replay carve-out that registerStorageMergeTree uses for new compatibility checks, plus a recovery-focused test.
There was a problem hiding this comment.
🕵 Same decision as on the Distributed thread: the guard is meant for newly created tables only. DatabaseReplicated recovery replaying a pre-existing arrayJoin projection is out of scope for this change.
|
Both reds are already owned, so no new PR from me here. 1. Two things the report does not show. The failing build I have not reproduced the interleaving behind this particular abort. A reproducer for the same assertion, both arms, does exist in the closed #102215 ( 2. |
`master` added a new `StorageDistributed` caller in `TableFunctionTraceView.cpp` that does not pass the `is_fresh_definition` argument this branch introduced, so the cluster pointer landed in the `bool` slot and the merge did not compile. It has no sharding key, and the table is built internally, so pass `false`. `05201_distributed_array_join_sharding_key_stored_metadata` collides with `05201_check_table_dropped_projection` now on `master`; renamed to `05290`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
| /// analyzer would have resolved later: the `unnest` alias (resolved by canonical name, so the | ||
| /// verdict does not depend on `normalize_function_names`) and a SQL UDF body that is inlined | ||
| /// into the projection query when it is built. `expressionContainsArrayJoin` does both. | ||
| if (expressionContainsArrayJoin(projection_definition->query)) |
There was a problem hiding this comment.
expressionContainsArrayJoin(projection_definition->query) only covers the (SELECT ...) projection form. PROJECTION p INDEX ... TYPE commit_order stores the user expression in projection_definition->index, so this guard is skipped, but ProjectionIndexCommitOrder::fillProjectionDescription then copies that INDEX expression into the synthetic projection SELECT list and still routes it through fillProjectionDescriptionByQuery. As a result, PROJECTION p INDEX arrayJoin(arr) TYPE commit_order is still accepted and reaches ProjectionDataSink, which fails inserts with the same row-count LOGICAL_ERROR this PR is trying to prevent.
Please reject arrayJoin in projection-index expressions too, or run the guard on the effective query after the index type expands it.
One conflict, in `registerStorageRemote`: this branch deletes the block whose logic moved into `parseAndValidateRemoteEngineTarget`, master keeps it. Took this branch's side by editing the marked region only, so master's auto-merged hunks in the same file stay. Master changed that block once since the previous merge. ClickHouse#121335 clears the column TTLs of a structure inferred from another table (`columns.clearColumnTTLs()`): `Remote` stores no data, and a copied TTL makes the table unloadable once an `ALTER` persists it. The block now exists only on master's side, so git reported nothing about that line. Ported to where this branch adopts the inferred columns, the only place they become the storage's structure; the preflight discards them and needs no change. Diffing master's block at the old and new merge bases shows that call as its only change. The `ErrorCodes` list conflicted too: kept master's new `ILLEGAL_COLUMN`, and `ACCESS_DENIED`, which has no use left in the file, stays removed. ClickHouse#117791's new `is_fresh_definition` constructor argument merged cleanly into this branch's `registerStorageRemote` call. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n `APPLY` lambda
`QueryOracleChecker` already refuses a query whose `WHERE` or `HAVING` defines an
alias that the rest of the query uses, because an oracle which removes that clause
rebinds the identifier to a same-named table column and the two executions stop
being comparable. The guard, `clauseDefinesAliasUsedElsewhere` into
`referencesAnyAlias`, is a generic `children` walk, and
`ASTColumnsApplyTransformer` copies `parameters` and `lambda` by hand in `clone`
instead of registering them as `children`. A use inside an `APPLY` lambda is
therefore invisible to the guard, while the analyzer does resolve that lambda
against the parent query scope. The six clause-removing oracles then proceed and a
valid query is rejected with a false `AST_FUZZER_ORACLE_MISMATCH`.
Measured on `t(i Int32, a Int32)` holding `(1,100),(2,201),(3,302)`, where the
column deliberately differs from the alias so the rebinding changes rows rather
than spelling:
SELECT * APPLY (x -> toInt32(x) + a) FROM t WHERE (i * 100 AS a) > 1
raised `Code: 906. TLP WHERE oracle mismatch!` with
`Only in partitioned: 202 401` (the alias `i * 100`) against
`Only in reference: 203 402` (the column). Over 8 fuzzed rounds per shape,
`ASTFuzzerOracleMismatches` was 6 for that spelling, 6 for `i + 1 AS a` and 6 for
the `COLUMNS('i')` form, and 0 after this change, while the alias-free control
kept its oracle checks (19 before, 31 after) so no coverage is traded away. The
same before and after pair holds for a `Nullable` or `LowCardinality` shadowing
column, an alias used in a nested lambda or in a scalar subquery inside the
`APPLY` lambda, and two chained transformers.
The loop is added to the traversal rather than to any oracle, so all seven call
sites in this file, that is six clause-removing oracles, are covered once. Making
`lambda` and `parameters` real `children` would fix every `children` walk in the
server at once, but it would newly descend every AST visitor into the lambda, so
the narrower per-screen route of ClickHouse#118224 and ClickHouse#121897 is kept here.
`hiddenApplyMembers` is copied byte-identically from ClickHouse#121897, which was still open
when this was written, at the same insertion point, so whichever merges second
resolves a duplicate definition by deleting one copy.
A third carrier of the same blindness, `arrayJoin` hidden in an `APPLY` lambda,
defeats `expressionContainsArrayJoin` in the same way and is measured, but that
helper is shared by eight non-oracle callers such as row policies, TTL and
constraints, so teaching it this node has a different blast radius and belongs
with ClickHouse#117791.
Related: ClickHouse#121897
Co-Authored-By: Claude Opus 5 <[email protected]>
arrayJoinis the one function that changes the number of rows in a block, and these two slots are both applied positionally to the block, so nothing lines up once it appears:ProjectionDataSinkrejects a block with more rows than the parent part with aLOGICAL_ERROR, so every insert into the table fails and aMATERIALIZE PROJECTIONmutation stays stuck insystem.mutations.ALTER ... ADD PROJECTIONon a populated table left it unable to accept any further insert.Distributedsharding key (arrayJoin in a Distributed sharding key is accepted then throws LOGICAL_ERROR or silently misroutes rows (sibling of #117014, #117022) #117269): the shard selector is applied positionally, so the insert either fails with "Size of selector ... doesn't match size of column" or, when the sizes happen to agree, routes a row by an unrelated row's array element.Both were accepted at DDL time, although
arrayJoinis already rejected for sorting keys, partition keys, sampling keys, secondary indexes,MATERIALIZED/ALIAS/DEFAULTcolumn expressions, mutations,PREWHERE, row policies,CHECKconstraints and TTL expressions. They are now rejected the same way, inCREATEand inALTER.The detection uses the shared
expressionContainsArrayJoinhelper, so theunnestalias is matched by canonical name (independently ofnormalize_function_names), a SQL UDF body that gets inlined later is descended into, and anarrayJoininside a nested subquery, which has its own scope and does not multiply the outer rows, stays allowed.Only a definition the user states now is rejected (
isFreshTableDefinition). A replayed one - a shortATTACH TABLE, the tables of anATTACH DATABASE, aReplicateddatabase's DDL replay, aRESTORE, server startup - still loads, because rejecting it there would fail the whole database load rather than the one table, and theDistributedsharding key is an engine argument thatALTERcannot change. For the same reason an unrelatedALTERof such a table does not revalidate the stored key.The TTL leg of the original change (#117014) is not here any more: the equivalent check landed on
masterseparately (#117266), covering the timestamp expression, theDELETE WHEREpredicate and theGROUP BY ... SETassignments.Closes: #117268
Closes: #117269
Related: #117014
Related: #117266
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
arrayJoinin a projection or in aDistributedsharding key is now rejected atCREATE/ALTERtime. It changes the number of rows, which made every insert into a table with such a projection fail with an exception, and misrouted or failed inserts into such aDistributedtable.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117791]
Version info
26.10.1.882-master(included in26.10and later)