Skip to content

Keep the part sorted when TTL GROUP BY ... SET rewrites a sorting key column - #119863

Merged
alexey-milovidov merged 7 commits into
masterfrom
fix-ttl-group-by-set-sort-order
Sep 23, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
fix-ttl-group-by-set-sort-order

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 13, 2026 •

Copy link
Copy Markdown
Member

TTL ... GROUP BY ... SET emits the aggregated rows at the position of their group in the merged stream, but a SET expression may assign arbitrary values to a column the sorting key is calculated from (for example ORDER BY (k, toStartOfDay(ts)) with SET k = max(v) or SET ts = ...), so an aggregated row could be less than the previously emitted one. The merge wrote such a part as is: a debug build threw the logical error Sort order of blocks violated in CheckSortedTransform, and a release build silently produced a part whose order and primary index do not match the data.

Now TTLAggregationAlgorithm calculates the full sorting key of every emitted row from the data (a mutation has only the primary key columns in its header, and after SET the sorting key columns calculated by the merge before the TTL step are stale) and compares it with the previously emitted row. If the order is violated, the columns the sorting key is calculated from (k and ts in the example) are replaced in the row with the values of the previous row, so the row gets the same sorting key and the part stays sorted after it is written and read again. The sorting key columns of the header, which are used for the primary index, are recalculated from the resulting data, so the primary index corresponds to the data. This is a simpler alternative to #108550, which re-sorts the output of the TTL step.

The test checks the physical order of the rows, compares the primary index (index_granularity = 1) with the data, covers the MATERIALIZE TTL mutation with PRIMARY KEY shorter than ORDER BY, and merges the written part again, which checks its order in debug builds.

Closes: #108514
Related: #108550

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):

Fix the order of rows in a data part written by a merge or a mutation with TTL ... GROUP BY ... SET when the SET clause assigns a new value to a column the sorting key is calculated from. Previously such a merge could produce a part that is not sorted and whose primary index does not match the data (a logical error Sort order of blocks violated in debug builds). Now the columns the sorting key is calculated from are replaced in an out-of-order row with the values of the previous row. Closes #108514.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.527-master (included in 26.10 and later)

alexey-milovidov and others added 2 commits September 13, 2026 22:18
… column

`TTL ... GROUP BY ... SET` emits the aggregated rows at the position of their group in the merged stream,
but a `SET` expression may assign arbitrary values to a column of the sorting key, so an aggregated row
could be less than the previously emitted one. The merge wrote such a part as is: a debug build threw
`Sort order of blocks violated` in `CheckSortedTransform`, and a release build produced a part whose
primary index does not match the data.

Now `TTLAggregationAlgorithm` tracks the sorting key of the last emitted row. If the next row violates
the order, its sorting key is replaced with the key of the previous row, so the output stays sorted
and the primary index stays consistent with the data.

Closes: #108514

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… on the number of merges

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b9df624]

Summary: ✅


AI Review

Summary

This PR fixes the primary-key / skip-index inconsistency from TTL ... GROUP BY ... SET by recomputing the sorting key from post-SET data and by moving mutation-time index materialization after TTLTransform. That closes the previously reported index issues, but one correctness gap remains: the new restoreSortOrder path mutates stored source columns after aggregation without rebuilding other stored generated columns derived from them, so the part can still contain self-contradictory rows.

Findings

❌ Blockers

  • [src/Processors/TTL/TTLAggregationAlgorithm.cpp:450] [dismissed by author -- https://github.com/Keep the part sorted when TTL GROUP BY ... SET rewrites a sorting key column #119863#discussion_r4052919999] restoreSortOrder now copies the previous row's source values into the current row for every column needed to compute the sorting key, but nothing afterwards recomputes stored generated columns derived from those sources. MutateAllPartColumnsTask only rebuilds primary/skip-index expressions after TTLTransform (src/Storages/MergeTree/MutateTask.cpp:2787), while stored DEFAULT/MATERIALIZED columns are written back exactly as they already exist in the block (stored DEFAULT/MATERIALIZED column is read as it was written in src/Storages/MergeTree/MergeTreeData.cpp:10201). We already have coverage that GROUP BY TTL preserves stored generated columns verbatim (tests/queries/0_stateless/04502_group_by_ttl_materialized_column.sql:1), so with this patch a non-expired row whose ts/k is copied forward can keep an old generated value such as month MATERIALIZED toYYYYMM(ts). That makes normal reads return rows whose stored generated columns no longer match their base data. Suggested fix: after restoreSortOrder changes any source column, recompute the dependent stored generated columns before writing the block (or reject this path when such dependencies exist).
Final Verdict

Changes requested: the index-consistency fix looks correct now, but the part can still persist wrong user-visible values through dependent stored generated columns after restoreSortOrder rewrites a row.

LLVM Coverage Report

Measured on commit b9df624.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 99/105 (94.29%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 13, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). label Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b9df624af with master 36ce602e4 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

23 object files changed (+69.57 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/TTL/TTLAggregationAlgorithm.cpp.o 228.30 KiB 273.41 KiB +45.11 KiB (+19.76%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

29 translation units recompiled, 230 s compile time in total, 29 of them have a recent master baseline.

Job report

alexey-milovidov and others added 2 commits September 19, 2026 00:46
…n columns, and cover the mutation path

The first version of `TTLAggregationAlgorithm::restoreSortOrder` compared and rewrote the sorting key
expression columns that the merge had calculated before the TTL step (`toStartOfDay(ts)`). Those columns
are not stored: the next merge recalculates the sorting key from the stored `ts`, so the part was still
out of order on disk and `CheckSortedTransform` threw the logical error `Sort order of blocks violated`
when the part was merged again. In addition, after `SET` the expression columns held the values calculated
before it, so the primary index did not correspond to the data even for rows in the right order.

Now the algorithm calculates the full sorting key from the source columns of the block itself (this also
covers a mutation, whose header has only the primary key columns), replaces the source columns of an
out-of-order row with the values of the previous row, and writes the recalculated sorting key columns into
the block for the primary index.

The test checks the physical order of the rows, compares the primary index with the data, covers
`MATERIALIZE TTL` with a `PRIMARY KEY` shorter than `ORDER BY`, and merges the written part again.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119863&sha=aa22ea9de8ab2beba8635e97cf52b40bbb29dabf&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
PR: #119863

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 2 commits September 19, 2026 09:51
…ms in a mutation

`MutateAllPartColumnsTask` materialized the primary key and the skip index expressions before `TTLTransform`,
so the cached expression columns described the data of the source part. `TTL ... GROUP BY ... SET` assigns new
values to the aggregated rows (and `restoreSortOrder` copies the sorting key source columns forward), so an
index such as `INDEX idx_month toYYYYMM(ts) TYPE minmax` kept the month of the source part and pruned the rows
of the new part away.

Move the index expression step after the TTL transforms and cover it with a `MATERIALIZE TTL` test.

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119863&sha=55a94809f223e37c899cc2c6c0f85acce3b803ec&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 (Logical error: 'GroupingAggregatedTransform pushed bucket 24 twice', STID 3994-4c1d, query from 04878_distributed_plan_shuffle_bucket_order_promise under the stress test's enable_cascades_optimizer = 1) and provide a fix in a separate PR. If the fix is already in progress, link it here. It looks like #115986, with an open fix in #119814.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Same route as #119814, the open fix you named, so there is no new PR from me. Fix-presence check on this head: #119814's tip 5cbdfc36 is not an ancestor of 55a94809, so the run was expected to red.

What the failing run shows (Stress test (arm_tsan) at 55a94809, abort at 2026-09-19 14:49:21):

  • The aborting query is 67183008-5cff-413d-8d3b-78b953930d63, with log_comment = 04878_distributed_plan_shuffle_bucket_order_promise.sql: the shuffle aggregation over remote('127.0.0.{2,3}', ..., t_shuffle_bucket_order) GROUP BY k.
  • Its changed settings carry enable_cascades_optimizer = true next to make_distributed_plan = true, distributed_aggregation_memory_efficient = true and enable_memory_bound_merging_of_aggregation_results = true, so the shard aggregation held the bucket-order promise and was planned by Cascades.
  • The stack is the initiator's memory-efficient merge: MergingAggregatedMemoryEfficientTransform.cpp:63 pushData, from tryPushTwoLevelData at :137 in prepare at :237, rejecting bucket 24. STID 3994-4c1d, the shape of [CI crash] GroupingAggregatedTransform pushData failure #115986.

That is the mechanism #119814 fixes, and #119814 also adds SET enable_cascades_optimizer = 0 to test 04878, which master's copy does not have yet. Until it lands, that test keeps reaching the route on any stress run: 18 master commits in the last 21 days and 121 different pull requests, across 8 stress flavours.

Nothing here comes from this PR. Its diff is in the TTL merge path (TTLAggregationAlgorithm, TTLTransform, MutateTask) and does not touch distributed aggregation planning.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 23, 2026
Merged via the queue into master with commit 49e3289 Sep 23, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-ttl-group-by-set-sort-order branch September 23, 2026 17:09
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants