Skip to content

Fix wrong results of a subquery that enables parallel replicas in its own SETTINGS when a projection answers part of it - #131618

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-pr-projection-initiator-per-read
Nov 17, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-pr-projection-initiator-per-read

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115916
Related: #123950
Related: #82807

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 of a subquery that enables parallel replicas in its own SETTINGS clause when the result comes from a projection, the min/max/count() part metadata or an exact count from the primary key. For example, SELECT * FROM (SELECT max(x) FROM t SETTINGS enable_parallel_replicas = 1, ...) returned 0.

Description

On 26.3.33.24 and 26.10.2.103, SELECT * FROM (SELECT max(k) FROM t SETTINGS enable_parallel_replicas = 1, max_parallel_replicas = 3, cluster_for_parallel_replicas = '...', parallel_replicas_for_non_replicated_merge_tree = 1) returns 0 instead of the maximum; with the same settings on the top-level query it is correct. On master sum() returns 0 the same way, which is the red 05033_recursive_cte_parallel_replicas in the Fast test of #115916.

The projection optimizers decided whether a coordinated read is the initiator's own share from is_parallel_replicas_initiator_with_projection_support, computed once from the context the plan is optimized with. The initiator's local plan is optimized with the outer query's settings, so with parallel replicas enabled only in the subquery the initiator took the follower branch: it returned an empty source instead of the _minmax_count_projection, _statistics_projection or _exact_count_projection block and skipped the projection read beside parts that lack the projection, which the followers skip by design.

The decision now uses ReadFromMergeTree::isParallelReplicasLocalPlanForInitiator(), which reads the read's own context and already answers the same question for the empty-ranges announcement in the same code; the plan-wide field is removed. Queries whose outer and subquery settings agree are unchanged.

The sum/avg half came with #123950, the rest with #82807, so reverting #123950 alone would not fix it.

The test covers the five sources and checks that parallel replicas and the expected source served each query. It fails on master and passes 50/50 with random settings.


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

Version info

  • Merged into: 26.11.1.2543-master (included in 26.11 and later)

groeneai and others added 2 commits November 14, 2026 11:22
…ections with parallel replicas

The aggregate and normal projection optimizers decided whether a coordinated read is the
initiator's own share (and so must return what a projection or a prepared source answers)
from `QueryPlanOptimizationSettings::is_parallel_replicas_initiator_with_projection_support`,
computed once from the context the whole plan is optimized with. The initiator's local plan
is optimized with a copy of the OUTER settings, so when parallel replicas are enabled only in
a subquery's SETTINGS the flag is false there: the initiator emitted a NullSource for the
`_minmax_count_projection`, `_statistics_projection` and `_exact_count_projection` blocks and
skipped the projection read beside parts without the projection, while the followers do the
same by design. `min`/`max`/`count` came back as 0 (since ClickHouse#82807), `sum`/`avg` as 0/nan (since
ClickHouse#123950), and projection-answered rows were dropped.

Use `ReadFromMergeTree::isParallelReplicasLocalPlanForInitiator()`, which reads the read's own
context and is already used by the same code for the empty-ranges announcement (and its
follower twin for the follower failpoints), and remove the plan-wide field. For a query whose
outer and subquery contexts agree the answer is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Assert in `system.query_log` that every query of the test is answered by the expected
projection or prepared source, not only that parallel replicas ran it. Pin
`auto_statistics_types = 'basic'` on the table and clamp `materialize_statistics_on_insert` to
1, so that the `sum`/`avg` query is answered from the per-part statistics in every randomized
run (without `basic` statistics or with statistics not materialized on insert it read the
parts and passed on master too). Move the parallel replicas settings that only matter in the
subquery to the session, so each subquery enables parallel replicas with one setting.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, head 390072d): 1 finding, fixed; round 2 clean
Finding Verdict
⚠️ Test-liveness: the sum/avg line was not served by _statistics_projection in 12 of 40 randomized runs (auto_statistics_types drawn without basic, or materialize_statistics_on_insert = 0), and the test did not say which source served each query AGREE, fixed: both settings pinned, and the system.query_log check now also asserts the source of every query
💡 Test repeated the full parallel-replicas settings in every subquery AGREE, fixed: inert settings moved to the session, subqueries keep only enable_parallel_replicas = 1

Round 2 (test-only delta): no findings.

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [390072d]

Summary: ✅


AI Review

Summary

Reviewed #131618 at 390072d2e13f3655ea170fae0323595bd4e26228, including all prior discussion. The change fixes missing projection and metadata-derived results when parallel replicas are enabled only in a subquery's SETTINGS, by determining the initiator role from each ReadFromMergeTree. No actionable findings. The new regression covers all five affected sources and passes in the Fast test report for this head. No local build or tests were run.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Five nested queries (minmax, statistics, exact count, aggregate and normal projection beside parts without them) return wrong values 20/20 on master; the new test fails 40/40 with random settings on master, with every value line wrong in every run.
b Root cause explained? The initiator's local plan is optimized with the outer query's QueryPlanOptimizationSettings, whose plan-wide initiator flag is false when only the subquery enables parallel replicas, so the initiator's read drops what projections and prepared sources answer, as the followers do by design.
c Fix matches root cause? Yes. The decision now comes from the read's own context (isParallelReplicasLocalPlanForInitiator(), already used for the empty-ranges announcement in the same code) and the plan-wide field is removed.
d Test intent preserved / new tests added? New SQL test covering the five sources plus a query_log check that parallel replicas and the expected projection or prepared source served each query; the table pins auto_statistics_types = 'basic', per-setting random-settings limits only, no no-random-* or no-parallel tags.
e Both directions demonstrated? Yes. Master: wrong values (test FAIL with the inverse diff); fix: correct values, test 50/50 OK with random settings and 10/10 OK in the ParallelReplicas configuration (master 10/10 FAIL).
f Fix is general across code paths? All carriers fixed: the minmax, statistics and exact-count blocks and the projection skip and fallback in the aggregate optimizer, the skip and fallback in the normal optimizer. Top-level queries return identical results on both builds (no double counting); 40 related tests pass.
g Fix generalizes across inputs (params/datatypes/wrappers)? The decision does not depend on column types; covered with and without parts lacking the projection, local plan 0/1, plan-based mode, random query and MergeTree settings.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; when outer and subquery settings agree the per-read answer equals the old flag.
i Invariants and contracts preserved? Exactly one replica, the initiator's local read, returns what a projection or prepared source answers; this now also holds in the nested shape. The fallback that is no longer called for non-coordinated reads was a no-op for them.

Session id: cron:clickhouse-impl-slot-5:20261114-115800

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Nov 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 390072d2e with master 8447a0ec2 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.59, programs/clickhouse-keeper ×0.66 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 8.8 s +5.4 s (+160%)
Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Nov 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 16, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 17, 2026
Merged via the queue into ClickHouse:master with commit 5c48ad1 Nov 17, 2026
604 of 608 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The release branches still have this bug. The repro in #134035 (a subquery with parallel replicas in its own SETTINGS, ORDER BY the key of a projection, next to a part without that projection) returns 0 rows instead of 20 on 26.8.45.6, 26.9.37.5 and 26.10.2.103, and on every release I tried from 26.5.7.64 on. It returns 20 at this PR's merge commit 5c48ad1c and 0 at its first parent e03ba314. The max() example from the description returns 0 instead of 99999 on 26.3.33.24 and 26.8.45.6 (three replicas, ReplicatedMergeTree).

This PR has no backport, so these branches would need v26.3-must-backport, v26.8-must-backport, v26.9-must-backport and v26.10-must-backport.

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). 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