Repository navigation
Build skip indexes from the merged rows when an INSERT merges its block - #123291
alexey-milovidov merged 7 commits into
Conversation
With optimize_on_insert, writeTempPartImpl evaluated the combined sorting key and skip index expression on the inserted block and then merged the whole block with the engine's algorithm. The merge treated the skip index input columns as data columns: SummingMergeTree summed them (length(name) 5+5+5 = 15), grouped two mapKeys(statsMap.a|b) inputs into a fake nested map, CoalescingMergeTree kept the last non-NULL a + b, AggregatingMergeTree applied the SimpleAggregateFunction and GraphiteMergeTree rolled them up. The index was then built from values that are not in the stored rows, so queries using it skipped granules with matching rows. For SummingMergeTree a summed index input also counted in the "all summed columns are zero" rule, so rows that must be deleted were kept. Background merges are not affected because MergeTask evaluates the skip index expressions after merging. Do the same on insert: when the block is merged and skip indexes are materialized, evaluate only the sorting key before the merge, then project the merged block back to the inserted columns and evaluate the combined expression on it. Reusing the combined builder keeps one source for index inputs and avoids duplicate columns when an index expression equals a sorting key expression. All other paths run the old code. ClickHouse#96880 hit the same root cause with a constant index input in CoalescingMergeTree and guarded it in SummingSortedAlgorithm; that guard stays because FINAL and PREWHERE still use it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…teMergeTree Replacing, Collapsing and VersionedCollapsing merges emit whole input rows, so skip index inputs computed before the merge are already exact for them. Exclude these modes from the post-merge evaluation so they run the previous code and do not evaluate the sorting key twice per block. Add a GraphiteMergeTree arm to the test: three points per path in one rollup window are rolled up into one row, and the index on the rolled-up Value must match the stored row. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review (2 rounds): 2 agreed and fixed, 1 disagreed, final round clean
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261001-143800 |
|
Workflow [PR], commit [e0d8b02] Summary: ✅
AI ReviewSummaryThis PR moves skip-index expression evaluation for Final Verdict
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units246 translation units recompiled, 2582 s compile time in total, 246 of them have a recent master baseline. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Wow! This is a great finding.
One question - why don't we always build indexes after insert's merge? Is it anyhow worse than building before merge?
|
Thanks. No, it is not worse. On master the index expressions are just evaluated in the same expression as the sorting key, which has to exist before the merge; nothing requires the index part to be there. A background merge already does it the other way: The PR keeps the old path for those three engines only because of my implementation: the post-merge step drops the computed columns and re-runs the combined sorting key + index expression, so the sorting key is evaluated twice, and my internal review flagged that as wasted work where the old path is already correct. On a 10M-row INSERT into SummingMergeTree the post-merge path measured the same as master (2.21 s vs 2.24 s, debug build). I can make it unconditional and evaluate only the index expressions after the merge, as |
|
Measured on ReplacingMergeTree: building the indexes after the merge is also faster when they are on expressions, even without duplicate keys. Before the merge, the index expression results are extra columns of the block, and the merge copies them row by row for every row it keeps ( INSERT of 8M rows into a ReplacingMergeTree (Release build), median server time:
The last row is the least favourable case: with indexes on plain columns nothing is saved, and the sorting key, a string hash, is evaluated twice. Evaluating only the index expressions after the merge, as proposed above, would remove that. For Replacing (also with SetupOne Release build (no LTO) of master e28af04 with this PR, x86-64, 4 vCPU. Both conditions ran in the same binary, selected by a temporary environment switch. Paired, interleaved runs (9 for rows 1–3, 7 for row 4) with the table recreated before each run; the change is the geometric mean of the paired ratios. A second run with the sides swapped reproduced rows 1 and 3 (−8.7%, −15.4%). Settings: CREATE TABLE src (ts DateTime, user_id UInt64, url String, status UInt16, v UInt64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO src SELECT toDateTime('2026-09-01 00:00:00') + intDiv(number, 100), number,
concat('https://example.com/', toString(cityHash64(number) % 100000), '/page?id=', toString(number)),
200 + number % 5, number
FROM numbers(8000000);
CREATE TABLE dst (ts DateTime, user_id UInt64, url String, status UInt16, v UInt64,
INDEX i_url lower(url) TYPE bloom_filter GRANULARITY 4,
INDEX i_len length(url) TYPE minmax GRANULARITY 4)
ENGINE = ReplacingMergeTree ORDER BY (toStartOfHour(ts), user_id);
INSERT INTO dst SELECT * FROM src; -- no duplicate keys
INSERT INTO dst SELECT ts, intDiv(user_id, 4), url, status, v FROM src; -- 75% duplicate keys |
|
@groeneai yes, make it unconditional. |
When an INSERT merges its block (optimize_on_insert), only the sorting key is evaluated before the merge, and only the skip index expressions are evaluated on the merged rows, as MergeTask does for background merges. This now applies to every engine that merges on insert, including Replacing, Collapsing and VersionedCollapsing, whose parts are unchanged (byte-identical hash_of_all_files) and whose index expressions are evaluated on fewer rows. The sorting key is no longer evaluated twice. An index whose expression is also a sorting key expression replaces that column with its value on the merged rows, which is what a background merge writes for the same table. It differs from the pre-merge value only when the merge rewrites the key's inputs, e.g. GraphiteMergeTree rounding Time; a test arm covers that case. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done in 4536d8e: every engine that merges on insert now evaluates the sorting key before the merge and only the skip index expressions after it. An index on a sorting key expression is also evaluated on the merged rows, as in a background merge; the test has a new GraphiteMergeTree arm for that case, where the rollup rounds |
… name The post-merge skip index evaluation erased every block column named like a computed index result, assuming it was a sorting key column computed before the merge. A stored column can have such a name, for example a column `length(name)` next to `INDEX length(name)`: the part was then written with the expression result instead of the inserted values, and a stored column of another type made the statistics builder throw a LOGICAL_ERROR. An index whose own expression computes a result with the name of an inserted column is now evaluated before the merge, in the combined sorting key and skip index expression, exactly as before the change, so such a column is resolved and written as on master. Every other index of the table is still evaluated on the merged rows. The test gets an arm with a stored `length(name)` column used by the sorting key: it must keep its inserted values, while a second index and the deletion of rows summed to zero must see the merged rows. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lumns An index expression whose result is named like an inserted column still runs before the insert merge (its result replaces that column, as on master, see ClickHouse#123415), but it no longer drags the other expressions of the same index along. With `INDEX idx (length(name), v % 7)` and a stored column `length(name)`, `v % 7` was computed before the merge, so the engine merge summed it, counted it as a summed column, and the index pruned matching granules. `getCombinedIndicesExpression` selects index expressions by their analyzed result names (`IndexDescription::column_names`), so a rewrite such as constant `if` folding is routed by the name it produces, and `getSkipIndicesExpression` returns nullptr when none is left. The post-merge evaluation also re-extracts subcolumns from the merged rows. A subcolumn read by the sorting key is extracted before the merge as a separate column, and `CoalescingMergeTree` can merge it to a value different from its parent's, so `mapKeys(stats.m)` was built from the stale copy (a regression of this PR; master built it before the merge). A physical column that has the name of a subcolumn is left as stored. The Graphite arm of the test now starts from midnight, as rollup windows above 900 s are aligned to the start of the day, not to the epoch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 87dcc64Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261010-180005 |
…index-build Conflict in getCombinedIndicesExpression with ClickHouse#123291, which made the key optional and added a per-expression filter for the expressions computed after an INSERT merges its block (getSkipIndicesExpression). The helper now always takes the key plus a `compute_key` flag. The post-merge caller passes the sorting key with compute_key = false: those columns are already in the block, and the writer replaces a block column named like an index expression with the recomputed result. Without the key names, a bloom_filter over mapKeys(m) on a table ordered by mapKeys(m) would recompute the sorting key column as Array(LowCardinality(...)) instead of its declared type. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #122232
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong query results with skip indexes on
SummingMergeTree,AggregatingMergeTree,CoalescingMergeTreeandGraphiteMergeTreetables: withoptimize_on_insert(the default), anINSERTbuilt every skip index whose expression is not a plain column from the rows before they were merged, so queries using the index could skip granules with matching rows.SummingMergeTreealso no longer keeps rows whose summed columns total zero because of such an index.Description
On 26.8.10.6, after
CREATE TABLE t (id UInt64, name String, v UInt64, INDEX il length(name) TYPE minmax) ENGINE = SummingMergeTree ORDER BY idand anINSERTof 3 rows perid,SELECT count() FROM t WHERE length(name) = 5returns 0 instead of 1000. Present since at least 23.8.Root cause:
writeTempPartImplevaluates the sorting-key and skip-index expressions, thenoptimize_on_insertmerges the whole block, so the engine aggregates the index inputs like data columns (length(name)is summed to 15, twomapKeys(...)inputs become a fake nested map). The index is then built from values that are not stored, and forSummingMergeTreethe summed index input also counts in the "all summed columns are zero" deletion rule.Change: when the block is merged on insert, only the sorting key is evaluated before the merge and the skip index expressions after it, as
MergeTaskdoes, for every engine (an index on a sorting key expression, and a subcolumn read before the merge, are also evaluated on the merged rows). An index expression whose result is named like a stored column keeps the old path (#123415), without the other expressions of its index. Replacing, Collapsing and VersionedCollapsing write byte-identical parts, faster as index columns are no longer copied through the merge. Existing parts get correct indexes on their next merge orMATERIALIZE INDEX; zero-sum rows kept because of such an index are removed only by a merge.Validation: the new test fails on master in 10 arms (Summing x6, Coalescing, Aggregating, Graphite x2) and passes with the fix (49/49 randomized runs). INSERT of 4M rows into a ReplacingMergeTree (debug build, median of 3): 3.48 s -> 2.15 s with
lower(url)andlength(url)indexes; 2.20 s -> 2.25 s (noise) with an index on the sorting keycityHash64(url).🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/123291]
Version info
26.10.1.2153-master(included in26.10and later)