Skip to content

Build skip indexes from the merged rows when an INSERT merges its block - #123291

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:skip-index-inputs-after-insert-merge
Oct 11, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:skip-index-inputs-after-insert-merge

Conversation

@groeneai

@groeneai groeneai commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122232

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 wrong query results with skip indexes on SummingMergeTree, AggregatingMergeTree, CoalescingMergeTree and GraphiteMergeTree tables: with optimize_on_insert (the default), an INSERT built 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. SummingMergeTree also 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 id and an INSERT of 3 rows per id, SELECT count() FROM t WHERE length(name) = 5 returns 0 instead of 1000. Present since at least 23.8.

Root cause: writeTempPartImpl evaluates the sorting-key and skip-index expressions, then optimize_on_insert merges the whole block, so the engine aggregates the index inputs like data columns (length(name) is summed to 15, two mapKeys(...) inputs become a fake nested map). The index is then built from values that are not stored, and for SummingMergeTree the 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 MergeTask does, 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 or MATERIALIZE 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) and length(url) indexes; 2.20 s -> 2.25 s (noise) with an index on the sorting key cityHash64(url).

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 1, 2026 14:08
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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Oct 1, 2026
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 2 agreed and fixed, 1 disagreed, final round clean
  • ⚠️ No GraphiteMergeTree arm although the entry names it. AGREE: arm added to the test.
  • ⚠️ Replacing / Collapsing / VersionedCollapsing evaluated the sorting key twice for no gain (their merge keeps whole rows). AGREE: they keep the old code path.
  • ⚠️ The test would also pass if skip indexes stopped being built. DISAGREE: the test fails on master in every index arm (the 0 there is index pruning), which is the defect this PR fixes; Bugfix validation shows it on CI.
  • Round 2 (after the two fixes): no findings.

@groeneai

groeneai commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test run through clickhouse local prints 0 1000 for every index arm and 1000 phantom rows on master, on a same-commit base build and on official 26.8.10.6; 10/10 runner FAILs on the base server.
b Root cause explained? writeTempPartImpl evaluates the skip index expressions before optimize_on_insert merges the block, so the engine aggregates the index inputs like data columns (summed, folded into a fake nested map, coalesced, rolled up) and the index is built from values that are not stored. A summed index input also stops SummingMergeTree from deleting zero-sum rows. Background merges evaluate index expressions after merging and are correct.
c Fix matches root cause? Yes. Only the sorting key is evaluated before the merge; the same combined sorting-key + skip-index expression is evaluated on the merged rows, as MergeTask does. No guard and no change in the merge algorithms.
d Test intent preserved / new tests added? New test 05315_skip_index_after_insert_merge with 7 arms: Summing (length(name) minmax, v % 7 minmax, two mapKeys bloom_filter indexes, zero-sum row deletion), Coalescing (a + b), Aggregating (SimpleAggregateFunction), Graphite (rolled-up Value). The scenario is pinned on the statements; no blanket tags.
e Both directions demonstrated? Yes. Base: all 7 arms wrong. Fix: all 7 correct, 50/50 randomized runs. Removing only the post-merge evaluation makes the test fail again.
f Fix is general across code paths? writeTempPartImpl is the only writer that merges on insert. Aggregate projection parts build only the implicit minmax indexes of add_minmax_index_for_*_columns, which exist only on their GROUP BY key columns (aggregate states are not numeric, string or temporal); the projection merge keeps those values per merged row and the index is built from the merged block. MergeTask already evaluates after the merge and mutations do not merge. Since 4536d8e every engine that merges on insert takes the new path, except an index whose own result has a stored column name (8b3987b).
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked: String, numeric, Map in Tuple, Nullable, LowCardinality(Nullable), subcolumns, an index equal to the sorting-key expression, partition and sort-key expressions, a block that becomes empty after the merge, exclude_materialize_skip_indexes_on_insert. Index types checked: minmax, bloom_filter, set and text. 543 related stateless tests were run with random settings and no new failures were found (each failure also failed on base).
h Backward compatible? (maintainer-approved exception only) No setting and no format change. New parts get the index a merge would build; existing parts are corrected by their next merge or MATERIALIZE INDEX.
i Invariants and contracts preserved? After the change the block has the same columns in the same order as before (inserted columns, then subcolumns, then key and index outputs), and they are computed from the stored rows. The block is sorted and has no permutation when the second evaluation runs. All other paths execute the old code.

Session id: cron:clickhouse-impl-self-slot-57:20261001-143800

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e0d8b02]

Summary: ✅


AI Review

Summary

This PR moves skip-index expression evaluation for optimize_on_insert parts from pre-merge rows to merged rows, while preserving the existing stored-column-name shadowing behavior and adding broad stateless coverage for SummingMergeTree, CoalescingMergeTree, AggregatingMergeTree, GraphiteMergeTree, and mixed composite-index cases. I re-checked the current diff and all prior discussion threads; the earlier concerns about stored-column shadowing, projection handling, and composite-index routing are addressed in the current code and tests, and I did not find a remaining correctness issue in the changed paths.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 1, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e0d8b0243 with master 5edd158a1 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 371a1f99e; 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.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

@alexey-milovidov alexey-milovidov self-assigned this Oct 1, 2026
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

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: MergeTask evaluates the sorting key before merging and the skip index expressions after it. For Replacing, Collapsing and VersionedCollapsing, building after the merge gives the same index (their merge keeps or drops whole rows) and evaluates fewer rows when some are dropped. Plain MergeTree does not merge on insert, so it is unaffected.

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 MergeTask does, so the sorting key is computed once. Should I push that to this PR?

@snelheidai

Copy link
Copy Markdown

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 (MergedData::insertRow).

INSERT of 8M rows into a ReplacingMergeTree (Release build), median server time:

Sorting key Skip indexes Duplicate keys in a block Before merge (PR head) After merge (f0903ec) Change (95% CI)
(toStartOfHour(ts), user_id) lower(url) bloom_filter, length(url) minmax none 3983 ms 3599 ms −9.4% (−11.1 to −7.6)
(toStartOfHour(ts), user_id) same 75% 2023 ms 1829 ms −10.8% (−12.4 to −9.2)
(cityHash64(url), user_id) same none 7724 ms 6539 ms −15.4% (−16.3 to −14.5)
(cityHash64(url), user_id) url bloom_filter, status minmax none 6310 ms 6353 ms +1.2% (−0.2 to +2.6)

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 ver / is_deleted), Collapsing and VersionedCollapsing, parts written both ways were byte-identical (system.parts.hash_of_all_files) with minmax, set and bloom_filter indexes on expressions, Map/Tuple subcolumns, ALIAS/MATERIALIZED columns, partitioning, TTL and a projection.

Setup

One 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: max_threads = 1, max_insert_threads = 1, default insert block size (~1M rows).

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

@alexey-milovidov

Copy link
Copy Markdown
Member

@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]>
@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

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 Time. Replacing, Collapsing and VersionedCollapsing write byte-identical parts, and their inserts with expression indexes are faster (numbers in the description).

… 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 87dcc64

Every failure below has an owner: a fixing PR (mine 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 (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR: UNKNOWN_TABLE (code 60) for the initiator-local _materialized_cte_c_* table when a reused MATERIALIZED CTE is read through parallel replicas with a local plan; 157 of 157 reruns pass. More than 70 PRs and 5 master runs show it since 2026-10-08 #123121 (mine, open)
Mergeable Check, PR praktika rollups of the row above #123121 (mine, open)

Session id: cron:our-pr-ci-monitor:20261010-180005

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 11, 2026
Merged via the queue into ClickHouse:master with commit c0579b9 Oct 11, 2026
165 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 11, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 12, 2026
…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]>
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 comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-self PR origin: self-found defect (impact-bar validated) 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.

4 participants