Skip to content

Do not use parallel replicas for a correlated subquery in a mergeTreeAnalyzeIndexes predicate - #119860

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:no-parallel-replicas-for-analyze-indexes-correlated-predicate
Sep 19, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:no-parallel-replicas-for-analyze-indexes-correlated-predicate

Conversation

@groeneai

@groeneai groeneai commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #95761
Related: #117610

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 a LOGICAL_ERROR (Initiator received more initial requests than there are replicas, or Duplicate announcement received for replica number N) when a mergeTreeAnalyzeIndexes predicate contained a correlated subquery and parallel replicas were enabled.

Description

With parallel replicas enabled, a mergeTreeAnalyzeIndexes predicate whose IN subquery contains a
correlated subquery fails:

SELECT count() FROM mergeTreeAnalyzeIndexes(currentDatabase(), t,
    (key IN (SELECT (SELECT key) FROM t2 ORDER BY key LIMIT 10)))
SETTINGS enable_parallel_replicas = 1, max_parallel_replicas = 2,
         cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost',
         parallel_replicas_for_non_replicated_merge_tree = 1,
         correlated_subqueries_use_in_memory_buffer = 0;

A release build returns Code: 49 LOGICAL_ERROR; a debug build aborts. Found by the AST fuzzer:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=95761&sha=2e03d4382b8fa296098f36e8897e581397ea0d37&name_0=PR&name_1=AST%20fuzzer%20(amd_debug,%20targeted,%20old_compatibility)

mergeTreeAnalyzeIndexes keeps its predicate as an AST and turns it into a query tree at execution
time, resolving it with resolveConstantExpression only. addQueryTreePasses does not run on that
tree, so DisableParallelReplicasPass never saw the predicate and the IN subquery was shipped to
the replicas with parallel replicas still enabled. Decorrelating it on a replica materializes the
referenced subplan a second time, so one table is read twice in one plan, both reads share a
stream_id, and the replica announces twice on the same coordinator.

Until 2825975ac13a5 this function disabled parallel replicas for its own predicate; that commit
moved the disable into the distributed-index-analysis driver, which does not cover a directly invoked
table function. Running the missing pass instead keeps the rule in one place. It fires only when a
correlated subquery is present: an uncorrelated IN (SELECT ...) predicate still uses parallel
replicas, which the new test asserts.

Results are unchanged, which the test also asserts. The sibling site in MergeTreeData.cpp is
unaffected: it bails out on any predicate containing a subquery before planning one.

Validation: the failure reproduces deterministically and is gone with the fix, each assertion of the
new test flipping individually; 50/50 randomized runs; the 21 existing tests calling
mergeTreeAnalyzeIndexes pass.


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

Version info

  • Merged into: 26.10.1.217 (included in 26.10 and later)

groeneai and others added 2 commits September 13, 2026 20:29
…AnalyzeIndexes predicate

With parallel replicas enabled, a mergeTreeAnalyzeIndexes predicate whose IN
subquery contains a correlated subquery tripped a LOGICAL_ERROR in the parallel
replicas coordinator: "Initiator received more initial requests than there are
replicas: replica_num=N", or its sibling "Duplicate announcement received for
replica number N" when the initiator has a local plan. A release build returns
Code: 49; a debug build aborts. Found by the AST fuzzer.

mergeTreeAnalyzeIndexes keeps its predicate as an AST and turns it into a query
tree at execution time, resolving it with QueryAnalyzer::resolveConstantExpression
only. addQueryTreePasses does not run on that tree, so DisableParallelReplicasPass
never saw the predicate and the IN subquery was hand-planned and shipped to the
replicas with parallel replicas still enabled. Each follower re-plans that SQL;
decorrelation references the outer subplan, and when
correlated_subqueries_use_in_memory_buffer is off, materializeQueryPlanReferences
replaces the reference with a clone of that subplan, ReadFromMergeTree included.
Two reads of one table share one stream_id, so getOrCreateCoordinator hands both
the same coordinator and the replica announces twice.

Until 2825975 this function disabled parallel replicas for its own predicate
directly. That commit moved the disable into distributedIndexAnalysisOnReplicas,
which does not cover a directly invoked table function. Rather than re-adding a
blanket disable, run the missing pass on the resolved predicate tree: the rule then
lives in one place, and the pass covers nested QueryNode/UnionNode contexts, which
the planner reads separately. Running it on the resolved tree also means a
SETTINGS clause on the subquery itself cannot re-enable parallel replicas, since
QueryTreeBuilder has already applied that clause to the subquery's own context.

The pass fires only when a correlated subquery is present, so an uncorrelated
IN (SELECT ...) predicate keeps parallel replicas and the deliberate move in
2825975 stands. The regression test asserts both directions.

The sibling site in MergeTreeData.cpp that resolves a predicate the same way is
unaffected: getPartitionIdsPrunedByPredicate returns nullopt for any predicate
containing an ASTSubquery before it plans one.

Model: us.anthropic.claude-opus-5
Co-Authored-By: Claude Opus 5 <[email protected]>
The tag's stated reason was that the test queries `system.text_log`, but every read
there is keyed on a `query_id` built from the test's own database name, so a test
running concurrently cannot perturb an assertion. Verified with 50 runs across 8
workers, and with the test interleaved with four other `system.text_log` readers.

`no-parallel-replicas` stays, because `tests/clickhouse-test` reads it three times
and this test manages the parallel replicas settings itself: it keeps
`enable_parallel_replicas` off unless the test turns it on, it excludes the test
from the `automatic_parallel_replicas_mode = 2` bundle that would otherwise repoint
`cluster_for_parallel_replicas` at a cluster with no local replica, and it skips the
test in the run that reports which tests are unsupported with parallel replicas.

Narrow the comment above the new `DisableParallelReplicasPass` call, in the source
and in the test header. Both said that `resolveConstantExpression` does not run
`addQueryTreePasses`, which is too wide a claim about that function: it hands a
query or union node to `evaluateScalarSubqueryIfNeeded`, which builds a
`QueryTreePassManager` and does run the passes. What holds is the tree-scoped
statement, so the comment now says the passes do not run on this tree. No behaviour
changes: the binary is bit-identical to the previous commit's.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=95761&sha=2e03d4382b8fa296098f36e8897e581397ea0d37&name_0=PR&name_1=AST%20fuzzer%20(amd_debug,%20targeted,%20old_compatibility)
Related: ClickHouse#95761
Related: ClickHouse#117610

Model: us.anthropic.claude-opus-5
Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 13, 2026
@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; 2 findings), plus my own cold read of
the resulting diff (4 findings). Rows 3 to 5 were then fixed in a second commit and the result was
re-reviewed the same way, cold: 0 findings.

# Sev Finding Verdict Evidence / action
1 ❌ A correlated predicate subquery can still use parallel replicas when only the subquery's own SETTINGS enables them, because the pass early-returns on the context it is given (StorageMergeTreeAnalyzeIndexes.cpp:152, DisableParallelReplicasPass.cpp:52) DISAGREE The first half is true, the consequence is not. Single-variable A/B, with correlated_subqueries_use_in_memory_buffer = 0 inside the subquery's own SETTINGS in both arms: outer ON reproduces the duplicate announcement on a pristine binary and is OK, 0 coordinators with the fix; outer OFF is OK, 1 coordinator on BOTH binaries, so the guard never trips there and nothing about that shape changed. The identical shape as a plain SELECT ... WHERE key IN (...), with no mergeTreeAnalyzeIndexes, measures the same on both binaries, so what remains is the pass's own per-run gate for every query, not a leg of this path. The prescribed remedy edits DisableParallelReplicasPass, which my open #115916 already changes, so it belongs there
2 💡 Issue #117610 is unrelated and the link should be dropped DISAGREE #117610 is mergeTreeAnalyzeIndexes: a malformed args_array argument raises a logical error ... instead of BAD_ARGUMENTS: same table function, same error class, fuzzer-found. Related: is the weakest of the three link keywords and this is its use
3 ⚠️ The new test's no-parallel tag is not strictly necessary AGREE, fixed Both system.text_log reads are keyed on a per-run query_id, so a concurrent test cannot perturb any assertion. Tag dropped, no-parallel-replicas kept, test re-run under the parallel runner
4 ⚠️ The commit message carries neither the CI report URL nor a link to the pull request it came from AGREE, fixed Both are now in the branch, and in the description above
5 💡 The in-diff comment claims resolveConstantExpression does not run addQueryTreePasses, which is too wide: it does, for a QUERY/UNION node and for every scalar subquery it evaluates (evaluateScalarSubqueryIfNeeded.cpp:214) AGREE, fixed Reworded to the tree-scoped claim, which is what the commit message already said
6 💡 Worth disclosing the outer-OFF shape as a residual in the description DROPPED My own read, refuted by the measurement in row 1: there is no defect there to disclose

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

@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM mergeTreeAnalyzeIndexes(currentDatabase(), t, (key IN (SELECT (SELECT key) FROM t2 ORDER BY key LIMIT 10))) with enable_parallel_replicas = 1, max_parallel_replicas = 2, cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost', parallel_replicas_for_non_replicated_merge_tree = 1, correlated_subqueries_use_in_memory_buffer = 0. Fired on the first attempt and on every pristine-binary run. Not a rare flake.
b Root cause explained? The predicate is resolved with resolveConstantExpression only, so addQueryTreePasses and therefore DisableParallelReplicasPass never run on it. The IN subquery is shipped to the replicas with parallel replicas enabled; decorrelating it on a replica materializes the referenced subplan a second time, so one table is read twice in one plan, both reads share a stream_id, and the replica announces twice on one coordinator.
c Fix matches root cause? Yes: it runs the missing pass on the resolved predicate tree. Not a widened bound, a no-random-* tag or a guard at the throw site; the coordinator's counter check is correct and untouched. Giving each read a distinct stream_id was rejected because it would trade the logical error for wrong results.
d Test intent preserved / new tests added? New stateless test 05211_parallel_replicas_analyze_indexes_correlated_subquery, six assertions including two positive controls. No existing test modified or weakened.
e Both directions demonstrated? Yes. Whole test: FAIL (server aborts, Duplicate announcement received for replica number 1) on pristine, OK with the fix. Because the abort ends the run at the first assertion, each assertion was also re-run in isolation against a freshly started server: the three correlated arms and the result-equality arm flip, both positive controls stay green, and the fixed output matches the reference byte for byte. Build IDs verified on both sides.
f Fix is general across code paths? Census was grep -rn "getPreparedSets().getSubqueries()" src/ (3 hits) plus grep -rln resolveConstantExpression src/ (6 files). This site is fixed. MergeTreeData.cpp resolves a predicate the same way but getPartitionIdsPrunedByPredicate returns nullopt for any predicate containing a subquery before the subquery loop, so it is unreachable for this defect. Planner.cpp is the normal path, whose tree did go through the passes. evaluateConstantExpression.cpp and InverseDictionaryLookupPass.cpp never plan prepared-set subqueries. Fixed at the source, not at the crash site.
g Fix generalizes across inputs (params/datatypes/wrappers)? The pass rewrites node contexts and reads no data, so type wrappers (Nullable, LowCardinality, Array, Map, Const) cannot change its behaviour and there is no boundary-value dimension. The dimensions that do matter are measured: parallel_replicas_local_plan 0 and 1 (both reproduce, both fixed), parallel_replicas_plan_based 0 and 1, correlated_subqueries_use_in_memory_buffer 0 and 1, automatic_parallel_replicas_mode 0 and 1, a subquery-level SETTINGS override, and one extra level of nesting. Three of those shapes are pinned in the test.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changes, so no SettingsChangesHistory.cpp entry; no serialization, format or protocol change; no persisted state. The one behaviour change is that such a predicate's subquery is no longer read with parallel replicas; results are unchanged, which the test asserts. An unpatched initiator still ships such a subquery to a patched follower, but the initiator owns that decision.
i Invariants and contracts preserved? DisableParallelReplicasPass::run early-returns unless the given context can use parallel replicas on the initiator, so it is a no-op when they are off and a follower keeps reading its assigned ranges. It runs on the resolved tree, after the query tree builder has applied each SELECT's own SETTINGS, so a nested clause cannot override it. It fires only when a correlated subquery is present, so an uncorrelated predicate keeps parallel replicas and the deliberate move in 2825975ac13a5 stands. The call sits after resolution and before collectSets, so no later step sees a half-rewritten tree. No lock, durability or crash-restart path is involved.

Session id: cron:clickhouse-impl-slot-6:20260913-185300

@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ec90cc6]

Summary: ✅


AI Review

Summary

This PR restores the missing DisableParallelReplicasPass on the predicate tree that mergeTreeAnalyzeIndexes resolves outside the normal query-pass pipeline, and adds a focused stateless regression test for correlated and uncorrelated subquery shapes. I did not find a remaining correctness, contract, or coverage issue in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit ec90cc6.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.40% -0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ec90cc606 with master 1ada34f52 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 0c3b387da; 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.

Compile time of recompiled translation units

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

Job report

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-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants