Repository navigation
Conversation
6d0b6df to
308133e
Compare
|
Workflow [PR], commit [b04c095] Summary: ❌
AI ReviewSummaryThe PR adds column matchers to stored column expressions and skip indices, with dependency validation and automatic repairs after schema changes. Two new correctness defects remain, and the claimed pending-index fix still leaves stale files usable in two supported paths. ❌ Block. Findings❌ Blockers
Missing context / blind spots
Final VerdictStatus: ❌ Block. Prevent rename capture, normalize UDF-backed transformers, and complete index invalidation for both repair modes and read settings. Add focused stateless regressions for those cases. The explicitly deferred findings above remain summary-only. |
Let's avoid adding it in this PR. We plan to make the ordinary tuple constructor return named tuples whenever possible. |
We plan to enable it by default. |
Allow and matchers in , , and expressions, and in skip index expressions. Matchers are expanded before validation so normal expression analysis still reports arity and type exceptions. Issue: ClickHouse#92266
Add `namedTuple` as a strict variant of `tuple` that always returns a named `Tuple` and reports an exception for duplicate or invalid argument names.
Extend the default-expression matcher stateless test to cover `asterisk_include_materialized_columns` and `asterisk_include_alias_columns` during default value evaluation.
Add a stateless test case where a `DEFAULT` expression with `*` expands into an indirect dependency cycle and reports `CYCLIC_ALIASES`.
…use `tuple` with a setting directly
Build the validation column snapshot with updated `default_desc.kind` values for `ADD COLUMN` and `MODIFY COLUMN`, so `*` and `COLUMNS` expansion sees the post-alter default kinds.
981800b to
2632f1b
Compare
…merging columns from `CLEAR COLUMN` `CLEAR COLUMN` of a whole `Nested` group (with `share_nested_offsets`) clears every column of the group, but the stale `MATERIALIZED` closure was seeded with the group name, which is not a column, so `MATERIALIZED` columns reading the group members kept their old values and the key checks were skipped. Seed it with the group members in both `AlterCommands::validate` and `MutationsInterpreter`. `CLEAR COLUMN` also rewrote a stale `MATERIALIZED` sign, version or `is_deleted` column of a merging engine, changing which rows survive merges. Reject that like the automatic rematerialization does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
CI failures of the previous run:
The thread about a skip index over a subcolumn being rebuilt from the stale subcolumn stays open. That bug also happens on |
…compact parts On wide parts, `CLEAR COLUMN` of a whole `Nested` group does not remove the stored values (the wide-part branch of `splitAndModifyMutationCommands` only handles real columns, also on master), so the test failed whenever the randomized `min_bytes_for_wide_part` produced wide parts. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=105045&sha=latest&name_0=PR PR: ClickHouse#105045 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pshot `setInsertContextValues` read the destination metadata before `lockForInsert`, and with `enable_shared_storage_snapshot_in_query` that snapshot is cached for the query, so an insert could keep an old expression across an `ALTER` that registered its repair mutation in between. Take the lock first. Snapshots of dependency targets are taken bypassing the query cache, since a `SELECT` of the same query may have cached one before their insert lock was taken. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…inferred `Nested` types
- A `*` or `COLUMNS('regexp')` matcher inside a lambda selecting a column whose name is a parameter
of an enclosing lambda is rejected: the expanded identifier would bind to the parameter.
`COLUMNS(a, b)` keeps resolving in the lambda scope, and leading `EXCEPT` can remove the column.
- The lambda of `APPLY` is a member outside `children`, so the substitution, renaming and
identifier-collection walks now visit it (and keep `lambda_arg` in sync with a renamed parameter).
- Renaming a capturing lambda parameter no longer rewrites the table column names of `EXCEPT`.
- `REPLACE` substitutes only the exact identifier of the column, not a field access `t.a` ending
with its name.
- `MaterializedColumnDependencies` tolerates legacy alias-lambda captures: only their raw inputs are
collected, and only recalculating such a column throws, so an unrelated on-fly mutation read or
`MATERIALIZE TTL` keeps working.
- The legacy-capture comparison in `AlterCommands::validate` skips renames of columns added by the
same `ALTER` (`ADD COLUMN z, RENAME COLUMN z TO w` threw `LOGICAL_ERROR`).
- `CREATE TABLE` revalidates the defaults with matchers against the final flattened schema when a
column type was inferred, since an inferred `Nested` type is flattened only there.
`makeStoredDefaultExpressionList` moved to `ColumnsDescription` for that.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
|
|
🕵 Merged Locally the The one open review thread, about a skip index over a subcolumn ( |
| for (const auto & [index_name, change_description] : getSkipIndicesWithChangedExpression(original_metadata, metadata, context)) | ||
| { | ||
| if (index_mode == AlterColumnSecondaryIndexMode::REBUILD) | ||
| result.push_back(createMaterializeIndexCommand(index_name)); |
There was a problem hiding this comment.
[P1] Disable obsolete index files while their repair is pending
Queuing the repair does not make reads safe after the new metadata is published. AlterConversions::addMutationCommand ignores both MATERIALIZE_INDEX and DROP_INDEX/clear, so MergeTreeDataSelectExecutor::canUseIndex still accepts the existing index files under the new expression.
For example:
CREATE TABLE t
(
src1 UInt64,
al UInt64 ALIAS greatest(COLUMNS('^src')),
INDEX idx al TYPE minmax GRANULARITY 1
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t (src1) VALUES (1);
SYSTEM STOP MERGES t;
ALTER TABLE t ADD COLUMN src2 UInt64 DEFAULT 1000
SETTINGS alter_sync = 0, mutations_sync = 0;
SELECT count() FROM t WHERE al = 1000
SETTINGS force_data_skipping_indices = 'idx';The predicate now means greatest(src1, src2) = 1000, but the old index contains [1,1] and prunes the matching row. Disabling skip indices returns the row. The wait in 04613_index_alias_matcher_dependency_recalculate hides this window; even a synchronous ALTER cannot protect concurrent readers. Track affected indices per part and exclude their old files until the rebuild/clear completes, covering both repair modes.
There was a problem hiding this comment.
🕵 Fixed in de18cb4. Pending MATERIALIZE INDEX and CLEAR INDEX commands are now passed to AlterConversions (counted separately as MutationCounters::num_index). For the parts such a mutation has not reached yet, the index is reported as pending a rebuild. canUseIndex rejects it in index analysis, in the read-time skip index reader, for dynamic indexes and for the TopK minmax index, and the text index is not read directly from such a part. Both repair modes (REBUILD and DROP) are covered, and so are MergeTree and ReplicatedMergeTree.
Note that your ADD COLUMN example already returned 1 before this change: ADD COLUMN produces a READ_COLUMN command with a type, so src2 is in the updated columns of the part and the index was already skipped. The window did reproduce with a changed ALIAS expression (MODIFY COLUMN al ALIAS greatest(COLUMNS('^src')) + 999 while merges are stopped returned 0). Current master returns the same wrong result there for good, because it never rebuilds the index. That case is now covered by 05459_default_expr_matcher_pending_index_rebuild.
There was a problem hiding this comment.
The current code still permits stale-index reads in two paths:
src/Storages/MergeTree/AlterConversions.cpp:253insertscommand.index_name, butcreateClearIndexCommandatsrc/Storages/AlterCommands.cpp:2959and theDROP_INDEXparser atsrc/Storages/MutationCommands.cpp:246put the index name incolumn_name. A pendingCLEAR INDEX idxtherefore marks the empty name, andisIndexPendingRebuild("idx")remains false. The original alias-change repro still prunes its matching row withalter_column_secondary_index_mode = 'drop'while merges are stopped.src/Storages/MergeTree/MergeTreeData.cpp:888and:959include index repairs only underneed_alter_mutations. Snapshot construction at:15554sets that flag fromapply_mutations_on_fly || apply_patch_parts, so setting both to0removes the invalidation marker even forMATERIALIZE INDEX. Applying those settings to the first query in05459_default_expr_matcher_pending_index_rebuildexposes the old minmax files again.
Use the command's actual index-name field for each command type and retain correctness-related index invalidation independently of mutation-on-read settings. Please cover both repair modes and the disabled-settings case.
There was a problem hiding this comment.
🕵 Both points fixed in 2c5a57d:
AlterConversionsnow takes the index name fromcolumn_nameforDROP_INDEXwithclear(both the parsedCLEAR INDEXand the one generated byALTER), and fromindex_nameforMATERIALIZE_INDEX.- Pending index rebuilds are included into the mutations snapshot regardless of
apply_mutations_on_fly/apply_patch_parts(needIncludeMutationToSnapshot,addSupportedCommands, and the early returns ofStorageMergeTree::getMutationsSnapshotandReplicatedMergeTreeQueue::getMutationsSnapshot, which now checknum_index).
05473_default_expr_matcher_review_followups_3 covers both repair modes (rebuild and drop) with the settings at their defaults and with both disabled.
|
|
||
| for (const auto & identifier : identifiers) | ||
| { | ||
| injectRequiredColumnsRecursively( |
There was a problem hiding this comment.
[P2] Materialize missing default inputs before nullable conversion
This recursive helper adds physical leaves, but omits an intermediate input that is itself missing from the part. That is insufficient for conversion defaults: IMergeTreeReader::performRequiredConversions runs before missing-default evaluation and analyzes only its current reader block.
CREATE TABLE t (a UInt8, b Nullable(UInt8))
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (1, NULL);
SYSTEM STOP MERGES t;
ALTER TABLE t ADD COLUMN c UInt8 DEFAULT a + 1;
ALTER TABLE t MODIFY COLUMN b UInt8 DEFAULT toUInt8(COLUMNS('^c$'))
SETTINGS mutations_sync = 0, alter_sync = 0;
SELECT b FROM t;Following c injects a, but not an evaluated c; the conversion expression still references c, so analysis raises UNKNOWN_IDENTIFIER instead of returning 2. The same input boundary loses an existing dependency read by an earlier PREWHERE stage: with a default over a, SELECT b FROM t PREWHERE a = 1 removes a from the post-reader, and conversion receives no previous-stage columns. Supply evaluated missing defaults and earlier-stage inputs to conversion, with focused coverage for both cases.
There was a problem hiding this comment.
🕵 This is not specific to column matchers. It already happens on master without this PR. With a binary built without this PR:
CREATE TABLE t (a UInt8, b Nullable(UInt8)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (1, NULL);
SYSTEM STOP MERGES t;
ALTER TABLE t ADD COLUMN c UInt8 DEFAULT a + 1;
ALTER TABLE t MODIFY COLUMN b UInt8 DEFAULT toUInt8(c) SETTINGS mutations_sync = 0, alter_sync = 0;
SELECT b FROM t; -- UNKNOWN_IDENTIFIER `c`The PREWHERE variant (MODIFY COLUMN b UInt8 DEFAULT a + 1, then SELECT b FROM t PREWHERE a = 1) also fails with UNKNOWN_IDENTIFIER a. The matcher form behaves the same as the explicit-column form. IMergeTreeReader::performRequiredConversions analyzes the conversion default against only the block of the current reader. That needs its own fix in the reader pipeline, separate from this PR, so I am leaving this thread open for it.
…cit list matcher
When a lambda parameter is alpha-renamed to avoid capturing a substituted column,
`COLUMNS(a) EXCEPT a` became `COLUMNS(a_1) EXCEPT a`, so the exclusion no longer matched
the element of the list. The operands of `EXCEPT` of an explicit list name its elements,
so rename them together with the parameter. The operands of `EXCEPT` of a table matcher
(`*`, `COLUMNS('regexp')`) still name table columns and are kept.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d is pending `AlterCommands::getMutationCommands` queues `MATERIALIZE INDEX` (or `CLEAR INDEX`) for a skip index whose effective expression changes, e.g. after `MODIFY COLUMN` of an `ALIAS` column it reads, or after a column matcher expands differently. The new metadata is published before the mutation reaches the parts, so until then a query interpreted the old index files with the new expression and could prune matching granules. Pending `MATERIALIZE INDEX` and `CLEAR INDEX` commands are now passed to `AlterConversions` (counted separately in `MutationCounters::num_index`), which reports the index as pending a rebuild for the parts the mutation has not reached. `canUseIndex` rejects such an index, the text index is not read directly from such a part, and the read-time skip-index paths that have no per-part check are disabled while such a mutation is pending. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts with the new `AlterConversions::getColumnsInvalidatingIndexes` on master are resolved by passing `AlterConversions` to `canUseIndex`, which checks both the indices pending a rebuild and `getColumnsInvalidatingIndexes`. The read-time skip-index paths (`MergeTreeSkipIndexReader`, dynamic indexes and the minmax index for TopK) check each part with `canUseIndex`, so the snapshot-wide gates in `ReadFromMergeTree` are kept as on master: the mutation counters of a snapshot include finished mutations, so gating on them would disable these paths long after a rebuild has finished. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
CI: the only red check was Two threads stay open on purpose. Both describe bugs that also exist on
|
| if (apply->lambda) | ||
| { | ||
| RenameColumnData lambda_data = data; | ||
| if (apply->lambda_arg == data.column_name) |
There was a problem hiding this comment.
[P1] Prevent the renamed column from being captured by an APPLY parameter
This masks a lambda parameter matching the old column name, but does not protect against rename_to matching the parameter. A valid rename silently changes stored values:
CREATE TABLE t
(
a UInt8, b UInt8,
c UInt8 DEFAULT identity(COLUMNS(a) APPLY (x -> x + b))
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t (a, b) VALUES (7, 100);
ALTER TABLE t RENAME COLUMN b TO x;
INSERT INTO t (a, x) VALUES (7, 100);
SELECT c FROM t ORDER BY c;The result is 14, 107: the stored lambda becomes x -> x + x, so subsequent expansion substitutes a for both occurrences. Both rows should compute 107. Alpha-rename parameters that collide with the destination name, keeping lambda_arg synchronized, or reject the rename before publishing metadata.
There was a problem hiding this comment.
🕵 Fixed in 740641a. Before the renamed identifiers are rewritten, a lambda parameter equal to the new name is renamed to a fresh one when the lambda body references the renamed column, and lambda_arg of APPLY is synchronized. This covers both APPLY (x -> x + b) and ordinary lambdas like arrayMap(x -> x + b, ...). After RENAME COLUMN b TO x the stored expression is COLUMNS(a) APPLY x_1 -> (x_1 + x) and your example returns 107, 107. Covered by 05473_default_expr_matcher_review_followups_3.
|
|
||
| for (auto & expanded_column : expanded_columns) | ||
| { | ||
| expandColumnMatchersImpl(expanded_column, columns, lambda_parameters); |
There was a problem hiding this comment.
[P1] Normalize UDF-backed APPLY before validating stored expressions
Function-form APPLY retains its function name as a string, and lambda-form APPLY keeps its lambda outside children, so the DDL UDF-inlining pass misses these calls. This walk subsequently sees an opaque emitted call such as uf(a); the analyzer expands its body after the schema-specific matcher pass.
CREATE FUNCTION uf AS v -> greatest(v, * EXCEPT c);
CREATE TABLE t
(
a UInt8,
y UInt8 ALIAS a + 100,
c UInt8 MATERIALIZED greatest(COLUMNS(a) APPLY uf)
) ENGINE = Memory;
INSERT INTO t (a) VALUES (1);CREATE TABLE succeeds, but the first INSERT throws UNSUPPORTED_METHOD because the UDF's matcher has no table source. With c ALIAS instead, the same row returns 1 or 101 solely according to asterisk_include_alias_columns, bypassing the schema-only expansion invariant. Normalize UDFs exposed by both transformer forms before persisting and validating the expression, then expand their matchers against the defining schema.
There was a problem hiding this comment.
🕵 Fixed in 9d69ad8. In the column and index declarations of CREATE and ALTER, APPLY f with a SQL UDF f is now turned into the lambda form APPLY __apply_argument -> f(__apply_argument), and UDF calls inside APPLY lambdas are inlined, before the expression is validated and persisted. The matchers from the UDF body are then expanded against the defining schema. Your example inserts and returns 1, and the ALIAS variant returns 1 for both values of asterisk_include_alias_columns. SELECT queries keep APPLY f as is, because inlining would change their result column names. Covered by 05473_default_expr_matcher_review_followups_3.
The failpoint `mt_insert_pause_before_commit_part` is server-wide, so `SYSTEM WAIT FAILPOINT` could return for an unrelated `MergeTree` insert, such as a system log flush. The guarded `ALTER` then ran before the test's own `INSERT` held the table share lock, succeeded, and the next `ADD COLUMN` failed with `DUPLICATE_COLUMN`. Wait until the `INSERT` itself is parked at the failpoint (by its stack in `system.stack_trace`), and run it with `async_insert = 0` so that it is the query that pauses. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=105045&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20AsyncInsert%2C%20s3%20storage%2C%20sequential) Co-Authored-By: Claude Opus 5.5 <[email protected]>
… on-the-fly settings `CLEAR INDEX` keeps the index name in `column_name`, not `index_name`, so a pending clear marked an empty name and the old index files were still used. Pending index rebuilds are now also included into the mutations snapshot when `apply_mutations_on_fly` and `apply_patch_parts` are both disabled: they are about correctness of index analysis, not about applying mutations on the fly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…med column `RENAME COLUMN b TO x` turned the stored `APPLY (x -> x + b)` (and `arrayMap(x -> x + b, ...)`) into `x -> x + x`. A lambda parameter with the new name is now renamed first when the body references the renamed column, and `lambda_arg` of `APPLY` is kept in sync. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d index definitions `UserDefinedSQLFunctionVisitor` did not reach `APPLY f` (only the name is kept) nor the lambda of `APPLY (x -> ...)` (not among the children), so a UDF body with a column matcher was expanded only by the analyzer, after the schema-only matcher expansion. In column and index declarations of `CREATE` and `ALTER`, `APPLY f` with a SQL UDF is now turned into the lambda form, and UDF calls in `APPLY` lambdas are inlined. `SELECT` queries are not affected, as inlining would change their result column names. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…default expressions Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed
The two older open threads (skip index over a subcolumn rebuilt from the stale subcolumn, and conversion defaults analyzed against only the current reader block) describe behaviour that is the same on |
…olumn-matcher Resolve the conflict in `AddingDefaultsTransform.cpp`: master replaced the direct required-columns lookup with `getHeaderColumnsReadByDefault`, which walks defaults of columns absent from the header. Keep master's walk, but compute each step's required columns with `getDefaultExpressionRequiredColumns` so column matchers and `ALIAS` references are handled the same way as in default evaluation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I thought it would be nice for text search applications. But it's not realistic for such a tiny feature to have 248 changed files and over 300 review iterations. |
|
Even if we need this feature, the implementation should be ten times simpler. |
This PR closes #92266
Support column matchers in column
DEFAULT,ALIAS,MATERIALIZED, andEPHEMERALexpressions, and in data skipping index expressions. This allows expressions such as*,COLUMNS('...'),COLUMNS(a, b),EXCEPT,APPLY, andREPLACEto be expanded before expression validation and execution.The change also addsnamedTuplefunction to make matcher-expanded named tuple expressions ergonomic in tests and user queries.The tests cover these use cases, direct and indirect cyclic default-expression dependency detection, and nested matcher expansion.
Changelog category:
Changelog entry:
*andCOLUMNSin column default value expressions,DEFAULT,ALIAS,MATERIALIZED, andEPHEMERALexpressions, and in data skipping index expressions.Note
About the newly addednamedTuplefunction: I read the previous discussions in [1], [2], and [3], and my impression is that the existingenable_named_columns_in_function_tuplesetting is not very discoverable. A separate function name may make the intention clearer and the feature easier to use, especially in this use case. It also avoids changing the behavior of the existing tuple function, so it should not introduce compatibility issues. Please let me know if this direction is not desirable.[1] #63524
[2] #54921
[3] #54881
Note
Medium Risk
Touches core expression/DDL validation paths (defaults, aliases, ALTER, mutations, skip indexes), which can affect query planning and error behavior if matcher expansion or cycle detection is incorrect.
Overview
Enables column matchers (e.g.
*,COLUMNS(...)plusEXCEPT/APPLY/REPLACE) inside columnDEFAULT/MATERIALIZED/ALIAS/EPHEMERALexpressions by expanding matchers before validation/execution, honoringasterisk_include_*settings and rejecting qualified matchers.Updates DDL/default validation, alias expansion, read-order optimization, merge/SELECT paths, and mutation/materialize flows to use a shared
cloneAndExpandColumnDefaultExpressionhelper and adds cycle detection that accounts for matcher-expanded dependencies.Extends skip index parsing/analysis to normalize matcher and alias usage (including cyclic-alias detection) before
TreeRewriteranalysis, and adds docs + comprehensive stateless tests covering matcher expansion, errors, and ALTER/mutation/index scenarios.Reviewed by Cursor Bugbot for commit 48ab80f. Bugbot is set up for automated code reviews on this repo. Configure here.
Workflow [PR]
Sync PR [sync-upstream/pr/105045]