Skip to content

Fix sort order violation for TTL GROUP BY SET on a column the sorting key depends on - #108550

Closed
groeneai wants to merge 84 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ttl-group-by-set-sort-key-resort
Closed

groeneai wants to merge 84 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ttl-group-by-set-sort-key-resort

Conversation

@groeneai

@groeneai groeneai commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #108514
Related: #119863

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed wrong results and a Sort order of blocks violated logical error (a corrupt part in a release build) for MergeTree tables whose TTL ... GROUP BY ... SET assigns a column the sorting key depends on, either directly or through a sorting-key expression such as toStartOfDay(ts). The aggregated rows are now re-sorted and the sorting-key expressions recomputed from the assigned values before the part is written, both during a merge and during ALTER TABLE ... MATERIALIZE TTL. The new ttl_resort_max_bytes_before_external_sort MergeTree setting (default 256 MiB, 0 disables spilling to disk) bounds that sort. Tables with more than one GROUP BY TTL keep the previous behavior and are not repaired.

Description

What breaks. TTLAggregationAlgorithm emits aggregated groups in input order, nothing re-derives
the sorting key after the SET, and the part writer takes the primary-key columns from that same
block by name. Two shapes: a directly assigned sort-key column (SET k = max(v)) leaves the data
unsorted, so a debug build aborts and a release build writes a corrupt part. A column a sorting-key
expression only reads (ORDER BY (k, toStartOfDay(ts)) with
SET ts) hides instead: MergeTask materializes that expression before the TTL step, so it keeps
its pre-SET value, stays ascending and is copied into the index. That index describes a day the data
no longer holds, so a key-range read misses rows (on master: 0 of 9) and the next merge, which
recomputes it from the stored ts, aborts.

Fix. After the TTL step, when a GROUP BY ... SET that can fire assigns a
sorting-key storage dependency, recompute the sorting-key expressions from the assigned values and
re-sort, on the merge path and on the MATERIALIZE TTL path; the new setting bounds that sort, since
background contexts disable external sorting.

A part with several GROUP BY TTLs is left as master writes it: an earlier SET can rewrite a column
a later clause groups by, and re-sorting would only hide the wrong groups.

Not fixed here, pre-existing on master: a subcolumn skip index is hardlinked unchanged by
MATERIALIZE TTL. A MATERIALIZED sorting-key column needs no repair: it is written from the value
the aggregation produced, so it agrees with its index.


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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE ... ORDER BY (k, toStartOfDay(ts)) TTL ... GROUP BY k, toStartOfDay(ts) SET ts = max(ts)+interval 100 years, k = max(v), two single-row inserts in different days, then OPTIMIZE TABLE ... FINAL aborts every time. Reproduced on the unfixed master snapshot (26.7.1.1) and the pre-edit worktree binary; 30/30 deterministic.
b Root cause explained? TTLAggregationAlgorithm::finalizeAggregates emits aggregated groups in input (already-sorted) order. The SET rewrites a sort-key column (k, and ts feeding toStartOfDay(ts)), so the produced stream is no longer ordered by the sorting key. The merge writer reads PK columns by name (incl. the materialized toStartOfDay(ts), still holding its pre-SET value) and writes without re-sorting → part with a primary index inconsistent with the data. Debug CheckSortedTransform aborts; release writes silently.
c Fix matches root cause? Yes. After the TTL step, when a GROUP BY TTL assigns a sorting-key dependency column, the sort-key expression columns are recomputed from the post-SET values and the stream is re-sorted by the sorting key — directly fixing the unsorted output and the stale materialized sort-key column. Not a band-aid (no widened bounds, no tag, no data reduction).
d Test intent preserved / new tests added? Yes. Existing 03545_number_of_rows_in_ttltransform (which intentionally exercises SET on sort-key columns) passes unchanged. New 04327_ttl_group_by_set_sort_key_resort asserts both correct results and that the part is physically sorted by the sorting key.
e Both directions demonstrated? Yes. Unfixed master snapshot: aborts with Sort order of blocks violated for column number 0, left: Float64_96827, right: Float64_41302. Fixed binary (Build ID verified, differs from pre-edit): passes, part physically sorted, 30/30.
f Fix is general across code paths? Yes. GROUP BY TTL forces the Horizontal merge algorithm (canVerticalTTLDelete returns false on hasAnyGroupByTTL), so the single-stream merge pipeline is the only affected path; the re-sort is placed there. The fix targets the produced-unsorted-stream root cause, not a single crash site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified with Float64, String, LowCardinality(String) and Nullable(Float64) sort keys, monotonic vs non-monotonic SET, SET on the first vs a deeper sort column. Control case (SET only a non-sort-key column) confirmed to be a no-op (gate does not fire). Float64/String/LowCardinality variants are in the regression test.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default, on-disk/wire format, or validation change. Behaviour only changes for the previously-broken case (it now produces a correctly sorted part instead of aborting / corrupting); the already-correct case is byte-for-byte unchanged (03545 reference unchanged).
i Invariants and contracts preserved? Yes. The fix restores the MergeTree invariant the writer relies on: the stream handed to the writer is sorted by the sorting key and the materialized sort-key expression column is consistent with the storage columns. The re-sort step is gated and only adds a recompute+sort; it does not alter the merge/aggregation semantics, row counts, or the TTL result values.

Session id: cron:clickhouse-worker-slot-4:20260625-200200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai — could you review this? It fixes a sort-order violation (silent primary-index corruption in release, LOGICAL_ERROR abort in debug) when a TTL ... GROUP BY ... SET clause assigns a sorting-key column: TTLAggregationAlgorithm emits groups in input order, so the merge writes an unsorted part. The fix recomputes the sort-key expression from the post-SET values and re-sorts the TTL merge output, gated so it is a no-op for all other merges. Closes #108514.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fa3f597]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR narrows the fix to the reduced scope requested in discussion: it detects firing TTL ... GROUP BY ... SET clauses that rewrite sorting-key storage dependencies, recomputes the sorting-key expressions from the post-SET values, re-sorts both the merge and MATERIALIZE TTL paths, and bounds that maintenance sort with ttl_resort_max_bytes_before_external_sort. On the current head, I did not find an unresolved correctness or contract violation inside that reduced scope.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit fa3f597.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 202/205 (98.54%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 25, 2026
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in e779631.

The gate now maps each sorting-key dependency to its storage column via getColumnNameInStorage before comparing with set_part.column_name, the same way extractMergingAndGatheringColumns does. So ORDER BY t.a + SET t = ... now resolves t.a -> t and the gate fires.

One more place needed the same treatment: the re-sort step built createSubcolumnsExtractionActions from the current header, which still holds the stale materialized t.a. The extractor saw t.a as available and skipped re-extraction, so the re-sort would have keyed on the pre-SET value. The step now hides the stale computed sort-key columns from the extractor's input header, so t.a is recomputed from the post-SET physical t.

Validated both directions on a debug build: ORDER BY t.a TTL ... GROUP BY t.a SET t = argMax(candidate, v) fails before the change (NOT_FOUND_COLUMN_IN_BLOCK for t.a in createMergedStream) and produces a correctly sorted part after it. Added a Tuple subcolumn case to 04327_ttl_group_by_set_sort_key_resort; a JSON subcolumn sort key was verified manually. 03545_number_of_rows_in_ttltransform still passes unchanged.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e779631

Every failed check below has an owner (a fixing PR). Mergeable Check / PR are aggregators that only reflect the rows below.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Hung check failed, possible deadlock found deadlock, chronic shutdown/teardown family (not PR-caused) #101680 / #105905 (ours, open)
Stress test (arm_debug) / Logical error 'Unexpected exception in refresh scheduling' (STID 2508-34af) RefreshTask shutdown crash (trunk bug); the Cannot-start-server and Check-failed rows on this lane are collateral of the same abort #105588 (ours, open)

Not PR-caused: this PR only changes src/Storages/MergeTree/MergeTask.cpp plus a TTL regression test; both failures are pre-existing chronic stress-test issues unrelated to the TTL merge re-sort.

Session id: cron:our-pr-ci-monitor:20260626-033000

@cv4g cv4g self-assigned this Jun 30, 2026
@cv4g

cv4g commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

@groeneai This fixes the MergeTask path at src/Storages/MergeTree/MergeTask.cpp:3208, but the same issue looks reachable via MATERIALIZE TTL in MutateTask (src/Storages/MergeTree/MutateTask.cpp lines 2171 and 2484) and possibly between multiple GROUP BY TTL algorithms executed by one TTLTransform (src/Processors/Transforms/TTLTransform.cpp lines 88 and 190). Should this PR cover these as well?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@cv4g Good catch on MutateTask / MATERIALIZE TTL. Confirmed reachable and fixed in bcd95db.

MutateTask (MATERIALIZE TTL): yes, fixed. A MATERIALIZE TTL mutation with a GROUP BY TTL goes through MutateAllPartColumnsTask (the GROUP BY forces isAffectingAllColumns()), which materializes the sorting-key expression before the TTLTransform (MutateTask.cpp:2154) and writes via MergedBlockOutputStream with rewrite_primary_key=true, rebuilding the index from the stream. The CheckSortedTransform added in MutationsInterpreter::execute() sits before the appended TTLTransform, so it never sees the post-SET order; nothing else guards it. So unlike the merge path, even a debug build does not abort here, it silently writes a corrupt part.

Reproduced on this branch (with the merge fix already in) using a single level-0 part so the mutation, not a background merge, applies the TTL:

CREATE TABLE t (k Float64, ts DateTime, v Float64)
ENGINE = MergeTree ORDER BY (k, toStartOfDay(ts))
TTL ts + toIntervalDay(1) GROUP BY k, toStartOfDay(ts)
    SET ts = max(ts) + interval 100 years, k = max(v)
SETTINGS min_bytes_for_full_part_storage = 128, materialize_ttl_recalculate_only = 0;
SYSTEM STOP TTL MERGES t;
INSERT INTO t VALUES (1.0, '2000-06-09 10:00', 96827), (1.0, '2000-06-10 10:00', 41302);
ALTER TABLE t MATERIALIZE TTL SETTINGS mutations_sync = 2;
-- before bcd95db: physical read order is k = 96827, 41302 (descending) -> corrupt index
-- after  bcd95db: k = 41302, 96827 (ascending) -> sorted

The fix extracts the gate and the recompute-and-resort into TTLResortUtils (shared by both paths) and applies it after the TTL step in MutateAllPartColumnsTask, mirroring the merge path. MutateSomePartColumnsTask is not affected: a GROUP BY TTL never routes there, and it writes via MergedColumnOnlyOutputStream with rewrite_primary_key=false (reuses the source index). Added MATERIALIZE TTL regressions to 04327 for a plain Float64 key and a Tuple subcolumn key.

Multiple GROUP BY TTL algorithms in one TTLTransform (TTLTransform.cpp:88/190): not a separate gap. The re-sort runs after the whole TTL step (the complete TTLTransform), so it covers the final stream regardless of how many algorithms ran inside it or in what internal order. The corruption only depends on the part written after the TTL step, which both paths now re-sort.

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the secondary-index finding in f977bca (full analysis in the inline thread). Net scope of this PR now: the sort-order re-sort covers both the merge path (MergeTask) and the mutation path (MutateTask / MATERIALIZE TTL), and the mutation path additionally rebuilds skip indices on subcolumns of TTL-rewritten columns instead of hardlinking them stale.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. MATERIALIZE TTL with GROUP BY ... SET t = argMax(cand, v) on a Wide part with INDEX idx t.a (subcolumn of t, not in the sorting key). Before the fix the index is hardlinked from the source part (same inode), secondary_indices_compressed_bytes = 0 in the new part, and it stops pruning; deterministic every run.
b Root cause explained? MutationsInterpreter::prepare compares index.expression->getRequiredColumns() (t.a) literally against the changed columns. A GROUP BY TTL records the rewritten physical column as the TTL_TARGET t, so t.a != t, the index is not added to materialized_indices, and on a full Wide part it is hardlinked unchanged (need_recalculate is false). Separately, the index expression was materialized before the TTL step, but the GROUP BY aggregation drops that column (zero rows), which aborts the TTL transform once the index is actually rebuilt.
c Fix matches root cause? Yes. (1) Map each index/projection required column to its storage column (Nested::tryGetColumnNameInStorage, same mapping as the sorting-key gate) before the comparison, so t.a -> t and the index is rebuilt. (2) Compute skip-index expressions AFTER the TTL step (and re-sort), mirroring the merge path, so they reflect post-SET values and are not dropped by the aggregation.
d Test intent preserved / new tests added? Yes. Existing 04327 cases unchanged and still pass. New case added: MATERIALIZE TTL + subcolumn skip index, asserting the rebuilt index returns the same rows with and without skip indexes (a stale index would prune rewritten values away).
e Both directions demonstrated? Yes. Before the fix: the index is hardlinked stale (proven by shared inode + secondary_indices_compressed_bytes = 0) and, once forced to rebuild, the pre-step expression aborts the mutation (LOGICAL_ERROR in TTLTransform). After: mutation succeeds, index registered, prunes against post-SET values.
f Fix is general across code paths? Yes. The mapping is applied to both the secondary-index and projection rebuild loops. Projections cannot reference subcolumns (Projections cannot contain individual subcolumns), so their whole-column case was already matched; the mapping keeps both paths consistent. The merge path already rebuilds all indices from the stream and was correct.
g Fix generalizes across inputs? Verified across: index column in the sorting key vs not in it (both rebuild and prune correctly), plain physical key column (already matched), Tuple subcolumn, value present only after SET vs absent. The pre-TTL materialization split (primary key before, skip indices after) holds whether or not the SET rewrites a sort-key column.
h Backward compatible? Yes. No setting, format, or on-disk change. Only the in-mutation decision of which indices to rebuild vs hardlink, and the order in which expression columns are computed in the pipeline.
i Invariants and contracts preserved? Yes. The written part's data, primary index, and skip indices are now mutually consistent. The GROUP BY TTL aggregation still receives its sort-key grouping columns before the step (primary-key expression is kept pre-step). No new throw paths across noexcept boundaries; gated to a no-op for non-GROUP-BY-TTL mutations.

Session id: cron:clickhouse-worker-slot-8:20260630-124500

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f977bca

CI fully finished (Finish Workflow: success). This PR fixes the TTL GROUP BY ... SET sort-order violation (STID 3413-350b) across the merge + mutate paths. Every failure below has an owner; none is PR-caused (this PR touches only the TTL-aggregation sort-key handling, none of the failing areas).

Check / test Reason Owner / fixing PR
Unit tests (asan_ubsan + msan, function_prop_fuzzer) / FunctionsStress.stress + AllTests crash (reinterpret(... AS Decimal256(N)) returns wrong scale: Const(Decimal256) instead of Decimal(76, N), INCORRECT_DATA) #108878 (ours, open) — "Fix reinterpret to Decimal/DateTime64 with a different scale"
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) / 00612_shard_count flaky (Code 102 Unexpected packet, connection-pool desync; 30 reruns all pass) #108854 (external, open) — fixes the distributed TablesStatus desync
Stress test (amd_tsan) + (arm_tsan) / "Hung check failed, possible deadlock found" deadlock (chronic hung-check family) #108212 (ours, merged) / #105905 (ours, open)
Bugfix validation (functional tests, amd64) / Environment setup (amd_msan) infra (msan re-prepare of stateful data failed in setup, not a test result) a fix task is moved to pending (investigating at full effort; fixing PR link to follow here)
Integration tests (arm_binary, distributed plan, 4/4) flaky (no per-test FAIL row; job-level only) a fix task is created (investigating; fixing PR link to follow here)
CH Inc sync - CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260630-173000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Re: the Integration tests (arm_binary, distributed plan, 4/4) line on the CI finish ledger — root cause was a transient Docker registry HTTP 500 on image pre-pull (Failed to pre-pull Docker images needed by the test batch), unrelated to this PR. Fixing PR for the pre-pull retry robustness: #108975.

groeneai and others added 4 commits July 11, 2026 11:22
A MergeTree table with `TTL ... GROUP BY ... SET <col> = <agg>` where the SET
clause rewrites a column the table's sorting key depends on (directly, or via an
expression such as toStartOfDay(ts)) produced an out-of-order data part during the
TTL merge.

TTLAggregationAlgorithm::finalizeAggregates emits aggregated groups in the input
(already-sorted) order, and the merge writer trusts the stream order: it reads the
primary-key columns by name (including the materialized sort-key expression column,
which still holds its pre-SET value) and writes them without re-sorting. When the
SET changes a sort-key column the produced part is therefore not sorted by the
sorting key. In a debug build the merge's CheckSortedTransform aborts the server
with "Sort order of blocks violated"; in a release build the part is written
silently with a primary index inconsistent with the data, which can return wrong
results for primary-key-filtered queries.

Fix: after the TTL step in the merge pipeline, when a GROUP BY TTL assigns a
sorting-key dependency column, recompute the sort-key expression columns from the
post-SET values (overwriting the now-stale materialized ones) and re-sort by the
sorting key. The step is gated so it is a no-op for every other merge. This
preserves the existing tested behaviour where SET targets a sort-key column but the
output happens to stay ordered (03545_number_of_rows_in_ttltransform).

Closes ClickHouse#108514

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…n sorting keys

The re-sort gate added for the TTL GROUP BY SET sort-order fix compared the
sorting-key dependency names against the SET target column name directly. A
sorting-key dependency can be a subcolumn (ORDER BY t.a requires t.a), while a
SET target is always a physical storage column (SET t = ...). The names never
matched for a subcolumn sorting key, so the gate did not fire and the part was
built from the stale pre-SET subcolumn value.

Map each sorting-key dependency to its storage column with getColumnNameInStorage
before comparing, the same way extractMergingAndGatheringColumns does. Also hide
the stale materialized sort-key columns from the subcolumn extractor in the
re-sort step so the subcolumn is recomputed from the post-SET physical column
instead of reusing the stale value.

Adds a Tuple subcolumn regression to 04327_ttl_group_by_set_sort_key_resort.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…n path

The same sort-order violation the merge path fixes is also reachable through
ALTER TABLE ... MATERIALIZE TTL. A MATERIALIZE TTL mutation with a GROUP BY TTL
runs MutateAllPartColumnsTask, which materializes the sorting-key expression
before the TTLTransform and writes through MergedBlockOutputStream
(rewrite_primary_key=true). When the GROUP BY ... SET rewrites a column the
sorting key depends on, the aggregation emits groups in input order, so the
stream is no longer ordered by the sorting key and the materialized sort-key
expression is stale. The mutation writer rebuilds the primary index from that
stream, so it gets an index inconsistent with the data; there is no
CheckSortedTransform after the TTL step in the mutation pipeline, so a debug
build does not even catch it and a release build silently writes a corrupt part.

Extract the gate (groupByTTLAssignsSortKeyColumn) and the recompute-and-resort
logic into TTLResortUtils, shared by both paths. After the TTL step in
MutateAllPartColumnsTask, when the gate fires, recompute the sorting-key
expression columns from the post-SET values and re-sort by the sorting key,
the same way the merge path does. Gated to a no-op for every other mutation.

MutateSomePartColumnsTask is not affected: a GROUP BY TTL forces the full
rewrite path, and that task writes through MergedColumnOnlyOutputStream with
rewrite_primary_key=false, which reuses the source part index.

Extends the regression test 04327_ttl_group_by_set_sort_key_resort with
MATERIALIZE TTL cases for a plain Float64 sort key and a Tuple subcolumn sort
key, asserting the produced part is physically ordered by the sorting key.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A `MATERIALIZE TTL` mutation with a `GROUP BY` TTL records the rewritten
physical columns as `TTL_TARGET` (for example `t`), while a skip index can
depend on a subcolumn of one of them (for example `INDEX idx t.a ...`). The
rebuild decision in MutationsInterpreter compared the index/projection required
columns against the changed columns literally, so `t.a` did not match the
changed physical column `t`: the index was not added to materialized_indices and
on a full Wide part it was hardlinked from the source part unchanged, keeping its
pre-SET minmax values. Queries using that index then prune against stale values
(missing rows) or, since the index was never registered in the new part's
checksums, stop pruning entirely. Map each required column to its storage column
(the same way the sorting-key gate does) before comparing, so subcolumn indices
and projections of a rewritten column are rebuilt.

Rebuilding the index exposed a second problem in the mutation pipeline. The
primary-key and skip-index expressions were materialized before the TTL step, but
a `GROUP BY` TTL aggregates the stream: the pre-step skip-index expression columns
are computed from pre-aggregation, pre-SET rows, and the aggregation can drop them
entirely, leaving a zero-row column that aborts the TTL transform. Mirror the
merge path: when a `GROUP BY` TTL runs, materialize only the primary-key
expression before the step (the aggregation groups by sort-key columns and needs
them present) and compute the skip-index expressions after it. When the SET also
rewrites a sort-key column, re-sort first so the rebuilt primary index matches the
written row order, then recompute the skip-index expressions from the post-SET
stream.

Extends 04327_ttl_group_by_set_sort_key_resort with a MATERIALIZE TTL case for a
skip index on a subcolumn of a TTL-rewritten column that is not in the sorting
key (so the primary index cannot mask a stale skip index): the rebuilt index must
return the same rows with and without skip indexes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-ttl-group-by-set-sort-key-resort branch from f977bca to a0d5af7 Compare July 11, 2026 11:37
A TTL GROUP BY SET can rewrite a column that a MATERIALIZED sort-key column
is computed from (e.g. d Date MATERIALIZED toDate(ts), ORDER BY d,
... GROUP BY d SET ts = ...). The aggregation updates ts but leaves the
stored d on its pre-SET value, so the part is written with stale sort-key
data and pruning/filtering on d uses the old value.

groupByTTLAssignsSortKeyColumn previously only detected a SET target that is
itself a sort-key dependency. Extend detection to also flag a SET target that
is a source of a MATERIALIZED sort-key column (analyzed the same way the
UPDATE mutation path builds column_to_affected_materialized), and recompute
those columns from their default expression before recomputing the sorting
key and re-sorting. Applied to both the merge (MergeTask) and mutation
(MutateTask, MATERIALIZE TTL) paths via shared TTLResortUtils helpers.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up commit f2aaf8e addresses the bot's MATERIALIZED sort-key finding.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE (ts DateTime, d Date MATERIALIZED toDate(ts)) ENGINE=MergeTree ORDER BY d; INSERT 10 rows; ALTER MODIFY TTL ts + toIntervalDay(1) GROUP BY d SET ts = max(ts) + interval 100 year; ALTER MATERIALIZE TTL -> every row has stale d (0/10 consistent). Merge variant with an order-reversing SET aggregate writes an unsorted part.
b Root cause explained? groupByTTLAssignsSortKeyColumn only compared SET targets against sort-key dependencies, so a SET on ts (a SOURCE of MATERIALIZED d) was not detected -> no resort/recompute. Even when the resort ran, it recomputed only the sort-key EXPRESSION, reading the stale stored d. So d kept its pre-SET value and pruning/order on d used it.
c Fix matches root cause? Yes. Detection now also flags a SET target that is a source of a MATERIALIZED sort-key column (analyzed like the UPDATE path's column_to_affected_materialized), and those columns are recomputed from their default expression (evaluateMissingDefaults after dropping the stale value) before the sort-key recompute + resort. Applied to both merge (MergeTask) and mutation (MutateTask) via shared TTLResortUtils.
d Test intent preserved / new tests added? Yes. Added merge + mutation regression cases in 04327 for a MATERIALIZED sort-key column whose source is SET, asserting d = toDate(ts) and physical sort order, optimize_sorting_by_input_stream_properties = 1 kept on. Existing 04327 cases unchanged and passing.
e Both directions demonstrated? Yes. Baseline binary (db34aa9c): mutation 0/10 and merge 0/10 consistent, merge part unsorted by d. Fixed binary (045483e1): both 10/10 consistent and physically sorted.
f Fix is general across code paths? Yes. Both TTL sort-key rewrite paths are covered: merge (MergeTask.cpp) and mutation MATERIALIZE TTL (MutateTask.cpp via resortPipelineAfterTTLGroupBySet), sharing the same detection + recompute helpers. Not a symptom guard: the stale value is recomputed at its source (the MATERIALIZED default expression).
g Fix generalizes across inputs? Verified: direct-SET sort-key col (existing cases) still work; MATERIALIZED sort-key col whose source is NOT set is correctly NOT triggered (no false positive) and stays sorted; subcolumn sort keys unaffected. Scope matches the UPDATE path: single-level materialized dependency. A materialized-of-materialized chain is a pre-existing shared limitation (the UPDATE path's column_to_affected_materialized is also single-level), noted in-thread; not expanded here to avoid scope creep.
h Backward compatible? Yes. No setting default, on-disk/wire format, or new validation change. Purely corrects the data written for an already-buggy TTL GROUP BY SET case; gated to a no-op for every other merge/mutation.
i Invariants and contracts preserved? Yes. The written part is now ordered consistently with its primary index (the invariant CheckSortedTransform enforces). The recompute DAG drops only the stale target columns and preserves all others (save_unneeded_columns), so block structure is unchanged for the rest of the stream.

Session id: cron:clickhouse-worker-slot-0:20260711-122100

…GROUP BY SET

Extend the MATERIALIZED-sort-key recompute for TTL GROUP BY SET in two ways:

1. Transitive closure: a SET on a base column can invalidate a MATERIALIZED
   sort-key column several hops away (x -> y MATERIALIZED toDate(x) -> z
   MATERIALIZED toYYYYMM(y), ORDER BY z). The affected-column detection now
   takes the fixpoint over the materialized-dependency graph and recomputes the
   intermediate hops (y before z), instead of a one-hop check that left z stale.

2. Subcolumn sources: buildRecomputeMaterializedColumnsDAG now prepends a
   subcolumn-extraction DAG (as AddingDefaultsTransform does) so a default
   expression reading a subcolumn (d MATERIALIZED toDate(tup.ts)) can be
   recomputed; previously it failed with NOT_FOUND_COLUMN_IN_BLOCK.

Both paths (merge and MATERIALIZE TTL) go through the shared helper. Regression
cases added to 04327 for the transitive chain and the subcolumn source.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed both clickhouse-gh[bot] findings on TTLResortUtils.cpp in 3071816.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. (#2 transitive) x->y MATERIALIZED toDate(x)->z MATERIALIZED toYYYYMM(y), ORDER BY z, SET x: stored z was stale (consistent=0 all rows). (#1 subcolumn) d MATERIALIZED toDate(tup.ts), ORDER BY d, SET over unrelated plain col: NOT_FOUND_COLUMN_IN_BLOCK: tup.ts. Both reproduce on demand via MATERIALIZE TTL.
b Root cause explained? (#2) groupByTTLAssignsSortKeyColumn/affected-detection was one-hop: getMaterializedColumnSourceColumns(z)=[y], SET target=x not in [y] -> not affected -> no recompute -> z written stale. (#1) buildRecomputeMaterializedColumnsDAG fed header_after_drop (physical tup only) to evaluateMissingDefaults, whose action requires the subcolumn tup.ts, which was never extracted.
c Fix matches root cause? Yes. (#2) getMaterializedColumnsAffectedBySet takes the fixpoint over the materialized-dependency graph; the recompute set includes intermediate hops in physical-column order (y before z). (#1) prepend a createSubcolumnsExtractionActions DAG before the evaluateMissingDefaults DAG, exactly as AddingDefaultsTransform does.
d Test intent preserved / new tests added? Yes. Existing 04327 cases unchanged and still pass. Added mat chain (two-hop) and mat subcol (subcolumn source) cases asserting both consistency (d = toDate(...) for all rows) and physical sort order.
e Both directions demonstrated? Yes. Pre-fix: #2 consistent=0, #1 NOT_FOUND tup.ts. Post-fix (Build ID ea48213b): #2 all consistent=1 and sorted; #1 recomputed correctly and sorted.
f Fix is general across code paths? Yes. Both fixes live in the shared TTLResortUtils helpers used by both the merge (MergeTask) and mutation (MutateTask MATERIALIZE TTL) paths.
g Fix generalizes across inputs? Transitive closure is arbitrary-depth (not just two-hop). Subcolumn extraction is generic (Tuple element here; same mechanism handles other subcolumn kinds). Note: a separate, pre-existing bug (TTL SET aggregate whose argument is itself a subcolumn, e.g. max(tup.ts)) is orthogonal to this PR and reproduces on master with no MATERIALIZED column; reported in-thread, out of scope here.
h Backward compatible? N/A. No setting, format, or on-disk change. Recompute only fires for the GROUP BY TTL SET affected-materialized case; no-op otherwise.
i Invariants and contracts preserved? Yes. Recompute runs before the sort-key recompute + re-sort, so the written part remains ordered consistently with its primary index. Pass-through columns preserved via save_unneeded_columns; recompute order respects the dependency chain.

Session id: cron:clickhouse-worker-slot-1:20260711-133400

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved

@alexey-milovidov alexey-milovidov left a comment

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.

.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed. I will cut this back to the bug I reported in #108514 and nothing else.

Kept: the firing-TTL gate, recomputing the sorting-key expression columns after a GROUP BY ... SET rewrote a column they read (including a MATERIALIZED column the sorting key reads, which is the same bug by another route), the re-sort on the merge and MATERIALIZE TTL paths, and ttl_resort_max_bytes_before_external_sort.

Dropped: everything folded in from #110098, that is recomputing every other MATERIALIZED column that reads a SET target, the multi-GROUP BY-TTL key rewrite, ttl_group_by_unsorted_max_bytes_before_external_group_by and the Aggregator spill work. That is all of TTLTransform, most of TTLAggregationAlgorithm, six of the eight new tests, and roughly two thirds of the diff.

Two consequences, since they are behaviour and not size:

  • Without the multi-TTL analysis, the re-sort would turn Sort order of blocks violated into silently wrong aggregates when several GROUP BY TTLs fire in one part. So I will skip the repair entirely when more than one can fire, leaving that shape exactly as it is on master.
  • I am not rejecting SET on a sort-key column at DDL level instead: the shape is correct when the rewrite is monotone, which 03545_number_of_rows_in_ttltransform covers.

The stale-MATERIALIZED gap is a real pre-existing bug (a minmax index built over such a column prunes rows a full scan returns), so dropping it here parks it rather than settles it.

I will push the reduced version. Tell me if you would rather cut it differently.

groeneai and others added 3 commits September 13, 2026 21:31
The PR carries three independent defect families in one diff and only one of them
is the reported bug (ClickHouse#108514): a `TTL ... GROUP BY ... SET` that assigns a column
the sorting key depends on. Alexey asked for the diff to be cut back to that bug,
so the work folded in from ClickHouse#110098 comes out.

What goes:

  - `TTLTransform`, `TTLAggregationAlgorithm` and `TTLColumnAlgorithm` return to
    master. They carried the chained-clause machinery: detecting that an earlier
    firing `SET` rewrote a column a later `GROUP BY` TTL groups by or expires on,
    the sorted/unsorted aggregation split with its hash-table spill, and the
    later clause's key refresh. None of it is needed to keep a single clause's
    output ordered by the sorting key.

  - the four helpers in `TTLResortUtils` that existed only for that detection
    (`groupByKeysAffectedByEarlierSet`, `groupByTTLExpiryAffectedByEarlierSet`,
    `groupByTTLSetExpressionsAffectedByEarlierSet`, `buildRefreshGroupByKeysDAG`)
    and the three private helpers that only fed them.

  - `ttl_group_by_unsorted_max_bytes_before_external_group_by`, which bounded
    that hash table. The setting never shipped (it was added on this branch), so
    its `SettingsChangesHistory` line goes with it rather than becoming a
    tombstone.

`getFiringGroupByTTLSetTargets` loses the `!fires` fallback that consulted
`groupByTTLExpiryAffectedByEarlierSet`, so its `context` argument is now unused
and the parameter goes too. That fallback treated a not-yet-expired clause as
firing when an earlier `SET` could move it into range; the next commit replaces it
with a plain bail-out for any part that has more than one `GROUP BY` TTL.

Co-authored-by: Claude Opus 5 <[email protected]>
The previous commit removed the machinery that made a chain of `GROUP BY` TTLs
correct, so a part with more than one of them must be left alone rather than
half-repaired.

`TTLTransform` runs the clauses in order over one stream. When an earlier clause's
`SET` rewrites a column a later clause groups by, the later `TTLAggregationAlgorithm`
receives an input that is no longer ordered by its own keys, and its
flush-on-key-change loop then closes a group early and reopens it, merging rows that
belong to different groups. Recomputing the sorting key and re-sorting the result
would write a part that is internally consistent and still holds those wrong groups,
i.e. it would hide the defect instead of fixing it.

`getFiringGroupByTTLSetTargets` therefore returns an empty set for such a table.
Both callers gate every repair on those targets (`groupByTTLAssignsSortKeyColumn`
returns false for an empty set), so the shape behaves exactly as it does on master.

This also makes the previous commit's removal of the expiry-chain fallback sound:
without the bail-out the gate could conclude "exactly one clause fires" for a table
where a later clause only becomes reachable after the first `SET`, and then repair
it.

Co-authored-by: Claude Opus 5 <[email protected]>
The remaining `MATERIALIZED` work comes out, leaving one repair for one defect: a
`TTL ... GROUP BY ... SET` that assigns a column the sorting key depends on.

A `GROUP BY` TTL's keys must be a prefix of the primary key
(`TTLDescription.cpp`, "TTL Expression GROUP BY key should be a prefix of primary
key"), and the writer takes a `MATERIALIZED` storage column out of the stream by
name rather than re-deriving it. So a `MATERIALIZED` sort-key column is written from
the value it already holds, and leaving it alone preserves the part's order; it is
recomputing it that assigns arbitrary new values the re-sort then has to repair. The
value does go stale with respect to its own expression once the `SET` rewrites a
source column, but that is the stale-`MATERIALIZED` gap this PR no longer claims to
close, and it is not what breaks the sorting key. Removed with it: the
materialized-dependency graph, the recompute step on both paths, and the warning for
a `MATERIALIZED` column that also reads an `EPHEMERAL` one.

The gate reduces to "is a `SET` target among the sorting key's storage
dependencies?", so `groupByTTLAssignsSortKeyColumn` no longer needs a context, and
`resortPipelineAfterTTLGroupBySet` no longer needs the target set.

`MutationsInterpreter` returns to master as well: `required_column_affected` changed
derived-artifact invalidation for every mutation path, and the subcolumn skip index
it fixed is not in the sorting key, so it does not belong to this defect either.

⚠️ The expression-placement split in `MutateTask` STAYS, and is now selected by
`resort_after_group_by_ttl` rather than by "the table has a `GROUP BY` TTL". It is
not a sibling of that revert. `MutationsInterpreter.cpp` marks every column
`TTL_TARGET` whenever the table has any `GROUP BY` TTL, on master too, so a computed
skip index over a rewritten sort-key column is selected for rebuilding on
`MATERIALIZE TTL` regardless. Materializing its expression before `TTLTransform`
would carry a pre-`SET` value into an index the re-sort does not touch, and
`MergeTreeDataPartWriterWide` writes that index from the stale column: an index that
prunes valid rows. Narrowing the flag returns every non-repair case to master's
combined placement, including the multi-clause shape the previous commit leaves
alone and a single clause whose `SET` misses the sorting key.

Co-authored-by: Claude Opus 5 <[email protected]>
Six of the eight test files covered the arms the previous commits removed, so they
go with them: 04511 and 04692 (multi-`GROUP BY`-TTL), 04691 (four `MATERIALIZED`
recompute arms plus four multi-TTL ones), 05046 and 05047 (the materialized sort-key
gate and the folded-in future/type arms), 05182 (the non-deterministic
`MATERIALIZED` boundary, which also needed the deleted setting).

04327 keeps the reported bug and loses two arms that never tested it: `t_mut_idx`
keeps its indexed `t.a` OUT of the sorting key on purpose, so it covers the reverted
`MutationsInterpreter` change, and `t_subwrap` covers a fuzzer-found type mismatch in
the reverted aggregation-finalization path (STID 2508-3698, pre-existing on master:
re-observed there before deleting the arm).

Five arms are added, four of them because nothing in the kept set could otherwise
observe a decision this cut makes:

  - `t_mut_computed_idx`: a COMPUTED skip index over a rewritten sort-key column,
    through `MATERIALIZE TTL`. This is what makes the expression-placement split in
    `MutateTask` observable: reduced to master's combined placement, the index is
    built from the pre-`SET` value and prunes granules that hold matching rows
    (measured: the forced-index read returns 0 of 3 rows).
  - `t_mat_prefix` / `t_mat_suffix`: a `MATERIALIZED` sort-key column in both
    positions, with rows per group straddling the TTL boundary so the aggregation
    interleaves aggregated and passed-through rows. These pin the property that
    licenses dropping the recompute: left alone, such a column keeps the part
    ordered. The expiry reads a separate column, which is what lets one group hold
    both expired and live rows.
  - `t_multi_ttl` + `t_single_ttl`: the multi-clause bail-out, read from the
    external-sort counter with the re-sort bounded at one byte, plus the same fixture
    with one clause as the control that must spill.
  - `t_not_firing`: the firing gate (an expired DELETE TTL beside a `GROUP BY ... SET`
    clause 40 years out), migrated from 04691 and paired with the same counter, since
    per-day row counts do not observe whether the repair was skipped.

`t_f64` also gains a non-expired row so the kept fix's own shape exercises the
flush-and-pass-through path; every arm previously inserted expired rows only.

⚠️ Both files' `... sorted` oracles are rewritten, including 04661's. As written they
compared a physical read against a second read with `ORDER BY <sorting key>` -- and
that read is answered from the part's own declared order, so both sides returned the
same rows and the oracle could not fail. Measured against a binary with the
mutation-path re-sort disabled: the part was physically `[96827, 41302]`, the old
oracle said "sorted", the new one (`phys = arraySort(phys)`, ordering done outside the
planner) says it is not. `optimize_read_in_order = 0` on the ORDER BY side does not
help. In a debug build the merge aborts before writing such a part, which is what has
been hiding this; on a release build the test would have passed on the corrupt part it
exists to catch.

Co-authored-by: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

I am not pushing the reduced version. You have your own fix in #119863, and the 880-line version I had ready next to your 131 is the same objection at a larger size. I am fine with this PR being closed in favour of it.

One measurement first, because it is the part of the reduction I could not find an equivalent of in your patch. The SET does not have to assign a sorting key column: assigning a column that a sorting key expression reads is enough, and then the column that goes out of order is the expression.

CREATE TABLE t (k Float64, ts DateTime('UTC'), v Float64)
ENGINE = MergeTree ORDER BY (k, toStartOfDay(ts))
TTL ts + toIntervalDay(1) GROUP BY k, toStartOfDay(ts)
    SET ts = toDateTime('2100-01-01 00:00:00', 'UTC') + toIntervalDay(toUInt32(max(v)))
SETTINGS index_granularity = 4, min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;

INSERT INTO t SELECT 1.0,
    toDateTime('2000-01-01 10:00:00', 'UTC') + toIntervalDay(number DIV 2) + toIntervalHour(number % 2),
    39 - (number DIV 2)
FROM numbers(80);
OPTIMIZE TABLE t FINAL;

k is never assigned, and the new day of each group moves backwards. On master 17e40134 and on an independently built 00260f98 (debug, clickhouse local) this aborts with

Logical error: 'Sort order of blocks violated for column number 2, left: UInt64_4105814400, right: UInt64_4105728000. Chunk 0, rows read 2.'

The two values are 2100-02-09 and 2100-02-08, so the column is toStartOfDay(ts) carrying post-SET values, and the abort lands in the merge that reads the part the TTL merge wrote rather than in the TTL merge itself, because CheckSortedTransform is added right after the merging transform and never after the TTL step. With the sorting key expression recomputed from the post-SET columns it passes, the part is sorted and the primary index matches the data. The same table with SET ts = max(ts) + INTERVAL 100 YEAR is fine on master, so it takes a rewrite that is not monotone in the group's day.

Does #119863 cover that shape? If it does, I will drop my branch. If it does not, tell me whether you want the recompute as a small separate change or would rather leave it.

@alexey-milovidov

Copy link
Copy Markdown
Member

No, it does not cover it.

restoreSortOrder compares the sorting key columns as they are in the block after finalizeAggregates. There toStartOfDay(ts) still holds the pre-SET value: it is copied from the aggregation key (or is any(...) when it is not a GROUP BY key), and only ts gets the SET value. The stale column is monotone, so nothing is replaced, the part is written in the stale order, and its primary index is built from the stale values. The next merge recomputes toStartOfDay(ts) from the stored ts and hits CheckSortedTransform.

I ran your reproducer with the patch of #119863 on top of master (a release build with clickhouse local, so instead of CheckSortedTransform the wrong result shows). The background TTL merge picks the part right after the insert, so OPTIMIZE is already the merge that reads the part the TTL merge wrote (the result is all_1_1_2):

master #119863
storage order of toStartOfDay(ts) is sorted no no
WHERE k = 1 AND toStartOfDay(ts) = '2100-02-08' 0 rows 0 rows
the same without the primary key 1 row 1 row

The direct shape from #108514 (SET k = max(v)) is what the patch fixes: both rows get k = 96827 and the part is sorted.

The CI of #119863 says the same: the flaky check of its own test 05089 aborted with left: 2100-06-11, right: 2050-01-01 on toStartOfDay(ts). That is the second table of the test, SET ts = max(ts) + INTERVAL 100 YEAR with a row that did not expire after the aggregated ones, in the runs where the background TTL merge came before OPTIMIZE. So this shape does not even need a rewrite that is non-monotone in the group's day: an aggregated row that jumps over a non-expired row is enough.

The clamp cannot be extended to this shape. toStartOfDay(ts) is derived from ts, so replacing it makes the primary index disagree with the data, and the next merge recomputes it from ts anyway, while replacing ts itself is not possible in general. That leaves re-sorting or refusing the shape, and refusing is not an option, because SET ts = max(ts) within the group's day is legitimate.

So push the reduced version here: the firing gate, the recompute of the sorting key expressions from the post-SET columns, the re-sort on the merge and MATERIALIZE TTL paths bounded by ttl_resort_max_bytes_before_external_sort, skipping the repair when more than one GROUP BY TTL can fire, and tests for exactly that. Nothing else. With the re-sort in place the clamp is redundant, so #119863 will be closed in favour of this PR, not the other way around.

@groeneai

Copy link
Copy Markdown
Collaborator Author

That settles it. I am pushing exactly that list: the firing gate, the recompute of the sorting key expression columns from the post-SET columns, the re-sort on the merge and MATERIALIZE TTL paths bounded by ttl_resort_max_bytes_before_external_sort, no repair at all when more than one GROUP BY TTL can fire, and tests for those. Everything else on the current head comes out.

Correcting one clause of my 2026-09-13 reply so the diff does not surprise you. It said the reduction keeps a MATERIALIZED column the sorting key reads, as the same bug by another route. That was wrong, and it is out. MergeTreeDataPartWriterWide::write takes each column out of the block by name rather than re-deriving it, and builds the primary index from that same block, so a MATERIALIZED sorting key column keeps the value the aggregation produced for it, which the SET does not touch, and the data and the index agree. What breaks there is the column's consistency with its own expression, not the sort order, and recomputing it is what breaks the order. The recompute therefore covers sorting key expressions only, and the materialized dependency graph, its recompute step, its EPHEMERAL warning and their tests go with it.

The tests will cover the form you named, an aggregated row jumping over a row that did not expire, and not only a rewrite that is non-monotone in the group's day. The monotone control in that comment returned rc 0 on master, so it covers one shape rather than the negative space.

One change that is not literally on your list but belongs to the MATERIALIZE TTL re-sort: on the mutation path the skip index expressions are materialized after the re-sort instead of before the TTL step. MutationsInterpreter marks every column TTL_TARGET when the table has any GROUP BY TTL, so a computed index over a rewritten sorting key column is rebuilt there regardless, and computing it before the step writes it from pre-SET values into an index that prunes valid rows. Every case without the repair keeps master's combined placement.

I will follow up here with the pushed sha and the diffstat.

groeneai and others added 2 commits September 18, 2026 19:52
The defect has two shapes and 04327 only observed one of them. When the SET
assigns a sort-key column directly the data comes out unsorted, which the
existing arms catch. When the SET assigns a column a sort-key EXPRESSION only
reads (`ORDER BY (k, toStartOfDay(ts))` with `SET ts`), the expression column
was materialized before the TTL step, so it keeps its pre-`SET` value, stays
ascending, passes the sort check and is copied into the index: the part is
written, the index then describes a day the data no longer holds, and a
key-range read misses rows. Nothing in the file asserted that. The only arm
touching this shape was `t_single_ttl`, and its oracle is an external-sort
counter, which says the repair ran, not that the result is right.

Three arms are added:

  - `t_expr_key`: the merge path with the rewrite non-monotone in the group's
    day, so `max(v)` descends as the input day ascends. Oracles are the
    physical order of the recomputed key, a pruning oracle comparing a
    key-range read against a full scan of the same predicate, and a following
    merge over the written part. On master the order oracle and the pruning
    oracle both return 0 (the read finds 0 of the 9 rows the full scan finds)
    and that following merge aborts with `Sort order of blocks violated for
    column number 2, left: UInt64_4105814400, right: UInt64_4105728000`.
  - `t_expr_key_live`: the same shape with a MONOTONE rewrite, where an
    aggregated row jumping over a row that did not expire is enough on its own:
    five expired days collapse into 2100-06 and one row at 2050-01-01 is passed
    through last, so the emitted key sequence ends below where it started.
  - `t_mut_expr_key`: the expression shape through `ALTER TABLE ...
    MATERIALIZE TTL`, which recomputes and re-sorts through its own
    implementation rather than the merge one. No arm exercised that with an
    expression key.

The order oracle uses `ORDER BY _part_offset`, the physical row number, so it
holds at any `max_threads`, and the part-count guard above each one keeps it
from going vacuous: with more than one active part `_part_offset` interleaves
them.

The two `MATERIALIZED` arms are dropped. They pinned a claim that is now
withdrawn: a `MATERIALIZED` sorting-key column is written from the value the
aggregation produced for it, and a `GROUP BY` TTL's keys are forced to be a
positional prefix of the primary key, so data and index agree and recomputing
it is what would break the order. There is no defect there to cover.

Co-authored-by: Claude Opus 5 <[email protected]>
Three correctness holes in the repair this PR adds, plus two test oracles that
could not fail.

A merge whose input part has no calculated TTL info evaluates every row
(`checkAllTTLCalculated` false sets `force_ttl`), so a `GROUP BY ... SET` on a
sorting-key column does rewrite that part's expired rows. The firing gate,
however, reads the COMBINED part infos, and `MergeTreeDataPartTTLInfos::update`
merges only the entries a part actually has: a missing entry leaves no trace, so
another input's future minimum was the only minimum the gate saw and it declined
the repair. The merge then wrote exactly the unsorted part this repair exists to
prevent. The gate now takes `force_ttl` and assumes every TTL fires when an
input's info is not calculated; the mutation path passes false, where one source
part makes a missing entry visible as a missing entry.

The bounded re-sort inherited `max_rows_to_sort` / `max_bytes_to_sort` /
`sort_overflow_mode` from the context, because `SortingStep::Settings` imports
them into `size_limits` and `fullSortStreams` installs a
`LimitsCheckingTransform`. Those settings bound a USER QUERY's result;
`makeQueryContextForMerge` overrides only `workload`, so ordinary hardening in
the server's default profile reached this maintenance sort, where under
`sort_overflow_mode = 'break'` the transform stops reading without an error and
the writer commits a TRUNCATED part. Measured on a server with
`max_rows_to_sort = 1` in the default profile: a three-row merge committed two
rows. The sort now clears `size_limits`. For the same reason
`ttl_resort_max_bytes_before_external_sort` is made the whole bound in both
directions: its documented `0` means do not spill, so an inherited query
threshold must not put spilling back.

The skip-index expression recomputed after the re-sort analysed ALL metadata
indices against the physical columns only, while the pre-TTL call it replaces on
that path analyses the SELECTED indices with the virtual columns in scope. An
implicit `minmax` index over `_block_number` therefore raised
`UNKNOWN_IDENTIFIER` and failed the whole mutation, in a configuration master
mutates fine. `getCombinedIndicesExpression` now accepts a nullable key
expression list so the skip-indices-only variant can sit beside its two
siblings and share their analysis.

Test side: the two arms asserting that no repair runs now also assert the
part_log row exists, so an empty `part_log` cannot satisfy them by accident, and
the mutation path gets its own not-yet-expired arm. 04661's order oracles read
physical order through `_part_offset` next to a parts count, instead of relying
on the fixture staying small enough for a single-threaded natural read.

Co-authored-by: Claude Opus 5 <[email protected]>
@groeneai groeneai changed the title Fix sort order violation for TTL GROUP BY with SET on a sorting key column Fix sort order violation for TTL GROUP BY SET on a column the sorting key depends on Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed the reduced version: 7324065265227d33ee71fb16f8ca3127c4fbae9a, 12 files changed, 1024 insertions(+), 10 deletions(-) against master.

Kept, exactly the list from your comment: the firing gate; the recompute of the sorting-key expression
columns from the post-SET values; the re-sort on the merge and MATERIALIZE TTL paths bounded by
ttl_resort_max_bytes_before_external_sort; no repair at all when a part has more than one
GROUP BY TTL; tests for those. Dropped: the materialized-dependency graph and its recompute, the
EPHEMERAL warning, the multi-GROUP BY-TTL key rewrite and its aggregation spill, the second
setting, and six of the eight test files.

One correction to what I wrote on 2026-09-13: I said the kept set includes "a MATERIALIZED column the
sorting key reads, which is the same bug by another route". That was wrong and it is out. A
GROUP BY TTL's keys are a positional prefix of the primary key (TTLDescription.cpp:1500-1508), and
MergeTreeDataPartWriterWide::write takes each column out of the block by name and builds
primary_key_block from that same block, so a MATERIALIZED sorting-key column keeps the value the
aggregation produced for it and the data and the index agree.

The regression tests cover both shapes your answer named: an aggregated row jumping over a row that did
not expire, and a rewrite non-monotone in the group's day (your own reproducer, which aborts the
following merge on master).

Known and not fixed here, all pre-existing on master: a subcolumn skip index is hardlinked unchanged by
MATERIALIZE TTL; a GROUP BY ... SET that rewrites a partition-key column leaves the part's
partition id describing values the rows no longer hold (the result part's partition is assigned before
any TTL work, MergeTask.cpp:899); and a Nullable DESC-suffix sorting key violates the order for a
reason of its own (addImplicitlyAggregatedColumns gives each uncovered column its own any, and any
skips NULLs).

Internal second-model review of this head

Two independent review rounds plus a second model on the finished tree; the first round sent five items
back before this push.

❌ Found and fixed before pushing

  • The firing gate declined the repair when one source part's TTL info was missing and another part's
    minimum was in the future: combined part infos cannot express a missing entry, while that same
    absence is what forces TTL evaluation. Reachable with ALTER ... MODIFY TTL +
    materialize_ttl_after_modify = 0 and a later insert. The gate now assumes every GROUP BY TTL
    fires when evaluation is forced; new arm, which is unsorted on the previous head.
  • The repair sort inherited max_rows_to_sort / max_bytes_to_sort from the server's default profile,
    and SortingStep enforces them with a LimitsCheckingTransform: under sort_overflow_mode = 'break'
    that stops reading and the writer commits a TRUNCATED part. Measured on a local server with those two
    settings in default: one of three rows silently lost from a committed part, and the order oracle
    cannot see it, because a truncated prefix of a sorted stream is sorted. Both limits are now cleared
    for this maintenance sort.
  • On the mutation path the post-re-sort skip-index expression analysed every metadata index against the
    physical columns, so an implicit minmax index over _block_number raised UNKNOWN_IDENTIFIER and
    failed the whole mutation. It now analyses only the indices selected for a rebuild, with the virtual
    columns in scope, exactly like the combined expression it replaced.
  • ttl_resort_max_bytes_before_external_sort = 0 now really disables spilling instead of falling back
    to an inherited query threshold.
  • Two gates had no negative oracle (the mutation-side firing gate, and "the SET misses the sorting
    key"); both now assert that the part_log row exists and ExternalSortWritePart is zero, and both flip
    when the gate is made unconditional.

⚠️ Raised and refuted, with evidence

  • The partition-key case above: the partition id is assigned at MergeTask.cpp:899 and
    MutateTask.cpp:4276, neither of which this diff touches, and master produces the same stale id plus
    an unsorted part, so this change strictly reduces the damage there. Raised in both rounds and left out
    deliberately, as scope.
  • "The gate can schedule a re-sort for a clause that executes no assignment" (a DELETE TTL empties the
    group first, or the forced-evaluation flag comes from another TTL family): true and intentional. With
    nothing rewritten the recompute is value-identical and the sort runs on an already-sorted stream, so
    the cost is CPU and temporary files, never a different part; and the plan is built before the TTL
    transform runs, so what actually fired cannot be read at that point.
  • Three more from the first round: the repair sort cannot be downgraded to FinishSorting (the merge
    plan reads parts through an ISourceStep, so applyOrder seeds no sorting property); it cannot
    desync a vertical merge's rows_sources mask (canVerticalTTLDelete is false for any table with a
    GROUP BY TTL, so the merge is always horizontal); and the physical-order oracles are not
    thread-dependent (one part below merge_tree_min_rows_for_concurrent_read is read by one stream; 50
    randomized runs of both files, 100/100). The two largest oracles moved to ORDER BY _part_offset
    anyway.

💡 Noted, not changed: the setting's own documentation does not repeat the multi-GROUP BY-TTL carve-out
that the changelog entry states; the recompute DAG is built twice (inline in MergeTask, and in
TTLResortUtils for the mutation path); two arms rely on OPTIMIZE winning the race with the background
merge that SYSTEM START MERGES releases, as five older arms in the same file already do.

Master rolled the version to 26.10 in c9ae3d3, so the record for
`ttl_resort_max_bytes_before_external_sort` was left in the 26.9 block of a
release that never had it. CI checks out the PR merged with its base, so the
`settings_changes_history` style check reads 26.10 from
cmake/autogenerated_versions.txt and rejects the 26.9 placement.
`compatibility` needs the same thing: the setting first appears in 26.10, so
`compatibility = '26.9'` has to hand out the old value 0.

The reason text goes from pre-26.9 to pre-26.10 for the same reason. The
recorded values are unchanged, so the newest recorded value is still 268435456
and 03999_stateless_settings_history, which compares the compiled default
against `argMax(new_value, (version, index))`, is unaffected.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

This PR was closed at 00:32:25Z with no comment, 50 minutes after I pushed the reduced version (7324065265227). I am not reopening it, but it is the opposite of the instruction I was working from, so I would rather ask than guess: the 17:31:24Z comment above ends with "#119863 will be closed in favour of this PR, not the other way around".

Where things stand: #108514 is open, #119863 is open and unchanged since 2026-09-14, and master has neither the re-sort nor ttl_resort_max_bytes_before_external_sort, so on master the #108514 shape still writes an unsorted part.

If the close was accidental, please reopen and I will finish the one outstanding item: a commit moving the ttl_resort_max_bytes_before_external_sort record from the 26.9 to the 26.10 merge-tree history block. That was the only ownable red on the pushed head (Style check / settings_changes_history, PR-caused, because master rolled to 26.10 in c9ae3d34635db); every other job was still running when the close cancelled the run. It is committed locally and I am holding it rather than pushing into a closed PR.

If the close was deliberate, say so and I will stop here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Reopened, so I pushed the one outstanding item: 4dd95a9700f55 moves the ttl_resort_max_bytes_before_external_sort record from the 26.9 to the 26.10 merge-tree block of SettingsChangesHistory.cpp (master rolled to 26.10 in c9ae3d34635db, and the style check reads the version from the merge commit). That was the only ownable red on 7324065265227. One file, +5/-1, fast-forward only. CI is running.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and verified the reduced head locally. Pushed 0d2109d9c2c0.

Entry state: head 4dd95a9700f5, MERGEABLE, CI green on that head (155 success / 18 skipped / 0 failed), one unresolved review thread, one AI "Request changes" verdict pointing at the same item.

  • Master merge. The merge base was 2026-09-11, i.e. 8 days and 4416 commits behind, so the branch was refreshed: git merge origin/master → 0d2109d9c2c0, zero conflicts. No test-number collision (04327_ttl_group_by_set_sort_key_resort and 04661_ttl_group_by_set_resort_external_sort_spill are both unique). The SettingsChangesHistory.cpp record stays correct after the merge: master is still VERSION_MINOR 10 and ttl_resort_max_bytes_before_external_sort sits in the single 26.10 merge-tree block. The diff against master is unchanged in scope — 12 files, +1028/-10.
  • Verification on the merged head (aarch64 release, incremental build green): both PR tests pass (04661 1.10 s, 04327 1.90 s). Because the diff touches code shared by every GROUP BY TTL, also swept all 110 stateless tests matching ttl: 99 pass, 1 skip, 10 fail — all ten environmental on a bare single-node server (7 × NO_ZOOKEEPER for the replicated sections, Unknown disk s3_disk, Unknown storage policy 'local_remote', Requested cluster 'test_cluster_two_shards' not found), with no reference diff anywhere in the log. Style checks cpp, whitespace_check, functional_tests_check and test_numbers_check clean.
  • The remaining review item (the MATERIALIZED sort-key dependency, both as the inline thread and as the AI blocker) was re-checked against this head rather than deferred, and the finding's premise does not reproduce: the reproducer's part is written sorted by d, CHECK TABLE returns 1 and the following merge is clean, because a GROUP BY TTL's keys are a positional prefix of the primary key and the writer builds the primary index from the block it writes. What remains is a stored MATERIALIZED column not equal to its expression, which master shares and which is outside the reduction requested in Fix sort order violation for TTL GROUP BY SET on a column the sorting key depends on #108550 (comment). Details and measurements in Fix sort order violation for TTL GROUP BY SET on a column the sorting key depends on #108550 (comment); thread resolved on that basis. Re-widening the scope is a maintainer call, so nothing was re-added here.

CI is running on 0d2109d9c2c0. Not merging — the merge is yours.

@alexey-milovidov
alexey-milovidov marked this pull request as draft September 23, 2026 01:12
@alexey-milovidov alexey-milovidov added the hold Skip for auto-updating. label Sep 23, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, I still prefer my implementation without resorting - in #119863. Thanks for the work!

@groeneai

Copy link
Copy Markdown
Collaborator Author

No objection. It also removes the need for the design decision left open here on 2026-08-16 (a per-clause firing flag versus a row-granular marker): restoreSortOrder recalculates the sorting key of every emitted row and compares it with the previous emitted one, carried across blocks, so aggregated and passed-through rows need no marker to tell them apart, and with no post-TTL MATERIALIZED recompute step left there is nothing else that needs one.

Computing the primary-key and skip-index expressions after the TTL transforms in MutateAllPartColumnsTask also covers the second mutation-path defect I had hit separately, where a rebuilt index described the source part's data instead of the rewritten part's.

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-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai hold Skip for auto-updating. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TTL GROUP BY + SET on a sort-key column corrupts merge output (Sort order of blocks violated; silent primary-key index corruption in release builds)

4 participants