Skip to content

Fix CollapsingMergeTree merges and FINAL splitting a cancel and a state row of one key from a merged part - #131513

Merged
tuanpach merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/collapsing-merged-part-cancel-state-pair
Nov 17, 2026
Merged

tuanpach merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/collapsing-merged-part-cancel-state-pair

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120649
Related: #58142

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 results of CollapsingMergeTree: a merge could keep a stale cancel row and change sum(sign) of a key, and SELECT ... FINAL could return a row of a cancelled object, when the oldest part holding the key was a merged part with a cancel and a state row of that key. The bug existed since 24.1.

Description

On 26.10.2.103, merging a CollapsingMergeTree part that kept a cancel/state pair of a key with a newer state row keeps the stale cancel row and returns sum(sign) = 0. With default settings:

CREATE TABLE t (id UInt64, sign Int8, s String) ENGINE = CollapsingMergeTree(sign) ORDER BY id;
INSERT INTO t VALUES (1, -1, 'a'), (1, 1, 'b');
OPTIMIZE TABLE t FINAL; -- the merged part keeps both rows
INSERT INTO t VALUES (1, 1, 'c');
OPTIMIZE TABLE t FINAL;
SELECT count(), sum(sign) FROM t; -- 2 0, expected 1 1

IMergingAlgorithmWithSharedChunks::rowsHaveDifferentSortColumns skips the key comparison for two rows of one source with a non-zero part level (#58142), assuming a merged part has one row per key. A Collapsing merge keeps up to two (the first cancel row and the last state row), so the pair was split into two key groups and the cancel row was collapsed on its own. SELECT ... FINAL could likewise return a row of a key whose rows all cancel.

The shortcut is now opt-in: only ReplacingSortedAlgorithm, whose merges keep one row per key, sets it, so Collapsing compares keys again, as in 23.8. Summing, Aggregating and Coalescing (IMergingAlgorithmWithDelayedChunk) also keep one row per key and are unchanged; VersionedCollapsing compares keys directly. Parts already written by affected versions are not repaired.

The new test fails on master in every randomized run and passes 50/50 with the fix. Worst-case cost (one 20M-row merged part plus a small overlapping cancel part, release build): +3 to 5% CPU for FINAL and OPTIMIZE ... FINAL on a UInt64 key, +0.4% for OPTIMIZE ... FINAL on a (String, UInt64) key, reads without FINAL unchanged.

My open #131494 changes the same helper (shortcut kept); whichever merges second needs a one-line rebase.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2554-master (included in 26.11 and later)

…te row of one key from a merged part

`IMergingAlgorithmWithSharedChunks::rowsHaveDifferentSortColumns` skipped the
key comparison for two rows of one source whose part level is non-zero
(added by ClickHouse#58142 in 24.1), on the premise that a merged part holds one row per
sort key. That holds for ReplacingMergeTree, but a CollapsingMergeTree merge
keeps the first cancel row and the last state row of a key when their counts
are equal and the last row is a state row. When such a part was the oldest
source of a key in a later merge or FINAL, the pair was split into two key
groups: the group head (the cancel row) was collapsed on its own. A merge then
kept the stale cancel row next to the newer state row (`sum(sign)` 1 -> 0,
written to disk), and FINAL could return a row of an object whose rows all
cancel.

The shortcut is now opt-in per algorithm: `ReplacingSortedAlgorithm` sets
`nonzero_level_parts_have_unique_keys`, so `CollapsingSortedAlgorithm` compares
the sort columns of every pair of rows again (the 23.8 behaviour) in merges,
vertical merges and FINAL. Summing, Aggregating and Coalescing use
`IMergingAlgorithmWithDelayedChunk` and keep one row per key, so their
shortcut is unchanged; VersionedCollapsing compares keys directly.

Parts already written by affected versions are not repaired.

Closes ClickHouse#120649

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 💡 The new nonzero_level_parts_have_unique_keys = true; sits between can_skip_to_run_end and uses_runs_of_equal_keys in the ReplacingSortedAlgorithm constructor AGREE, noted cosmetic, not blocking
2 💡 Collapsing merges and FINAL compare keys again for rows of merged parts AGREE, noted +3 to 5% CPU in the worst case (numbers in the description); a sign-aware shortcut is not exact on parts already written by affected versions (a merged part can hold two cancel rows of one key)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261114-024000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's SQL with clickhouse local gives count() = 2, sum(sign) = 0 on every run on master (expected 1 1); the new test fails 10/10 randomized runs on master.
b Root cause explained? rowsHaveDifferentSortColumns returns "different key" without comparing for two rows of one source with part level > 0 (#58142). A Collapsing merge keeps a cancel and a state row of a key, so such a pair is split into two key groups and the cancel row is collapsed alone.
c Fix matches root cause? Yes. The "one row per key in a merged part" premise is now opt-in per algorithm; only Replacing asserts it, Collapsing compares keys. No guard at the output, no setting.
d Test intent preserved / new tests added? New stateless test 05638_collapsing_merged_part_cancel_state_pair for the merge path and the FINAL path. No existing test changed.
e Both directions demonstrated? Yes. Master: test FAIL 10/10 (and 3/3 with optimize_on_insert = 0), repro 2 0. Fix: test OK 50/50 randomized, repro 1 1; Build IDs differ. Vertical merges (part_log.merge_algorithm = Vertical) behave the same.
f Fix is general across code paths? Both callers of the helper checked: Collapsing fixed, Replacing keeps the shortcut (one row per key). The same shortcut in IMergingAlgorithmWithDelayedChunk (Summing, Aggregating, Coalescing) is correct (one row per key); VersionedCollapsing compares keys directly; Graphite does not use it.
g Fix generalizes across inputs (params/datatypes/wrappers)? The defect is in row grouping, independent of column types. Checked UInt64 and (String, UInt64) keys, horizontal and vertical merges, FINAL with and without do_not_merge_across_partitions_select_final, insert merge on and off.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only how rows are grouped during merges and FINAL (the 23.8 behaviour). Parts written by affected versions are not rewritten.
i Invariants and contracts preserved? rowsHaveDifferentSortColumns now returns true only when keys differ for Collapsing; the prev_unequal_column hint is maintained as for any other pair. Replacing behaviour is unchanged (the flag is set in its constructor). Regression sweep of 334 merge/FINAL tests: no new failure.

Session id: cron:clickhouse-impl-self-slot-57:20261114-015302

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c222b7a]

Summary: ✅


AI Review

Summary

Reviewed #131513 at c222b7aba733fab9533115a0492c7fac3d2f1d9c. The change restores correct key grouping for CollapsingMergeTree merges and FINAL when a merged part retains a cancel/state pair, while preserving the shortcut for ReplacingMergeTree. No actionable findings. The new regression test passed in the Fast test report; tests were not rerun locally.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. can be tested Allows running workflows for external contributors labels Nov 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c222b7aba with master cb1a0d516 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.63, programs/clickhouse-keeper ×0.68 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 9.7 s +6.1 s (+167%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.5 s +5.4 s (+254%)
Compile time of recompiled translation units

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

Job report

@tuanpach tuanpach self-assigned this Nov 17, 2026
@tuanpach
tuanpach added this pull request to the merge queue Nov 17, 2026
Merged via the queue into ClickHouse:master with commit 2b5b2ac Nov 17, 2026
604 of 608 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 17, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
…g-merge-no-per-row-rowref

Conflicts resolved against master:
- ClickHouse#126158 added [[nodiscard]] to lines this PR edits: kept, except on
  RowRefWithOwnedChunk::firstNonEqualSortColumnsWith, which this PR removes.
- ClickHouse#131513 gated the part-level shortcut of rowsHaveDifferentSortColumns with
  nonzero_level_parts_have_unique_keys: the cursor overload keeps that gate,
  so CollapsingMergeTree still compares rows of merged parts.
- ClickHouse#131560 counts selected rows in vertical FINAL: kept, the selection is
  appended with push_back instead of insert(Field).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
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-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... 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.

Collapsing merge changes sum(sign): level>0 part's key pair never re-collapsed

3 participants