Repository navigation
Fix multiple GROUP BY TTL losing groups when an earlier SET rewrites a later TTL's group_by key - #110098
Fix multiple GROUP BY TTL losing groups when an earlier SET rewrites a later TTL's group_by key#110098groeneai wants to merge 22 commits into
Conversation
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260711-153500 |
|
Workflow [PR], commit [dbd6f71] Summary: ❌
AI ReviewSummaryThis PR closes a long chain of real correctness bugs around Findings
Final VerdictNeeds changes before merge. The main correctness work in this series looks sound, but the remaining |
… 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]>
|
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: Finding B (TTLResortUtils.cpp — non-sort-key MATERIALIZED columns). Correct: the recompute set was restricted to MATERIALIZED sort-key columns, so Test Pre-PR validation gate (click to expand)
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]>
|
Addressed the three follow-up Pre-PR validation gate (click to expand)
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]>
|
Fixed a flaky-check failure in the new test Root cause. The non-sort-key MATERIALIZED case and the skip-index case both used Fix. Push the post-SET Verified 60/60 green locally with randomized settings on the debug build. Pre-PR validation gate (click to expand)
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]>
…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]>
|
Round-5 bot findings H1/H2/H3 addressed in c20a639 (stacked on #108550, merge after it).
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260712-033900 |
…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]>
|
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)
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]>
|
Round-7 fix (1599857) validation gate: Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260712-065000 |
…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]>
|
Round-8 findings (chained SET->later-TTL firing in Pre-PR validation gate (click to expand)
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]>
Flaky-check fix (head b478bb4)The Root cause: in 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- Pre-PR validation gate (click to expand)
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]>
|
Pushed Root cause: Fix: coerce the Pre-PR validation gate (click to expand)
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]>
|
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): Merge-side (3566041088): In-transform (3566041092): Pre-PR validation gate (click to expand)
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_; |
There was a problem hiding this comment.
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".
CI finish ledger — fefe6e9Every failure below has an owner. Only
Session id: cron:our-pr-ci-monitor:20260714-093000 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 701/735 (95.37%) · Uncovered code |
CI finish ledger — dbd6f71Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-053000 |
|
Fixing PR for the |
…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]>
|
🕵 Closing: the whole of this change is now folded into #108550 (commit This branch was a content superset of #108550 — it carried that pull request's sort-key repair as well as the multi- Everything is preserved in #108550: Please review in #108550. |
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed data loss with multiple
TTL ... GROUP BY ... SETexpressions where an earlierSETrewrites a column that a laterGROUP BYTTL 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
TTLAggregationAlgorithmassumes its input is ordered by its owngroup_by_keys: it flushes the aggregation state as soon as it observes a new key value.TTLTransformruns the GROUP BY TTL algorithms sequentially on the same block, so when an earlier TTL'sSETrewrites a column that is a later TTL'sgroup_bykey, 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 (smallmerge_max_block_size) is lost entirely.TTLTransformnow tracks theSETtargets of earlier GROUP BY TTLs. For a later TTL whosegroup_bykey can be rewritten by one of them, itsTTLAggregationAlgorithmis 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_bykey 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 (aLOGICAL_ERRORabort 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 test04511_ttl_multi_group_by_set_rewrites_keyreproduces the fragmentation both within a block and across blocks.