Repository navigation
Conversation
Previously, `ALTER TABLE MATERIALIZE COLUMN` only blocked columns that were directly listed in `ORDER BY`. Columns used inside sort key function expressions (e.g., `ORDER BY metroHash64(c1, c2)`) were not checked, allowing materialization to recalculate their values and break the sort order of existing data parts. Now checks both `getSortingKeyColumns` (direct columns) and `getSortingKey().expression->getRequiredColumns` (columns used in sort key expressions). Fixes ClickHouse#93139
|
Workflow [PR], commit [bdec641] Summary: ❌
AI ReviewSummaryThe PR protects Findings
Final VerdictStatus: Distinguish row-TTL rewrite targets from column resets in the index guards, supply independent TTL subcolumn inputs during recalculation, and cover both cases with stateless regressions. |
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
|
Hello! Can this PR be merged soon? |
…umn-sort-key-expr
Workflow files in this branch were stale or had been deleted as a workaround for GitHub's workflow-scope check. Restoring them to match `master` so the PR diff no longer contains those unrelated changes.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 7ccb1df. Configure here.
Address Cursor Bugbot finding (low severity) by using `metadata_snapshot->getColumnsRequiredForSortingKey` and `metadata_snapshot->getSortingKeyColumns` instead of directly dereferencing `sorting_key.expression`. Both helpers internally check `hasSortingKey` and return an empty `Names` when no sorting key is set, eliminating the theoretical null pointer dereference on a default-constructed `KeyDescription`. This also matches the existing pattern at line 505 of the same file. No functional change.
This bug fix should only touch `MutationsInterpreter.cpp` and the new test. Restore `.github/PULL_REQUEST_TEMPLATE.md` and `.github/dependabot.yaml` to match `master` — these diffs were unrelated scope creep left over from an imperfect `.github/` restore on the fork branch and would otherwise be merged into `master`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ort key The guard added for `MATERIALIZE COLUMN` compared exact names from `getColumnsRequiredForSortingKey` with the target column. Sorting-key dependencies can be subcolumns: for a table like `t Tuple(k UInt64, v UInt64) MATERIALIZED (rand64(), a) ORDER BY t.k`, `getColumnsRequiredForSortingKey` returns `t.k`, but `ALTER TABLE ... MATERIALIZE COLUMN t` targets `t`. The exact-name check missed this, so materializing the parent was still allowed and could invalidate the sort order of existing parts. Resolve each sorting-key dependency with `getColumnOrSubcolumn` and compare `getNameInStorage` against the materialized column, mirroring the subcolumn-parent check already done in `validateUpdateColumns` for `UPDATE`. Adds a regression test materializing a parent whose subcolumn is in `ORDER BY`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…umn-sort-key-expr
…umn-sort-key-expr
…umn-sort-key-expr
|
Merged the latest All four review threads are resolved and the code/test are intact:
The only CI failure was @groeneai, could you investigate this |
|
@alexey-milovidov filed separate PR #106516 for the Root cause (CIDB-confirmed, 38 distinct PRs in 14d, 0 master, 100% on Fix: narrow regex in |
…down noise The upgrade-check post-restart `<Error>` scrub catches a chronic shutdown-time log line emitted by `StorageKafka2`'s background `KafkaConsumer2::getAllTopicPartitionOffsets` poll loop when the Redpanda broker is in transition during the upgrade restart sequence: ``` <Error> StorageKafka2 (test_X.`03923_kafka2_keeper_offsets_test_X_kafka` (uuid)): Exception during get topic partitions from Kafka: Local: Broker transport failure ``` The line is produced by `LOG_ERROR` at `KafkaConsumer2.cpp:317` from the `cppkafka::HandleException` catch branch; the only call site is the background poll path in `KeeperHandlingConsumer.cpp:174`. The existing `[rdk:FAIL]`-prefix allowlist filter only matches raw librdkafka tagged log lines and does not cover this wrapper-exception variant. CIDB confirms this is widespread chronic noise, not a code regression: 38 hits across 38 distinct PRs in the last 14 days (8 / 16 / 14 on 2026-06-02 / 06-03 / 06-04), 0 master, 100% on `Upgrade check (amd_release)`, 100% involve `03923_kafka2_keeper_offsets`. The pattern has been visible since 2026-03-05 (test added 2026-02-15). Reported by @ alexey-milovidov on PR ClickHouse#99647 (recent spike since 2026-06-02). The added regex requires BOTH the `StorageKafka2` engine context AND the `Broker transport failure` symptom together, mirroring the narrowing approach used by the existing `rdk:FAIL.*Connect to.*failed: Connection refused` filter. Real `StorageKafka2` regressions (authentication failures, timeouts, protocol errors, other broker errors raised in this same code path) still surface. Related: ClickHouse#99647 Related: ClickHouse#101576 Co-Authored-By: Claude Opus 4.8 <[email protected]>
`MATERIALIZE COLUMN` recalculates a column's values, which invalidates the sort order of any data sorted by it. The previous fix only guarded the base table's sorting key, but a column can also be used in the `ORDER BY` of a projection (e.g. `PROJECTION p (SELECT * ORDER BY metroHash64(c2))`). `MATERIALIZE COLUMN` does not add the column to the set of updated columns, so the projection is hardlinked rather than rebuilt. If the materialized column is required by the projection's sorting key, the already-materialized projection parts would keep their stale sort order while the base column changes underneath them, leaving queries reading inconsistent or wrongly-ordered projection data. Refactor the sorting-key check into a helper that also runs over every projection's metadata, and reject the mutation when the column is required by a projection's sorting key. Extend the regression test with a projection case. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The test grew to 49 cases and exceeded the 180 s limit in the flaky check (ASan, S3 storage, metadata in Keeper) of the `CH Inc sync` job: "Test runs too long (> 180s). Make it faster." Cases 1-16 stay in `04046_materialize_column_sort_key_expr`; cases 17-28, 29-41 and 42-49 move unchanged to `05321_materialize_column_merge_semantic_ttl`, `05322_materialize_column_ttl_target_derived` and `05323_materialize_column_dependency_layers`. The concatenated references are identical to the original one. ClickHouse/clickhouse-private#52628 ClickHouse#99647 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…umn-sort-key-expr
…TERIALIZED` column A stored `MATERIALIZED` column that also reads an `EPHEMERAL` column is kept out of `materialized_column_dependencies`, so the fail-close check for a TTL-driven reset in `MATERIALIZE COLUMN` did not see it: with `y TTL c + ...`, `e ... EPHEMERAL` and `m MATERIALIZED y + e`, `MATERIALIZE COLUMN c` reset `y` and left `m` stale without an error or a warning. Check `ephemeral_reading_materialized` in the same guard. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The |
…reading `MATERIALIZED` column feeds a key A stored `MATERIALIZED` column that also reads an `EPHEMERAL` column is kept out of `column_to_affected_materialized` and is never recomputed by a mutation. If it reads the materialized column (directly or through a recomputed `MATERIALIZED` hop) and feeds the sorting key, the partition key, a projection sorting key or the engine sign/version/is_deleted column, the key would keep stale values. Run the same key checks over such columns. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…umn-sort-key-expr
…OLUMN` When `MATERIALIZE COLUMN` makes the mutation run the full TTL pass (`ExecuteTTLType::NORMAL`), `TTLTransform` executes every column TTL of the table whose target is in the block, not only those reached through the rewritten columns. On a compact part an independent expired column TTL thus reset its target, while a projection reading that target was hardlinked with stale values, and the merge-semantic guard did not see the reset of e.g. the `is_deleted` column. Now every column TTL target is streamed together with its TTL inputs whenever the full TTL pass runs, so the result does not depend on the part format and the generic derived-object scan rebuilds the projections, skip indices and statistics reading it. The merge-semantic guard now checks the columns that actually have a column TTL; a row TTL, which only deletes rows, no longer makes it refuse materializing a column of a `ReplacingMergeTree(ver)` table. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99647&sha=afa33aa0a1ee41ffafcde1aa125aba0d76bd7d5d&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29 ( |
|
This is the row-policy route again: with From this run (tree
Both master runs you mention are the same mechanism. 2026-10-15 is the same 04891 query. 2026-10-23 is #114955 is still a draft (converted by its assignee on 2026-10-16) and conflicts with master. |
| { | ||
| if (dependency.kind == ColumnDependency::TTL_EXPRESSION | ||
| || dependency.kind == ColumnDependency::TTL_TARGET) | ||
| dependencies.insert(dependency); |
There was a problem hiding this comment.
[P2] Supply every TTL expression input for the recalculation pass
This only collects TTL dependencies reachable from rewritten_columns, but any TTL_EXPRESSION enables TTLCalcTransform, which evaluates all TTL rules in the metadata. When no TTL_TARGET is found, the expansion below never runs, so unrelated TTL inputs are absent on wide parts.
Reproduced with a wide MergeTree sorted by id, columns (id UInt64, c DateTime MATERIALIZED toDateTime(2000000000), d DateTime, y UInt64 TTL d + INTERVAL 1 SECOND), and table TTL c + INTERVAL 1 DAY RECOMPRESS CODEC(LZ4). After inserting (id, d, y) = (1, toDateTime(2000000000), 100) and changing c's expression to toDateTime(2000000010), MATERIALIZE COLUMN c SETTINGS mutations_sync = 2 fails with NOT_FOUND_COLUMN_IN_BLOCK: d is missing, only c is available, While executing TTL_CALC. The compact-part control succeeds.
Once TTL recalculation is requested, feed the expression/condition inputs of every TTL algorithm that will run, as the MATERIALIZE TTL path does, rather than only the rules depending on the rewritten column. Please add a wide-part regression combining a recompression TTL and an independent column TTL.
There was a problem hiding this comment.
🕵 This is now covered by the generic fix from master (a08f418, "Read the inputs of all TTL rules when a mutation recalculates TTL infos"), merged into this branch: when there is a TTL_EXPRESSION but no TTL_TARGET, getColumnsRequiredToRecalculateTTL feeds the inputs of every TTL rule. I added your wide-part recompression + independent column TTL reproducer to 05497_materialize_column_ttl_wide_part_inputs; it passes.
There was a problem hiding this comment.
[Major] The full-column case is fixed, but the same missing-input failure remains when an independent TTL reads a subcolumn. At src/Interpreters/MutationsInterpreter.cpp:244-246, getColumnsRequiredToRecalculateTTL drops d.ts because columns.hasPhysical("d.ts") is false; the later call at line 2568 therefore still supplies only c.
Reproduced with the Fast test binary for bdec641cae4e:
CREATE TABLE t
(
id UInt64,
c DateTime MATERIALIZED toDateTime(2000000000),
d Tuple(ts DateTime),
y UInt64 TTL d.ts + INTERVAL 1 SECOND
)
ENGINE = MergeTree ORDER BY id
TTL c + INTERVAL 1 DAY RECOMPRESS CODEC(LZ4)
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
SYSTEM STOP TTL MERGES t;
INSERT INTO t (id, d, y) SELECT 1, tuple(toDateTime(2000000000)), 100;
ALTER TABLE t MODIFY COLUMN c DateTime MATERIALIZED toDateTime(2000000010);
ALTER TABLE t MATERIALIZE COLUMN c SETTINGS mutations_sync = 2;The accepted mutation fails with UNFINISHED: TTL_CALC cannot find d.ts and reports that the block contains only c. The control using a whole DateTime column succeeds. Resolve TTL inputs to their physical storage parents (or retain readable subcolumns) in the helper, and cover this wide-part variant before treating the all-inputs fix as complete.
…MATERIALIZE COLUMN` When `MATERIALIZE COLUMN` makes the mutation run the full TTL pass (a column TTL reads a rewritten column), `TTLTransform` also executes the table's row TTLs and resets expired column-TTL targets to their `DEFAULT` expression. On a wide part only the streamed columns were in the block, so a row TTL deleted rows from the rewritten columns only (inconsistent part), and a reset failed with `NOT_FOUND_COLUMN_IN_BLOCK` when the `DEFAULT` read another column. Promote the mutation to rewriting every physical column when the table has a row / rows-where / group-by TTL (as `MATERIALIZE TTL` and the direct row-TTL dependency already do), and feed the inputs of the `DEFAULT` expression of every column-TTL target. The TTL recalculation case without a TTL target is already covered by `getColumnsRequiredToRecalculateTTL` from `master`; the new test covers it too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed Remaining red on the previous head is unrelated: |
…and `ALIAS` in TTL defaults - Match column-TTL targets against the sign/version/is_deleted columns subcolumn-aware, so a column TTL on the parent of e.g. `flags.del` refuses `MATERIALIZE COLUMN` instead of resurrecting deleted rows. - Feed the inputs of the independent move and recompression TTLs to the full TTL pass, so a wide part does not fail with `NOT_FOUND_COLUMN_IN_BLOCK`. - Expand `ALIAS` columns in the `DEFAULT` expression of a TTL target, both when collecting its inputs in `MutationsInterpreter` and when `TTLTransform` builds the reset expression. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…` reads an `EPHEMERAL` column The full TTL pass resets an expired column TTL target to its `DEFAULT` expression. An `EPHEMERAL` input of that expression is not stored, so `TTLTransform` could not evaluate it and the queued mutation never finished (`NOT_FOUND_COLUMN_IN_BLOCK`). The command is now refused during validation with `CANNOT_UPDATE_COLUMN`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Pushed |
| { | ||
| for (const auto & required_column : index.expression->getRequiredColumns()) | ||
| { | ||
| if (std::ranges::find(ttl_target_columns, required_column) != ttl_target_columns.end()) |
There was a problem hiding this comment.
[Major] Keep row-TTL rewrite targets out of the column-reset index refusals
ttl_target_columns includes every physical column when a row TTL needs recalculation, even though that TTL only filters rows. Consequently this check rejects safe materialization whenever a computed skip index reads any column:
CREATE TABLE t
(
id UInt64,
c DateTime MATERIALIZED toDateTime(2000000000),
INDEX ix (id + 1) TYPE minmax GRANULARITY 1
)
ENGINE = MergeTree ORDER BY id TTL c + INTERVAL 1 DAY
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO t (id) VALUES (1);
ALTER TABLE t MATERIALIZE COLUMN c SETTINGS mutations_sync = 2;Reproduced with this head's Fast test binary: CANNOT_UPDATE_COLUMN claims the TTL resets id, although this table has no column TTL. The equivalent MATERIALIZE TTL succeeds and its forced-index query returns the row. An index on an unrelated tuple subcolumn is incorrectly rejected by the preceding guard too.
Please use actual column-reset targets (column_ttl_targets, as the engine-column guard already does) for both index refusals, while retaining row-TTL targets for streaming/rebuilds. Add a row-TTL regression with computed and subcolumn indexes.

Changelog category: Bug Fix (user-visible misbehavior in an official stable release)
Changelog entry: Fixed
ALTER TABLE ... MATERIALIZE COLUMNforMergeTreetables: materializing a column required by a key expression (sorting key, partition key, projection sorting key, or the engine sign/version column) — directly or via a dependentMATERIALIZEDcolumn — is now refused instead of silently corrupting the sort order / partition assignment of existing parts. Dependent skip indices, projections, statistics and TTL bounds that read a recomputed column are rebuilt instead of being hardlinked with stale values.Documentation entry for user-facing changes
What this PR does
ALTER TABLE MATERIALIZE COLUMN c2was allowed whenc2appeared inside a sort key expression likeORDER BY metroHash64(c1, c2), but was correctly blocked for direct sort keys likeORDER BY c2. Materializing such a column recalculates its values (e.g.,MATERIALIZED now()produces new timestamps), which invalidates the sort order of existing data parts. Subsequent merges or deletes then fail with:Root cause
The original check only consulted
getSortingKeyColumns(), which returns the top-level column names inORDER BY. For function-based keys likeORDER BY metroHash64(c1, c2), the column names aremetroHash64(c1, c2)— notc1orc2. So the check missed columns used as arguments to sort key functions.Fix
MATERIALIZE COLUMNnow mirrors the protectionsUPDATEalready has, refusing the command (withCANNOT_UPDATE_COLUMN) when the materialized column — or a storedMATERIALIZEDcolumn computed from it (one level, matchingUPDATE) — is required to evaluate:getColumnsRequiredForSortingKey, subcolumn-aware);CollapsingMergeTreesign /ReplacingMergeTreeversion).When the command is allowed, a dependent stored
MATERIALIZEDcolumn is recomputed in an extra mutation stage, and any skip index / projection / statistics / TTL expression that reads a rewritten column is fed into the mutation stream so the derived object is rebuilt instead of hardlinked with stale values.Test plan
04046_materialize_column_sort_key_expr.sqlcovering: direct sort key column, sort-key function expression, subcolumn-parent sort key, projection sorting key, partition key (and subcolumn-parent partition key), skip-index/projection/statistics rebuild, dependentMATERIALIZEDcolumns (recompute and key-feeding refusal), TTL recalculation, and the engine sign/version columns. A column not used in any key still materializes successfully (no over-rejection).05137_materialize_column_materialized_over_alias,05321_materialize_column_merge_semantic_ttl,05322_materialize_column_ttl_target_derived,05323_materialize_column_dependency_layersand05453_materialize_column_independent_column_ttl(independent column TTLs executed by the full TTL pass: projection rebuild on compact and wide parts,is_deletedreset refusal, no refusal for a row TTL onReplacingMergeTree(ver)).Closes: #93139
Workflow [PR]
Sync PR [sync-upstream/pr/99647]