Skip to content

Refuse to materialize columns used in sort key expressions - #99647

Open
Onyx2406 wants to merge 77 commits into
ClickHouse:masterfrom
Onyx2406:fix/materialize-column-sort-key-expr
Open

Onyx2406 wants to merge 77 commits into
ClickHouse:masterfrom
Onyx2406:fix/materialize-column-sort-key-expr

Conversation

@Onyx2406

@Onyx2406 Onyx2406 commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category: Bug Fix (user-visible misbehavior in an official stable release)
Changelog entry: Fixed ALTER TABLE ... MATERIALIZE COLUMN for MergeTree tables: 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 dependent MATERIALIZED column — 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

  • Documentation is not required (bug fix)

What this PR does

ALTER TABLE MATERIALIZE COLUMN c2 was allowed when c2 appeared inside a sort key expression like ORDER BY metroHash64(c1, c2), but was correctly blocked for direct sort keys like ORDER 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:

Logical error: 'Sort order of blocks violated for column number 2'

Root cause

The original check only consulted getSortingKeyColumns(), which returns the top-level column names in ORDER BY. For function-based keys like ORDER BY metroHash64(c1, c2), the column names are metroHash64(c1, c2) — not c1 or c2. So the check missed columns used as arguments to sort key functions.

Fix

MATERIALIZE COLUMN now mirrors the protections UPDATE already has, refusing the command (with CANNOT_UPDATE_COLUMN) when the materialized column — or a stored MATERIALIZED column computed from it (one level, matching UPDATE) — is required to evaluate:

  • the table sorting key expression (getColumnsRequiredForSortingKey, subcolumn-aware);
  • the partition key expression;
  • a projection's sorting key expression;
  • the engine merge-semantic column (CollapsingMergeTree sign / ReplacingMergeTree version).

When the command is allowed, a dependent stored MATERIALIZED column 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

  • Stateless test 04046_materialize_column_sort_key_expr.sql covering: 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, dependent MATERIALIZED columns (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).
  • Stateless tests 05137_materialize_column_materialized_over_alias, 05321_materialize_column_merge_semantic_ttl, 05322_materialize_column_ttl_target_derived, 05323_materialize_column_dependency_layers and 05453_materialize_column_independent_column_ttl (independent column TTLs executed by the full TTL pass: projection rebuild on compact and wide parts, is_deleted reset refusal, no refusal for a row TTL on ReplacingMergeTree(ver)).
  • CI (full test suite)

Closes: #93139


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

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
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bdec641]

Summary: ❌

job_name test_name status info comment
La Casa Del Dolor (amd_tsan) FAIL
Logical error: Directory 'A' is virtual (STID: 6611-5f8f) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR protects MATERIALIZE COLUMN from changing key inputs, recomputes dependent MATERIALIZED columns, and rebuilds dependent artifacts and TTL metadata. Reviewing head bdec641cae4e found two remaining Major issues, both reproduced with that head's Fast test binary: safe row-TTL mutations are rejected, and an accepted TTL-recalculation mutation fails on an omitted subcolumn input. Request changes.

Findings

⚠️ Majors

  • src/Interpreters/MutationsInterpreter.cpp:2005,2034: Row filtering is mistaken for column resets. A row TTL marks every physical column as TTL_TARGET. With id UInt64, c DateTime MATERIALIZED toDateTime(2000000000), INDEX ix (id + 1) TYPE minmax, and table TTL c + INTERVAL 1 DAY, MATERIALIZE COLUMN c throws CANNOT_UPDATE_COLUMN, claiming the TTL resets id, although there is no column TTL. An unrelated tuple-subcolumn index is also incorrectly refused. The equivalent MATERIALIZE TTL succeeds and its forced-index query returns the row. Restrict both index refusals to actual column_ttl_targets, retaining row-TTL targets for streaming and rebuilds; add focused regressions for both index shapes.

  • src/Interpreters/MutationsInterpreter.cpp:244–246,2568: TTL recalculation still omits independent subcolumn inputs. getColumnsRequiredToRecalculateTTL discards d.ts through hasPhysical, so a wide table with d Tuple(ts DateTime), y UInt64 TTL d.ts + INTERVAL 1 SECOND, and a recompression TTL over materialized c accepts MATERIALIZE COLUMN c but fails in the background with UNFINISHED: TTL_CALC cannot find d.ts in a block containing only c. The whole-column control succeeds. Resolve these dependencies to physical storage parents or preserve readable subcolumns, and add a wide-part regression. This is the remaining subcolumn case of the existing TTL-input finding.

Final Verdict

Status: ⚠️ Request changes

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.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 16, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

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.

@PedroTadim

Copy link
Copy Markdown
Member

Hello! Can this PR be merged soon?

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label May 21, 2026
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.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 7ccb1df. Configure here.

alexey-milovidov and others added 2 commits May 24, 2026 18:07
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]>
alexey-milovidov and others added 4 commits May 30, 2026 02:00
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master into the branch (8bd97b7bc9a..306eb1dee3e) to refresh on a clean base and re-trigger CI. No conflicts; the net diff versus master is unchanged (only MutationsInterpreter.cpp plus the 04046_materialize_column_sort_key_expr test).

All four review threads are resolved and the code/test are intact:

  • direct sort-key column, function-expression sort key (ORDER BY metroHash64(c1, c2)), and the subcolumn-parent case (ORDER BY t.k while materializing t) are all refused via getColumnsRequiredForSortingKey + the getColumnOrSubcolumn/getNameInStorage check mirroring validateUpdateColumns;
  • a non-sort-key column still materializes successfully.

The only CI failure was Upgrade check (amd_release) → Error message in clickhouse-server.log, caused by StorageKafka2 ... Exception during get topic partitions from Kafka: Local: Broker transport failure. This is unrelated to this PR (which does not touch Kafka). CIDB confirms it is a widespread environment flaky: the same Broker transport failure upgrade-check failure hit 33 distinct PRs in the last 14 days, with a sharp spike starting 2026-06-02 (8 on 06-02, 18 on 06-03, 12 on 06-04).

@groeneai, could you investigate this Upgrade check flaky (StorageKafka2 Broker transport failure flagged in upgrade_error_messages.txt, recent spike since 2026-06-02) and provide a fix in a separate PR? If a fix is already in progress, please link it here.

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov filed separate PR #106516 for the Upgrade check (amd_release) StorageKafka2 ... Local: Broker transport failure flake.

Root cause (CIDB-confirmed, 38 distinct PRs in 14d, 0 master, 100% on Upgrade check (amd_release), 100% involve 03923_kafka2_keeper_offsets; pattern visible since 2026-03-05): the KafkaConsumer2::getAllTopicPartitionOffsets background poll loop (KeeperHandlingConsumer.cpp:174) keeps polling Kafka metadata while Redpanda is in transition during the upgrade restart, cppkafka raises HandleException("Local: Broker transport failure"), and KafkaConsumer2.cpp:317 logs it as <Error>. The existing [rdk:FAIL]-prefix allowlist filter only matches raw librdkafka tagged log lines, which is a different shape; this wrapper-exception variant was unfiltered.

Fix: narrow regex in tests/docker_scripts/upgrade_runner.sh requiring BOTH StorageKafka2 engine context AND Broker transport failure symptom together (mirrors existing rdk:FAIL.*Connect to.*failed: Connection refused filter). Real StorageKafka2 regressions (auth, timeouts, other broker errors) still surface.

pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Jun 6, 2026
…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]>
alexey-milovidov and others added 2 commits October 4, 2026 08:50
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]>
alexey-milovidov and others added 2 commits October 12, 2026 02:10
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The AST fuzzer (amd_debug, targeted) failure (Sort order of blocks violated, https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99647&sha=eb6d533c1e0bf77d635d231d0bddeb1e229085f8&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29) is not caused by this PR. The server log shows it comes from the existing 03263_forbid_materialize_sort_key scenario: ADD COLUMN b Float64, MODIFY ORDER BY (a, b), then MODIFY COLUMN b DEFAULT rand64() % 100000, then a regular merge of parts written before b existed. No mutation ran on that table. The same failure shows up on many unrelated PRs, and the fix is in progress in #124234. I also merged the latest master into this branch.

alexey-milovidov and others added 2 commits October 19, 2026 23:08
…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]>
alexey-milovidov and others added 2 commits October 27, 2026 07:32
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @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 (Logical error: Coordination mode mismatch for stream ...: got Default, expected WithOrder, STID 6117-726a, in ParallelReplicasReadingCoordinator::getOrCreateCoordinator) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR: it also happens on master (Stress test (amd_debug), 2026-10-15 and 2026-10-23), and the earlier issue #106039 is closed.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the row-policy route again: with serialize_query_plan = 1 the row policy is applied only on the initiator, so the initiator and the replicas plan different reads (#112891). The fix in progress is #114955 (mine, open).

From this run (tree a7dc613cccfa, query b5941d47): the aborted query is SELECT id, department FROM t_mt_index_rp ORDER BY id from 04891_mergetree_index_respects_row_policy.sql (table ORDER BY (department, id)), with parallel replicas and the local plan. The AST fuzzer had replaced the test's policy with department = '257', which matches no row.

  • Initiator: Key condition: (column 0 in ['257', '257']), 0 marks to read. department is fixed, so ORDER BY id follows the sorting key and the coordinator is created as WithOrder.
  • Replica (77bb7d71), deserialized plan without the policy: Key condition: unknown, 4 marks, default reading, so it announces Default and getOrCreateCoordinator throws.

Both master runs you mention are the same mechanism. 2026-10-15 is the same 04891 query. 2026-10-23 is 4060_row_policy_projection_not_found_column.sql with the policy fuzzed to tenant = toLowCardinality('testtesttesttest'): the initiator selected 0/1 parts by partition key and registered WithOrder, the replicas (no policy) selected 1/1 parts and the aggregate projection, and announced Default.

#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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 2 commits November 4, 2026 06:13
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed b5205f12d3c7..7fcf0fd74ff2: merged current master (clean) and addressed the three open review threads (row-TTL promotion to all physical columns and feeding DEFAULT inputs of column-TTL targets for the full TTL pass; the TTL-recalculation case is covered by master), with a new wide-part test 05497_materialize_column_ttl_wide_part_inputs. The PR tests pass locally.

Remaining red on the previous head is unrelated: Stress test (arm_asan_ubsan, s3) fails with Cannot write to canceled buffer in the client (ClientBase::runInteractive), tracked in #125973 with the fix in progress in #126142; Build profile diff failed on infrastructure (LogClusterNotReady).

alexey-milovidov and others added 2 commits November 12, 2026 00:15
…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]>
alexey-milovidov and others added 2 commits November 20, 2026 18:30
…` 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed ca59868b496e..bdec641cae4e: merged current master (clean) and addressed the open review thread — MATERIALIZE COLUMN is now refused when the TTL pass would reset a column to a DEFAULT expression reading an EPHEMERAL column, with a new test 05839_materialize_column_ttl_default_ephemeral. All PR tests pass locally on the merged tree.

{
for (const auto & required_column : index.expression->getRequiredColumns())
{
if (std::ranges::find(ttl_target_columns, required_column) != ttl_target_columns.end())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: 'Sort order of blocks violated for column with materialized column

6 participants