Skip to content

Introduce MergeTree Queue Engine - #99509

Open
Michicosun wants to merge 80 commits into
masterfrom
merge_tree_queue_engine
Open

Michicosun wants to merge 80 commits into
masterfrom
merge_tree_queue_engine

Conversation

@Michicosun

@Michicosun Michicosun commented Mar 14, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Introduced the experimental MergeTreeQueue and ReplicatedMergeTreeQueue engines, which keep rows in commit order using the engine-managed _block_number and _block_offset sorting key. Enable the allow_experimental_merge_tree_queue setting to create such a table. This is built on top of support for arbitrary virtual columns in the MergeTree sorting key, which lets data be sorted by insertion order without duplicating it in a projection.


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

@clickhouse-gh

clickhouse-gh Bot commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [06da17c]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
Stateless tests (amd_tsan, flaky check) FAIL
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_msan, flaky check) FAIL
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
Stateless tests (amd_binary, flaky check) FAIL
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
05023_merge_tree_sorting_key_virtual_columns FAIL cidb
Integration tests (amd_asan_ubsan, db disk, 6/8) FAIL
test_prometheus_protocols/test_compliance.py::test_promql_extended_support FAIL cidb

AI Review

Summary

This PR introduces the experimental MergeTreeQueue / ReplicatedMergeTreeQueue engines, extends MergeTree sorting/projection handling around _block_number and _block_offset, and adds focused regression coverage for the new commit-order paths. Most of the earlier queue and virtual-key invariants now have explicit guards, but one create-like entrypoint still bypasses the projection feature gate, so the experimental projection surface is not fully guarded yet.

PR Metadata

Changelog category is correct: this is an Experimental Feature. The Changelog entry is required for that category, and the current entry is specific and user-readable: it names the new engines, the required setting, and the supporting virtual-column behavior.

Findings

⚠️ Majors

  • src/Storages/MergeTree/MergeTreeData.cpp:1411 create_gate_violated treats every ATTACH as metadata replay, but MergeTreeData sets attach = true for full-definition ATTACH TABLE ... UUID '...' (...) / ATTACH TABLE ... FROM '/path' (...) as well. That lets fresh user input bypass allow_commit_order_projection (and the same helper also exempts _part_offset projections): CREATE TABLE rejects a projection using _block_number / _block_offset when the gate is off, while a full-definition ATTACH still accepts it. The gate needs the same fresh-definition distinction that registerStorageMergeTree now uses for queue and sorting-key validation.
    Suggested fix: distinguish short/replayed attach from full-definition attach here (or validate these gates earlier in registerStorageMergeTree) and cover it with a focused full-definition-attach regression.
Tests
  • ⚠️ Add a regression for full-definition ATTACH of a table definition containing a commit-order projection with allow_commit_order_projection = 0, analogous to 05045_merge_tree_full_definition_attach_validation.
Final Verdict

Status: ⚠️ Request changes
Minimum required action: close the full-definition ATTACH bypass for the projection feature gate and add the focused regression that proves the gate holds on that entrypoint too.

LLVM Coverage Report

Measured on commit 06da17c.

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: 393/406 (96.80%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 14, 2026
@Michicosun
Michicosun force-pushed the merge_tree_queue_engine branch from 980daf1 to 65371cf Compare March 24, 2026 23:26
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

alexey-milovidov and others added 4 commits August 28, 2026 01:48
`05023_merge_tree_sorting_key_virtual_columns` failed whenever the test runner randomized
`enable_block_number_column` / `enable_block_offset_column` to 1, because the expected
`BAD_ARGUMENTS` for a sorting key over disabled block columns never fired. Add the
`no-random-merge-tree-settings` tag.

`04042_merge_tree_queue_no_merging_modes` failed in the flaky checks with
`TABLE_ALREADY_EXISTS: Mapping for table with UUID=... already exists`: the full-definition
`ATTACH` cases used hardcoded UUIDs, and the UUID mapping is server-global, so concurrent or
repeated runs of the test collide. Move those cases to a new shell test,
`05045_merge_tree_full_definition_attach_validation.sh`, which generates a fresh UUID per run.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99509&sha=dffb3042c8f3982f9a134605130c9b41e51c46a3&name_0=PR
PR: #99509

Co-Authored-By: Claude Fable 5 <[email protected]>
Addresses the three AI-review blockers on the validation introduced for sorting keys over
MergeTree virtual columns:

* The validation in `registerStorageMergeTree` ran only for `args.mode <= CREATE`, so a
  full-definition `ATTACH TABLE ... UUID '...' <definition>` bypassed it. Key it off the
  fresh-definition condition already used for the TTL and queue validation (the flag is renamed
  to `is_fresh_table_definition` since it is no longer queue-specific).

* The `ALTER MODIFY/RESET SETTING` guard for `enable_block_number_column` /
  `enable_block_offset_column` was queue-only, but a regular `MergeTree` can now declare a
  sorting key over these columns too, and disabling the settings afterwards would leave the next
  merge unable to materialize the key columns. Reject disabling a setting whenever the current
  sorting key requires the corresponding column.

* The post-commit primary-index repair (`IMergeTreeDataPart::correctVirtualColumnsInIndex`)
  rewrites only a bare `_block_number` key column. A key expression over `_block_number`
  (e.g. `_block_number + 1`, or one mixing it with real columns) cannot be recomputed from the
  stored index values, so a level-0 part would keep an index built from the placeholder written
  at insert time, silently breaking key-condition pruning. Reject such key expressions at
  `CREATE`: the real value is assigned only when the insert commits, and the bare column is the
  only repairable (and the only meaningful) form.

PR: #99509

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (9 days / ~7.5k commits; the PR was CONFLICTING — a criss-cross merge base, resolved by re-applying the PR's delta onto the current master tree; only two trivial conflicts, in Settings.cpp and the MutationsInterpreter.cpp includes), fixed the two CI test failures, and addressed all three AI-review blockers.

CI failures (both in the tests added with the sorting-key validation on 2026-08-19):

  • 05023_merge_tree_sorting_key_virtual_columns failed whenever the runner randomized enable_block_number_column / enable_block_offset_column to 1 (the expected BAD_ARGUMENTS never fired) — added the no-random-merge-tree-settings tag.
  • 04042_merge_tree_queue_no_merging_modes failed in the flaky checks with a UUID collision: the full-definition ATTACH cases used hardcoded UUIDs, and the mapping is server-global. Those cases moved to the new 05045_merge_tree_full_definition_attach_validation.sh, which generates a fresh UUID per run (verified with 4 concurrent runs locally).

AI-review blockers (details in the thread replies):

  • the virtual sorting-key validation now also applies to a full-definition ATTACH (is_fresh_table_definition);
  • disabling enable_block_* settings is rejected whenever the current sorting key requires them, not only for the queue engines;
  • a key expression over _block_number is rejected at CREATE, because the level-0 primary-index repair can only reconstruct the bare column (an expression mixing it with real columns cannot be recomputed from the stored index values).

All 15 tests of the PR pass locally against the rebuilt binary; check_cpp.sh is clean.

CI of the previous head: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99509&sha=dffb3042c8f3982f9a134605130c9b41e51c46a3&name_0=PR

alexey-milovidov and others added 2 commits August 30, 2026 15:32
…26.9 block

The setting was recorded under 26.8, but 26.8 has been released without
this change, so the `settings_changes_history` style check demands the
record under the current version block (26.9).

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99509&sha=2667e1a3d1270dbb320531ac4c5cc8336cd2b1c3&name_0=PR&name_1=Style%20check
#99509

Co-Authored-By: Claude Fable 5 <[email protected]>
…gine

# Conflicts:
#	src/Storages/MergeTree/registerStorageMergeTree.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Fixed the only CI failure (Style check, settings_changes_history): the allow_experimental_merge_tree_queue record moved from the 26.8 block to the current 26.9 block of SettingsChangesHistory.cpp, since 26.8 has been released without this change. Also merged master (~1.4k commits; one trivial conflict in registerStorageMergeTree.cpp, where master removed the now-unused allow_experimental_codecs extern next to this PR's allow_experimental_merge_tree_queue one).

Verified locally with the branch binary: incremental build is clean, all 15 queue/commit-order tests pass (04032, 04037–04044, 04145, 04695, 04726, 05023, 05045), and 03999_stateless_settings_history passes with the moved record.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99509&sha=2667e1a3d1270dbb320531ac4c5cc8336cd2b1c3&name_0=PR&name_1=Style%20check

@abashkeev abashkeev added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 3, 2026
…gine

# Conflicts:
#	src/Storages/MergeTree/MergeTreeDataWriter.cpp
#	src/Storages/MergeTree/MergeTreeDataWriter.h
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Updated the branch: merged master (8 days / ~4.2k commits; the pull request was CONFLICTING) in 9cbf905fc9d9.

Conflicts were mechanical, in one place: master added a use_selected_codec parameter to MergeTreeDataWriter::writeProjectionPartImpl (used to skip the approximate-default-codec re-selection), while this branch had added std::optional<UInt64> block_number there. Resolution keeps both — the final signature is ..., bool try_adaptive_codec, std::optional<UInt64> block_number, bool use_selected_codec = false — and writeTempProjectionPart now forwards master's /*try_adaptive_codec=*/ !is_explicit_recompression together with the branch's block_number.

Verified locally: incremental ninja clickhouse clean, check_style.py clean (the two local failures are environment artifacts — broken symlinks inside the reused build directory and the settings-history check needing CI's changed_files hook data), and all 16 tests of this pull request pass against a private server (04032, 04037–04044, 04145, 04695, 04726, 05023, 05045 and 03999_stateless_settings_history).

The only CI red on the previous head was Stress test (amd_debug) → Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-4e52), which is unrelated to this change: it fires on PR=0 (master) and on dozens of unrelated pull requests every day, and it is tracked by #118722 with fixes already in flight (for example #118359). @groeneai, no action needed from me here — flagging it so it is not silently dismissed.

Review state: zero unresolved review threads, and the AI Review verdict on the previous head was "✅ No actionable findings in the current code". The remaining open item is still a design call for the author/maintainer: whether to extend the queue-engine contract to cover partitioning instead of rejecting PARTITION BY.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator

Confirming it is owned and not dismissed, with one correction to the pointer.

STID 0250-4e52 pools several unrelated producers behind one message, so the stack picks the owner, not the function name. The report on 70e80814a is the _path / _file object storage prefilter, with no FilterTransform::doTransform frame:

src/Functions/in.cpp:128: FunctionIn::executeImpl
src/Storages/VirtualColumnUtils.cpp:419: getFilterByPathAndFileIndexes
src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:581: createFileIterator
src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp:179: createIterator

That carrier is fixed by #112968 (merged 2026-09-03 22:37Z in f16484443, which ships 04669_object_storage_path_filter_global_in.sql, the globalIn case). f16484443 is an ancestor of 9cbf905fc9d9 and was not in 70e80814a, so I do not expect it on the current head. It had 0 reports anywhere since 2026-09-04, against 12 to 42 a day in the week before the merge.

#118722 and #118359 are mine, but they track the FilterTransform carrier, which is a different producer from this red. Neither closes every 4e52 producer.

alexey-milovidov and others added 2 commits September 16, 2026 19:37
…gine

# Conflicts:
#	src/Core/Settings.cpp
#	src/Core/SettingsChangesHistory.cpp
#	src/Storages/MergeTree/registerStorageMergeTree.cpp
#	tests/queries/0_stateless/04726_streaming_queries_commit_order_snapshot_plan.reference
…xpression

The rejection of key expressions over `_block_number` (only the bare
column can be repaired in the primary index of a level-0 part) walked the
original sorting-key AST. `InterpreterCreateQuery::createTable` inlines
SQL user-defined functions before the storage sees the definition, so a
`_block_number` hidden in a UDF body was already rejected through DDL, but
the invariant depended on that interpreter ordering. Analyze every key
element the same way `KeyDescription::getKeyFromAST` analyzes the whole
key and reject an element whose resolved dependencies include
`_block_number`, so the check holds regardless of how the expression was
spelled.

Regression cases with SQL UDFs added to
`05023_merge_tree_sorting_key_virtual_columns`, including a UDF that
expands to the bare column, which is a valid bare key.

Addresses the AI review thread on
#99509

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Updated the branch: merged master (8 days / ~5k commits; the pull request was CONFLICTING) in e7b0c61, and hardened the _block_number sorting-key check from the open AI review thread in 8b78891.

Conflicts were mechanical, in four files: Settings.cpp (master reclassified the neighbouring time_series_prefer_recent_samples_table as PRIVATE_PREVIEW), SettingsChangesHistory.cpp (adjacent additions in the 26.9 block), registerStorageMergeTree.cpp (master renamed allow_experimental_unique_key to enable_unique_key in the settings declarations), and the reference of 04726_streaming_queries_commit_order_snapshot_plan, where master reordered the two automatic min-max skip indexes in the EXPLAIN output; the branch's part counts were carried over onto master's ordering.

The review thread fix: the bare-_block_number invariant is now checked on the resolved expression of each key element, not on the original AST, with SQL UDF regression cases in 05023_merge_tree_sorting_key_virtual_columns. Details are in the thread reply.

Verified locally: incremental ninja clickhouse clean, check_cpp.sh clean, and all 16 tests of this pull request pass against a private server (04032, 04037–04044, 04145, 04695, 04726, 05023, 05045 and 03999_stateless_settings_history).

@groeneai, thanks for the correction on the STID 0250-4e52 owner; noted that the report on the earlier head was the _path/_file object-storage prefilter carrier fixed by #112968, which this branch has carried since the previous merge. The CI on the previous head (9cbf905) finished with no red, consistent with that.

The remaining open item is unchanged and is a design call for the author/maintainer: whether to extend the queue-engine contract to cover partitioning instead of rejecting PARTITION BY.

alexey-milovidov and others added 3 commits September 23, 2026 14:20
…gine

Conflict in `04040_commit_order_projection_merge_levels`: master fixed the
`part_log` race of this test in the `.sql` version (drop the table before
`SYSTEM FLUSH LOGS`, bound `SYSTEM SYNC MERGES` with `max_execution_time`),
while this branch had converted it to a `.sh` with a `sleep` retry loop.
Took master's `.sql` (no sleep loop) and kept this branch's expectations
(`level-1 merges` label; projections are merged, never rebuilt).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Master bumped the version to 26.10, so the style check requires the record
under the current block.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`IMergeTreeDataPart::setIndex` called `correctVirtualColumnsInIndex`, which
looked up the part's metadata with `getMetadataSnapshot`, i.e. from the
current metadata of the table. An `INSERT` writing parts with the snapshot
it took at query start still materializes a projection that a concurrent
`ALTER TABLE ... DROP PROJECTION` has already removed, so the lookup threw
`NO_SUCH_PROJECTION_IN_TABLE` and failed the insert
(`05201_check_table_dropped_projection` in the Fast test). The same applies
to the synthetic projection part of `WhatIfProjectionEstimator`, whose
projection need not exist in the table at all.

Pass the metadata the index was computed with to `setIndex` explicitly.
`loadIndex` keeps using the snapshot it already takes.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99509&sha=8b78891f5ae47a68dda3ff932a09d19b4ebdafc7&name_0=PR&name_1=Fast%20test
#99509

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (the PR was CONFLICTING) and fixed both CI reds of the previous head, pushed 8b78891f5ae4..06da17ce0ad2:

  • Merge conflict in 04040_commit_order_projection_merge_levels: master fixed the part_log race of this test in its .sql form (drop the table before SYSTEM FLUSH LOGS, bound SYSTEM SYNC MERGES with max_execution_time), while this branch had turned it into a .sh with a sleep retry loop. I took master's .sql and kept this branch's expectations (level-1 merges: projections merged, never rebuilt).
  • Style check (settings_changes_history): moved the allow_experimental_merge_tree_queue record to the new 26.10 block.
  • Fast test 05201_check_table_dropped_projection was caused by this PR. setIndex → correctVirtualColumnsInIndex looked up the part's metadata in the table's current metadata. When an INSERT still writes a projection that a concurrent DROP PROJECTION has already removed, that lookup threw NO_SUCH_PROJECTION_IN_TABLE and the insert failed. setIndex now takes the metadata the index was built with (the writer's snapshot, the mutation's snapshot, or the WhatIfProjectionEstimator projection).

Checked locally: incremental build is clean; all 15 PR tests, 05201 and 03999_stateless_settings_history pass. The one open review thread (UDF / _block_number key check) was addressed in 8b78891 and already has a reply.

/// `createTableFromAST`), and `SECONDARY_CREATE` (DDL replay in `Replicated` databases, `RESTORE`)
/// also replays previously validated definitions - those must stay loadable regardless of the
/// current settings.
const bool is_fresh_table_definition = args.mode <= LoadingStrictnessLevel::CREATE

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.

This fresh-definition split is exactly what the projection feature gates are still missing. MergeTreeData treats every LoadingStrictnessLevel::ATTACH as attach = true (src/Storages/MergeTree/MergeTreeData.cpp:823), so a full-definition ATTACH TABLE ... UUID '...' (...) ENGINE = MergeTree ... PROJECTION ... is handled like metadata replay there and skips the CREATE-only allow_commit_order_projection / allow_part_offset_column_in_projections gates.

That leaves a fresh-input bypass: with allow_commit_order_projection = 0, the equivalent CREATE TABLE throws, but a full-definition ATTACH still accepts a projection using _block_number / _block_offset. Could we reuse is_fresh_table_definition for those projection gates too (or validate them earlier in registerStorageMergeTree), and add a regression next to 05045_merge_tree_full_definition_attach_validation?

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants