Skip to content

Do not apply the lazy FINAL rewrite to a bucketed distributed read - #112493

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-112332-bugb-lazy-final-distributed-buckets
Nov 2, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-112332-bugb-lazy-final-distributed-buckets

Conversation

@groeneai

@groeneai groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112332

Changelog category (leave one):

  • Experimental Feature

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

With make_distributed_plan and query_plan_optimize_lazy_final both enabled, a FINAL query on a ReplacingMergeTree with a WHERE or PREWHERE no longer returns each row once per reader task.

Description

On master, with make_distributed_plan = 1 and query_plan_optimize_lazy_final = 1, a filtered FINAL query on a ReplacingMergeTree returns each row once per distributed reader task. On the reporter's 80000-row table, against a local count() = 26667: 53334, 106668 and 213336 at 2, 4 and 8 buckets. count() and sum(v) inflate by the same factor, so the result is duplicated rather than mis-merged.

Root cause. tryMakeDistributedRead bucketizes the read early in optimizeTree, building primary-key-range layers so a deduplication group stays inside one bucket. Those mark ranges reach the worker in a per-read read_bucket_<N> task parameter, which initializePipeline only consumes while distributed_read_bucket_count is non-zero. The worker re-runs the pass list, where optimizeLazyFinal fires and replaces the reading step with fresh reads carrying no bucket state. With the count back at zero, the parameter is ignored and every task merges the whole table, while the exchange still unions them.

This declines the rewrite when the read is bucketed, as canUseProjectionForReadingStep already does for the projection passes. Propagating the bucket state instead would be a new distributed-FINAL algorithm: a lane's marks are resolved on the worker against a part set the rewrite re-partitions, and the set-building replacement has no notion of a primary-key interval.

Validation. The new test 05401_lazy_final_distributed_buckets asserts that the read is bucketed (a GatherExchange above it in EXPLAIN PLAN) and compares every arm against the local oracle. On master without the guard exactly the four correctness arms fail, and every other line passes. Lazy FINAL is unchanged for local and non-bucketed reads, because the guard keys on the bucket count and not the setting. The CLICKHOUSE_CLOUD relaxation in supportsBucketedRead is untested here.


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

Version info

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

With make_distributed_plan = 1 and query_plan_optimize_lazy_final = 1, a FINAL
query on a ReplacingMergeTree that also carries a WHERE or PREWHERE returned each
row once per distributed reader task, inflating aggregates by the number of tasks.

tryMakeDistributedRead bucketizes the read early in optimizeTree and, for FINAL,
builds primary-key-range layers so a deduplication group stays inside one bucket.
Those mark ranges travel to the worker in the read_bucket task parameter, and
initializePipeline only consumes them while distributed_read_bucket_count is
non-zero. The worker re-runs the whole pass list on the fragment. There the
coordinator's incidental bail on getAnalyzedResult does not apply, because
deserialize rebuilds the read with a null analyzed result and make_distributed_plan
is false on the fragment context, so optimizeLazyFinal fires and replaces the
reading step with fresh reads that never receive setDistributedRead. With the
count back at zero the read_bucket parameter is ignored, every task reads all
parts and performs a complete FINAL merge, and the exchange still unions the tasks.

Decline the rewrite when the read is bucketed. Propagating the bucket state
instead would be a new distributed FINAL algorithm rather than a smaller fix: a
lane's marks are resolved on the worker against a part set the rewrite
re-partitions, and the set-building replacement has no notion of a primary-key
interval, so two lanes could each claim a duplicate key.
canUseProjectionForReadingStep already declines for bucketed reads for the same
reason, and DistributedPlanExecutor disables the implicit count projection on the
worker with the same argument.

Extend 04359_distributed_final_modifiers rather than weakening it. The arms need a
larger fixture: on the 80000-row table the FINAL read is never bucketed, which is
why this never reddened that file. Each arm asserts distribution and compares
against the local oracle rather than a bucket multiplier, since the observed factor
is the effective task count and not the requested count. optimize_aggregation_in_order
is pinned in the lazy section because it makes the rewrite about two orders of
magnitude slower without changing any result; that is pre-existing behaviour and
reproduces on master with make_distributed_plan = 0.

Related: ClickHouse#112332
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 findings from an independent reviewer, 4 from my own cold review; 0 blockers, 1 major adjudicated)

Before opening this PR I reviewed the resulting code cold (without reading the implementation notes), then had an independent model re-review the full diff, its callers and the bucket setup/serialization/execution paths. Verdicts below; every one is backed by a code citation or a measurement, not prose.

⚠️ bucket-guard-liveness (major) - DISAGREE, the requested arm is unsatisfiable by construction

The reviewer asked for a make_distributed_plan = 1 query "forced to remain non-bucketed" that must still show a lazy-FINAL plan node, arguing that a guard keyed on the setting rather than the bucket count would pass every assertion here while breaking non-bucketed distributed reads.

That state does not exist. For a ReadFromMergeTree read, "distributed" and "bucketed" are the same condition: tryMakeDistributedRead calls setupDistributedReadBuckets and returns at makeDistributed.cpp:597-598 when it yields 0, which is before the GatherExchangeStep is created at :620. Every zero-return inside setupDistributedReadBuckets (unsupported bucketed read, SAMPLE, Graphite, unsafe or mixed-order primary key, empty analysis, tasks <= 1) therefore produces a plan with no distribution at all. So a setting-keyed guard could not break a non-bucketed distributed read, because there is no such read.

Independently, a setting-keyed guard is not expressible where the rewrite actually fires. The rewrite fires on the worker, and makeContextForLocalExecution sets make_distributed_plan = false on the fragment context (DistributedPlanExecutor.cpp:816); the remote path deserializes a fragment whose context never had it set. On the worker the setting reads false, so a setting-keyed guard would be a no-op that fixes nothing. The bucket count is the only state that survives, restored at ReadFromMergeTree.cpp:5774 during deserializeQueryPlan.

The underlying worry - "would these arms still pass if bucketing silently declined?" - is answered by the arms that exist. Each compares against a locally computed oracle, and in the mutation run the three bucket arms redden with distinct values (266668, 533336, 1066672), which is only possible if each one genuinely bucketed at its own count; a silently-declining bucketization would have left all three at the oracle.

💡 oversized-fixture-rationale (nit) - DISAGREE, the smaller fixture is the fragile one

The reviewer noted that the existing 80000-row table already asserts its filtered FINAL read distributes, so a 400000-row fixture looks unnecessary. The observation is accurate and the conclusion inverts.

Those pre-existing assertions hold only because tests/clickhouse-test unconditionally injects max_threads (32 with probability 0.03, else 1..3). With max_threads unset, the FINAL read on the 80000-row table does not distribute - reproducible on master's own unmodified file. The mechanism is in the code the finding cites: the FINAL bucket budget is target_buckets * lanes_per_task * span_marks / total_marks with lanes_per_task = min(requested_num_streams, max_final_threads) (ReadFromMergeTree.cpp:5419-5421), and tasks <= 1 returns 0 (:5479), so on a high-core machine with max_threads unset the arithmetic can collapse to a single task.

The larger fixture is what removes that dependence: the new arms were measured stable across max_threads in {default, 1, 3, 32} at all three bucket counts. Reusing the smaller table would make them silently vacuous in exactly the --no-random-settings flavors (azure, coverage, stress, Fast test), which is strictly worse. The reviewer's second point - that enabling the lazy pass cannot change the coordinator's bucketing decision - is correct and not in dispute; the fixture size is about whether the read is bucketed at all, not about the lazy pass perturbing it.

💡 explain-disjunct-dead-name (nit, from my own review) - AGREE, disclosed

The new lazy local still rewrites assertion ORs three plan-step name patterns, and %LazilyUnordered% can never match: LazilyUnorderedReadFromMergeTree::getName returns LazilyReadFromMergeTree (LazilyUnorderedReadFromMergeTree.h:30), and EXPLAIN PLAN prints getName (QueryPlan.cpp:408). The assertion is still live and load-bearing through its other two patterns (LazyFinalKeyAnalysis, LazyReadReplacingFinal), both of which are real step names and both of which redden when the guard is removed - so this is a dead disjunct, not a dead assertion. Recording it here rather than churning the diff; the correct spelling for that third pattern is LazilyReadFromMergeTree.

💡 PR metadata (nits, from my own review) - AGREE, fixed before opening

The issue link was inside the leading HTML comment and so did not render; it is now a visible Related: line in the full-URL form the template asks for. The title now backticks FINAL, and the changelog entry is in the present tense per docs/changelog_entry_guidelines.md.

Verified, not findings

The guard sits before all three replacement constructions and before the expensive selectRangesToRead, so no path can leave a partially rewritten plan. Carrier enumeration was done independently: constructions of a new ReadFromMergeTree or LazilyUnorderedReadFromMergeTree under src/Processors/QueryPlan/Optimizations/ occur in exactly one file, this one; the projection passes already carry the identical guard at projectionsCommon.cpp:75 and additionally reject isQueryWithFinal at :79; optimizeLazyMaterialization2 moves the same step rather than replacing it, so bucket state stays on the executing read. All three new reference (count, sum) pairs were re-derived arithmetically and match exactly.

Session id: cron:clickhouse-review-slot-49:20260729-214000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A 400000-row ReplacingMergeTree with SYSTEM STOP MERGES, then SELECT count(), sum(v) FROM t FINAL WHERE k % 3 = 0 SETTINGS make_distributed_plan = 1, distributed_plan_default_reader_bucket_count = 4, query_plan_optimize_lazy_final = 1, min_filtered_ratio_for_lazy_final = 0.0 against a server with the stateless-worker endpoint enabled. Fires on demand, no randomization needed. The reporter's 80000-row fixture is vacuous: its FINAL read is never bucketed, so every arm on it returns the correct value.
b Root cause explained? Yes. tryMakeDistributedRead bucketizes the read early in optimizeTree and, for FINAL, builds primary-key-range layers so a deduplication group stays inside one bucket. The layer marks travel to the worker in the read_bucket task parameter, and initializePipeline only consumes them while distributed_read_bucket_count is non-zero. The worker re-runs the whole pass list on the fragment; there the coordinator's incidental bail (getAnalyzedResult) does not apply, because deserialize rebuilds the read with a null analyzed result, so optimizeLazyFinal fires and replaces the reading step with fresh reads that never receive setDistributedRead. With the count back at zero, read_bucket is ignored, every task reads all parts and performs a complete FINAL merge, and the exchange still unions the tasks, so each row appears once per task.
c Fix matches root cause? Yes. The defect is that a plan pass replaced a read pinned to coordinator-selected per-bucket marks; the fix makes that pass decline exactly when the read is so pinned, using the existing public getDistributedReadBucketCount. It is not a widened bound, not a no-random-* tag, not a data-size reduction, and not a defensive check masking an upstream problem. canUseProjectionForReadingStep already declines for bucketed reads for the same documented reason, and DistributedPlanExecutor disables the implicit count projection on the worker with the same argument.
d Test intent preserved / new tests added? Yes. All nine existing assertions in 04359_distributed_final_modifiers are byte-unchanged (verified by diffing against git show origin/master:); nothing was weakened. Twelve new lines were added covering bucket counts 2/4/8, PREWHERE, a no-filter control, a lazy-off control, a local-still-rewrites control, and a per-arm distribution assertion so a future change that silently stops distributing cannot make the counts trivially correct.
e Both directions demonstrated? Yes. On the pristine merge-base build the four correctness arms return 266668, 400002, 666670 and 400002 against a local oracle of 133334; on the fixed build all four return 133334. Both runs were on Build-ID-verified binaries with the server's buildId() matched to readelf -n before each verdict.
f Fix is general across code paths? Yes. The guard returns before every read-construction site in the pass, so one guard covers all of them. Every other pass that runs after tryMakeDistributedRead and constructs a read was enumerated: the two projection passes are refused by canUseProjectionForReadingStep, which contains the identical bucket guard and additionally rejects isQueryWithFinal; the implicit count projection is already disabled on the worker; the parallel-replicas passes are mutually exclusive with make_distributed_plan; ReadFromObjectStorageStep is unreachable because the pass casts to ReadFromMergeTree. Fixed at the pass that drops the state, not guarded at the point where the wrong rows appear.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes for the axes that exist. The guard tests one size_t on one step class, so type wrappers do not apply. Verified across bucket counts 2/4/8, WHERE and PREWHERE, filter and no filter, local and distributed, bucketed and non-bucketed (ORDER BY tuple(), where setupDistributedReadBuckets returns 0), max_threads in {default, 1, 3, 32}, and both Compact and Wide parts. enable_vertical_final and do_not_merge_across_partitions_select_final route through the same field, so they are covered uniformly.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No setting default moves, no serialization change, no header change, so no SettingsChangesHistory.cpp entry is needed. Behaviour changes only for queries that currently return wrong results. Lazy FINAL is unaffected for local and non-bucketed distributed reads, because the guard keys on the step's bucket count rather than on the setting.
i Invariants and contracts preserved? Yes. The invariant is that a plan pass must not replace a ReadFromMergeTree whose read is pinned to coordinator-selected per-bucket marks. The guard is a pure early return placed before any mutation of the reading step, so no path leaves partially-rewritten state and there is nothing to unwind on an error or early return. It reads one accessor, acquires no locks, adds no shared state, and cannot throw.

Session id: cron:clickhouse-impl-slot-45:20260729-193300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @davenger, could you review this? tryMakeDistributedRead pins a FINAL read to per-bucket primary-key-range mark ranges that travel in the read_bucket task parameter, but the worker re-runs the pass list and optimizeLazyFinal replaces the reading step with fresh reads carrying no bucket state, so read_bucket is ignored and every reader task returns the whole deduplicated result.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1dfdf31]

Summary: ✅


AI Review

Summary

The change prevents lazy FINAL rewrites from discarding the mark ranges assigned to bucketed distributed reads. The guard covers all replacement paths and preserves local optimization. No actionable findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 30, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@KochetovNicolai I am not sure if this is fixing an issue. Please close the PR if this is not needed.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.30% -0.10%
Functions 91.90% 91.80% -0.10%
Branches 78.50% 78.40% -0.10%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6857586

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica 1 for unknown stream ... (STID 5217-5b3d) chronic trunk bug in the parallel-replicas reading coordinator, master-reachable #111689 (ours, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Server died shard death cascade of the same logical error above, one event #111689 (ours, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 02770_async_buffer_ignore (result differs with reference) chronic S3 profile-events nondeterminism, 27 rows across 17 unrelated pull requests and 2 master runs in 30 days a fix task owns this (investigating at full effort, fixing-PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260730-163853

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@serxa serxa assigned serxa and unassigned serxa Sep 14, 2026
Reviewer request. The detail moves here from the code:

A distributed read (make_distributed_plan) is pinned by tryMakeDistributedRead
to the coordinator's per-bucket mark ranges, chosen so that a deduplication
group stays inside one bucket. The ranges travel in a per-read read_bucket_<N>
task parameter, not inside the step, and initializePipeline only consumes them while
distributed_read_bucket_count is non-zero. The replacement reads that the lazy
FINAL rewrite builds carry no bucket state, so every task would read all parts
and return the whole deduplicated result. The projection optimizations are
disabled for distributed reads by the same guard (projectionsCommon.cpp).

The test comment claiming that an 80000-row table is not bucketed is dropped:
since the fixed per-task layer budget in setupDistributedReadBuckets it is, at
every max_threads value.

Comment-only change: the comment-stripped files are identical to the previous
head.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 15, 2026
The flaky check ran the whole of 04359_distributed_final_modifiers 50 times
in parallel under the thread fuzzer, and after master switched the FINAL
bucket budget to a fixed 16 lanes per task the file exceeded the 180 s
limit (debug p50 ~129 s, several runs over 180 s and four 600 s timeouts).
Most of the cost was the 400000-row fixture plus master's own arms, which
the flaky check bills to any PR that extends the file.

The lazy FINAL arms now live in 05401_lazy_final_distributed_buckets and
04359 is restored to master, following the in-tree preference for a new
test over extending an existing one. The fixture is 20000 rows per part:
the read is bucketed only above distributed_plan_max_rows_to_broadcast
(20000 selected rows), so 40000 still distributes and still reproduces the
bug at 2, 4 and 8 buckets on master. The separate 80000-row table for the
local rewrite arms is replaced by the same fixture.

The two "read distributes" checks now look for a GatherExchange directly
above the read in EXPLAIN PLAN. EXPLAIN PIPELINE's
ReadFromDistributedPlanSource is also present when the read is not
bucketed (measured: 10000 rows per part gives 1 there, 0 here, and no
overcount on master), so it could not catch a vacuous fixture.

The test session also sets distributed_plan_fallback_to_local_execution = 0,
as 04359 does for its distributed arms, so a planner rejection of the
aggregating arms fails the test instead of passing through a local read.

Also drops the `%LazilyUnordered%` disjunct, which never matches: the step
prints its name as LazilyReadFromMergeTree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim PedroTadim self-assigned this Oct 30, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed?

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai are you sure this is the best fix?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, it is still needed. I re-measured today on master bee6deac (no diff to your merge d1026fb7 under src/Processors, src/QueryPipeline, src/Storages/MergeTree). Only the two opt-in settings are needed:

CREATE TABLE t (k UInt64, v UInt64, ver UInt64) ENGINE = ReplacingMergeTree(ver) ORDER BY k;
SYSTEM STOP MERGES t;
INSERT INTO t SELECT number, number, 1 FROM numbers(2000000);
INSERT INTO t SELECT number, number + 5, 2 FROM numbers(2000000);
SELECT count() FROM t FINAL WHERE v < 100000 SETTINGS make_distributed_plan = 1, query_plan_optimize_lazy_final = 1;

Master returns 199990. This PR's head 1dfdf315 returns 99995, which matches make_distributed_plan = 0 and query_plan_optimize_lazy_final = 0. The new test fails on master (2x/4x/8x at 2/4/8 buckets) and passes on this head.

On the fix: the alternative is to keep lazy FINAL and limit its reads to the task's bucket. I don't think that is fix-sized. A bucket is marks plus merge borders (DistributedReadBucket, MergeTreeFinalMerge.h:34), and the worker resolves them only at pipeline build, from the task parameter (ReadFromMergeTree.cpp:5423). Everything the rewrite builds (the non-intersecting read, the set-building read, LazyFinalKeyAnalysisStep, LazyReadReplacingFinalStep, LazilyUnorderedReadFromMergeTree) works over the whole parts_with_ranges, so each one would need the lane's marks and borders.

So I did what the code already does for the other rewrites a bucketed read cannot re-derive: projections (projectionsCommon.cpp:62), the text index trivial count (optimizeTrivialCountFromTextIndex.cpp:191), and the implicit count projection on the worker (DistributedPlanExecutor.cpp:996). The read stays distributed and uses the regular bucketed FINAL, which is correct. Only the lazy rewrite of a bucketed read is lost. Not bucketing such reads would keep lazy FINAL but run the whole FINAL on one node, which I think is the worse trade-off when the query asked for make_distributed_plan.

@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1dfdf3154 with master 2d61726eb (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.

Compile time of recompiled translation units

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

Job report

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 2, 2026
Merged via the queue into ClickHouse:master with commit 561272e Nov 2, 2026
180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 2, 2026
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-experimental Experimental Feature 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.

5 participants