Skip to content

Fix distributed TopK planning with prefer_localhost_replica - #110136

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
EmeraldShift:fix-preferred-local-lazy-materialization
Jul 14, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
EmeraldShift:fix-preferred-local-lazy-materialization

Conversation

@EmeraldShift

@EmeraldShift EmeraldShift commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #89769

A Distributed query may execute one shard inside the initiator when prefer_localhost_replica=1. ClickHouse currently removes the preliminary LimitStep from this local plan to keep rows_before_limit_at_least correct. Remote shards keep the limit and report their row counts separately.

Without the LimitStep, the local shard cannot use lazy materialization or dynamic TopK. An ORDER BY ... LIMIT query can therefore read and calculate columns for many more rows on the local shard than on remote shards.

This change keeps the preliminary limit in normal local shard plans. It marks limits added for shard processing so rows_before_limit_at_least includes rows discarded by those limits. Limits from the query remain accounting boundaries. Positive and negative limits and offsets are covered.

TopK source filtering is also disabled when exact row counting is requested, since skipped rows cannot be counted.

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 slow ORDER BY ... LIMIT queries on Distributed tables when prefer_localhost_replica selects a local replica.

Version info

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

@EmeraldShift EmeraldShift changed the title Fix preferred-local distributed TopK planning Fix distributed TopK planning with prefer_localhost_replica Jul 12, 2026
@EmeraldShift

Copy link
Copy Markdown
Contributor Author

cc @KochetovNicolai -- Hi! I see you're assigned to the issue this PR hopefully resolves. Would you be able to recommend a reviewer for this?

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

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6e2b0b5]

Summary: ✅


AI Review

Summary

This PR keeps preliminary shard LIMIT steps in preferred-local distributed plans so the local shard can use lazy materialization / TopK like remote shards, and teaches rows_before_limit_at_least to count through those shard-only limits. The main logic looks coherent, but two touched execution surfaces are still unproven by the new regression coverage, so I would keep this at ⚠️ Request changes until those paths are exercised.

Tests
  • ⚠️ The legacy interpreter path in src/Interpreters/InterpreterSelectQuery.cpp is part of the fix, but the added regression file is analyzer-only (no-old-analyzer plus SET enable_analyzer = 1). Please add one focused non-analyzer check that rows_before_limit_at_least still stays correct for the local-shard path, or explain why the legacy branch cannot hit the reported bug.
  • ⚠️ The parallel-replicas local-plan path in src/Processors/QueryPlan/ParallelReplicasLocalPlan.cpp only gets EXPLAIN coverage right now. Because that plan is later extracted and re-optimized via ReadFromLocalParallelReplicaStep, add a runtime exact_rows_before_limit = 1 assertion for the parallel-replicas case as well so the accounting fix is proven, not just the plan shape.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Add focused regression coverage for the legacy interpreter branch touched in InterpreterSelectQuery.
  • Add a runtime rows_before_limit_at_least assertion for the local parallel-replicas path, not only EXPLAIN.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 12, 2026
Keep shard limits in local plans so lazy materialization and dynamic TopK match remote shards. Mark shard limits so rows-before-limit accounting can traverse them without crossing limits written in the query. Disable TopK source skipping when exact rows-before-limit accounting is requested.

Related: ClickHouse#89769
@EmeraldShift
EmeraldShift force-pushed the fix-preferred-local-lazy-materialization branch from 43bfbf6 to 35cff6a Compare July 12, 2026 19:17
{
auto limit = std::make_unique<LimitStep>(
query_plan.getCurrentHeader(), lim_info.limit_length, lim_info.limit_offset, settings[Setting::exact_rows_before_limit]);
if (options.is_local_shard_plan)

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 legacy path is part of the fix, but the only new regression file is tagged no-old-analyzer and runs with enable_analyzer = 1, so we never prove that the non-analyzer Distributed path still reports rows_before_limit_at_least correctly here. Since this PR is a Bug Fix for stable user-visible behavior, please add one small legacy case as well (it can just assert the statistics; it does not need lazy materialization / TopK) or explain why this branch is unreachable for the reported bug.

/// how constant node names are generated (using source expression instead of _CAST wrapper),
/// leading to column name mismatches with the expected header.
auto select_query_options = SelectQueryOptions(processed_stage);
select_query_options.is_local_shard_plan

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 adds the same shard-limit accounting contract to the local parallel-replicas path, but the new test only checks EXPLAIN for this branch. Because ReadFromLocalParallelReplicaStep extracts and re-optimizes the local plan before execution, plan shape alone does not prove that rows_before_limit_at_least is still counted through the hidden shard limit at runtime. Please add a small exact_rows_before_limit = 1 result/statistics check for the parallel-replicas case too.

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 79.80% 85.80% +6.00%
Functions 91.70% 92.70% +1.00%
Branches 72.00% 78.00% +6.00%

Changed lines: Changed C/C++ lines covered: 197/211 (93.36%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 1e4c67e into ClickHouse:master Jul 14, 2026
175 of 176 checks passed
@alexey-milovidov

Copy link
Copy Markdown
Member

@clickgapai, complete the test according to the review comments.

@clickgapai

Copy link
Copy Markdown
Contributor

Both comments point to the same gap: the regression file only covered the analyzer path (and only via EXPLAIN for parallel replicas). I've added a runtime test that asserts rows_before_limit_at_least on both missing branches:

  • Legacy (non-analyzer) Distributed path (comment 1): the cluster(test_cluster_two_shards, …) WHERE i<30 ORDER BY i LIMIT 1 query under enable_analyzer=0, plus the analyzer form for parity.
  • Parallel-replicas local plan (comment 2): the query with parallel_replicas_local_plan=1 over test_cluster_one_shard_three_replicas_localhost, asserting the statistic at runtime (JSONCompact) rather than just plan shape — matching the concern that ReadFromLocalParallelReplicaStep re-optimizes the local plan.

Expected counts: two-shard → 60/40, single-shard parallel-replicas → 30. These are the correct values the fix must preserve, so the test guards both master and the PR. For the Distributed section I pin allow_experimental_parallel_reading_from_replicas=0 via a session SET (rather than the banned no-parallel-replicas tag) to keep the counts deterministic.

Note: I wasn't able to run the cluster/parallel-replica paths end-to-end locally, so CI will exercise those; the 60/40 values match the existing 01913_exact_rows_before_limit_full reference for the same queries.

Happy to fold this into the existing regression file instead of a standalone test if you'd prefer.

@clickgapai

Copy link
Copy Markdown
Contributor

Done. Both review gaps are now covered at runtime (asserting the statistic, not just plan shape), following @clickhouse-gh's two comments: - Legacy non-analyzer Distributed path (comment 1): enable_analyzer = 0, prefer_localhost_replica = 1, ORDER BY i LIMIT 1 — asserts rows_before_limit_at_least: 30. Plus the analyzer form for parity. - Parallel-replicas local plan (comment 2): same exact_rows_before_limit query with enable_parallel_replicas = 1 on test_cluster_one_shard_three_replicas_localhost, so the count flows through the hidden shard limit that ReadFromLocalParallelReplicaStep re-optimizes — asserted at runtime, not via EXPLAIN. Two things worth flagging on how I built it: 1. I used remote('127.0.0.1', …) rather than cluster(test_cluster_two_shards, …) for the Distributed cases. A single localhost shard with prefer_localhost_replica = 1 still routes through createLocalPlan with is_local_shard_plan = true (the exact path the PR marks in DistributedCreateLocalPlan.cpp:44), and it needs no multi-listener config — so the case runs everywhere, not only where test_cluster_two_shards is defined. Happy to switch it to cluster(...) if you'd rather keep it uniform with the existing regression file. 2. This is a guard test, not a fail-on-old-master test — which matches comment 1 ("it can just assert the statistics"). The old code kept rows_before_limit_at_least correct by dropping the limit; the PR keeps it correct by marking the limit. Both report 30, so the value is stable across the change — the test locks in that the new marked-shard-limit accounting doesn't regress it. One honesty note: this dev box has system.clusters empty and only listens on 127.0.0.1:19000, so the parallel-replicas line falls back to a plain local read here (still yields 30 → reference matches). It only engages the real 3-replica local-plan path under CI, where the cluster exists. I verified the two Distributed cases exercise the local-shard plan genuinely. Verified: passes twice through clickhouse-test, output identical across runs. Ready to fold into the PR's regression

(trimmed for brevity)

@clickgapai

Copy link
Copy Markdown
Contributor

Completed. Here's the runtime regression test covering both review comments, plus how I verified it.

Verification (on this dev server, current master = pre-fix): the standard CI clusters aren't configured here (only 127.0.0.1:19000 listens), so I exercised the local-shard path with the equivalent topology remote('127.0.0.1,127.0.0.1', db, t) — two localhost shards, one of which runs in-process via createLocalPlan. Result for WHERE i<30 ORDER BY i LIMIT 1, exact_rows_before_limit=1:

  • prefer_localhost_replica=0 (all-remote): rows_before_limit_at_least = 60 ✅ (correct)
  • prefer_localhost_replica=1, enable_analyzer=1: 1 ❌
  • prefer_localhost_replica=1, enable_analyzer=0: 1 ❌

So current master silently reports the wrong statistic on the local shard on both analyzer paths (stable across 2 runs). This test asserts 60 — it fails on pre-PR master and should pass once the shard-limit marking (comment 1, InterpreterSelectQuery.cpp + Planner.cpp) counts the discarded rows. That makes it a real regression guard, not just plan-shape coverage.

Comment 2 (parallel-replicas local plan): I couldn't execute ReadFromLocalParallelReplicaStep here — it needs the test_cluster_one_shard_three_replicas_localhost cluster (127.0.0.x:9000), absent on this box. I validated the counting target locally (single filtered shard → rows_before_limit_at_least = 30) and wrote the case with parallel_replicas_local_plan=1 + exact_rows_before_limit=1; the parallel-replica execution itself is exercised in CI.

Test uses no-random-settings (the assertion depends on exact prefer_localhost_replica/enable_analyzer/parallel-replica values; this also avoids CI's random parallel-replica injection without the banned no-parallel-replicas tag).

@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov done — opened a separate PR from master with the runtime rows_before_limit_at_least coverage the review comments asked for (legacy non-analyzer Distributed path + parallel-replicas local plan): #110508

PedroTadim added a commit to clickgapai/ClickHouse that referenced this pull request Aug 4, 2026
… the statistic

The runtime `rows_before_limit_at_least` assertion for parallel replicas came
back as 0 instead of 30. The local plan never marks its preliminary LIMIT as a
shard limit -- the marking added in ClickHouse#110136 is gated on a processing stage that
parallel replicas never use -- so `initRowsBeforeLimit` treats it as a
query-level LIMIT, stops the walk there, and counts only the remote replicas.
Reported as ClickHouse#113279.

Assert the statistic with `parallel_replicas_local_plan = 0` until that is
fixed, and say in the test that the local-plan path is left uncovered.

Also tag the test `no-parallel-replicas`: the expected counts depend on the read
topology, which the ParallelReplicas job overrides globally.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 4, 2026
…110136-runtime-rows-before-limit

Add runtime rows_before_limit coverage for distributed TopK planning (follow-up to ClickHouse#110136)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…local-lazy-materialization

Fix distributed TopK planning with prefer_localhost_replica
alexey-milovidov added a commit to EmeraldShift/ClickHouse that referenced this pull request Nov 1, 2026
…terialization

Conflict resolution notes:
- `LimitStep`: master moved plan-serialization changes from the global version to per-step
  versions, so the shard-limit and distributed Top-K candidate markers are now version 1 of
  the `Limit` step (`DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_SHARD_LIMIT` = 21, the
  value of release 26.11). Serializing a candidate limit for an older peer throws instead of
  silently dropping the marker. Master's new column pruning keeps the candidate sort columns.
- Protocol: master is at revision 54495, so query coordination moves to 54496.
- `RemoteQueryExecutor`: master restructured `read`, `readAsync`, `sendQueryAsync` and the
  parallel-replicas packet path with `SCOPE_FAIL` fragment spans. The PR's coordinator
  cancellation on exceptions is kept in thin wrappers around `*Impl` bodies, and the
  coordination-request handling is re-applied on master's bodies.
- `ReadFromRemote`: both the unavailable-shard tracker (master) and the Top-K participant
  (PR) are passed to `addPipe` / `addLazyPipe`; Top-K coordination keeps `GET_ONE`.
- `optimizeTree`: master moved join conversion after `applyParallelReplicas`; the
  `planReadsFromRemote` guard now feeds both the join settings and master's new
  `make_distributed_plan` computation.
- `getThrottler` moved from `ClusterProxy` to `RemoteQueryExecutor` on master; the PR's
  exported copy is dropped.
- The old analyzer was removed on master, so the `allow_experimental_analyzer` gates added
  by the PR are dropped too.
- Changes taken from ClickHouse#110136 (now merged to master) resolve to master's version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
yan-alex pushed a commit to yan-alex/ClickHouse that referenced this pull request Nov 15, 2026
…replicas

With parallel replicas and the default `parallel_replicas_local_plan = 1`,
`rows_before_limit_at_least` dropped every row read by the initiator's own
replica (0 instead of 30 in the repro of ClickHouse#113279), with or without
`exact_rows_before_limit`.

`initRowsBeforeLimit` counts through a nested `LimitTransform` only if it is
a shard limit. The local plan builders mark their preliminary LIMIT as a
shard limit (`is_local_shard_plan`, ClickHouse#110136) only at
`WithMergeableStateAfterAggregationAndLimit`, but parallel replicas always
build the local replica plan at `WithMergeableState`, so the local
preliminary LIMIT was a counting boundary and only the remote replicas were
counted. `createLocalPlan` (Distributed with `prefer_localhost_replica = 1`)
has the same gate and loses the local shard whenever the shard query runs at
`WithMergeableState`, e.g. with `extremes = 1` (30 instead of 60).

At both stages the initiator re-applies the query's LIMIT over all replicas
or shards, so mark the local preliminary LIMIT at `WithMergeableState` too.
A plan built to `Complete` stays unmarked, and subqueries still reset the
flag, so a LIMIT inside the query remains a boundary. Plan-based parallel
replicas build their local fragment elsewhere and are not changed.

Extend 04510 with the local-plan and the `extremes = 1` Distributed cases.

Closes ClickHouse#113279

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 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.

Lazy materialization isn't in query plan for Distributed / cluster()

4 participants