Skip to content

Enable lazy materialization for ORDER BY ... LIMIT in distributed plans (make_distributed_plan=1) - #113111

Merged
shankar-iyer merged 7 commits into
ClickHouse:masterfrom
shankar-iyer:worker_side_lazy_mat
Aug 7, 2026
Merged

shankar-iyer merged 7 commits into
ClickHouse:masterfrom
shankar-iyer:worker_side_lazy_mat

Conversation

@shankar-iyer

Copy link
Copy Markdown
Member

ORDER BY ... LIMIT k under make_distributed_plan never used lazy materialization. The plan was distributed before the lazy-materialization pass runs, so the LIMIT ends up above a GatherExchange and the pattern that optimizeLazyMaterialization() looked for did not match. Now, each replica fragment now carries top-k LimitStep, so the replica applies lazy materialization over its own parts/ranges and reads the wide columns only for the rows its local top-k kept.

Impact : With this implementation, each replica in the query could end up reading k wide granules and thus across the cluster a total of (num_replicas * k) wide granules could be read

Changelog category

  • Performance Improvement

Changelog entry

  • Enabled lazy materialization for ORDER BY ... LIMIT k queries in distributed query plans (make_distributed_plan)

`ORDER BY ... LIMIT` under `make_distributed_plan` did not use lazy
materialization: the plan is distributed before the lazy-materialization pass
runs, so the `LIMIT` ends up above a `GatherExchange` and the pattern no longer
matches. The rewrite has to run per fragment on the worker anyway, because the
main and lazy reads share in-memory row positions, and the worker already
re-optimizes the fragment it deserializes.

* `tryMakeDistributedSorting` adds a `LimitStep` for the bound the sorting step
  already applies: `SortingStep::serialize` drops the limit and the query's
  `LIMIT` stays on the coordinator, so the worker's sorting step arrived with
  `limit = 0`. `pushDownLimit` folds it back, which also stops a worker from
  sorting its whole bucket instead of its top N.

* Lazy materialization and lazy FINAL no longer descend below a logical
  exchange on the initiator, where the two branches would be split across
  stages.

Extra bytes read for a deferred column drop ~20x (200k rows, 200-byte payload,
4 read buckets).

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

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [75171e7]

Summary: ✅


AI Review

Summary

This PR restores lazy materialization for ORDER BY ... LIMIT under make_distributed_plan by carrying a fragment-local top-N bound and by keeping the initiator-side lazy passes from descending across logical exchanges. The rewrite itself looks coherent and CI is green, but the new exact_rows_before_limit regression only checks plan shape instead of the user-visible counter contract, so I do not think that edge case is fully proved yet.

Findings

⚠️ Major

  • [tests/queries/0_stateless/04665_distributed_plan_lazy_materialization.sql:106] exact_rows_before_limit promises an exact rows_before_limit_at_least, but the new test only asserts that EXPLAIN no longer shows Limit (local top-N). That is a weaker property than the contract being fixed, so a future fragment-local truncation could undercount again while this test still passes. Add a result-level assertion that compares the reported rows_before_limit_at_least for make_distributed_plan = 0 and 1 with exact_rows_before_limit = 1.
Final Verdict

⚠️ Changes needed before merge: the main rewrite looks sound, but the exact_rows_before_limit fix needs a contract-level regression test instead of an EXPLAIN-shape check.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.80% 91.90% +0.10%
Branches 78.80% 78.80% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

The only flagged query is tpch_adapted_1_official Q4, a small improvement (-5.0%, -54ms). This PR is confined to the distributed query-planner: it inserts a local top-N bound inside distributed sorting fragments so ORDER BY ... LIMIT can materialize wide columns lazily, and keeps lazy branches from crossing a logical exchange. Q4 has no LIMIT and this scale-1 single-instance run does not build distributed plans, so the changed code never executes for it; I've downgraded the Q4 improvement to not_sure as run-to-run variance. The envelope/era gates flagged one unstable ClickBench cell (28) but produced no verdict-bearing rows there, which is consistent with the diff.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 1080 1026 -5.0% <0.0001 plan_change: This PR only adds a local top-N LimitStep to the distributed-plan sorting path (make_distributed_plan with an ORDER BY ... LIMIT). Q4 has no LIMIT and this single-instance run does not use distributed plans, so the -5.0% is run-to-run variance, not a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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: 53d1e226-60b7-43aa-81d5-b097aade8340
  • MIRAI run: a9d839d2-c370-454f-a377-1d0761284126
  • PR check IDs:
    • clickbench_13517_1786011494
    • clickbench_13531_1786011493
    • clickbench_13537_1786011493
    • tpch_adapted_1_official_13543_1786011493
    • tpch_adapted_1_official_13573_1786011493
    • tpch_adapted_1_official_13587_1786011493

@shankar-iyer

Copy link
Copy Markdown
Member Author

The integration test failure shows the exact plan change this PR does -

E   Failed: distributed plan does not match the expected reference
E   --- ACTUAL PLAN ---
E   Expression (Project names)
E     Limit (preliminary LIMIT)
E       GatherExchange (sorted by (__table1.id DESC, __table1.group_key ASC))
E         Limit (local top-N)
E           Sorting (Sorting for ORDER BY)
E             Expression ((Before ORDER BY + Projection))
E               Expression ((WHERE + Change column names to column identifiers))
E                 ReadFromMergeTree (default.big)
E   --- EXPECTED PLAN ---
E   Expression (Project names)
E     Limit (preliminary LIMIT)
E       GatherExchange (sorted by (__table1.id DESC, __table1.group_key ASC))
E         Sorting (Sorting for ORDER BY)
E           Expression ((Before ORDER BY + Projection))
E             Expression ((WHERE + Change column names to column identifiers))
E               ReadFromMergeTree (default.big)

);

-- Optimization should not be shipped in distributed plan if exact_rows_before_limit is set
SELECT 'local top-N in fragment with exact_rows_before_limit=1', countIf(explain LIKE '%Limit (local top-N)%') > 0

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.

exact_rows_before_limit is a contract on rows_before_limit_at_least, but this new regression only asserts that the EXPLAIN output no longer contains Limit (local top-N). That is weaker than the behavior the fix is trying to preserve: any future fragment-local truncation that does not print this exact node would still pass while undercounting the result statistic again. Please add one result-level check that compares the reported rows_before_limit_at_least between make_distributed_plan = 0 and 1 with exact_rows_before_limit = 1.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

How is this weaker?

Your recommendation is to prevent any future breakages with distributed plans, could be unrelated to the lazy materialization optimization enabled in this PR.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I tried to add a testcase, but what you are reporting has a pre-existing problem. rows_before_limit_at_least is not reported at all for distributed plans. I ran the below query and the field is missing.

SELECT a FROM t_dist_lazy ORDER BY b, a LIMIT 1 FORMAT JSONCompact
SETTINGS make_distributed_plan = 1, exact_rows_before_limit = 1,
    output_format_write_statistics = 0, output_format_json_quote_64bit_integers = 0;

Distributed plans use ReadFromDistributedPlanSource and that is not mainitaining/publishing the counter.

@shankar-iyer

Copy link
Copy Markdown
Member Author

Workflow [PR], commit [75171e7]

AI Review

Summary

This PR restores lazy materialization for ORDER BY ... LIMIT under make_distributed_plan by carrying a fragment-local top-N bound and by keeping the initiator-side lazy passes from descending across logical exchanges. The rewrite itself looks coherent and CI is green, but the new exact_rows_before_limit regression only checks plan shape instead of the user-visible counter contract, so I do not think that edge case is fully proved yet.

Findings

⚠️ Major

  • [tests/queries/0_stateless/04665_distributed_plan_lazy_materialization.sql:106] exact_rows_before_limit promises an exact rows_before_limit_at_least, but the new test only asserts that EXPLAIN no longer shows Limit (local top-N). That is a weaker property than the contract being fixed, so a future fragment-local truncation could undercount again while this test still passes. Add a result-level assertion that compares the reported rows_before_limit_at_least for make_distributed_plan = 0 and 1 with exact_rows_before_limit = 1.
Final Verdict

⚠️ Changes needed before merge: the main rewrite looks sound, but the exact_rows_before_limit fix needs a contract-level regression test instead of an EXPLAIN-shape check.

For the only comment, I have responded here : https://github.com/ClickHouse/ClickHouse/pull/113111/changes/BASE..75171e7a83efaa2ae0eca1d7e7a980a47b5c044d#r3726612858

@shankar-iyer
shankar-iyer added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit b311947 Aug 7, 2026
354 of 355 checks passed
@shankar-iyer
shankar-iyer deleted the worker_side_lazy_mat branch August 7, 2026 18:22
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements 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