Skip to content

Do not read in order for DISTINCT from a FINAL read that uses vertical FINAL - #131547

Merged
fm4v merged 8 commits into
ClickHouse:masterfrom
groeneai:distinct-in-order-vertical-final
Nov 17, 2026
Merged

fm4v merged 8 commits into
ClickHouse:masterfrom
groeneai:distinct-in-order-vertical-final

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131268

Changelog category (leave one):

  • Performance Improvement

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

A DISTINCT over a FINAL read of a ReplacingMergeTree table no longer reads in the sorting key order when the read would otherwise use vertical FINAL (enable_vertical_final), unless a LIMIT lets it stop early. Reading in order turned vertical FINAL off and made such queries up to 2 times slower, also through a join with query_plan_read_in_order_through_join. Closes #131268.

Description

Option 2 as ruled on the issue: #131268 (comment)

buildInputOrderInfo(DistinctStep &) asked the FINAL read for the sorting key order, which turns vertical FINAL off (requestReadingInOrder). The order only helps the preliminary DISTINCT, as the final one stays a hash set. The request is now declined when the read would use vertical FINAL.

Exception: a LIMIT that can stop the DISTINCT early keeps the plan, unless a sort, an aggregation, a set or a join's build input reads the DISTINCT to the end first. Vertical FINAL emits a block only once the merge has passed its last row, so without it these queries got 1.4-11x slower.

LIMIT BY in order and Merge tables also turn vertical FINAL off when reading in order; unchanged here.

clickhouse local, max_threads = 8, the issue's tables as ReplacingMergeTree (80 parts, merges stopped), medians:

Query master this PR
Issue query (query_plan_read_in_order_through_join = 0: 1.97 s) 2.83 s 1.99 s
DISTINCT c1, c2 ... FINAL WHERE c3 LIKE 'v1%' 2.64 s 2.03 s
DISTINCT c1, c2 ... FINAL, non-Nullable key 0.87 s 0.51 s
DISTINCT c1, c2 ... FINAL, Nullable key, no filter 2.49 s 2.69 s
DISTINCT c1 ... FINAL LIMIT 10; issue query + LIMIT 10 0.49 s; 0.26 s same plan
DISTINCT c1, c2 ... FINAL ORDER BY c1, c2 2.16 s same plan

The Nullable-key row without a filter is the cost accepted in the ruling.

Validation: a new stateless test checks each plan (master fails the full-read cases, the change without the exception fails the early-stop ones); the new performance test is 1.2-2.9x faster; 170 existing FINAL + DISTINCT tests are unchanged.


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

Version info

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

groeneai and others added 5 commits November 14, 2026 03:13
…l FINAL

`ReadFromMergeTree::requestReadingInOrder` turns vertical `FINAL` off, so a
preliminary `DISTINCT` over a `ReplacingMergeTree` `FINAL` read traded the
cheaper vertical `FINAL` for an in-order `DISTINCT` (ClickHouse#131268, option 2 as
ruled by the owner). Decline the in-order request in
`buildInputOrderInfo(DistinctStep &)` when the read would use vertical `FINAL`.

WIP (IMPL r1): the plan's STOP rule fired on early-exit DISTINCT ... LIMIT N
shapes; see the replan request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Vertical `FINAL` delivers its first block only after the whole merge, so a
`DISTINCT ... LIMIT N` that reads in order and stops after the first merged
blocks is faster than one over vertical `FINAL`. Decline the in-order request
for a vertical-`FINAL` read only when no `LIMIT` (own, or above it through
streaming steps) and no hinted `DISTINCT` above it can stop reading early.

Related: ClickHouse#131268

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ⚠️ LIMIT 18446744073709551615 OFFSET 1 has no representable bound, yet canStopReadingEarly treats it as stopping early and keeps the in-order read (optimizeReadInOrder.cpp:1704) DISAGREE The plan kept is master's plan, so such a query is never slower than before. Any representable LIMIT above the number of distinct rows (LIMIT 1000000000) also reads to the end and cannot be told apart at planning time, so a getLimitWithOffset check would only cover the overflow value of the same case. No code added.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261114-053601

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test's EXPLAIN PIPELINE checks print 1 0 instead of 0 1 on master for the three cases without LIMIT (every run); the issue query is 2.83 s on master and 1.99 s with the change (max_threads = 8, 80 parts, medians of 10).
b Root cause explained? buildInputOrderInfo(DistinctStep &) requested reading in order from the FINAL read, and requestReadingInOrder turns vertical FINAL off, so every row went through the ReplacingSorted merge to feed a preliminary DISTINCT that gains little from the order.
c Fix matches root cause? Yes. The request is declined at that one place when the read would use vertical FINAL, unless a LIMIT lets the DISTINCT stop reading early (then the in-order plan is faster and is kept). No tag, no threshold.
d Test intent preserved / new tests added? New stateless test with 8 plan checks (2 controls: enable_vertical_final = 0, ORDER BY), new performance test; 170 existing tests with FINAL and DISTINCT pass unchanged.
e Both directions demonstrated? Master fails cases 1, 3, 8; the change passes; the change without the LIMIT exception fails cases 5-7, and with only the DISTINCT's own LIMIT it fails cases 6-7. 50/50 randomized runs pass.
f Fix is general across code paths? Direct reads and reads through a join take the same branch; ORDER BY or aggregation in order above already turned vertical FINAL off (pipeline unchanged); both optimizer passes that call optimizeDistinctInOrder pass the live traversal stack.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured with Nullable and non-Nullable keys, 80 and 10 parts, LIMIT 1/10/45, LIMIT above a subquery, ARRAY JOIN and a join, exact_rows_before_limit, with and without a filter. Only ReplacingMergeTree uses vertical FINAL.
h Backward compatible? (maintainer-approved exception only) Plan choice only, results identical, no default changed; enable_vertical_final = 0 or optimize_distinct_in_order = 0 give the old plans.
i Invariants and contracts preserved? The DISTINCT result does not depend on its input order; on the declined path applyOrder is not called, as on the function's other early returns. The new helper only reads the plan.

Session id: cron:clickhouse-impl-slot-40:20261114-041300

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6a79580]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, targeted) FAIL
05401_aggregation_nullable_fixed_keys_batch_pack FAIL cidb IGNORED

AI Review

Summary

Preserves vertical FINAL for full-read DISTINCT queries while retaining ordered reads when a limit can stop execution early. The previous early-stop finding is fixed. Reviewed the current diff and prior discussion; the focused test passed all 12 plan checks, and eight additional checks covered range limits, aggregation, swapped join inputs, and equivalent results with vertical and horizontal FINAL. The reported before/after measurements support the performance improvement. No unresolved findings at 6a79580efb3848f4e45327df87ef134678a48df6.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements 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... labels Nov 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6a79580ef with master d011c6b84 (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

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

Job report

…MIT AFTER

`canStopReadingEarly` accepted only a closed list of streaming steps between
the preliminary `DISTINCT` and a `LIMIT`, so an outer `LIMIT` above a hash
join's probe input or a window, and `LIMIT n AFTER`, lost the in-order read
and waited for vertical `FINAL` instead: about 10x slower than master
(80 parts x 50,000 rows, `max_threads = 8`: join 0.085 -> 0.909 s, window
0.080 -> 0.915 s, `LIMIT AFTER` 0.082 -> 0.897 s).

The walk now ends with "cannot stop early" only at a step that reads its input
till the end: a sort, an aggregation, building a set, the build input of a
join that fills its right side first, or a `LIMIT` that reads till the end.
Any other step continues, so a step that is not listed keeps master's plan
rather than the slower vertical one. Which input a join builds its table from
is known only after the logical join is converted, so a `JoinStepLogical`
defers the decision to the second `optimizeDistinctInOrder` pass, which sees
the `JoinStep`. `LimitRangeStep` stops reading outside `ALL` mode when it has
a limit or `UNTIL`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bad2536

Every failure below has an owner: a fixing PR (mine 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
Performance Comparison (arm_release, master_head, iceberg_local, 1/3) perf harness, not this PR's code: this PR adds a performance test, so the Iceberg jobs run only that test, none of its queries ran on both servers there, and compare.sh stops with INCORRECT_RESULT_OF_SCALAR_SUBQUERY before writing report/all-query-metrics.tsv (Errors while building the report.) #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 2/3) same harness failure as the row above #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 3/3) same harness failure as the row above #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 1/3) same harness failure as the row above #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 2/3) same harness failure as the row above #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 3/3) same harness failure as the row above #129874 (mine, open)
PR praktika rollup of the rows above #129874 (the owner above)

Session id: cron:our-pr-ci-monitor:20261114-150101

@fm4v

fm4v commented Nov 16, 2026

Copy link
Copy Markdown
Member

@groeneai merge master and resolve conflicts

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master in c5c3ddd. The only conflict was LimitRangeStep.h, where master added [[nodiscard]] to the getters; the new canStopReadingEarly got it too. The new test passes, also 50 times with random settings.

While re-checking I measured one more case this PR makes slower: SELECT DISTINCT c1 FROM t FINAL over a single merged part with a Nullable key (50 distinct values, vertical FINAL still runs there) goes from 0.34 s to 0.48 s (the PR's CI release build, enable_vertical_final = 0 as master's plan, max_threads = 8, medians of 15). Over 80 parts the same query is 7% faster, and a merged part with a non-Nullable key is 2-4.5x faster. It is the same trade-off as the accepted Nullable-key row in the description, so I left it as is.

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 16, 2026

@clickhouse-gh clickhouse-gh Bot left a comment

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.

AI review approves this commit, see the AI Review comment.

… runs

The test reads `ReplacingMergeTree` tables with `FINAL`, which the Iceberg
rewrite of the performance comparison cannot run (`Storage IcebergLocal
doesn't support FINAL`). Adding it scheduled the six Iceberg jobs on this
test only, and they failed with no query measured on both servers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 16, 2026 16:41

AI review of a later commit does not approve the PR, see the AI Review comment.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6a79580

Every failure below has an owner: a fixing PR (mine 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 (arm_asan_ubsan, azure, targeted) / 05401_aggregation_nullable_fixed_keys_batch_pack not from this PR: only the plain SELECT DISTINCT a, nb case (optimize_distinct_in_order = 0) differs, 17013 rows instead of 17146, while the in-order cases this PR changes are correct. The byte-identical wrong result hit 1 other PR in the same job today (report) a fix task is created (investigating at full effort, fixing-PR link to follow here)
PR praktika rollup of the row above a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20261116-180018

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05401_aggregation_nullable_fixed_keys_batch_pack (Stateless tests (arm_asan_ubsan, azure, targeted)) created: #132147

@fm4v
fm4v added this pull request to the merge queue Nov 17, 2026
Merged via the queue into ClickHouse:master with commit 571f1d8 Nov 17, 2026
190 of 192 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 18, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 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... pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

query_plan_read_in_order_through_join=1: FINAL + INNER JOIN + DISTINCT runs the hash-join probe in a single stream (1.6x slower)

4 participants