Skip to content

Support FINAL reads in distributed query plans (make_distributed_plan) - #108148

Merged
davenger merged 32 commits into
masterfrom
distributed-plan-pk-range-final
Jul 8, 2026
Merged

davenger merged 32 commits into
masterfrom
distributed-plan-pk-range-final

Conversation

@davenger

@davenger davenger commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

Motivation

make_distributed_plan could distribute ordinary MergeTree reads across the cluster, but not SELECT ... FINAL. FINAL deduplicates rows that share a primary key during a merge, so its input can't be split arbitrarily — as a result FINAL queries stayed single-node.

Approach

Split a FINAL read into primary-key-range buckets so that every row sharing a key lands in exactly one bucket. Each bucket is read and FINAL-merged independently — in parallel across nodes — and the results are concatenated. Ranges that don't overlap across parts skip the merge entirely (only the engine's sign / is-deleted filter is applied), and when FINAL does not merge across partitions each partition is split on its own.

Main changes

  • New MergeTreeFinalMerge module that shares the FINAL logic between the single-node and distributed paths: addMergingFinal, buildDistributedFinalPipe, and readNonIntersectingFinalWithEngineFilter.
  • ReadFromMergeTree gains serializable per-bucket primary-key-range layer state (DistributedReadBucket); the coordinator ships each bucket's authoritative marks (plus FINAL borders and index) as a per-task parameter, with multiple merge lanes per task for parallelism.
  • The query-plan serialization version is bumped and carried into step serialization, so a bucketed read from an incompatible version is rejected rather than misparsed.
  • Shapes a bucketed read cannot reproduce (read-in-order, projections, text-index tasks, Graphite FINAL) fall back to a serial read instead of failing.

Covered by new stateless tests 04356–04360 (PK-range layers, per-partition FINAL, more engines, read modifiers, non-intersecting ranges) and multi-node integration coverage.


Changelog category (leave one):

  • Experimental Feature

Changelog entry:

Support distributed query-plan reads for SELECT ... FINAL on MergeTree-family tables when make_distributed_plan is enabled.

Version info

  • Merged into: 26.7.1.645 (included in 26.7 and later)

davenger and others added 16 commits June 19, 2026 15:58
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…s partitions

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…fied distributed read

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…arallelism

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

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79d1ee1]

Summary: ✅


AI Review

Summary

This PR adds distributed FINAL support for make_distributed_plan by splitting MergeTree reads into primary-key-range buckets, shipping per-bucket mark state, and reusing shared FINAL-merge helpers on the receiving side. The main correctness issues from earlier review rounds around bucket payload shipping and empty ordinary-FINAL tasks look addressed in the current code, but the query-plan serialization bump now broadens the compatibility break to all distributed-plan fragments during mixed-version rollouts, not just the new bucketed FINAL layout.

Missing context / blind spots
  • ⚠️ The Cloud-only ReadFromMergeTreeAtWorker implementation is not present in this checkout, so I could not fully validate the shared-storage worker path that now relies on ReadFromMergeTreeAtWorker::canCreateFrom and the new getSamplingFilter plumbing. A private-repo checkout or Cloud CI coverage for that path would close this gap.
Findings
  • ❌ Blockers
    • [src/Core/ProtocolDefines.h:65] Bumping DBMS_QUERY_PLAN_SERIALIZATION_VERSION to 2 changes the compatibility contract for the entire make_distributed_plan feature, not just bucketed FINAL. DistributedPlanExecutor::serializeQueryPlan always writes the current global plan version (src/QueryPipeline/DistributedPlanExecutor.cpp:604), while QueryPlan::deserialize rejects any higher version immediately (src/Processors/QueryPlan/Serialization.cpp:169-172). During a rolling upgrade, a new initiator will therefore break even plain distributed-plan reads/joins/aggregations against old workers before the worker ever inspects whether the fragment contains a bucketed ReadFromMergeTree.
    • Suggested fix: serialize/advertise query-plan version 2 only for fragments that actually need the new bucketed-read layout, or negotiate/downgrade the plan version per worker/task for legacy-compatible fragments. If mixed-version execution is intentionally no longer supported for make_distributed_plan, that rollout break needs an explicit guard and user-facing documentation instead of an implicit global version bump.
Final Verdict
  • Status: ❌ Block
  • Minimum required action: avoid forcing query-plan serialization version 2 for legacy-compatible distributed-plan fragments; otherwise this PR makes every make_distributed_plan query fail on mixed-version clusters instead of only rejecting the new distributed FINAL shape.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jun 22, 2026
Comment thread src/Core/ProtocolDefines.h Resolved
davenger and others added 2 commits June 23, 2026 11:12
…der query-plan serialization version

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… to the step deserializer

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Core/ProtocolDefines.h Resolved
…ibutedFinalPipe` helper

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…onIntersectingFinalWithEngineFilter`

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
davenger and others added 2 commits June 23, 2026 23:53
… skip distributed FINAL for Graphite

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…not reproduce

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

clickhouse-gh Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🔴 AI verdict: degradation — 3 regressed, 3 improved out of 38 analysed

This PR reworks distributed read bucketing and adds parallel FINAL, changing how MergeTree reads are split into per-bucket mark slices. On TPC-H the three join/read-heavy queries regress: Q7 (71ms to 629ms) and Q4 (329ms to 960ms) are large and consistent — the base runs were noisy but the new version is steadily much slower — and Q8 shifts +23.5%. On ClickBench the same bucketing change lines up with modest, consistent improvements (Q4 -17%, Q15 -13%, Q28 -5.5%). Net: the new bucketing helps simple scan/aggregate reads but clearly hurts the TPC-H join inputs, which is worth investigating before merge.

clickbench

🟢 3 improved

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 4 improvement 263 217 -17.5% <0.0001 plan_change: Distributed read bucketing rework changes read parallelism; ~17% faster, consistent across both tests.
🟢 15 improvement 243 211 -13.2% <0.0001 plan_change: Same distributed-read bucketing rework; ~13% faster, confirmed by both tests.
🟢 28 improvement 6292 5944 -5.5% <0.0001 plan_change: Long aggregation ~5.5% faster; modest but clear, in line with the read-bucketing change.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🔴 3 regressed

Flagged queries (3 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 4 regression 329 960 +191.9% <0.0001 plan_change: Base measurements very noisy but new version consistently ~3x slower — large, real regression on the distributed read pa
🔴 7 regression 71 629 +785.9% <0.0001 join_operator: Join-heavy query: base noisy but source stable at 629ms vs 71ms; large regression from reworked distributed read bucketi
🔴 8 regression 170 210 +23.5% <0.0001 join_operator: Multi-join query +23.5%, both tests agree; consistent with changed distributed read bucketing feeding the joins.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: ceec60b3-9991-4e6b-82e7-9eb0d59411d4
  • MIRAI run: b6de1f92-ddcb-430d-acbc-88627bfb99a1
  • PR check IDs:
    • clickbench_682230_1782953411
    • clickbench_682244_1782953411
    • clickbench_682250_1782953411
    • tpch_adapted_1_official_682257_1782953411
    • tpch_adapted_1_official_682269_1782953411
    • tpch_adapted_1_official_682283_1782953411

@shankar-iyer shankar-iyer self-assigned this Jun 24, 2026
davenger and others added 2 commits June 25, 2026 10:18
…d guard bucketed reads

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
davenger and others added 5 commits June 25, 2026 19:46
@davenger
davenger marked this pull request as ready for review July 1, 2026 10:17
@davenger davenger changed the title [WIP] Support FINAL reads in distributed query plans (make_distributed_plan) Support FINAL reads in distributed query plans (make_distributed_plan) Jul 1, 2026
/// marks travel in the `read_bucket` task parameter. The deserializer rejects a version-1 bucketed step (its
/// trailing part-name payload would desync the plan), so all `make_distributed_plan` nodes need one version.
static constexpr auto DBMS_QUERY_PLAN_SERIALIZATION_VERSION = 2;
/// Version 1 added the initiator's settings changes to the task.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This version bump widens the compatibility break from the new bucketed FINAL layout to every make_distributed_plan query. DistributedPlanExecutor::serializeQueryPlan always emits DBMS_QUERY_PLAN_SERIALIZATION_VERSION (src/QueryPipeline/DistributedPlanExecutor.cpp:604), and an older worker rejects any higher plan version before it even reaches ReadFromMergeTree (src/Processors/QueryPlan/Serialization.cpp:169-172). That means a rolling upgrade now breaks even plain distributed-plan reads/joins/aggregations that never use bucketed FINAL: a new initiator will send version 2, and a v1 worker will fail the fragment immediately instead of running the old-compatible plan.

Please keep serializing legacy-compatible fragments as version 1 (or negotiate the query-plan version per worker/task) and reserve version 2 for fragments that actually contain a bucketed ReadFromMergeTree. Otherwise this PR effectively requires a lockstep cluster upgrade for the whole experimental distributed-plan feature, not just the new FINAL path.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.60% -0.10%

Changed lines: Changed C/C++ lines covered: 457/513 (89.08%) · Uncovered code

Full report · Diff report

{
const size_t global_mark = global_offset + covered;
while (current_bucket + 1 < bucket_count && global_mark >= bucket_end_global(current_bucket))
++current_bucket;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Perfect! Favours allocating contiguous whole parts to workers.

const size_t non_intersecting_buckets = std::max<size_t>(1, span_budget * non_intersecting_marks / span_marks);
for (auto & slice : sliceMarksAcrossBuckets(ranges.non_intersecting_parts_ranges, non_intersecting_buckets))
if (!slice.empty())
buckets.push_back({std::move(slice), /*needs_merge=*/ false, {}, 0});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Non-intersecting ranges go first into the buckets and then the intersecting will be accumulated in the rear. So some replicas may only do non-merges and the some replica(s) in the replica list will get all the merge work. Should be fine, we can revisit if needed.

@davenger
davenger added this pull request to the merge queue Jul 8, 2026
Merged via the queue into master with commit c8d03ac Jul 8, 2026
347 of 348 checks passed
@davenger
davenger deleted the distributed-plan-pk-range-final branch July 8, 2026 07:22
alexey-milovidov added a commit that referenced this pull request Jul 8, 2026
Resolve conflicts from master's distributed-FINAL refactor (#108148),
which relocated the standalone expression-compilation call sites this PR
migrates:

- `PartsSplitter.cpp`: master extracted the per-layer range-filter
  building out of `readByLayers` into a new `applyRangeFilterFromAST`
  helper. Kept master's structure (dropped the now-moved inline block)
  and applied this PR's migration to the helper
  (`TreeRewriter`+`ExpressionAnalyzer` -> `analyzeExpressionToActionsDAG`).

- `ReadFromMergeTree.cpp`: master moved `addMergingFinal`,
  `createExpressionForPositiveSign` and `createExpressionForIsDeleted`
  into the new `MergeTreeFinalMerge.cpp`. Took master's side (removed the
  local definitions; `addMergingFinal` is now declared in
  `MergeTreeFinalMerge.h`). The remaining in-file site
  (`spreadMarkRangesAmongStreamsWithOrder`) keeps this PR's migration.

- `MergeTreeFinalMerge.cpp` (new on master): applied this PR's migration
  to the relocated `createExpressionForPositiveSign` /
  `createExpressionForIsDeleted` (`analyzeExpressionToActions`) and
  swapped the includes. This transformation is byte-identical to the one
  this PR already applied to these functions in their pre-refactor
  location in `ReadFromMergeTree.cpp`.

`analyzeExpressionToActions`/`analyzeExpressionToActionsDAG` default
`add_aliases = false`, matching the old `getActionsDAG(false)` behavior.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 8, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-pk-range-final

Support FINAL reads in distributed query plans (make_distributed_plan)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants