Skip to content

Do not apply parallel replicas to the child plans of a Merge table - #112849

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix-merge-table-parallel-replicas
Aug 9, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix-merge-table-parallel-replicas

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

ReadFromMerge materializes the plan of every underlying table lazily, while the outer plan is already being executed. Plan-based parallel replicas (parallel_replicas_plan_based = 1) was still applied to those child plans, and the shipped fragment was wrong in two ways:

  • The filters pushed down into the child plan were lost, so with parallel_replicas_local_plan = 0 any query with a WHERE over a Merge table silently returned no rows — SELECT count() FROM merge(currentDatabase(), 't') WHERE name = '1' returned 0 instead of 1.
  • When the filter referenced a subquery set, the outer plan's addStepsToBuildSets had already moved the source plan out of the FutureSetFromSubquery, so serializing the fragment threw LOGICAL_ERROR Cannot serialize FutureSetFromSubquery with no query plan. This is the shape the AST fuzzer keeps hitting: SELECT count() FROM merge(currentDatabase(), 'test_local') WHERE name GLOBAL IN (SELECT name FROM test_distributed).

The guard added by #112443 (planHasSubquerySet) only looks for a DelayedCreatingSetsStep in the plan being optimized, which a Merge child plan never has.

Parallel replicas are now disabled for Merge child plans, both in the optimization settings and in the child context — the conversion re-checks canUseParallelReplicasOnInitiator against the context captured by the reading step, not only the optimization settings. This restores the documented behavior that queries over Merge tables run on a single replica (#67770); proper support is being added separately by #110972 behind parallel_replicas_allow_merge_tables.

New test 04665_merge_table_parallel_replicas_child_plan covers the wrong-result shapes, both subquery shapes, and asserts that a plain table read is still distributed so parallel replicas are not over-disabled.

Follow-up from review: make_distributed_plan also leaked into the child pipelines through ReadFromMerge::buildPipeline. Distributing the child plans of a Merge table is a supported feature (see 04367_distributed_plan_merge_scatter_multishard), so it stays enabled — except when the query has subquery sets, whose source plans the outer plan's addStepsToBuildSets has already consumed: a distributed child fragment referencing such a set failed to serialize with the same Cannot serialize FutureSetFromSubquery with no query plan logical error. Such child plans now stay local, covered by the new test 04827_merge_table_make_distributed_plan_child_plan.

Closes: #112848
Related: #112443
Related: #110972
Related: #67770

CI report where the AST fuzzer hit this: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110968&sha=67c1d446e4881a0bebbf05446dc39948f79e6222&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 (#110968)

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 (the WHERE clause was ignored) and a logical error Cannot serialize FutureSetFromSubquery with no query plan for queries over Merge tables and the merge table function when plan-based parallel replicas were enabled.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.1055 (included in 26.8 and later)
  • Backported to: 26.7.13.6

`ReadFromMerge` materializes the plan of every underlying table lazily, while the
outer plan is already being executed. Plan-based parallel replicas
(`parallel_replicas_plan_based = 1`) was still applied to those child plans, and
the shipped fragment was wrong in two ways:

* The filters pushed down into the child plan were lost, so any query with a
  `WHERE` over a `Merge` table silently returned no rows. With
  `parallel_replicas_local_plan = 0`,
  `SELECT count() FROM merge(currentDatabase(), 't') WHERE name = '1'`
  returned `0` instead of `1`.

* When the filter referenced a subquery set, the outer plan's
  `addStepsToBuildSets` had already moved the source plan out of the
  `FutureSetFromSubquery`, so serializing the fragment threw
  `Cannot serialize FutureSetFromSubquery with no query plan`. This is the
  shape the AST fuzzer hit with
  `SELECT count() FROM merge(currentDatabase(), 'test_local') WHERE name GLOBAL IN (SELECT name FROM test_distributed)`.

Disable parallel replicas for `Merge` child plans, both in the optimization
settings and in the child context - the conversion re-checks
`canUseParallelReplicasOnInitiator` against the context captured by the reading
step, not only the optimization settings. This restores the documented behavior
that queries over `Merge` tables run on a single replica (#67770); proper
support is being added separately by #110972 behind
`parallel_replicas_allow_merge_tables`.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f05e878]

Summary: ✅


AI Review

Summary

This PR stops Merge child plans from re-entering plan-based parallel replicas and keeps make_distributed_plan enabled for those children except when the outer query carries subquery-backed sets, which is the remaining unsupported serialization case. I re-read the current StorageMerge.cpp, the added stateless coverage, the existing inline threads, and the PR discussion; after the latest f05e878e3a67 update I do not see any remaining correctness, coverage, or metadata issues worth a new review comment.

Final Verdict

✅ No new findings in the current diff.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.90% +0.10%

Changed lines: Changed C/C++ lines covered: 34/35 (97.14%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 1, 2026
…the regression test

The test switched to `parallel_replicas_local_plan = 1` but only re-ran two
`count()` queries there. The structural check above it matches only
`ReadFromParallelReplicas`, so a regression that distributes the `Merge` child
plan in local-plan mode - where the read is wrapped in `ReadFromLocalReplica` /
`ReadFromRemoteParallelReplicas` - would not have been caught.

Add, for `parallel_replicas_local_plan = 1`: the `GLOBAL IN` reproducer that
used to throw `Cannot serialize FutureSetFromSubquery with no query plan`, an
`EXPLAIN` assertion that the `Merge` child read carries none of the three
distributed-read wrappers, and the matching positive control on a plain table.

Verified against a binary with the `StorageMerge.cpp` fix reverted: the new
`EXPLAIN` assertion returns `1` instead of `0` and the new `GLOBAL IN` query
throws the logical error, so neither assertion is vacuous.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 14/14 (100.00%) · Uncovered code

Full report · Diff report

Comment thread src/Storages/StorageMerge.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f05e878e3 with master 9b6a2d734 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e2194b4a8; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.65 MiB 687.62 MiB -3.02 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

…ns of a `Merge` table

`ReadFromMerge::buildPipeline` built the child pipeline with raw
`QueryPlanOptimizationSettings(context)` from the outer query context, and
`QueryPlan::buildQueryPipeline` runs `convertToDistributed` whenever
`make_distributed_plan` is set, regardless of `optimize_plan`. So with
`make_distributed_plan = 1`, a `Merge` child plan was converted to a
distributed plan mid-execution, failing with `Unknown query plan step:
GatherReceive` (and `Cannot serialize FutureSetFromSubquery with no query
plan` when the query had subquery sets already consumed by the outer plan's
`addStepsToBuildSets`).

Clear `make_distributed_plan` in `getChildPlanOptimizationSettings`, use that
helper in `buildPipeline`, and clear the setting in the child context as well
(mirroring `enable_parallel_replicas`, for nested interpreters).

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112849&sha=bc9bb1384ce09061a1573db7b3ac6691766e1cbf&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The Stress test (arm_debug) hung check is unrelated to this PR: the server was idle (all threads waiting in futex/poll) but the global memory tracker had drifted to "would use 128.92 GiB" while actual RSS was 1.17 GiB, so every new connection was rejected with MEMORY_LIMIT_EXCEEDED. The same Hung check failed, possible deadlock found failure occurs daily on master and on dozens of unrelated PRs (53 occurrences on 2026-08-05 alone), and I found no open tracking issue for the memory-tracker drift.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

Confirmed unrelated to this PR, and I agree it is accounting rather than real memory pressure. Sharpening the mechanism: the refused request is 0 bytes (attempt to allocate chunk of 0.00 B) and RSS is 1.18 GiB against a 47.36 GiB cap, so the counter is wrong, not the memory use. MemoryWorker stores measured RSS every tick, which is why current RSS stays accurate, but amount is only corrected when it goes negative (MemoryWorker.cpp:985-988; memory_worker_correct_memory_tracker defaults to 0 at ServerSettings.cpp:1258), so positive drift is permanent for the life of the server.

The refusal site is CurrentMemoryTracker::check(), which is allocImpl(0, /*enforce=*/true) (CurrentMemoryTracker.cpp:115-119), and it sits pre-auth at TCPHandler.cpp:2075 and unconditionally inside aggregation at Aggregator.cpp:891. So no probe connects, stress.py writes the deadlock row with no processlist and no stacktraces, and a genuine deadlock in such a run would be indistinguishable from this. That masking is the part I would call a defect independent of the counter.

On tracking: I did not open a separate issue, I posted the full analysis as a comment on 113408: #113408 (comment). It covers the counter path, the candidate unmatched addition (adjustOnBackgroundTaskEnd does an unsaturated parent.amount.fetch_sub over a process-context child, MemoryTracker.cpp:543-552), and three fixes I tried and discarded with the reason each one fails.

There is no fix PR, and I do not want to imply one is on the way, because what is left is a taxonomy choice rather than a local fix: either fix the counter (the unsaturated background-task-end and free paths), or give the stress harness a terminal status for "alive but refusing all requests" so this stops being reported as a deadlock. Two questions at the end of that comment are waiting on your call; either answer unblocks me and I will implement it.

Breadth, so the scope is not overstated. Keyed on attempt to allocate chunk of 0.00 B under this test name, 30 days gives 15 rows, of which 2 are genuine OOMs (RSS above the cap), leaving 13 rows / 11 PRs / 2 master. The bare Hung check failed, possible deadlock found name is a symptom bucket rather than this family: 585 rows / 384 PRs / 80 master over the same window, and of the 53 rows on 2026-08-05, zero carry this drift signature.

…the query has subquery sets

Fast test on the previous commit caught that clearing \`make_distributed_plan\`
unconditionally breaks 04367_distributed_plan_merge_scatter_multishard:
distributing the child plans of a \`Merge\` table is a supported feature (the
double-application of the transforms is fenced by \`planContainsLogicalExchange\`
in \`optimizeTree.cpp\`, and \`ReadFromMerge::buildPipeline\`'s conversion is the
run that materializes the logical exchanges inserted at child-plan creation).
The \`Unknown query plan step: GatherReceive\` failure that motivated the blanket
clearing was an artifact of reproducing with \`clickhouse local\`, which never
calls \`QueryPlanStepRegistry::registerPlanSteps\` (only \`Server.cpp\` does), so
any distributed child plan fails to deserialize there; on a server that path
works.

The genuine bug is narrower: when the query has subquery sets
(\`IN (SELECT ...)\`), the outer plan's \`addStepsToBuildSets\` has already moved
the source plan out of every \`FutureSetFromSubquery\` by the time the lazily
materialized child plans are optimized, so a distributed child fragment
referencing such a set fails to serialize with the logical error
\`Cannot serialize FutureSetFromSubquery with no query plan\`. Clear
\`make_distributed_plan\` for the child plans only in that case, detected via the
prepared sets of the outer query's planner context.

The test now asserts both directions on a 100k-row \`Merge\` child: without
subquery sets the child plan contains exchanges and executes correctly
(positive control that the feature still applies), and with \`GLOBAL IN\` the
child plan has no exchanges and the query succeeds. Plain \`IN\` and
aggregation/ORDER BY shapes are excluded: converting an outer plan whose worker
stage would carry an unserializable step (\`ReadFromMerge\`, the EXPLAIN
wrapper's \`ReadFromStorage\`) is rejected upfront with \`SUPPORT_IS_DISABLED\` -
a pre-existing limitation unrelated to the child plans.

Fast test failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112849&sha=425692c16c6deb6481fa26a0617ebb9efbda5ae6&name_0=PR&name_1=Fast%20test
(#112849)

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok. Half of this change is related to the fact that the distributed plan does not work.

@alexey-milovidov alexey-milovidov self-assigned this Aug 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 9, 2026
Merged via the queue into master with commit 2b2987c Aug 9, 2026
355 of 356 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-merge-table-parallel-replicas branch August 9, 2026 22:30
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 9, 2026
alexey-milovidov added a commit that referenced this pull request Aug 10, 2026
…Merge` read

`Merge` table support for parallel replicas needs the opposite of what the master
merge brought in from #112849: a replica reading for an initiator builds its child
plans through `createChildrenPlans`, and every child reading step must read only
the mark ranges the coordinator hands out to it - which is exactly what
`enable_parallel_replicas` in the child context enables. Clearing it made every
replica read every child table in full, so every coordinated `Merge` read returned
its rows multiplied by the number of replicas (`04666`, `04667`, `04828`, `04829`
all returned three times their rows locally).

Clear the setting only when this `Merge` read is not itself a part of coordinated
reading with parallel replicas; the gate additionally requires
`parallel_replicas_allow_merge_tables`, so the behavior #112849 restored for the
default configuration is untouched. The initiator's own local plan does not depend
on the setting - its child reading steps are replaced with local parallel replicas
reading steps right after they are created.

The plan-level flag stays cleared for every child plan
(`getChildPlanOptimizationSettings`): plan-based parallel replicas must not
distribute a lazily built child plan, which is what #112849 fixed.
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 13, 2026
…rom a self-matching merge() child

PR ClickHouse#112849 fixed the coordinator guard trips (`Initiator received more initial
requests than there are replicas`, `Duplicate announcement received for replica
number N`) that fired when a `merge()` regex matched the outer table itself, but
its test 04665 never reaches the announcement guards on the pre-fix code: its
fixture aborts earlier with `Cannot serialize FutureSetFromSubquery with no query
plan` and uses the default index granularity, at which the initiator claims every
mark range and the followers are cancelled before announcing.

This fixture (from the AST fuzzer signature, STIDs 8765-7cc2/8765-7341) reddens
6/6 without the `enable_parallel_replicas` clear in
`ReadFromMerge::createChildrenPlans` and passes with it, in both
`parallel_replicas_local_plan` modes.

Related: ClickHouse#112849
Related: ClickHouse#110972

Co-Authored-By: Claude Fable 5 <[email protected]>
scanhex12 pushed a commit to aaron276h/ClickHouse that referenced this pull request Sep 4, 2026
…ing a read

With parallel_replicas_plan_based = 1, a query over a system log table or a
SQL SECURITY DEFINER view failed on the initiator with

    LOGICAL_ERROR: Next task callback is not set for query with id: <uuid>

applyParallelReplicas marks the coordinated read with
enableParallelReadingFromReplicasForSerialization, which deliberately attaches
no callbacks: the step is only serialized and shipped to replicas, where
deserialize rebuilds it and resolves the callbacks from the context.
createParallelReplicasPlan then clones that fragment once more to build the
initiator's local arm, and ReadFromMergeTree::clone() passed the
marked-but-callback-less state back through the constructor. The constructor
cannot distinguish "marked for serialization" from "replica side, resolve from
the context", so it took its context fallback, and an initiator holds no
coordinator callback.

Ordinary plan-based queries survive that fallback only because Context's copy
constructor carries the callbacks TCPHandler installed. Instrumenting the
constructor showed the fallback is taken on the ordinary path too, and merely
happens to find a callback there. The failing shapes read under a context built
fresh from the global context, which never holds them: a system log storage, or
a DEFINER view.

clone() now copies the flag and both callback optionals directly, so a copy no
longer re-derives state from the context. All three fields move together:
restoring only the flag would drop the callbacks of a marked read that has them,
which getParallelReadingExtension asserts on. The constructor's context fallback
is unchanged, since deserialize, StorageMergeTree::read and
StorageReplicatedMergeTree::readLocalImpl rely on it on a follower.

Both branches of that fallback were reachable with the same state: with the
first one made non-throwing, the same query threw the sibling message from
Context::getMergeTreeReadTaskCallback, so copying both optionals is required.

Still reproduced with both in-flight Merge route fixes applied (ClickHouse#112849,
ClickHouse#113788), so this is a separate defect rather than one of those routes.

Related: ClickHouse#111677
@nickitat nickitat added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 18, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 18, 2026
PedroTadim added a commit that referenced this pull request Sep 19, 2026
Cherry pick #112849 to 26.7: Do not apply parallel replicas to the child plans of a Merge table
PedroTadim added a commit that referenced this pull request Sep 19, 2026
The only conflict was an unrelated `ProcessList.h` include that master carries
next to the new `PreparedSets.h` and 26.7 does not have. Everything else applies
verbatim.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
robot-clickhouse added a commit that referenced this pull request Sep 19, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 19, 2026
Backport #112849 to 26.7: Do not apply parallel replicas to the child plans of a Merge table
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 13, 2026
04665 is claimed by two live open PRs (ClickHouse#112846, ClickHouse#112849). The collision is
silent: the filenames differ so git reports no conflict, and
check_gaps_in_tests_numbers only rejects gaps of 100 or more, never
collisions. 04666, 04670, 04674 and 04675 are claimed too, by ClickHouse#112816,
ClickHouse#112458 and unpublished branches respectively.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

5 participants