Repository navigation
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-4:20260625-200200 |
|
cc @CurtizJ @KochetovNicolai — could you review this? It fixes a sort-order violation (silent primary-index corruption in release, LOGICAL_ERROR abort in debug) when a |
|
Workflow [PR], commit [fa3f597] Summary: ❌
AI ReviewSummaryThis PR narrows the fix to the reduced scope requested in discussion: it detects firing Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit fa3f597.
Changed lines: Changed C/C++ lines covered: 202/205 (98.54%) · Uncovered code |
|
Fixed in e779631. The gate now maps each sorting-key dependency to its storage column via One more place needed the same treatment: the re-sort step built Validated both directions on a debug build: |
CI finish ledger — e779631Every failed check below has an owner (a fixing PR).
Not PR-caused: this PR only changes Session id: cron:our-pr-ci-monitor:20260626-033000 |
|
@groeneai This fixes the MergeTask path at |
|
@cv4g Good catch on MutateTask ( Reproduced on this branch (with the merge fix already in) using a single level-0 part so the mutation, not a background merge, applies the TTL: CREATE TABLE t (k Float64, ts DateTime, v Float64)
ENGINE = MergeTree ORDER BY (k, toStartOfDay(ts))
TTL ts + toIntervalDay(1) GROUP BY k, toStartOfDay(ts)
SET ts = max(ts) + interval 100 years, k = max(v)
SETTINGS min_bytes_for_full_part_storage = 128, materialize_ttl_recalculate_only = 0;
SYSTEM STOP TTL MERGES t;
INSERT INTO t VALUES (1.0, '2000-06-09 10:00', 96827), (1.0, '2000-06-10 10:00', 41302);
ALTER TABLE t MATERIALIZE TTL SETTINGS mutations_sync = 2;
-- before bcd95db: physical read order is k = 96827, 41302 (descending) -> corrupt index
-- after bcd95db: k = 41302, 96827 (ascending) -> sortedThe fix extracts the gate and the recompute-and-resort into Multiple |
|
Addressed the secondary-index finding in f977bca (full analysis in the inline thread). Net scope of this PR now: the sort-order re-sort covers both the merge path (MergeTask) and the mutation path (MutateTask / Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-8:20260630-124500 |
CI finish ledger — f977bcaCI fully finished (Finish Workflow: success). This PR fixes the TTL
Session id: cron:our-pr-ci-monitor:20260630-173000 |
|
Re: the |
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]>
f977bca to
a0d5af7
Compare
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]>
|
Follow-up commit f2aaf8e addresses the bot's MATERIALIZED sort-key finding. Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260711-122100 |
…GROUP BY SET Extend the MATERIALIZED-sort-key recompute for TTL GROUP BY SET in two ways: 1. Transitive closure: a SET on a base column can invalidate a MATERIALIZED sort-key column several hops away (x -> y MATERIALIZED toDate(x) -> z MATERIALIZED toYYYYMM(y), ORDER BY z). The affected-column detection now takes the fixpoint over the materialized-dependency graph and recomputes the intermediate hops (y before z), instead of a one-hop check that left z stale. 2. Subcolumn sources: buildRecomputeMaterializedColumnsDAG now prepends a subcolumn-extraction DAG (as AddingDefaultsTransform does) so a default expression reading a subcolumn (d MATERIALIZED toDate(tup.ts)) can be recomputed; previously it failed with NOT_FOUND_COLUMN_IN_BLOCK. Both paths (merge and MATERIALIZE TTL) go through the shared helper. Regression cases added to 04327 for the transitive chain and the subcolumn source. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed both clickhouse-gh[bot] findings on TTLResortUtils.cpp in 3071816. Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260711-133400 |
|
Agreed. I will cut this back to the bug I reported in #108514 and nothing else. Kept: the firing-TTL gate, recomputing the sorting-key expression columns after a Dropped: everything folded in from #110098, that is recomputing every other Two consequences, since they are behaviour and not size:
The stale- I will push the reduced version. Tell me if you would rather cut it differently. |
The PR carries three independent defect families in one diff and only one of them is the reported bug (ClickHouse#108514): a `TTL ... GROUP BY ... SET` that assigns a column the sorting key depends on. Alexey asked for the diff to be cut back to that bug, so the work folded in from ClickHouse#110098 comes out. What goes: - `TTLTransform`, `TTLAggregationAlgorithm` and `TTLColumnAlgorithm` return to master. They carried the chained-clause machinery: detecting that an earlier firing `SET` rewrote a column a later `GROUP BY` TTL groups by or expires on, the sorted/unsorted aggregation split with its hash-table spill, and the later clause's key refresh. None of it is needed to keep a single clause's output ordered by the sorting key. - the four helpers in `TTLResortUtils` that existed only for that detection (`groupByKeysAffectedByEarlierSet`, `groupByTTLExpiryAffectedByEarlierSet`, `groupByTTLSetExpressionsAffectedByEarlierSet`, `buildRefreshGroupByKeysDAG`) and the three private helpers that only fed them. - `ttl_group_by_unsorted_max_bytes_before_external_group_by`, which bounded that hash table. The setting never shipped (it was added on this branch), so its `SettingsChangesHistory` line goes with it rather than becoming a tombstone. `getFiringGroupByTTLSetTargets` loses the `!fires` fallback that consulted `groupByTTLExpiryAffectedByEarlierSet`, so its `context` argument is now unused and the parameter goes too. That fallback treated a not-yet-expired clause as firing when an earlier `SET` could move it into range; the next commit replaces it with a plain bail-out for any part that has more than one `GROUP BY` TTL. Co-authored-by: Claude Opus 5 <[email protected]>
The previous commit removed the machinery that made a chain of `GROUP BY` TTLs correct, so a part with more than one of them must be left alone rather than half-repaired. `TTLTransform` runs the clauses in order over one stream. When an earlier clause's `SET` rewrites a column a later clause groups by, the later `TTLAggregationAlgorithm` receives an input that is no longer ordered by its own keys, and its flush-on-key-change loop then closes a group early and reopens it, merging rows that belong to different groups. Recomputing the sorting key and re-sorting the result would write a part that is internally consistent and still holds those wrong groups, i.e. it would hide the defect instead of fixing it. `getFiringGroupByTTLSetTargets` therefore returns an empty set for such a table. Both callers gate every repair on those targets (`groupByTTLAssignsSortKeyColumn` returns false for an empty set), so the shape behaves exactly as it does on master. This also makes the previous commit's removal of the expiry-chain fallback sound: without the bail-out the gate could conclude "exactly one clause fires" for a table where a later clause only becomes reachable after the first `SET`, and then repair it. Co-authored-by: Claude Opus 5 <[email protected]>
The remaining `MATERIALIZED` work comes out, leaving one repair for one defect: a `TTL ... GROUP BY ... SET` that assigns a column the sorting key depends on. A `GROUP BY` TTL's keys must be a prefix of the primary key (`TTLDescription.cpp`, "TTL Expression GROUP BY key should be a prefix of primary key"), and the writer takes a `MATERIALIZED` storage column out of the stream by name rather than re-deriving it. So a `MATERIALIZED` sort-key column is written from the value it already holds, and leaving it alone preserves the part's order; it is recomputing it that assigns arbitrary new values the re-sort then has to repair. The value does go stale with respect to its own expression once the `SET` rewrites a source column, but that is the stale-`MATERIALIZED` gap this PR no longer claims to close, and it is not what breaks the sorting key. Removed with it: the materialized-dependency graph, the recompute step on both paths, and the warning for a `MATERIALIZED` column that also reads an `EPHEMERAL` one. The gate reduces to "is a `SET` target among the sorting key's storage dependencies?", so `groupByTTLAssignsSortKeyColumn` no longer needs a context, and `resortPipelineAfterTTLGroupBySet` no longer needs the target set. `MutationsInterpreter` returns to master as well: `required_column_affected` changed derived-artifact invalidation for every mutation path, and the subcolumn skip index it fixed is not in the sorting key, so it does not belong to this defect either.⚠️ The expression-placement split in `MutateTask` STAYS, and is now selected by `resort_after_group_by_ttl` rather than by "the table has a `GROUP BY` TTL". It is not a sibling of that revert. `MutationsInterpreter.cpp` marks every column `TTL_TARGET` whenever the table has any `GROUP BY` TTL, on master too, so a computed skip index over a rewritten sort-key column is selected for rebuilding on `MATERIALIZE TTL` regardless. Materializing its expression before `TTLTransform` would carry a pre-`SET` value into an index the re-sort does not touch, and `MergeTreeDataPartWriterWide` writes that index from the stale column: an index that prunes valid rows. Narrowing the flag returns every non-repair case to master's combined placement, including the multi-clause shape the previous commit leaves alone and a single clause whose `SET` misses the sorting key. Co-authored-by: Claude Opus 5 <[email protected]>
Six of the eight test files covered the arms the previous commits removed, so they
go with them: 04511 and 04692 (multi-`GROUP BY`-TTL), 04691 (four `MATERIALIZED`
recompute arms plus four multi-TTL ones), 05046 and 05047 (the materialized sort-key
gate and the folded-in future/type arms), 05182 (the non-deterministic
`MATERIALIZED` boundary, which also needed the deleted setting).
04327 keeps the reported bug and loses two arms that never tested it: `t_mut_idx`
keeps its indexed `t.a` OUT of the sorting key on purpose, so it covers the reverted
`MutationsInterpreter` change, and `t_subwrap` covers a fuzzer-found type mismatch in
the reverted aggregation-finalization path (STID 2508-3698, pre-existing on master:
re-observed there before deleting the arm).
Five arms are added, four of them because nothing in the kept set could otherwise
observe a decision this cut makes:
- `t_mut_computed_idx`: a COMPUTED skip index over a rewritten sort-key column,
through `MATERIALIZE TTL`. This is what makes the expression-placement split in
`MutateTask` observable: reduced to master's combined placement, the index is
built from the pre-`SET` value and prunes granules that hold matching rows
(measured: the forced-index read returns 0 of 3 rows).
- `t_mat_prefix` / `t_mat_suffix`: a `MATERIALIZED` sort-key column in both
positions, with rows per group straddling the TTL boundary so the aggregation
interleaves aggregated and passed-through rows. These pin the property that
licenses dropping the recompute: left alone, such a column keeps the part
ordered. The expiry reads a separate column, which is what lets one group hold
both expired and live rows.
- `t_multi_ttl` + `t_single_ttl`: the multi-clause bail-out, read from the
external-sort counter with the re-sort bounded at one byte, plus the same fixture
with one clause as the control that must spill.
- `t_not_firing`: the firing gate (an expired DELETE TTL beside a `GROUP BY ... SET`
clause 40 years out), migrated from 04691 and paired with the same counter, since
per-day row counts do not observe whether the repair was skipped.
`t_f64` also gains a non-expired row so the kept fix's own shape exercises the
flush-and-pass-through path; every arm previously inserted expired rows only.
⚠️ Both files' `... sorted` oracles are rewritten, including 04661's. As written they
compared a physical read against a second read with `ORDER BY <sorting key>` -- and
that read is answered from the part's own declared order, so both sides returned the
same rows and the oracle could not fail. Measured against a binary with the
mutation-path re-sort disabled: the part was physically `[96827, 41302]`, the old
oracle said "sorted", the new one (`phys = arraySort(phys)`, ordering done outside the
planner) says it is not. `optimize_read_in_order = 0` on the ORDER BY side does not
help. In a debug build the merge aborts before writing such a part, which is what has
been hiding this; on a release build the test would have passed on the corrupt part it
exists to catch.
Co-authored-by: Claude Opus 5 <[email protected]>
|
I am not pushing the reduced version. You have your own fix in #119863, and the 880-line version I had ready next to your 131 is the same objection at a larger size. I am fine with this PR being closed in favour of it. One measurement first, because it is the part of the reduction I could not find an equivalent of in your patch. The CREATE TABLE t (k Float64, ts DateTime('UTC'), v Float64)
ENGINE = MergeTree ORDER BY (k, toStartOfDay(ts))
TTL ts + toIntervalDay(1) GROUP BY k, toStartOfDay(ts)
SET ts = toDateTime('2100-01-01 00:00:00', 'UTC') + toIntervalDay(toUInt32(max(v)))
SETTINGS index_granularity = 4, min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO t SELECT 1.0,
toDateTime('2000-01-01 10:00:00', 'UTC') + toIntervalDay(number DIV 2) + toIntervalHour(number % 2),
39 - (number DIV 2)
FROM numbers(80);
OPTIMIZE TABLE t FINAL;
The two values are 2100-02-09 and 2100-02-08, so the column is Does #119863 cover that shape? If it does, I will drop my branch. If it does not, tell me whether you want the recompute as a small separate change or would rather leave it. |
|
No, it does not cover it.
I ran your reproducer with the patch of #119863 on top of master (a release build with
The direct shape from #108514 ( The CI of #119863 says the same: the flaky check of its own test The clamp cannot be extended to this shape. So push the reduced version here: the firing gate, the recompute of the sorting key expressions from the post- |
|
That settles it. I am pushing exactly that list: the firing gate, the recompute of the sorting key expression columns from the post- Correcting one clause of my 2026-09-13 reply so the diff does not surprise you. It said the reduction keeps a The tests will cover the form you named, an aggregated row jumping over a row that did not expire, and not only a rewrite that is non-monotone in the group's day. The monotone control in that comment returned rc 0 on master, so it covers one shape rather than the negative space. One change that is not literally on your list but belongs to the I will follow up here with the pushed sha and the diffstat. |
The defect has two shapes and 04327 only observed one of them. When the SET
assigns a sort-key column directly the data comes out unsorted, which the
existing arms catch. When the SET assigns a column a sort-key EXPRESSION only
reads (`ORDER BY (k, toStartOfDay(ts))` with `SET ts`), the expression column
was materialized before the TTL step, so it keeps its pre-`SET` value, stays
ascending, passes the sort check and is copied into the index: the part is
written, the index then describes a day the data no longer holds, and a
key-range read misses rows. Nothing in the file asserted that. The only arm
touching this shape was `t_single_ttl`, and its oracle is an external-sort
counter, which says the repair ran, not that the result is right.
Three arms are added:
- `t_expr_key`: the merge path with the rewrite non-monotone in the group's
day, so `max(v)` descends as the input day ascends. Oracles are the
physical order of the recomputed key, a pruning oracle comparing a
key-range read against a full scan of the same predicate, and a following
merge over the written part. On master the order oracle and the pruning
oracle both return 0 (the read finds 0 of the 9 rows the full scan finds)
and that following merge aborts with `Sort order of blocks violated for
column number 2, left: UInt64_4105814400, right: UInt64_4105728000`.
- `t_expr_key_live`: the same shape with a MONOTONE rewrite, where an
aggregated row jumping over a row that did not expire is enough on its own:
five expired days collapse into 2100-06 and one row at 2050-01-01 is passed
through last, so the emitted key sequence ends below where it started.
- `t_mut_expr_key`: the expression shape through `ALTER TABLE ...
MATERIALIZE TTL`, which recomputes and re-sorts through its own
implementation rather than the merge one. No arm exercised that with an
expression key.
The order oracle uses `ORDER BY _part_offset`, the physical row number, so it
holds at any `max_threads`, and the part-count guard above each one keeps it
from going vacuous: with more than one active part `_part_offset` interleaves
them.
The two `MATERIALIZED` arms are dropped. They pinned a claim that is now
withdrawn: a `MATERIALIZED` sorting-key column is written from the value the
aggregation produced for it, and a `GROUP BY` TTL's keys are forced to be a
positional prefix of the primary key, so data and index agree and recomputing
it is what would break the order. There is no defect there to cover.
Co-authored-by: Claude Opus 5 <[email protected]>
Three correctness holes in the repair this PR adds, plus two test oracles that could not fail. A merge whose input part has no calculated TTL info evaluates every row (`checkAllTTLCalculated` false sets `force_ttl`), so a `GROUP BY ... SET` on a sorting-key column does rewrite that part's expired rows. The firing gate, however, reads the COMBINED part infos, and `MergeTreeDataPartTTLInfos::update` merges only the entries a part actually has: a missing entry leaves no trace, so another input's future minimum was the only minimum the gate saw and it declined the repair. The merge then wrote exactly the unsorted part this repair exists to prevent. The gate now takes `force_ttl` and assumes every TTL fires when an input's info is not calculated; the mutation path passes false, where one source part makes a missing entry visible as a missing entry. The bounded re-sort inherited `max_rows_to_sort` / `max_bytes_to_sort` / `sort_overflow_mode` from the context, because `SortingStep::Settings` imports them into `size_limits` and `fullSortStreams` installs a `LimitsCheckingTransform`. Those settings bound a USER QUERY's result; `makeQueryContextForMerge` overrides only `workload`, so ordinary hardening in the server's default profile reached this maintenance sort, where under `sort_overflow_mode = 'break'` the transform stops reading without an error and the writer commits a TRUNCATED part. Measured on a server with `max_rows_to_sort = 1` in the default profile: a three-row merge committed two rows. The sort now clears `size_limits`. For the same reason `ttl_resort_max_bytes_before_external_sort` is made the whole bound in both directions: its documented `0` means do not spill, so an inherited query threshold must not put spilling back. The skip-index expression recomputed after the re-sort analysed ALL metadata indices against the physical columns only, while the pre-TTL call it replaces on that path analyses the SELECTED indices with the virtual columns in scope. An implicit `minmax` index over `_block_number` therefore raised `UNKNOWN_IDENTIFIER` and failed the whole mutation, in a configuration master mutates fine. `getCombinedIndicesExpression` now accepts a nullable key expression list so the skip-indices-only variant can sit beside its two siblings and share their analysis. Test side: the two arms asserting that no repair runs now also assert the part_log row exists, so an empty `part_log` cannot satisfy them by accident, and the mutation path gets its own not-yet-expired arm. 04661's order oracles read physical order through `_part_offset` next to a parts count, instead of relying on the fixture staying small enough for a single-threaded natural read. Co-authored-by: Claude Opus 5 <[email protected]>
|
Pushed the reduced version: Kept, exactly the list from your comment: the firing gate; the recompute of the sorting-key expression One correction to what I wrote on 2026-09-13: I said the kept set includes "a The regression tests cover both shapes your answer named: an aggregated row jumping over a row that did Known and not fixed here, all pre-existing on master: a subcolumn skip index is hardlinked unchanged by Internal second-model review of this headTwo independent review rounds plus a second model on the finished tree; the first round sent five items ❌ Found and fixed before pushing
💡 Noted, not changed: the setting's own documentation does not repeat the multi- |
Master rolled the version to 26.10 in c9ae3d3, so the record for `ttl_resort_max_bytes_before_external_sort` was left in the 26.9 block of a release that never had it. CI checks out the PR merged with its base, so the `settings_changes_history` style check reads 26.10 from cmake/autogenerated_versions.txt and rejects the 26.9 placement. `compatibility` needs the same thing: the setting first appears in 26.10, so `compatibility = '26.9'` has to hand out the old value 0. The reason text goes from pre-26.9 to pre-26.10 for the same reason. The recorded values are unchanged, so the newest recorded value is still 268435456 and 03999_stateless_settings_history, which compares the compiled default against `argMax(new_value, (version, index))`, is unaffected. Co-Authored-By: Claude Opus 5 <[email protected]>
|
This PR was closed at 00:32:25Z with no comment, 50 minutes after I pushed the reduced version ( Where things stand: #108514 is open, #119863 is open and unchanged since 2026-09-14, and master has neither the re-sort nor If the close was accidental, please reopen and I will finish the one outstanding item: a commit moving the If the close was deliberate, say so and I will stop here. |
|
Reopened, so I pushed the one outstanding item: |
…oup-by-set-sort-key-resort
|
🕵 Merged Entry state: head
CI is running on |
|
No objection. It also removes the need for the design decision left open here on 2026-08-16 (a per-clause firing flag versus a row-granular marker): Computing the primary-key and skip-index expressions after the TTL transforms in |
Closes: #108514
Related: #119863
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results and a
Sort order of blocks violatedlogical error (a corrupt part in a release build) forMergeTreetables whoseTTL ... GROUP BY ... SETassigns a column the sorting key depends on, either directly or through a sorting-key expression such astoStartOfDay(ts). The aggregated rows are now re-sorted and the sorting-key expressions recomputed from the assigned values before the part is written, both during a merge and duringALTER TABLE ... MATERIALIZE TTL. The newttl_resort_max_bytes_before_external_sortMergeTreesetting (default 256 MiB,0disables spilling to disk) bounds that sort. Tables with more than oneGROUP BYTTL keep the previous behavior and are not repaired.Description
What breaks.
TTLAggregationAlgorithmemits aggregated groups in input order, nothing re-derivesthe sorting key after the
SET, and the part writer takes the primary-key columns from that sameblock by name. Two shapes: a directly assigned sort-key column (
SET k = max(v)) leaves the dataunsorted, so a debug build aborts and a release build writes a corrupt part. A column a sorting-key
expression only reads (
ORDER BY (k, toStartOfDay(ts))withSET ts) hides instead:MergeTaskmaterializes that expression before the TTL step, so it keepsits pre-
SETvalue, stays ascending and is copied into the index. That index describes a day the datano longer holds, so a key-range read misses rows (on master: 0 of 9) and the next merge, which
recomputes it from the stored
ts, aborts.Fix. After the TTL step, when a
GROUP BY ... SETthat can fire assigns asorting-key storage dependency, recompute the sorting-key expressions from the assigned values and
re-sort, on the merge path and on the
MATERIALIZE TTLpath; the new setting bounds that sort, sincebackground contexts disable external sorting.
A part with several
GROUP BYTTLs is left as master writes it: an earlierSETcan rewrite a columna later clause groups by, and re-sorting would only hide the wrong groups.
Not fixed here, pre-existing on master: a subcolumn skip index is hardlinked unchanged by
MATERIALIZE TTL. AMATERIALIZEDsorting-key column needs no repair: it is written from the valuethe aggregation produced, so it agrees with its index.
Workflow [PR]
Sync PR [sync-upstream/pr/108550]