Skip to content

Fix multiple GROUP BY TTL losing groups when an earlier SET rewrites a later TTL's group_by key - #110098

Closed
groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ttl-multi-group-by-set-rewrites-key
Closed

groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ttl-multi-group-by-set-rewrites-key

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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 data loss with multiple TTL ... GROUP BY ... SET expressions where an earlier SET rewrites a column that a later GROUP BY TTL groups by. The later aggregation could fragment or drop groups (with a small merge block size, entire groups were lost) because it assumed its input was still ordered by its grouping key.

Description

TTLAggregationAlgorithm assumes its input is ordered by its own group_by_keys: it flushes the aggregation state as soon as it observes a new key value. TTLTransform runs the GROUP BY TTL algorithms sequentially on the same block, so when an earlier TTL's SET rewrites a column that is a later TTL's group_by key, that later algorithm's input is no longer ordered by the key. It then finalizes each non-contiguous run of the same key as its own group. The aggregation state also persists across blocks, so a key that recurs across block boundaries (small merge_max_block_size) is lost entirely.

TTLTransform now tracks the SET targets of earlier GROUP BY TTLs. For a later TTL whose group_by key can be rewritten by one of them, its TTLAggregationAlgorithm is told the input is not ordered by its keys; it then accumulates every expired row into the aggregation state and finalizes once at end of stream, so all rows of a key merge into a single group regardless of order. The ordered fast path is unchanged.

A group_by key must be a prefix of the sorting key, so the rewritten column is always a sort-key column. On master this same scenario also hits the sort-order-violation handled by #108550 (a LOGICAL_ERROR abort in debug / corrupt part in release) before the aggregation runs, so this change is stacked on #108550 and targets its branch content; it should be merged after #108550 (or folded in, reviewer's choice). The new test 04511_ttl_multi_group_by_set_rewrites_key reproduces the fragmentation both within a block and across blocks.

groeneai and others added 8 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]>
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]>
…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]>
…ET resort gate

Collecting materialized-source columns analyzed every MATERIALIZED default
expression against getAllPhysical(), which excludes EPHEMERAL columns, so a
table with a MATERIALIZED sort-key column defined over an EPHEMERAL source
(sk String MATERIALIZED reverse(eph)) made the resort gate throw
UNKNOWN_IDENTIFIER during the merge/mutation even when the TTL SET did not
touch the sort key. Include ephemeral columns in the analysis set (mirroring
the UPDATE mutation path in MutationsInterpreter::prepare) and skip
materialized columns whose sources include an ephemeral column: they cannot be
recomputed from on-disk data, and since a SET target is always a physical
column they can never be transitively affected anyway.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…a later TTL's group_by key

With more than one GROUP BY TTL, an earlier TTL's SET can rewrite a column that
is a later GROUP BY TTL's group_by key. TTLAggregationAlgorithm assumes its input
is ordered by its own group_by_keys and flushes the aggregation state on every
observed key change, so once the input is no longer ordered by that key it
finalizes each non-contiguous run of the same key as its own group. Aggregation
state also persists across blocks, so with a small merge block size a key that
recurs across block boundaries is lost entirely (e.g. 100 rows collapsing to a
total of 3).

TTLTransform now tracks the SET targets of earlier GROUP BY TTLs and, for a later
TTL whose group_by key can be rewritten, tells its TTLAggregationAlgorithm the
input is not ordered by its keys. That algorithm then accumulates every expired
row into the aggregation state and finalizes once at end of stream, merging all
rows of a key into one group regardless of order. The sorted path is unchanged.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. TTL ts1+toIntervalDay(1) GROUP BY k SET k=max(v), ts2+toIntervalDay(1) GROUP BY k SET payload=sum(payload) then OPTIMIZE FINAL. Deterministic: 3 rows give sum(payload)=300 instead of 700; with merge_max_block_size=8, 100 rows collapse to total=3.
b Root cause explained? TTLAggregationAlgorithm::execute flushes the whole aggregation state (finalizeAggregates, dump+invalidate) on every observed group_by-key change, assuming input ordered by its group_by_keys. TTLTransform runs the GROUP BY TTL algorithms sequentially on the same block, so when an earlier TTL's SET rewrites a later TTL's group_by key, that key is no longer ordered and each non-contiguous run of a key is finalized separately. State persists across blocks, so a key recurring across block boundaries is lost.
c Fix matches root cause? Yes. TTLTransform tracks earlier GROUP BY TTLs' SET targets; for a later TTL whose group_by key is such a target it sets input_sorted_by_group_by_keys=false, and that algorithm then accumulates all expired rows into the aggregation state and finalizes once at end of stream. Targets the exact ordering assumption; the ordered fast path is unchanged.
d Test intent preserved / new tests added? New test 04511_ttl_multi_group_by_set_rewrites_key added, covering both within-block and cross-block (merge_max_block_size=8) fragmentation. No existing test weakened.
e Both directions demonstrated? Yes. Without fix (baseline #108550): repro1 sum=300, repro2 total=3. With fix: repro1 sum=700 (2 groups), repro2 total=100 (3 groups). Both on Build-ID-verified debug binaries.
f Fix is general across code paths? Yes. Both the merge (TTLTransform via MergeTask) and mutation (MutateTask, e.g. MATERIALIZE TTL) paths construct the same TTLTransform, so the detection applies to both. The change is in the shared algorithm, not one call site.
g Fix generalizes across inputs? The fix is on the group-by ordering path, independent of column datatypes / wrappers (Nullable/LowCardinality/etc.) and of the aggregate functions used in SET. Detection is purely structural (a group_by key equals an earlier TTL's SET target column name), so it holds across all input types and multi-TTL chains.
h Backward compatible? Yes. No setting, format, or on-disk change. Pure correctness fix: previously-lost groups are now preserved. No SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. The deferred path reuses the existing Aggregator/calculateAggregates/finalizeAggregates machinery (standard cross-block GROUP BY) and only omits the mid-stream flush; TTL-info recomputation and the empty-block end-of-stream finalize are unchanged. Non-expired rows still pass through unchanged. Output ordering after SET is restored by #108550's sort-key resort (a group_by key is always a sort-key prefix), which this PR is stacked on.

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

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

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dbd6f71]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
01666_merge_tree_max_query_limit FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
02354_distributed_with_external_aggregation_memory_usage FAIL cidb

AI Review

Summary

This PR closes a long chain of real correctness bugs around GROUP BY TTLs whose earlier SET clauses rewrite later keys, expiry inputs, or downstream MATERIALIZED columns. Most of those fixes now look coherent in both the merge and MATERIALIZE TTL paths, but one major firing-state false positive still remains: a GROUP BY TTL whose WHERE matches no rows is still treated as "firing", which reintroduces the whole-part unsorted / re-sort pessimizations on parts where that TTL rewrote nothing.

Findings

⚠️ Majors

  • [src/Processors/Transforms/TTLTransform.cpp:111-149, src/Storages/MergeTree/TTLResortUtils.cpp:723-749, src/Storages/MergeTree/MergeTreeDataWriter.cpp:294-359] group_by_ttl_fires and getFiringGroupByTTLSetTargets both use min == 0 as "this GROUP BY TTL may fire", but MergeTreeDataWriter::updateTTL also leaves min/max at zero when the TTL's WHERE filter matches no rows at all. So an earlier clause like TTL1 ... GROUP BY k SET k = ... WHERE flag = 1 with every flag = 0 still gets treated as if it rewrote k: later TTLs are forced onto executeUnsorted, and the merge path still runs the materialized-column refresh / sort-key re-sort repairs for a SET that never executed. Suggested fix: stop overloading min == 0 for both "uninitialized" and "no qualifying rows" by carrying an explicit "filter matched rows" bit in the stored TTL info, or by feeding back "actually aggregated rows" from the earlier algorithm before propagating its SET targets.
Final Verdict

Needs changes before merge. The main correctness work in this series looks sound, but the remaining min == 0 firing heuristic still leaves a real whole-part performance regression for GROUP BY TTLs with WHERE predicates that match no rows.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 11, 2026
… multi GROUP BY TTL SET

The earlier fix used a raw name comparison between a later GROUP BY TTL's
group_by keys and earlier SET targets. group_by keys are primary-key column
names, so a key can be a computed expression (toStartOfDay(ts)), a subcolumn
(t.a), or a MATERIALIZED column, while a SET target is always a physical column.
The raw comparison missed those derived keys: the later TTLAggregationAlgorithm
kept the streaming fast path and read the stale derived key, fragmenting or
mis-grouping rows even after the earlier SET.

Now the key is mapped back to its physical storage dependencies before comparing;
when an earlier SET rewrote any dependency, the later algorithm is told its input
is unsorted and the derived key columns are refreshed in the block before it runs
(both in consume and in the end-of-stream flush in generate, which the mutation
path relies on for the last group).

Separately, the materialized-column recompute was restricted to MATERIALIZED
columns in the sorting key. A SET can leave any MATERIALIZED column stale
(TTLAggregationAlgorithm keeps it as any(col) from the pre-SET rows), which writes
wrong stored data and wrong rebuilt skip indices/projections. The recompute now
covers every MATERIALIZED column transitively affected by a SET target, and runs
independently of the sort-key re-sort in both the merge and mutation paths.

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

Copy link
Copy Markdown
Collaborator Author

Both findings confirmed as real data corruption and fixed in 95d87f9 (verified both directions on a local debug build).

Finding A (TTLTransform.cpp — derived group_by keys). Correct: group_by_keys are primary-key column names (TTLDescription.cpp sets result.group_by_keys = pk_columns[..]), so a key can be a computed expression (toStartOfDay(ts)), a subcolumn (t.a), or a MATERIALIZED column, while a SET target is always physical. The raw-name comparison missed those, left input_sorted_by_group_by_keys = true, and the later aggregation read the stale derived key. Fix: groupByKeysAffectedByEarlierSet maps each key back to its physical storage dependencies (via getColumnNameInStorage for subcolumns, the primary-key expression's required columns for computed keys, and the transitive MATERIALIZED-source graph) and compares against the earlier SET targets → sets input_sorted = false; buildRefreshGroupByKeysDAG then recomputes the derived key column(s) in the block before the later algorithm consumes it (reusing the sorting-key expression recompute for computed/subcolumn keys and the MATERIALIZED-default recompute for materialized keys). This refresh is applied both in consume and in the end-of-stream flush in generate — the latter mattered: the MATERIALIZE TTL mutation path flushes the last group there, and without it that group still fragmented (GROUP BY t.a SET t=..., GROUP BY t.a SET payload=sum and GROUP BY toStartOfDay(ts) SET ts=... both now merge non-adjacent groups correctly).

Finding B (TTLResortUtils.cpp — non-sort-key MATERIALIZED columns). Correct: the recompute set was restricted to MATERIALIZED sort-key columns, so d Date MATERIALIZED toDate(ts), ORDER BY k, ... SET ts = ... left the stored d (and any rebuilt skip index / projection over it) stale. Fix: new getGroupByTTLSetAffectedMaterializedColumns returns every MATERIALIZED column transitively affected by a SET target; recomputeAffectedMaterializedColumns recomputes them before the part is written, run independently of the sort-key re-sort gate in both the merge path (MergeTask) and the mutation path (MutateTask). Verified: stored d is now toDate(post-SET ts) and a minmax skip index over d observes the fresh value.

Test 04511_ttl_multi_group_by_set_rewrites_key extended with computed-key, subcolumn-key, non-sort-key-materialized, MATERIALIZE-TTL, and skip-index-preservation cases. Changelog category unchanged (Bug Fix). Stacked on #108550 — merge after it.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A: MATERIALIZE TTL with GROUP BY toStartOfDay(ts) SET ts=... fragments the last group into extra rows on pristine HEAD (4 stored rows vs 2). B: d MATERIALIZED toDate(ts), SET ts=... stores stale d. Both reproduce every run via clickhouse-local.
b Root cause explained? A: key is a PK column name (computed/subcolumn/materialized); earlier SET rewrites a column it derives from, but the derived key column in the block is not refreshed → later aggregation groups by the stale key (raw-name gate missed it) and the end-of-stream flush path never refreshed at all. B: recompute set was gated to sort-key materialized columns, so other affected MATERIALIZED columns are written as any(col) from pre-SET rows.
c Fix matches root cause? Yes. A: dependency-map the key → input_sorted=false + refresh derived key columns in both consume and generate. B: recompute all SET-affected MATERIALIZED columns, ungated from the sort-key re-sort. No bounds widened, no no-random-* tags, no data reduction.
d Test intent preserved / new tests added? Yes. Existing 04511 cases unchanged and still pass; added computed-key, subcolumn-key, non-sort-key-materialized, MATERIALIZE-TTL, and skip-index-preservation cases that assert merged groups / fresh stored column / fresh index.
e Both directions demonstrated? Yes. Every new case fails on pristine PR HEAD (A: 4 stored rows / stale d / index prunes the fresh row) and passes with the fix (2 rows / fresh d / row found).
f Fix is general across code paths? Yes. Both the merge (MergeTask) and mutation (MutateTask, MATERIALIZE TTL) writers, and both the streaming and end-of-stream (generate) flush paths in TTLTransform, are covered. Not a point guard at the crash site.
g Fix generalizes across inputs? Yes. Key forms covered: physical, computed (toStartOfDay(ts)), subcolumn (t.a), and MATERIALIZED column used as key; MATERIALIZED recompute is a transitive fixpoint (multi-hop x→y→z); EPHEMERAL-sourced MATERIALIZED columns are correctly skipped (cannot be recomputed from disk, and a physical SET target can never transitively reach them).
h Backward compatible? Yes. No setting defaults, on-disk/wire formats, or metadata changed; the new recompute/refresh steps only run when a GROUP BY TTL SET affects a derived key or a MATERIALIZED column, and are a no-op for every other merge/mutation.
i Invariants and contracts preserved? Yes. The written part stays ordered by its sorting key (existing re-sort unchanged), block structure (header == data, equal column sizes) is preserved by the ExpressionActions passthrough, and stored MATERIALIZED columns / rebuilt skip indices / projections now match their defining expressions on the post-SET data.

Session id: cron:clickhouse-worker-slot-2:20260711-171900

…cope, warn on ephemeral-mixed materialized

Addresses three follow-up review findings on the multi GROUP BY TTL SET fix:

F1: a computed group_by key over a MATERIALIZED source (ORDER BY toStartOfMonth(d),
d MATERIALIZED toDate(ts), earlier SET ts) rebuilt the key from the stale stored d, so the
later GROUP BY grouped by the pre-SET month. buildRefreshGroupByKeysDAG now also refreshes the
affected MATERIALIZED sources when an expression key merely reads one, then rebuilds the key.

F2: a MATERIALIZED column reading both an EPHEMERAL column and a SET target cannot be recomputed
(ephemeral columns are not on disk). getStaleEphemeralMaterializedColumnsAffectedBySet detects
these; the merge and mutation paths log a warning (mirroring MutationsInterpreter::prepare for
UPDATE) instead of silently writing a stale value.

F3: the affected-by-earlier-SET check pulled in the whole primary-key expression's source columns,
so an unrelated SET on a sibling sort-key column (ORDER BY (toStartOfDay(ts), user_id), grouping
only by toStartOfDay(ts), SET user_id) wrongly forced executeUnsorted. getGroupByKeyStorageDependencies
now scopes to the specific key's expression node.

Extends 04511 with computed-key-over-materialized-source, per-key-scope, and ephemeral-mixed cases.

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

Copy link
Copy Markdown
Collaborator Author

Addressed the three follow-up clickhouse-gh[bot] findings on TTLResortUtils.cpp in dade957 (in-thread replies above). Summary: (F1) the materialized-source recompute now runs whenever a computed/subcolumn key reads an affected MATERIALIZED column, not only when the key name is one; (F2) an EPHEMERAL-mixed MATERIALIZED column that reads a SET target is now warned about (fail-loud, mirroring MutationsInterpreter::prepare) instead of silently written stale; (F3) the affected-by-SET check is scoped to the specific group_by key's expression node, not the whole primary-key expression, preserving the ordered fast path for unrelated SETs.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. F1: ORDER BY toStartOfMonth(d), d MATERIALIZED toDate(ts), earlier SET ts, via MATERIALIZE TTL -> 4 physical rows pre-fix. F2: m MATERIALIZED concat(toString(x), eph) + SET x -> stale m / no warning pre-fix. F3: ORDER BY (toStartOfDay(ts), user_id) grouping only by toStartOfDay(ts) + SET user_id -> affected_by_earlier_set wrongly true pre-fix.
b Root cause explained? F1: buildRefreshGroupByKeysDAG gated the materialized refresh on the key being a MATERIALIZED column, so a computed key reading a MATERIALIZED source rebuilt from the stale stored value -> grouped by pre-SET month. F2: getMaterializedColumnSourceColumns returned nullopt on any EPHEMERAL dep, so an EPHEMERAL+SET-target column was dropped as "unaffected". F3: getGroupByKeyStorageDependencies used the whole PK expression's getRequiredColumns(), pulling in sibling sort-key columns unrelated to the specific key.
c Fix matches root cause? Yes. F1: set needs_materialized_refresh when any expression key's per-key deps intersect the affected MATERIALIZED set; refresh sources first, then rebuild the key. F2: new getStaleEphemeralMaterializedColumnsAffectedBySet + warning in both merge and mutation paths. F3: new getExpressionOutputInputColumns walks only the specific key node's sub-DAG INPUT leaves.
d Test intent preserved / new tests added? Preserved (no assertions weakened). 04511 extended with F1 (computed-key-over-materialized-source), F3 (per-key scope), and F2 (ephemeral-mixed) cases.
e Demonstrated both directions? Yes. F1 case yields 4 rows on pristine HEAD (95d87f9) and 2 with the fix. F2 warning present with fix, absent before (verified in merge log). Full 04511 matches the reference on the fixed binary via a real server; the pre-fix binary diverges on the F1 rows.
f Fix general, not a narrow patch? Yes. F1 covers any expression/subcolumn key reading any transitively-affected MATERIALIZED source. F2 covers any MATERIALIZED column mixing EPHEMERAL + a SET target, in both merge and mutation paths. F3 uses generic per-node DAG dependency extraction, with a conservative whole-expression fallback.
g Generalizes across inputs/types/wrappers? Yes. Keys covered: physical, subcolumn (t.a), computed (toStartOfDay(ts), toStartOfMonth(d)), MATERIALIZED. Sources traversed transitively (chained materialized defaults). Subcolumn reads mapped through getColumnNameInStorage.
h Backward compatible? Yes. No setting, format, or on-disk change. The changes only make the written part correct (F1/F2) or avoid an unnecessary slow path (F3). F2 adds a log warning only.
i Invariants/contracts preserved? Yes. Stream-ordered-by-sort-key invariant into the writer is upheld (F1 refreshes derived keys before aggregation; F3 keeps the fast path only when the key is genuinely ordered). No trust-boundary widening; evaluateMissingDefaults/subcolumn-extraction contracts reused unchanged.

Bug Fix category retained. Stacked on #108550 — merge after it.

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

The non-sort-key MATERIALIZED and skip-index cases used SET ts = max(ts) +
toIntervalYear(5). max(2020) + 5y = 2025, which is still expired, so the
GROUP BY TTL is eligible to re-fire on a later merge and add another 5 years.
Whether it fires once (2025) or twice (2030) depends on merge scheduling, so
the printed ts flaked in the flaky-check (2030 in reference vs 2025 observed)
across all four sanitizers. The invariant under test (d = toDate(ts)) held in
both cases; only the absolute value was volatile.

Use +50y so the post-SET row is no longer expired and the TTL fires exactly
once, removing the non-determinism at its source while preserving the
freshness intent. No randomization opt-out needed.

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

Copy link
Copy Markdown
Collaborator Author

Fixed a flaky-check failure in the new test 04511_ttl_multi_group_by_set_rewrites_key (commit dca486c).

Root cause. The non-sort-key MATERIALIZED case and the skip-index case both used SET ts = max(ts) + toIntervalYear(5). max(2020-01-02) + 5y = 2025-01-02, which is still expired (now is 2026), so the GROUP BY TTL stays eligible and can re-fire on a later merge, adding another 5 years to 2030-01-02. Whether it fires once (2025) or twice (2030) depends on merge scheduling, so the printed ts was non-deterministic. The flaky-check caught it on all four sanitizers (reference had 2030-01-02, the reruns observed 2025-01-02). The invariant the case verifies, d = toDate(ts), held in both cases; only the absolute value was volatile.

Fix. Push the post-SET ts 50 years into the future (toIntervalYear(50) -> 2070-01-02). The post-SET row is then no longer expired, so the TTL fires exactly once and the value is stable across merge schedules. This removes the non-determinism at its source and keeps the freshness intent (the case still asserts d = toDate(ts) and the skip index still observes the fresh d). No randomization opt-out (no-random-*) was needed; the test stays parallel-safe and under full CI randomization.

Verified 60/60 green locally with randomized settings on the debug build.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET ts = max(ts)+toIntervalYear(5) leaves ts=2025 (still expired); a single extra OPTIMIZE FINAL flips it to 2030 on demand (.scratch/caseB.sql).
b Root cause explained? Yes. Non-idempotent SET keeps ts expired -> GROUP BY TTL re-fires a scheduling-dependent number of times -> printed ts varies (2025 vs 2030).
c Fix matches root cause? Yes. +50y makes the post-SET row unexpired so the TTL fires exactly once; the flakiness is removed at its source, not masked.
d Test intent preserved? Yes. Both cases still assert d = toDate(ts) (freshness) and the skip index still finds the row via fresh d; only the absolute year changed (2030 -> 2070). No assertion weakened, no no-random-* tag added.
e Demonstrated both directions? Yes. Old reference (2030) diverged from the deterministic new output (2070); with the fix the sole reference diff is that line and 60/60 randomized runs pass.
f Fix general, not a narrow patch? Yes. Both occurrences of the non-idempotent max(ts)+toIntervalYear(5) pattern (case B and the skip-index case) were fixed; the other cases use idempotent SETs and were already deterministic.
g Generalizes across inputs? N/A - test-determinism fix, not a code-behavior change.
h Backward compatible? N/A - test-only change.
i Invariants/contracts preserved? N/A - test-only change; no source touched.

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

When an earlier GROUP BY TTL runs unsorted, it finalizes via the aggregator
hash table (Aggregator::convertToChunks), which does not preserve primary-key
order. A later GROUP BY TTL keyed on a shorter, unaffected key prefix therefore
also receives an unordered stream and must run unsorted too; otherwise its
streaming flush-on-key-change re-fragments the scrambled groups.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
…TL SET

Three follow-up fixes for the multi GROUP BY TTL SET-rewrites-key handling:

- Transitive EPHEMERAL fail-loud: getStaleEphemeralMaterializedColumnsAffectedBySet
  only warned about a MATERIALIZED column that directly reads both an EPHEMERAL
  column and a SET target. A downstream MATERIALIZED column (m2 MATERIALIZED
  lower(m1) over m1 MATERIALIZED concat(toString(x), eph)) is equally
  unrecomputable and stale but was silently written. Build the full
  materialized-dependency graph keeping ephemeral-reading nodes and report the
  intersection of the unrecomputable and SET-affected transitive closures.

- Runtime (not metadata-only) fast-path gating in TTLTransform: a later GROUP BY
  TTL was forced onto executeUnsorted whenever an earlier GROUP BY TTL clause with
  a rewriting SET merely EXISTS. Gate on whether that earlier TTL actually fires in
  this part (its group_by_ttl.min <= current_time), so a not-yet-expired earlier
  TTL no longer costs a later one the streaming fast path. Conservative when forced
  or when TTL info is missing.

- Runtime sort-key-repair gating in MergeTask: the sort-key recompute + re-sort was
  gated only on need_remove_expired_values plus groupByTTLAssignsSortKeyColumn, both
  metadata-only, so a part with an unrelated expired TTL and a not-yet-firing
  GROUP BY ... SET on the sort key paid a whole-part O(n log n) re-sort for nothing.
  Add anyGroupByTTLFires and gate all three GROUP BY SET repairs on it.

Extends 04511_ttl_multi_group_by_set_rewrites_key with the transitive-ephemeral,
no-op-earlier-TTL, and unrelated-expired-TTL cases.

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

Copy link
Copy Markdown
Collaborator Author

Round-5 bot findings H1/H2/H3 addressed in c20a639 (stacked on #108550, merge after it).

  • H1 (TTLResortUtils.cpp, transitive EPHEMERAL fail-loud): warning now propagates through downstream MATERIALIZED columns (m1 -> m2), not just the first omitted node.
  • H2 (TTLTransform.cpp, runtime vs metadata): a later GROUP BY TTL keeps the streaming fast path when the earlier rewriting TTL does not actually fire in this part.
  • H3 (MergeTask.cpp, runtime vs metadata): the sort-key repair / re-sort is gated on whether a GROUP BY ... SET TTL actually fires, not on the mere presence of any expired TTL.
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. H1: m1 MATERIALIZED concat(toString(x),eph), m2 MATERIALIZED lower(m1), GROUP BY k SET x -> only m1 warned before, m2 silently stale (confirmed via system.text_log). H2: TTL1 ts+40y GROUP BY k SET ts, TTL2 ts+1d GROUP BY k SET payload -> TTL2 forced unsorted though TTL1 no-op. H3: firing DELETE WHERE payload<5 + GROUP BY toStartOfDay(ts) SET ts at +40y -> whole-part re-sort ran for nothing (confirmed via a temporary trace log).
b Root cause explained? H1: getStaleEphemeralMaterializedColumnsAffectedBySet did a one-hop check; getMaterializedColumnSourcesMap drops ephemeral-reading nodes, so a downstream materialized column depending on them is invisible. H2/H3: input_sorted_by_group_by_keys (TTLTransform) and the sort-key-repair gate (MergeTask) were decided from metadata (clause exists) rather than runtime (does the GROUP BY ... SET TTL actually have expired rows in this part).
c Fix matches root cause? Yes. H1: full materialized-dependency graph keeping ephemeral nodes, intersection of unrecomputable and SET-affected transitive closures. H2: group_by_ttl_fires predicate on group_by_ttl.min <= current_time, gates the cascade flag and the earlier-SET-targets set. H3: anyGroupByTTLFires gates all three MergeTask GROUP BY SET repairs.
d Test intent preserved / new tests added? Yes. 04511 extended with H1 (transitive ephemeral chain), H2 (no-op earlier TTL, correctness preserved), H3 (unrelated expired TTL, no needless sort). No existing case weakened.
e Both directions demonstrated? H1: m2 now warned (was not). H2/H3: gate flips false when the GROUP BY ... SET TTL does not fire and true when it does (verified via trace); correctness preserved in both. 50/50 randomized runs green.
f Fix is general across code paths? H1 covers arbitrary-depth chains via fixpoint. H2 handles any number of earlier TTLs. H3 gates all three repair kinds. Mutation path (MATERIALIZE TTL) always builds TTLTransform with force=true, so its GROUP BY TTL always fires -> no needless-sort concern there; H3's finding is MergeTask-specific and fixed there.
g Fix generalizes across inputs? Ephemeral closure handles subcolumn sources (mapped through tryGetColumnNameInStorage) and transitive chains. Firing predicate handles missing/uninitialized TTL info conservatively (assume fires). Computed / subcolumn / materialized keys all covered by the existing dependency mapping.
h Backward compatible? Yes. No setting, format, or on-disk change. H1 adds a warning path; H2/H3 only avoid work that was semantically unnecessary. The conservative fallbacks (force / missing info -> may fire) preserve the previous correctness guarantees.
i Invariants and contracts preserved? Yes. Block-structure / primary-index consistency is preserved: the sort-key re-sort still runs whenever a GROUP BY ... SET on the sort key actually fires (H3), and the unsorted path is still taken whenever a firing earlier TTL scrambles order (H2). The gates only skip work when the SET provably does not run in this part.

Session id: cron:clickhouse-worker-slot-0:20260712-033900

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
…UP BY TTL SET

I1: buildRecomputeMaterializedColumnsDAG passed the full stream header to
createSubcolumnsExtractionActions, which returns early when a required subcolumn
is already present. A subcolumn materialized before the TTL step (e.g. tup.ts for
ORDER BY tup.ts) goes stale after SET tup = ..., so a MATERIALIZED column like
d MATERIALIZED toDate(tup.ts) was recomputed from the pre-SET subcolumn. Drop
re-extractable derived subcolumns (parent physical column also in the stream)
alongside the stale materialized values so they are re-extracted from the post-SET
physical column, mirroring buildRecomputeSortKeyExpressionDAG.

I2: the MergeTask GROUP BY SET repairs (materialized recompute, sort-key re-sort,
ephemeral warning) were gated on anyGroupByTTLFires (whole-part) plus metadata-only
affected-column checks, so a firing TTL that does not touch the sort key still paid
a whole-part sort-key re-sort because a not-yet-expired GROUP BY ... SET touched it.
Replace anyGroupByTTLFires with getFiringGroupByTTLSetTargets (SET targets of only
the TTLs that actually fire) and gate each repair on those targets via set-target
overloads of getStaleEphemeralMaterializedColumnsAffectedBySet,
getGroupByTTLSetAffectedMaterializedColumns, and groupByTTLAssignsSortKeyColumn.

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

Copy link
Copy Markdown
Collaborator Author

Round-6 fix (commit 37841d3, base c20a639) addresses both clickhouse-gh[bot] findings I1 (subcolumn-source staleness) and I2 (per-firing-TTL gating).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. I1: ORDER BY tup.ts, d Date MATERIALIZED toDate(tup.ts), GROUP BY tup.ts SET tup = (max(tup.ts)+50y, 9) + OPTIMIZE FINAL -> stored d stale (d_fresh=0) every run. I2: ORDER BY (toStartOfDay(ts),k), firing TTL1 GROUP BY toStartOfDay(ts),k SET payload + not-expired TTL2 GROUP BY toStartOfDay(ts) SET ts (+40y) -> firing set targets = [payload] deterministically.
b Root cause explained? I1: buildRecomputeMaterializedColumnsDAG passed the full stream header to createSubcolumnsExtractionActions, which returns early when the required subcolumn is already present; add_primary_key_expression pre-extracts tup.ts, and after SET tup that copy is stale, so d recomputed from it. I2: the repair gate used whole-part anyGroupByTTLFires + metadata-wide affected-column checks, so a firing TTL that does not touch the sort key still paid a whole-part re-sort because a not-yet-expired sibling SET names the sort key.
c Fix matches root cause? Yes. I1: drop re-extractable derived subcolumns (parent physical column also in stream) with the stale materialized values so they rebuild from the post-SET physical column (mirrors buildRecomputeSortKeyExpressionDAG). I2: getFiringGroupByTTLSetTargets returns SET targets of only the FIRING TTLs; each repair gated on those targets via set-target overloads.
d Test intent preserved / new tests added? Yes. 04511 extended with --- I1 (asserts d_fresh=1 post-SET) and --- I2 (one group per (day,k), summed payload). Existing cases unchanged (append-only reference diff).
e Both directions demonstrated? Yes. I1: pristine 5bc66cd7 d_fresh=0 -> fixed d_fresh=1. I2: fixed binary logs firing targets=[payload], assigns_sort_key=false (no re-sort) in the negative case; targets=[ts,payload], assigns_sort_key=true (re-sort runs, ts->2070) in the positive control.
f Fix is general across code paths? Yes. I1 fixes the shared buildRecomputeMaterializedColumnsDAG used by both merge (MergeTask) and mutation (via recomputeAffectedMaterializedColumns / resortPipelineAfterTTLGroupBySet) and by buildRefreshGroupByKeysDAG. I2's set-target overloads keep the parameterless entry points (used by MutateTask, force=true) behaving identically.
g Fix generalizes across inputs? I1 covers any tuple/named-tuple subcolumn source and chained materialized columns (drop rule is by physical-parent-in-stream, not a specific name). I2 is independent of datatype.
h Backward compatible? Yes. No setting, format, or on-disk change; pure pipeline-construction correctness/perf fix. No SettingsChangesHistory change needed.
i Invariants and contracts preserved? Yes. I1 keeps block-structure consistency (stale subcolumns dropped then re-extracted, no duplicate columns; verified 40/40 randomized runs). I2 preserves the sort-order contract: the re-sort still runs whenever a firing SET touches the sort key; it is only skipped when no firing SET does, so the written part stays consistent with its primary index.

Stacked on #108550, merge after it. Bug Fix category retained.

Session id: cron:clickhouse-worker-slot-0:20260712-052100

The round of buildRecomputeMaterializedColumnsDAG that hides stale
pre-extracted subcolumns dropped every re-extractable subcolumn in the
stream, not just the ones feeding the recomputed MATERIALIZED columns.
With ORDER BY (d, t.a), d MATERIALIZED toDate(ts), an earlier SET ts and
a later GROUP BY d, the unrelated pass-through sort-key subcolumn t.a was
dropped and never restored, so TTLAggregationAlgorithm threw
NOT_FOUND_COLUMN_IN_BLOCK. Only drop a re-extractable subcolumn when its
physical parent is a source of one of the recomputed columns.

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

Copy link
Copy Markdown
Collaborator Author

Round-7 fix (1599857) validation gate:

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE ... ts DateTime, t Tuple(a,b), d Date MATERIALIZED toDate(ts) ORDER BY (d, t.a) TTL ts+1d GROUP BY d, t.a SET ts=max(ts)+50y, ts+2d GROUP BY d SET payload=sum(payload); INSERT + OPTIMIZE FINAL threw Not found column t.a in block on 37841d3 every run.
b Root cause explained? The round-6 stale-subcolumn drop in buildRecomputeMaterializedColumnsDAG dropped EVERY re-extractable subcolumn in the stream. When the refresh path drives a physical MATERIALIZED group_by key, expression_keys is empty so this helper is the whole rewrite. It recomputes d but also drops the unrelated pass-through sort-key subcolumn t.a, which nothing restores. TTLAggregationAlgorithm iterates header.getNames() and does getByName("t.a") -> NOT_FOUND_COLUMN_IN_BLOCK.
c Fix matches root cause? Yes. Drop a re-extractable subcolumn only when its physical parent is a SOURCE of one of the recomputed MATERIALIZED columns (derived from each column's default expression via getMaterializedColumnSourceColumns). Stale inputs (tup.ts feeding d) are still dropped; unrelated t.a is kept.
d Test intent preserved / new tests added? Added case I3 to 04511. All prior cases (basic, subcolumn key I1, per-firing-TTL gating I2) unchanged and still pass.
e Both directions demonstrated? Fails on 37841d3 (NOT_FOUND t.a), passes on 1599857 (one group per (d, t.a)).
f Fix is general across code paths? The helper is the single point used by both merge (buildRefreshGroupByKeysDAG, recomputeAffectedMaterializedColumns) and mutation paths; the narrowing applies to all of them. buildRecomputeSortKeyExpressionDAG already scopes to sort-key columns and is unaffected.
g Fix generalizes across inputs? Source detection strips subcolumns to physical parents (Nested::tryGetColumnNameInStorage) and handles ephemeral sources, so it covers tuple subcolumns, plain physical, and multi-hop materialized chains. Boundary: no recomputed materialized column -> recompute_source_parents empty -> no subcolumn dropped (only the stale materialized values), which is correct.
h Backward compatible? N/A. Internal TTL merge/mutation rewrite; no setting, format, or on-disk change.
i Invariants and contracts preserved? Yes. The block handed to TTLAggregationAlgorithm retains every column of the input header (pass-through subcolumns are no longer removed); the algorithm's header.getNames() contract holds. Recomputed columns still overwrite their stale values.

Session id: cron:clickhouse-worker-slot-0:20260712-065000

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
…efresh drop

An earlier GROUP BY ... SET can move a later GROUP BY TTL from won't-fire to
fires within the same merge/mutation, so the precomputed group_by_ttl.min is
only a valid won't-fire proof for the unmodified part. Treat a later TTL as
firing whenever an earlier fired SET rewrote a column its expiry expression
reads, in both TTLTransform (fast-path/order decision) and MergeTask
(getFiringGroupByTTLSetTargets repair gate).

Also drop stale re-extractable subcolumns subcolumn-granularly in
buildRecomputeMaterializedColumnsDAG: only the specific subcolumns the recompute
reads, not every subcolumn sharing a rewritten physical parent, so an unrelated
sibling sort-key subcolumn (t.a for ORDER BY (d, t.a), d MATERIALIZED toDate(t.b))
is preserved instead of throwing NOT_FOUND_COLUMN_IN_BLOCK.

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

Copy link
Copy Markdown
Collaborator Author

Round-8 findings (chained SET->later-TTL firing in TTLTransform/MergeTask, and subcolumn-granular refresh drop) addressed in e9c599f.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. B: ORDER BY d, d MATERIALIZED toDate(ts), TTL1 GROUP BY d SET ts2=min(ts2)-20y + TTL2 ts2+1d GROUP BY d SET ts=max(ts)+50y, plain OPTIMIZE -> d stale. C: ORDER BY (d, t.a), d MATERIALIZED toDate(t.b), earlier SET t, later GROUP BY d -> Not found column t.a (merge and mutation). A shares B's root cause (TTLTransform-side analogue).
b Root cause explained? The per-part precomputed group_by_ttl.min proves "won't fire" only for the UNMODIFIED part; an earlier firing GROUP BY ... SET can move a later TTL's expiry base from future to expired in the same run, so the later TTL fires yet was excluded from the firing gate (B/A). Separately, round-7 dropped stale subcolumns by physical-parent name, over-dropping unrelated sibling subcolumns of a rewritten parent (C).
c Fix matches root cause? Yes. groupByTTLExpiryAffectedByEarlierSet treats a later TTL as firing when an earlier fired SET target is in its expiry columns; wired into TTLTransform (A) and getFiringGroupByTTLSetTargets (B). buildRecomputeMaterializedColumnsDAG drops only the specific subcolumns the recompute reads (C).
d Test intent preserved / new tests added? Yes. 04511 extended with J1 (sibling subcolumn preserved, d fresh) and J2 (chained-min invalidation, d never stale). Existing cases unchanged.
e Both directions demonstrated? Yes. On round-7 HEAD (faafce27): C8d throws Not found column t.a, B8c writes d stale=1. With the fix (e4e138ad): C8d 40 rows + d fresh, B8c stale=0.
f Fix is general across code paths? Yes. Chained-firing gate applies in both the streaming decision (TTLTransform) and the merge repair gate (MergeTask); MutateTask uses force=true so all TTLs fire (parameterless overloads apply). Subcolumn drop fix is shared by merge, mutation, and buildRefreshGroupByKeysDAG (all call the one helper).
g Fix generalizes across inputs? Yes. Expiry-column mapping handles physical, subcolumn (mapped to parent) and WHERE-clause reads. Subcolumn drop is keyed on the exact subcolumns read, covering tuple/nested parents; sibling subcolumns preserved regardless of arity.
h Backward compatible? Yes. No setting, format, or on-disk change. The changes make previously-skipped correctness repairs run (fix stale data / crash) and only tighten/loosen an internal fast-path decision; no user-visible behavior change beyond correctness.
i Invariants and contracts preserved? Yes. The written part's block structure is preserved (sibling subcolumns kept, no column dropped without restore); the sort-key/primary-index consistency invariant is upheld (chained-fired SET now triggers the re-sort/recompute); the "input ordered by group_by keys" contract of TTLAggregationAlgorithm is only asserted when actually true.

Session id: cron:clickhouse-worker-slot-0:20260712-080700

buildRecomputeMaterializedColumnsDAG rewrote a MATERIALIZED default's
subcolumn reads to getSubcolumn(parent, ...) before analysis, so
requiredSourceColumns() reported only the physical parent (tup) and
never the subcolumn (tup.ts). recompute_read_subcolumns stayed empty,
the stale pre-SET tup.ts was not dropped, and d = toDate(tup.ts) was
recomputed from the stale value under parallel merges. Analyze the
expression as written so the subcolumn read is reported by name.

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

Copy link
Copy Markdown
Collaborator Author

Flaky-check fix (head b478bb4)

The 04511 flaky-check failures (amd_debug/asan/tsan/msan) were a real correctness gap, not test noise. The I1 case (d MATERIALIZED toDate(tup.ts), SET tup = ...) intermittently wrote d stale (d_fresh=0).

Root cause: in buildRecomputeMaterializedColumnsDAG, the round-7 subcolumn-granular drop analyzed the MATERIALIZED default AFTER replaceSubcolumnsToGetSubcolumnFunctionInQuery rewrote tup.ts into getSubcolumn(tup, 'ts'). requiredSourceColumns() then reported only the physical parent tup, never the subcolumn tup.ts, so recompute_read_subcolumns was always empty. The stale pre-SET tup.ts already extracted into the stream (for ORDER BY tup.ts) was not dropped, and d was recomputed from it. Under parallel merges the outcome depended on evaluation ordering, so it flaked. Confirmed by tracing requiredSourceColumns(): with the rewrite it returns [tup], without it [tup.ts].

Fix: analyze the default expression as written (no getSubcolumn rewrite), so the subcolumn read is reported by name and dropped, forcing re-extraction from the post-SET parent.

Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. clickhouse-test --flaky-check --test-runs N --jobs 8 reproduces (6-7 FAIL / 120 runs); single-threaded masks it. Trace confirmed the empty recompute_read_subcolumns.
b Root cause explained? Yes. replaceSubcolumnsToGetSubcolumnFunctionInQuery collapses tup.ts to parent tup in requiredSourceColumns(), so the stale pre-extracted tup.ts is never dropped and d = toDate(tup.ts) recomputes from it.
c Fix matches root cause? Yes. Removes the rewrite so analysis reports the subcolumn tup.ts, which the existing drop logic then handles.
d Test intent preserved? Yes. No test weakened; the existing I1 assertion (d = toDate(tup.ts)) now holds deterministically.
e Both directions? Yes. Before: 6-7 FAIL / 120x8 runs. After: 0 FAIL across 120 runs x 10 jobs (two batches), plus 50 normal randomized runs.
f General, not narrow? Yes. The fix is in the shared subcolumn-detection loop; it applies to every MATERIALIZED default reading a subcolumn of a SET target, not just tup.ts.
g Generalizes across inputs? Yes. Subcolumn detection now works for any parent.sub read; sibling subcolumns still preserved (J1 case unchanged).
h Backward compatible? N/A (internal merge/TTL recompute path; no format/setting/default change).
i Invariants preserved? Yes. Block structure unchanged; the DAG still drops only recompute-feeding subcolumns and preserves pass-through columns (no NOT_FOUND_COLUMN_IN_BLOCK).

Session id: cron:clickhouse-worker-slot-1:20260712-110800

The GROUP BY TTL aggregation finalization only restored a top-level
LowCardinality wrapper on SET expression results. When the SET target and
its source differ in a nested wrapper (e.g. target Tuple(UInt32, UInt32) vs
argMax over Tuple(LowCardinality(UInt32), UInt32)), the raw result column was
appended to the result block with a type that diverges from the declared
column type, tripping the block-structure type check and aborting the merge
in debug/sanitizer builds. Coerce the result to the declared type with
castColumn, which also subsumes the previous LowCardinality-only handling.

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

Copy link
Copy Markdown
Collaborator Author

Pushed 1677e6d1: fix for the AST fuzzer LOGICAL_ERROR (STID 2508-3698) on this PR.

Root cause: TTLAggregationAlgorithm::finalizeAggregates only restored a top-level LowCardinality wrapper on the GROUP BY TTL SET result. When the SET target and its source differ in a NESTED wrapper (e.g. target Tuple(UInt32, UInt32) vs argMax over Tuple(LowCardinality(UInt32), UInt32)), the raw result column was appended to the result block with a type diverging from the declared column type, tripping the block-structure assertTypeEquality check and aborting the merge in debug/sanitizer builds. This code path is identical to master, so the assertion is latent on trunk; it surfaced only here because the targeted fuzzer seeds from this PR's new Tuple GROUP-BY-TTL-SET tests.

Fix: coerce the SET result to the declared column type with castColumn (subsumes the previous LowCardinality-only handling). Added a regression case t_subwrap to 04327 (Tuple with a LowCardinality inner element in the SET source). Verified the fix generalizes across Nullable-inner Tuple, LowCardinality-inner Array, and scalar LowCardinality.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110098&sha=b478bb4e25a432b6ad4385d4b057d1c783cf560a&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. cand Tuple(a LowCardinality(UInt32), b UInt32), t Tuple(a UInt32, b UInt32), SET t = argMax(cand, v), OPTIMIZE FINAL aborts every time (repro2.sql variant B) on the pre-fix binary.
b Root cause explained? Yes. Aggregation strips wrappers; SET result Tuple(LowCardinality(UInt32), UInt32) diverges from declared t type Tuple(UInt32, UInt32) in a nested element; the LC-restore block only checked top-level lowCardinality() (false for a Tuple), so the divergent column was appended -> ColumnTuple::insertRangeFrom -> assertTypeEquality abort.
c Fix matches root cause? Yes. castColumn(result, declared_type) coerces the SET result to the exact declared type before the insert, keeping the block structure valid for any divergence, not just top-level LC.
d Test intent preserved / new tests added? Yes. Added t_subwrap to 04327 covering the nested-wrapper SET case; existing t_lc (top-level LC restore) still passes unchanged.
e Both directions demonstrated? Yes. Pre-fix binary (Build AD2029D0) aborts on t_subwrap-shaped input; post-fix binary (F422920C) passes 04327 + 04511 and prints the correct rewritten value.
f Fix is general across code paths? Yes. Single finalization path handles all SET parts; castColumn is the standard coercion used elsewhere. Not a symptom guard - it fixes where the divergent column is produced/consumed.
g Fix generalizes across inputs? Yes. Verified with Nullable-inner Tuple, LowCardinality-inner Array, and scalar LowCardinality SET sources - all coerce correctly.
h Backward compatible? Yes. No setting, format, or default change; only fixes an abort that could never succeed before.
i Invariants preserved? Yes. Restores the block-structure invariant (result block column types == declared header types) that the old narrow restore violated for nested wrappers.

Session id: cron:clickhouse-worker-slot-0:20260712-231500

… inputs

groupByTTLExpiryAffectedByEarlierSet compared a later TTL's expiry storage
columns only against the earlier SET targets directly, so an expiry that reads
a MATERIALIZED column derived from a SET target (e.g. d MATERIALIZED toDate(ts2),
expiry d + 1d, earlier SET ts2) was missed. Expand the comparison through the
materialized dependency graph.

Two consequences fixed:
- Merge-side (getFiringGroupByTTLSetTargets): the later TTL is now included in
  the firing set, so its own SET target's dependent MATERIALIZED columns are
  recomputed instead of written stale.
- In-transform (TTLTransform): the affected MATERIALIZED expiry input is now
  refreshed from post-SET storage before the later TTLAggregationAlgorithm runs,
  so isTTLExpired reads the post-SET value instead of skipping aggregation.

Regression cases K1 (merge-side) and K2 (in-transform) added to 04511.

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

Copy link
Copy Markdown
Collaborator Author

Both round-9 findings confirmed with an instrumented A/B (pre-fix vs post-fix, Build-ID-verified debug binary) and fixed in 1604cbc.

Root cause (single defect, two surfaces): groupByTTLExpiryAffectedByEarlierSet compared a later TTL's expiry storage columns only against the earlier SET targets directly, so an expiry that reads a MATERIALIZED column derived from a SET target (d MATERIALIZED toDate(ts2), expiry d + 1d, earlier SET ts2) was not detected. Fixed by expanding the earlier SET targets through the materialized dependency graph (getMaterializedColumnsAffectedBySet) before the comparison.

Merge-side (3566041088): getFiringGroupByTTLSetTargets now includes the later TTL, so its own SET target is in firing_set_targets and the dependent MATERIALIZED columns (e.g. d = toDate(ts)) are recomputed at MergeTask.cpp:3248 instead of written stale. Instrumented pre-fix showed firing_set_targets=[ts2], affected_materialized_columns=[d2] (missing d); post-fix includes ts and recomputes d.

In-transform (3566041092): buildRefreshGroupByKeysDAG now also refreshes the affected MATERIALIZED columns the expiry reads, and TTLTransform builds the refresh when the expiry is affected (not only the group_by key). So isTTLExpired evaluates on the post-SET d instead of reading the stale in-stream value and skipping aggregation.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. K1 (merge-side): d != toDate(ts) count 1 pre-fix, 0 post-fix. K2 (in-transform): max(payload)=toYear(max(d)) false pre-fix, true post-fix. Both via OPTIMIZE FINAL on a single fixed insert. Background-merge variant (merge_with_ttl_timeout=0) shows the in-transform skip directly: payload 10 (skipped) pre-fix, post-SET year post-fix.
b Root cause explained? Yes. groupByTTLExpiryAffectedByEarlierSet matched only direct expiry storage columns against the earlier SET targets; a MATERIALIZED expiry input derived from a SET target was never mapped to its physical source, so the later TTL was excluded from firing detection and its derived expiry input was left stale.
c Fix matches root cause? Yes. The comparison is expanded through the materialized dependency graph (the same graph the PR already uses for group_by keys); no symptom masking.
d Test intent preserved / new tests? Yes. K1 and K2 added to 04511; existing A..J cases unchanged and still pass.
e Demonstrated both directions? Yes. K1/K2 fail on the pre-fix binary and pass on the post-fix binary (A/B on the same worktree).
f Fix general, not a narrow patch? Yes. The expansion is applied to both surfaces that call the detection (merge firing gate and in-transform refresh) and to both expiry and WHERE columns, transitively through multi-hop MATERIALIZED chains.
g Generalizes across inputs? Yes. Covers direct SET target, one-hop and multi-hop MATERIALIZED derivation, and subcolumn expiry reads (mapped to storage parent by the existing helper).
h Backward compatible? Yes. No setting, format, or default change; only widens detection of an already-handled staleness class.
i Invariants preserved? Yes. The refresh reuses the existing recompute-materialized / recompute-sort-key DAGs; block structure and the "recompute before the later algorithm consumes the block" ordering are unchanged.

Session id: cron:clickhouse-worker-slot-1:20260713-231200

A later GROUP BY TTL whose expiry or WHERE reads a subcolumn of a column an
earlier SET rewrites (ORDER BY tup.ts, TTL1 SET tup, TTL2 tup.ts + 1d) kept the
pre-SET subcolumn pre-extracted before the TTL step. buildRefreshGroupByKeysDAG
only repaired group_by keys and affected MATERIALIZED columns, so the stale
subcolumn survived; executeExpressionAndGetColumn then preferred it over
re-extracting from the post-SET parent, and the TTL evaluated expiry on the
pre-SET value (skipping aggregation or firing on wrong rows).

Drop such stale expiry/WHERE subcolumns and re-extract them from the post-SET
parent, subcolumn-granular so an unrelated pass-through sibling subcolumn is
kept. Extends the round-9 derived-expiry refresh (which handled MATERIALIZED
inputs) to subcolumn inputs.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The chain-fire / pre-refresh handling (an earlier firing GROUP BY ... SET
can move a later TTL from future to expired in the same block) was scoped
to later GROUP BY TTLs. A later column TTL is built from
old_ttl_infos.columns_ttl[...] and TTLColumnAlgorithm::execute bails when
its precomputed min (over the pre-SET values) is in the future, so the
column was skipped even after an earlier SET moved its expiry input into
the past. If the column TTL expires on a MATERIALIZED input derived from a
SET target, the stored value is also read stale.

TTLTransform now detects the interaction for each later column TTL with the
same groupByTTLExpiryAffectedByEarlierSet check used for GROUP BY TTLs,
tells TTLColumnAlgorithm to skip the stale min/max shortcuts and recompute
expiry per row, and pre-refreshes the affected MATERIALIZED/subcolumn
expiry inputs (buildRefreshGroupByKeysDAG) before the algorithm runs.

Regression: 04511 M1 (direct expiry column) and M2 (MATERIALIZED expiry
input); both keep the stale payload before the fix and reset it after.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
if (it == old_ttl_infos.group_by_ttl.end())
return true;
const auto min_ttl = it->second.min;
return min_ttl == 0 || min_ttl <= current_time_;

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.

min == 0 here is not just "missing/uninitialized". MergeTreeDataWriter::updateTTL leaves a GROUP BY TTL info at {min=0,max=0} when its WHERE filter matches no rows, so a shape like TTL1 ... GROUP BY k SET k = max(v) WHERE flag = 1, TTL2 ... GROUP BY k SET payload = sum(payload) with all flag=0 still makes this branch treat TTL1 as firing.

That means earlier_group_by_set_targets still picks up k, TTL2 is forced onto executeUnsorted, and the merge-side twin in getFiringGroupByTTLSetTargets will also trigger the full re-sort / materialized refresh path for a part where the earlier TTL actually rewrote nothing. Correctness survives only because of the extra resort, but the whole-part external-aggregation and O(n log n) sort cost comes back for WHERE-filtered TTLs that do no work.

This needs a separate "has any qualifying rows" signal (or runtime feedback from TTLAggregationAlgorithm), not min == 0, which currently conflates "uninitialized" with "filter matched nothing".

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — fefe6e9

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Block structure mismatch in A stream: different columns (STID 0993-27f0) logical-error (chronic trunk UnionStep/optimizer; 103 PRs / 4 master, 14d; unrelated to this PR's TTL/merge diff) #107719 (ours, open)
Stress test (arm_asan_ubsan) / Hung check failed, possible deadlock found deadlock (chronic trunk leaked-local-ThreadPool; 279 PRs / 73 master, 14d) #105905 (ours, merged diagnostic) / a fix task is tracked at full effort (fixing-PR link to follow here)
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260714-093000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 701/735 (95.37%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — dbd6f71

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky under parallel replicas: the per-table max_concurrent_queries throttle is keyed on query id, so one statement becomes several same-table reads that compete against themselves #112385 (ours, open)
Stateless tests (arm_binary, parallel) / 02354_distributed_with_external_aggregation_memory_usage Code 241 on the INSERT at the CI 5G profile memory limit; the runner reproduced it 17/25 times with the same randomized settings, and it also hits master a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260729-053000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 02354_distributed_with_external_aggregation_memory_usage Code 241 red: #112478

alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Aug 1, 2026
…ERIALIZED columns

Merge branch 'groeneai/fix-ttl-multi-group-by-set-rewrites-key' into
groeneai/fix-ttl-group-by-set-sort-key-resort.

The AI review of this pull request blocks it on two correctness gaps that
were both already implemented in the separate draft ClickHouse#110098, which is a
content superset of this branch and therefore effectively a stacked pull
request. Project convention is to keep such dependent work in a single
pull request, and the second gap is a behavioural regression of this
change on its own (the repair sort turns a loud `Sort order of blocks
violated` into silently wrong TTL aggregates), so both fixes belong here:

* Every `MATERIALIZED` column that transitively reads a `GROUP BY TTL`
  `SET` target is now recomputed, not only the sorting-key subset
  (`getGroupByTTLSetAffectedMaterializedColumns`,
  `recomputeAffectedMaterializedColumns`), so neither the stored column
  nor a rebuilt skip index or projection is written stale. Mixed
  `EPHEMERAL` + regular sources cannot be recomputed during a merge, so
  they are reported via `getStaleEphemeralMaterializedColumnsAffectedBySet`
  with a warning, mirroring `MutationsInterpreter::prepare` for `UPDATE`.
* Multiple `GROUP BY` TTLs in one `TTLTransform` no longer lose groups
  when an earlier `SET` rewrites a later TTL's `group_by` key or expiry
  input (`groupByKeysAffectedByEarlierSet`,
  `groupByTTLExpiryAffectedByEarlierSet`, `buildRefreshGroupByKeysDAG`,
  and the non-streaming path in `TTLAggregationAlgorithm`).
* Each repair is gated on the `SET` targets of the `GROUP BY` TTLs that
  can actually fire in the part (`getFiringGroupByTTLSetTargets`), so a
  not-yet-expired `GROUP BY ... SET` on the sorting key does not force a
  whole-part re-sort.

Conflicts were the two branches' independent copies of the shared code;
resolved as the union, keeping the newer bounded-spill work from this
branch: `resortPipelineAfterTTLGroupBySet` and the merge path keep the
`MergeTreeSettings` argument and `buildTTLResortSortingSettings`, so the
repair sort remains bounded by
`ttl_resort_max_bytes_before_external_sort`.

Tests `04511_ttl_multi_group_by_set_rewrites_key` and the widened
`04327_ttl_group_by_set_sort_key_resort` come from ClickHouse#110098;
`04661_ttl_group_by_set_resort_external_sort_spill` stays.

Addresses ClickHouse#108550 (comment)
and ClickHouse#108550 (comment)
Related: ClickHouse#110098

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Closing: the whole of this change is now folded into #108550 (commit 4923a335d75).

This branch was a content superset of #108550 — it carried that pull request's sort-key repair as well as the multi-GROUP BY TTL and full-MATERIALIZED-graph fixes — so as separate pull requests the two both rewrote the same functions and this one was effectively stacked on unmerged work. The project convention is to keep such dependent work in a single pull request, and the AI review of #108550 blocked it on exactly the two gaps fixed here (stale non-sort-key MATERIALIZED columns, and the multi-GROUP BY TTL case that the repair sort turns from a loud Sort order of blocks violated into silently wrong aggregates), so they belong in the same change.

Everything is preserved in #108550: groupByKeysAffectedByEarlierSet, groupByTTLExpiryAffectedByEarlierSet, buildRefreshGroupByKeysDAG, the non-streaming TTLAggregationAlgorithm path, getFiringGroupByTTLSetTargets, getGroupByTTLSetAffectedMaterializedColumns, recomputeAffectedMaterializedColumns, getStaleEphemeralMaterializedColumnsAffectedBySet, and the tests 04511_ttl_multi_group_by_set_rewrites_key and the widened 04327_ttl_group_by_set_sort_key_resort. On top of that, #108550's bounded-spill work is kept, so resortPipelineAfterTTLGroupBySet still honours ttl_resort_max_bytes_before_external_sort.

Please review in #108550.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 18, 2026
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]>
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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants