Skip to content

UNIQUE KEY: merge - #123013

Open
murphy-4o wants to merge 36 commits into
masterfrom
unique-key/stack-test/merge
Open

murphy-4o wants to merge 36 commits into
masterfrom
unique-key/stack-test/merge

Conversation

@murphy-4o

@murphy-4o murphy-4o commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Part of #103486

  • Merges run on UNIQUE KEY tables: the rows dead at the merge's snapshot are dropped, the merged part's unique-key index is merged from the sources' indexes, and rows killed while the merge ran are carried into the merged part's bitmap at commit.
  • A merge or mutation task starts its transaction only once its source parts' commits are visible, and a merge result rolled back at commit is left for the cleanup thread, as stock does.
  • Vertical merges skip the same rows in every column; OPTIMIZE ... DEDUPLICATE and TTL merges are refused.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

…snapshot, and commit through UniqueKeyTxnCommit::merge

- MergeTask captures the input bitmaps at merge start (captureUniqueKeyMergeInputBitmaps), drops
  dead rows from the inputs (MergeTreeSequentialSource, RangesInDataPart::delete_bitmap), builds
  MergedPartOffsets for every unique-key merge, keeps the text-index merge off that mapping,
  merges horizontally, and writes the merged part's dense index with SSTIndexWriter before
  finalizePart; UniqueKeyDenseIndexOps::writeDenseIndexOnMerge goes.
- MergePlainMergeTreeTask commits under its own uk_txn through UniqueKeyTxnCommit::merge. The
  task's transaction begins once its sources are visible (beginUniqueKeyTransaction waits out a
  source still inside its commit), so its snapshot covers their creation; a rolled-back result is
  dropped from the working set so a retry can reuse its name.
- OPTIMIZE and background merges run; the TTL case and DEDUPLICATE are refused
  (checkUniqueKeyOptimizeIsPossible, selectPartsToMerge, optimizeDryRun), and the TTL comments
  stop saying merges are disabled.
- The unique_key_merge_pause_before_commit and unique_key_merge_fail_after_publish failpoints, the transaction_hold_unknown_state hook in
  TransactionManager, the UniqueKeyMergeInputRowsSkipped ProfileEvent.
- Tests: 04109 cases 1-4, 04159, 04173, 04185, 04194 case 2, 04158_optimize_rejected deleted; 04168 case 1's
  merge lines, 04171 case 1, 04163 case 5's merge lines.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@murphy-4o
murphy-4o added this pull request to stack #123004 September 30, 2026 07:51
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cf6e525]

Summary: ✅


AI Review

Summary

Enables horizontal and vertical merges for experimental UNIQUE KEY tables, filters snapshot-dead rows, streams the merged dense index, and reconciles later deletions at commit. Reviewed PR head cf6e525c9ce90e06fa50bba7aa6e23b8fa1961a5, the full diff, and all prior discussion. The duplicate-tracker memory-limit finding remains open. The previously dismissed commit-wait and resource concerns below also remain applicable; no duplicate inline comments were posted.

Findings

❌ Blockers

  • MergePlainMergeTreeTask.cpp:166: A cancelled merge can still hold shutdown indefinitely after losing its Keeper commit reply. UniqueKeyTxnManager::commitTransaction reaches waitForLostCommitReply, whose waitStateChange calls ignore merge cancellation. Server shutdown joins the merge executor before shutting down the transaction manager, so the latter's shutdown check cannot release this wait. Make commit waits cancellation-aware while retaining protection against subsequent writes beside an unresolved transaction. [dismissed by author -- UNIQUE KEY: merge #123013 (comment)] The claimed external fix remains absent from the current code, including its explicit cancellation TODO.

⚠️ Majors

  • UniqueKeyMergedIndex.cpp:152: The per-source duplicate trackers allocate approximately 512 MiB near the permitted UInt32 merge-row limit. std::vector<bool> allocations do not enforce the memory limit, so constructing and zeroing them can exceed background/server limits before another allocation stops the merge. Use VectorWithMemoryTracking<bool> for both the member and its construction. Existing unresolved finding: UNIQUE KEY: merge #123013 (comment).

  • UniqueKeyTxnCommit.cpp:562: Late-delete reconciliation expands the entire bitmap with toVector while holding the partition write guard. In narrow mode this uses approximately 12 bytes per deletion across the result and temporary arrays: 100 million late deletions require approximately 1.2 GB before mapping. This can discard a completed merge and delay partition writers despite a compact input bitmap. Iterate incrementally with cancellation checks. [dismissed by author -- UNIQUE KEY: merge #123013 (comment)] The current code still materializes both arrays under the guard.

  • UniqueKeyDenseIndexOps.cpp:229: Rebuilding a missing/corrupt dense index retains every unique-key column of the part, then encodes/sorts those values for the writer. Newly enabled merges can produce parts much larger than insertion blocks, so rebuilding one such part can exhaust the startup/attach memory budget. Use a bounded streaming or external-sort rebuild. [dismissed by author -- UNIQUE KEY: merge #123013 (comment)] Processing one part does not bound its key payload.

  • StorageMergeTree.cpp:2079: Stored non-ordinary UNIQUE KEY definitions remain loadable, but this gate now enables their merges. For example, stored ReplacingMergeTree(ver) ORDER BY g UNIQUE KEY id metadata can contain distinct live IDs sharing g; replacement then reduces rows beyond the bitmap filter, and the new row-map consistency check rejects the merge with a LOGICAL_ERROR exception. Refuse non-ordinary modes in selection and both optimize entrypoints until supported. [dismissed by author -- UNIQUE KEY: merge #123013 (comment)] The fresh-definition restriction still exempts stored metadata replay, explicitly covered by test_unique_key_on_a_non_plain_engine_still_loads.

Tests
  • ⚠️ The repaired offset guards have no focused regression coverage: add small cases for an out-of-range late bitmap offset beyond the first 65,536-row container, and a valid-checksum source SST containing duplicate row offsets. These were requested in the original safety threads.
  • ⚠️ The current CI reports report no test failures, but the targeted stateless report contains zero test results and the finish job requests a full-suite rerun after the review-thread gate. Obtain successful executions of the new merge, late-kill, bitmap-carry, source-visibility, and vertical-merge tests. No local tests were run because this review job has no ClickHouse binary and nested Praktika runs are prohibited.
Final Verdict

Status: ❌ Block

Make merge commit waits cancellable, enforce the duplicate-trackers' memory limit, and address or explicitly track the remaining dismissed concerns. Supply regression coverage for the repaired corruption checks and CI results for the new merge tests.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 30, 2026
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit cf6e525c9ce90e06fa50bba7aa6e23b8fa1961a5 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

murphy-4o and others added 2 commits September 30, 2026 23:00
The merge passes its merge-list flag to the commit, so a background merge waiting on a lost commit
reply gives up once shutdown cancels it instead of holding shutdown. Removing a rolled-back merge
result is retried while a reader holds it, so an immediate retry of the merge can reuse its name.
A merge no longer refuses while a transaction is undetermined. 04173 kills the stranded INSERT
before its checks, fails loudly when a wait times out, keeps the late-kill tables' key column dense
and reads part names from system.parts, and its refusal case goes; 04185 reads part names from
system.parts.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
murphy-4o and others added 3 commits October 1, 2026 10:35
Comment thread src/Storages/StorageMergeTree.cpp Resolved
murphy-4o and others added 2 commits October 2, 2026 11:47
murphy-4o and others added 2 commits October 3, 2026 18:03
@murphy-4o
murphy-4o marked this pull request as ready for review October 3, 2026 10:31
CurtizJ pushed a commit to CurtizJ/ClickHouse that referenced this pull request Oct 4, 2026
…ueries_probability

Under `ignore_drop_queries_probability` a DROP of a table that does not
store data on disk was rewritten to TRUNCATE. For object storage tables
(`ENGINE = S3/Azure/HDFS/...`, also through the `s3://` URL delegate),
`Alias` tables and `CREATE TABLE ... AS <table function>` proxies that
TRUNCATE acts on data outside the server: it deletes the remote objects,
empties the alias target, or truncates whatever the table function points
at. A real DROP of the same table touches none of it.

On an unreachable endpoint the TRUNCATE retries for ~41 minutes
(500 attempts, 5 s backoff cap) while holding the table's DDL guard. In
the Upgrade check (amd_release) on PR ClickHouse#123013 the faked DROP of 05059's
`ENGINE = S3('http://localhost:19999/dummy.parquet', ...)` table hung
this way; a later `DROP DATABASE` of the shared stress database then
prepared every table for shutdown (bricking the replica of
`t_lightweight_mut_3`) and blocked behind it holding
`restart_replica_mutex`, so the pre-upgrade cleanup could neither kill
the leftover replicated mutation (TABLE_IS_READ_ONLY) nor restart the
replica (ABORTED).

Such DROPs are now ignored, as for tables that store data on disk. The
table survives either way, so the set of tables left behind by Stress
and the Upgrade check does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
murphy-4o and others added 2 commits October 4, 2026 09:21
…flag on the merge commit, 04168 merge case

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Diskein Diskein self-assigned this Oct 14, 2026
# Conflicts:
#	src/Storages/MergeTree/MergeTreeData.cpp
#	src/Storages/MergeTree/MergeTreeData.h
murphy-4o and others added 2 commits October 18, 2026 21:02
The dense index stores row numbers as UInt32, so a merge past that failed
after writing the whole part and was selected again. Join the text and
vector similarity indexes in the stock merge row cap instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`toMergedRow` counted the dead rows before each index entry with `rank`, which walks every
container before the row. Cache the dead rows before each container per source, and count a
range with `roaring_bitmap_range_cardinality_closed`, which reads only the containers it covers.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
murphy-4o and others added 3 commits October 20, 2026 18:17
A fresh ATTACH TABLE could still create a UNIQUE KEY table with a stored
`_part_index` column, whose merges then read it as the source index.
UNIQUE KEY tables are experimental, so no stored metadata needs the exemption.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
murphy-4o and others added 4 commits November 10, 2026 10:47
# Conflicts:
#	src/Common/ProfileEvents.cpp
#	src/Storages/MergeTree/MergeTask.cpp
@clickhouse-gh clickhouse-gh Bot added comp-unique-key Unique key in MergeTree: uniqueness enforced on insert through a key index (SST / dense index), d... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026
Base automatically changed from unique-key/stack-test/delete to master November 24, 2026 03:50
murphy-4o and others added 2 commits November 24, 2026 13:48
# Conflicts:
#	src/Storages/MergeTree/MergePlainMergeTreeTask.cpp
#	src/Storages/MergeTree/MergeTask.cpp
#	src/Storages/MergeTree/MergeTask.h
#	src/Storages/MergeTree/UniqueKey/DeleteBitmap.h
Mark the unique-key merge accessors [[nodiscard]] and bound 04197's
system.text_log scan by event_time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…merge, review trims

- The merge row map rejects source rows past the part (snapshot bitmaps and late kills), and the merged
  dense-index build rejects a source index that maps two keys to one row, both with CORRUPTED_DATA.
- A background merge on a unique-key table runs under its own transaction instead of keeping the one it
  was selected under open and committing it after the merge.
- The merged dense-index builder is a free function; UniqueKeyMergeInputRowsSkipped is dropped
  (input_rows_filtered counts it); the transaction overload of makeDeleteBitmapSnapshot is private.
- Comment, naming and test trims; master's include order and 04171 case numbers are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
part.name, entries, part.rows_count);

SourceCursor cursor{
.source_index = i, .part = &part, .reader = reader, .iterator = reader->newIterator(), .seen_rows = std::vector<bool>(part.rows_count)};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Major] Enforce the memory limit for the per-row duplicate tracker

seen_rows now allocates one bit per physical source row for every source before the SST scan starts. A permitted merge near the UInt32 row limit therefore allocates about 512 MiB here, even for ORDER BY tuple() where no full row mapping is needed. With the default min_allocation_size_to_throw_on_memory_limit = 0, allocations through std::allocator are counted but never refused by the memory tracker. Constructing and zeroing these vectors can consequently exceed the background/server memory limit before a later tracked allocation gets a chance to stop the merge; concurrent merges multiply that excess.

Use VectorWithMemoryTracking<bool> for seen_rows (including its construction here), so the duplicate-offset validation can raise MEMORY_LIMIT_EXCEEDED before allocating its row-sized buffer. This container stays local to the cursor, so no interface conversion or copy is needed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-unique-key Unique key in MergeTree: uniqueness enforced on insert through a key index (SST / dense index), d... pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants