Repository navigation
Do not apply the lazy FINAL rewrite to a bucketed distributed read - #112493
PedroTadim merged 5 commits into
Conversation
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
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.
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-45:20260729-193300 |
|
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. |
|
Workflow [PR], commit [1dfdf31] Summary: ✅
AI ReviewSummaryThe change prevents lazy Final VerdictStatus: ✅ Approve |
|
@KochetovNicolai I am not sure if this is fixing an issue. Please close the PR if this is not needed. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
CI finish ledger - 6857586Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260730-163853 |
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]>
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]>
|
@groeneai is this PR still needed? |
|
@groeneai are you sure this is the best fix? |
|
Yes, it is still needed. I re-measured today on master 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 On the fix: the alternative is to keep lazy So I did what the code already does for the other rewrites a bucketed read cannot re-derive: projections ( |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 16 s compile time in total, 7 of them have a recent master baseline. |
Related: #112332
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
With
make_distributed_planandquery_plan_optimize_lazy_finalboth enabled, aFINALquery on aReplacingMergeTreewith aWHEREorPREWHEREno longer returns each row once per reader task.Description
On master, with
make_distributed_plan = 1andquery_plan_optimize_lazy_final = 1, a filteredFINALquery on aReplacingMergeTreereturns each row once per distributed reader task. On the reporter's 80000-row table, against a localcount() = 26667:53334,106668and213336at 2, 4 and 8 buckets.count()andsum(v)inflate by the same factor, so the result is duplicated rather than mis-merged.Root cause.
tryMakeDistributedReadbucketizes the read early inoptimizeTree, building primary-key-range layers so a deduplication group stays inside one bucket. Those mark ranges reach the worker in a per-readread_bucket_<N>task parameter, whichinitializePipelineonly consumes whiledistributed_read_bucket_countis non-zero. The worker re-runs the pass list, whereoptimizeLazyFinalfires 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
canUseProjectionForReadingStepalready does for the projection passes. Propagating the bucket state instead would be a new distributed-FINALalgorithm: 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_bucketsasserts that the read is bucketed (aGatherExchangeabove it inEXPLAIN 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. LazyFINALis unchanged for local and non-bucketed reads, because the guard keys on the bucket count and not the setting. TheCLICKHOUSE_CLOUDrelaxation insupportsBucketedReadis untested here.Workflow [PR]
Sync PR [sync-upstream/pr/112493]
Version info
26.11.1.1064-master(included in26.11and later)