Skip to content

Support parallel replicas for Merge tables and the merge() table function - #110972

Closed
alexey-milovidov wants to merge 68 commits into
masterfrom
parallel-replicas-merge-tables
Closed

alexey-milovidov wants to merge 68 commits into
masterfrom
parallel-replicas-merge-tables

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Closes: #67770
Related: #95128

Queries over Merge tables and the merge table function can now be executed with parallel replicas, gated behind a new setting parallel_replicas_allow_merge_tables (default off).

Previously such queries always ran on a single replica (#67770): on the CI Logs cluster, SELECT count() FROM text_log WHERE message LIKE '%test%' reads at 100 GB/sec using 10 replicas, while the same query through merge() reads at 10 GB/sec on one replica.

The implementation follows the same approach as parallel replicas over views (parallel_replicas_allow_view_over_mergetree) rather than the per-table-coordinator UNION expansion attempted in the earlier PR #95128: the whole first stage of the query (including aggregation) is offloaded to the replicas, and reading from every underlying MergeTree table is coordinated by a single reading coordinator, where each underlying table forms its own data stream (the same stream_id multiplexing that already serves UNION ALL views over MergeTree and projection splits).

  • On secondary replicas, the child reading steps created by ReadFromMerge pick up the coordination callbacks from the query context naturally, one announcement per underlying table.
  • On the initiator, createLocalPlanForParallelReplicas finds the ReadFromMerge step and switches it into a mode where each child reading step is created as a local parallel replicas reading step wired to the initiator's coordinator (ReadFromMerge::enableParallelReplicasLocalPlan).
  • A storage created by a table function does not exist on remote replicas under its generated id (_table_function database), so for merge(...) the remote reading step is created without a "main table"; otherwise the tables-status check would mark every remote replica as unusable.

Eligibility (checked on the initiator and re-checked on the replicas): every underlying table must be a MergeTree table, and non-replicated underlying tables additionally require parallel_replicas_for_non_replicated_merge_tree. A Merge table with a non-MergeTree child, no children at all, or FINAL falls back to regular single-replica execution, because any child that cannot be coordinated at the level of parts and mark ranges would be read in full by every replica and duplicate its rows in the result.

Changelog category (leave one):

  • New Feature

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

Support parallel replicas for Merge tables and the merge table function (enabled by the setting parallel_replicas_allow_merge_tables): reading from every underlying MergeTree table, and the whole first stage of the query, is now distributed across the replicas of the cluster. Closes #67770.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…tion

Reading from every underlying MergeTree table of a Merge table is
coordinated across replicas: each underlying table forms its own data
stream in the reading coordinator (the same multiplexing that serves
UNION ALL views over MergeTree and projection splits). The whole first
stage of the query, including aggregation, is offloaded to the replicas.

On secondary replicas the child reading steps of ReadFromMerge pick up
the coordination callbacks from the query context naturally. On the
initiator the local plan converts each child reading step into a local
parallel replicas reading step wired to the initiator's coordinator.

A storage created by a table function does not exist on remote replicas
under its generated id (_table_function database), so for merge() the
remote reading step is created without a main table to check on
connection establishment.

Gated behind a new setting parallel_replicas_allow_merge_tables
(default off). Eligible only when every underlying table is a MergeTree
table; non-replicated underlying tables additionally require
parallel_replicas_for_non_replicated_merge_tree.

Closes #67770
@mintlify

mintlify Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 19, 2026, 7:18 AM

@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [63f0ef0]

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 19, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
alexey-milovidov and others added 2 commits July 19, 2026 21:53
…lakiness

Address the AI review of #110972.

1. FINAL over the merge() table function no longer bypasses the parallel-replicas
   FINAL guard. The planner-level guard in `Planner.cpp` that disables task-based
   parallel replicas for `FINAL` only inspected `TableNode`s, so `merge(...) FINAL`
   kept parallel replicas enabled and reached `ReadFromMergeTree::spreadMarkRanges`
   with `is_parallel_reading_from_replicas`, hitting a logical error
   (`!is_parallel_reading_from_replicas`). The guard now inspects
   `TableFunctionNode`s too, so `... FROM merge(...) FINAL` falls back to
   single-replica execution (or throws `SUPPORT_IS_DISABLED` when parallel replicas
   are forced), exactly like `... FROM t FINAL`.

   Found by the AST fuzzer:
   SELECT sumWithOverflow(v) IGNORE NULLS FROM merge(currentDatabase(), '^t_pr_merge_[12]$') FINAL;

2. Added stateless regression cases to `04612_parallel_replicas_merge_tables`: an
   ordered query with `LIMIT` over a `Merge` table (the read-in-order optimization
   materializes the child plans; it must coexist with enabling parallel replicas on
   the step), and `FINAL` over both a `Merge` table and the `merge()` table function.

3. Made the integration test deterministic: hand out small mark segments
   (`parallel_replicas_mark_segment_size = 10`) so reading work is spread across all
   replicas instead of a single (usually local) replica grabbing a whole underlying
   table at once, which made `_assert_all_replicas_participated` racy on the small
   dataset (`assert 0 >= 2`).

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

Copy link
Copy Markdown
Member Author

Addressed the AI review in 681eef3 (after merging the latest master):

Blocker PlannerJoinTree.cpp:1320 — merge(...) FINAL bypasses the FINAL guard (real, confirmed by the AST fuzzer): the planner-level guard in Planner.cpp that disables task-based parallel replicas for FINAL only inspected TableNodes. It now inspects TableFunctionNodes too, so ... FROM merge(...) FINAL falls back to single-replica execution (or throws SUPPORT_IS_DISABLED when parallel replicas are forced), exactly like ... FROM t FINAL. Verified locally: SELECT sumWithOverflow(v) IGNORE NULLS FROM merge(...) FINAL no longer hits the !is_parallel_reading_from_replicas logical error.

Blocker StorageMerge.cpp:648 — ordered query reaching enableParallelReplicasLocalPlan with child plans already created: I could not reproduce this. createLocalPlanForParallelReplicas calls enableParallelReplicasLocalPlan on the freshly extractQueryPlan()-ed plan before any optimization runs (the read-in-order pass runs later, during buildQueryPipeline/QueryPlan::optimize), so child_plans is still empty at that point. I added a stateless regression case (SELECT k, v FROM t_pr_merge ORDER BY k LIMIT 5 under parallel replicas); its plan shows ReadFromMerge under ReadFromRemoteParallelReplicas and it runs without the logical error.

Tests: added FINAL (Merge table and merge()) and ORDER BY ... LIMIT cases to 04612_parallel_replicas_merge_tables, and made the integration test deterministic (parallel_replicas_mark_segment_size = 10) so the reading work spreads across replicas instead of a single local replica grabbing a whole underlying table (the cause of the flaky assert 0 >= 2).

…tatistics for table functions

The `ReadFromRemoteParallelReplicas` step of a table function read has an
empty storage id, so `calculateHashFromStep` contributed no source identity
at all, and different `merge(...)` sources with the same plan shape could
collide in `HashTablesStatistics` and reuse the wrong aggregation/join size
hints. Hash the tree hash of the remote query instead.

Addresses the AI review.
The plain query with `ORDER BY` is executed with read-in-order, so the
parallel replicas reading coordinator works in the `WithOrder` mode, which
hands out up to `min_marks_per_task` marks (16384, more than the whole test
table) to whichever replica requests work first — the remote replicas can
legitimately end up reading nothing, and
`_assert_all_replicas_participated` fails with `participants == 0`.
On top of that, the query condition cache remembers matching granules from
previous runs of the same query (flaky-check reruns), shrinking the read to
a few marks. Disable `optimize_read_in_order` for this query so the default
coordinator mode spreads `parallel_replicas_mark_segment_size` segments
across replicas, disable `use_query_condition_cache`, and raise
`parallel_replicas_connect_timeout_ms` so slow CI runners do not silently
drop remote replicas.

Both the failure mode (zero secondary queries with read-in-order) and the
fix (two remote replicas reading rows on every run) were reproduced locally
on a three-replica localhost cluster.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110972&sha=681eef394b2902e8a1ec7e887e7a8a6efee648dd&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29
PR: #110972
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the remaining AI review Major and the flaky integration test (after merging the latest master):

calculateHashTableCacheKeys.cpp — table-function reads lost their source identity: when ReadFromRemoteParallelReplicas reads from a table function, the storage id is empty, so the step contributed no identity to the HashTablesStatistics key. Now the tree hash of the remote query is hashed instead, so different merge(...) sources with the same plan shape no longer collide (55e5464).

test_parallel_replicas_merge_tables::test_non_aggregate_query failing with participants == 0 (CI report): the ORDER BY query is executed with read-in-order, so the reading coordinator works in the WithOrder mode, which hands out up to min_marks_per_task marks (16384 — more than the whole test table) to whichever replica requests work first; the remote replicas can legitimately read nothing, and parallel_replicas_mark_segment_size does not apply to that mode. Additionally, the query condition cache shrinks repeated runs of the same query (flaky-check reruns) to a handful of marks. The test now disables optimize_read_in_order for the participation-asserted query, disables use_query_condition_cache, and raises parallel_replicas_connect_timeout_ms. Reproduced both the failure mode (zero secondary queries under WithOrder) and the fix (two remote replicas reading rows on every run) locally on a three-replica localhost cluster (147a7b7).

…as selector

The query-level selector and tracking (getSupportingParallelReplicasQueries,
findTableForParallelReplicas) rejected all TABLE_FUNCTION nodes, so merge(...)
inside a JOIN or a subquery never set parallel_replicas_node /
parallel_replicas_table, and such queries missed the whole-stage offload that
the single-designated-leaf contract of allowParallelReplicasForJoinTree
promises (while a Merge table already followed it).

- getSupportingParallelReplicasQueries and findTableForParallelReplicas now
  accept a TableFunctionNode whose storage is StorageMerge (the only table
  function eligible for parallel replicas), with the same eligibility checks
  as the TableNode case (canUseParallelReplicas, no FINAL).
- findTableForParallelReplicas and GlobalPlannerContext::parallel_replicas_table
  now carry an IQueryTreeNode (a TableNode or a TableFunctionNode).
- buildQueryPlanForParallelReplicas sends an empty StorageID when the designated
  table expression is a table function: the storage it creates does not exist on
  remote replicas under its generated id.
- The follower-side guard in buildQueryPlanForTableExpression compares the
  designated table expression instead of only TableNode, so a merge(...) leaf
  keeps coordinated reading and sibling leaves have parallel replicas disabled.
- The dummy-table replacement now preserves table expression modifiers of table
  functions, so FINAL is not lost during the candidate analysis.

Addresses the AI review finding on the PR.

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

Copy link
Copy Markdown
Member Author

Addressed the remaining AI review Major in ecf4f67: the query-level parallel-replicas selector (getSupportingParallelReplicasQueries / findTableForParallelReplicas) no longer hard-stops on TABLE_FUNCTION nodes — merge(...) in a JOIN or a subquery now designates the parallel-replicas leaf, so the whole join stage is offloaded to replicas as a single WithMergeableState query (verified by EXPLAIN in the new stateless test 04613_parallel_replicas_merge_tables_join, which also covers LEFT/RIGHT joins, subqueries, and the merge(...) FINAL fallback).

The remaining red, AST fuzzer Logical error: Cannot serialize FutureSetFromSubquery with no query plan (STID 2678-3c21), is unrelated to this PR: it is a bug in the experimental plan-based parallel replicas feature from #108504 (parallel_replicas_plan_based + serialize_query_plan; the failing query touches neither Merge tables nor merge()), and the fix is already in progress in #110874, which references this very fuzzer report.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The remaining red, Stress test (arm_msan) Cannot start clickhouse-server (report), is unrelated to this PR: the server fails to restart because the fabricated parts of test_7.t_plt_reparent (from 04063_part_loading_tree_rollback_reparent) have unreadable transaction metadata — Part all_2_3_1_0 intersects previous part all_1_2_2_1 and the transaction metadata of at least one of them could not be read. This is the known stress-test environment issue #111053, with the fix in progress in #111055. This PR touches neither part loading nor transactions.

Everything else is green and the AI review verdict is ✅ Approve.

Parallel replicas over `Merge` tables and the `merge` table function are
implemented only for the read-tasks mode, where every underlying `MergeTree`
table forms its own data stream in the reading coordinator. The custom-key
mode addresses the remote read by the storage id, which for a table function
is the synthetic `_table_function.merge` id that does not exist on the
replicas.

Without this guard, `parallel_replicas_mode = 'custom_key_range'` (or
`custom_key_sampling`) together with `parallel_replicas_allow_merge_tables = 1`
failed for `merge(...)` with `ALL_CONNECTION_TRIES_FAILED`: `There is no table
_table_function.merge on server`, and returned wrong results (all zeros) for a
`Merge` table. Now such a query runs on a single replica, as it did before
`parallel_replicas_allow_merge_tables` was introduced.

Also move the `parallel_replicas_allow_merge_tables` entry in the settings
changes history from 26.7 (already released) to 26.8, which is what the
upgrade check compares against.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI on 5ad4ebd1506 (the master merge): the actionable red was the Upgrade check (amd_release) — parallel_replicas_allow_merge_tables was recorded in the settings changes history under 26.7, which is already released, so the check compares against a 26.7 binary that does not have the setting. Moved the entry to 26.8 in 1cb9adc.

The same commit addresses the AI review Major (custom-key parallel replicas over Merge): reproduced locally on a 3-replica localhost cluster that with parallel_replicas_mode = 'custom_key_range' + parallel_replicas_allow_merge_tables = 1, merge(...) failed with ALL_CONNECTION_TRIES_FAILED: There is no table _table_function.merge on server, and a Merge table silently returned 0 0 0. The custom-key branch in PlannerJoinTree now rejects StorageMerge entirely, so such a query runs on a single replica as before the setting existed. New test 04652_parallel_replicas_merge_tables_custom_key (both custom-key modes, table and table function); A/B verified against a binary without the guard; 04612 and 04613 still pass.

The two remaining reds are unrelated AST-fuzzer failures reproduced on master and on many other PRs today, and both already have a fix in progress:

Comment thread src/Storages/StorageMerge.cpp Resolved
The child plans of `ReadFromMerge` are built and optimized lazily, when the
pipeline is initialized, with a context derived from the initiator's local plan
for parallel replicas - and in that context parallel replicas are switched off.
Their reading steps, on the other hand, have just been wrapped into parallel
replicas reading steps, so the projection optimizations classified the
initiator-local child as a remote replica
(`is_parallel_replicas_initiator_with_projection_support` was false while
`isParallelReadingEnabled` was true) and replaced the projection read with a
`NullSource`, dropping the rows that only the initiator was supposed to return.

Restore the flag for such child plans from the initiator context that requested
the local plan, so a `Merge` child behaves exactly like a plain `MergeTree`
table read on the initiator. Introduce
`isParallelReplicasInitiatorWithProjectionSupport` so that the condition is
written in one place.

New test `04655_parallel_replicas_merge_tables_projections`. Verified A/B on a
3-replica localhost cluster: without the fix, a filtered read over a `Merge`
table whose underlying tables have parts both with and without the projection
returns `2 1063` instead of `4 6147`; with the fix both the `Merge` table and
the `merge` table function return the correct result.

Also renumber the custom-key test to `04654` - master has meanwhile taken the
`04652` prefix.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed e53c292 on top of a fresh master merge (e94daaf, no conflicts; the branch had gone a week behind and GitHub reported it as CONFLICTING).

AI review blocker (StorageMerge.cpp child-plan optimization) — confirmed real and fixed. Details are in the review thread: the child plans of ReadFromMerge were optimized with a context in which parallel replicas are switched off, while their reading steps had already been wrapped into parallel replicas reading steps, so the projection optimizations took the initiator-local child for a remote replica and replaced its projection read with a NullSource. The reachable path is optimizeUseNormalProjection (the child plans carry no Aggregating step), and A/B on a 3-replica localhost cluster shows 2 1063 instead of 4 6147 without the fix. New test 04655_parallel_replicas_merge_tables_projections; the custom-key test was renumbered to 04654 because master has taken the 04652 prefix.

Remaining red before this push — Stress test (amd_debug), Logical error: Inconsistent KeyCondition behavior — unrelated to this PR: over the last five days it fired on master itself (pull_request_number = 0) as well as on 86 other pull requests in a single day. Tracked in #112418, with fixes in flight in #111964 and #112231.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the Fast test timeout in 9548463. 04903_parallel_replicas_merge_tables_repeated_storage paused a query that retained the table reference, then performed a synchronous DROP TABLE; the drop waited for the paused query before the test could release its failpoint. The mid-pause drop now sets database_atomic_wait_for_drop_and_detach_synchronously = 0, so it detaches from the catalog and the test can release the query.

Validated with bash -n and git diff --check.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the Fast test timeout in 831897639605. The aliasless merge() form used by 04838_parallel_replicas_merge_tables_sibling_child_set does not enter the parallel-replicas failpoint, leaving SYSTEM WAIT FAILPOINT blocked. The paused phase now uses the already-validated aliased query, which still exercises the sibling child-set mismatch. Validated with bash -n and git diff --check.

@devcrafter

Copy link
Copy Markdown
Member

@alexey-milovidov I'd suggest to go forward with implementation based on plan-based parallel replicas #115001. It's a way more natural to get support for Merge table with parallel replicas

…erge-tables

# Conflicts:
#	src/Common/FailPoint.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Superseded by the plan-based implementation in #115001. This branch has been reconciled with master first (merge 63f0ef0eefc2), but the newer implementation is the natural path forward and avoids retaining the legacy query-tree protocol.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 13, 2026
`merge('regexp')` takes its database from the current database of the
server that resolves it. The analyzer resolved the node with the
initiator's current database but kept the single argument in the query
tree, so every rendering of the query for another server (Distributed,
remote, cluster, `*Cluster` table functions, query-based parallel
replicas, serialized plans) sent `merge('regexp')`, and the receiver
matched the regexp against its own default database: wrong rows, or
CANNOT_EXTRACT_TABLE_STRUCTURE when that database has no matching table.

After resolving a one-argument `merge`, insert the source database as
the first argument of the node. The change is made in the query tree and
not only in the rendered text, because an `IN` set is named after the
tree hash of its subquery and that name appears in the columns of the
WithMergeableState header that the initiator matches by name: with a
render-only change, `countIf(x IN (SELECT ... FROM merge('re')))` over
two shards fails with NOT_FOUND_COLUMN_IN_BLOCK.

A secondary query keeps the form it was sent in, so that its tree hashes
like the sender's: an initiator of an older version sends one argument,
and a receiver that inserted the database would fail the same way.

This is the resolve-time part of ClickHouse#110972, which ClickHouse#115001 superseded
without carrying it.

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

This branch was successfully deployed

1 active deployment
staging - docs — 63f0ef0e Deployed Aug 18, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parallel replicas are not implemented for Merge tables

3 participants