Skip to content

Disable split_intersecting_parts_ranges_into_layers_final for queries with FINAL that read in the order of the primary key - #110431

Merged
KochetovNicolai merged 10 commits into
masterfrom
final-skip-layers-split-in-order-limit
Jul 28, 2026
Merged

KochetovNicolai merged 10 commits into
masterfrom
final-skip-layers-split-in-order-limit

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Queries with FINAL that read in the order of the primary key (ORDER BY a prefix of the sorting key) with a small LIMIT no longer use split_intersecting_parts_ranges_into_layers_final.

The split delayed the first block (the downstream merge had to wait for every layer) and did speculative parallel reading and merging that was discarded once the limit was reached; such queries are now up to 3x faster. Layer splitting is unchanged for full ordered scans, large limits, and aggregation in order.

image

Version info

  • Merged into: 26.8.1.267 (included in 26.8 and later)

KochetovNicolai and others added 2 commits July 14, 2026 17:01
…rder and a small limit

Under read-in-order all layer streams are consumed by a single downstream
merging transform, which cannot emit anything until every layer produces its
first block. With a small query limit the result is expected to come from the
first layer only, so splitting only adds speculative work that is thrown away
once the limit is reached, delays the first block, and pays the planning-time
primary key index sweep. Keep a single lazy merging stream instead when the
pushed-down limit is smaller than the expected rows per layer.

Layers are still used for read-in-order without a limit (full ordered scans)
and for aggregation/distinct in order, where the whole ordered stream is
consumed and the parallel FINAL merging pays off.

Co-Authored-By: Claude Fable 5 <[email protected]>
Local perf.py comparison against the parent commit (48-core ARM machine,
release build, 32 intersecting parts, 32M rows):
- FINAL ORDER BY k LIMIT 100: -65% (0.293s -> 0.102s)
- FINAL WHERE v = 7 ORDER BY k LIMIT 100 (selective filter): -45% (0.299s -> 0.163s)
- control FINAL ORDER BY k LIMIT 4000000 (keeps layers): +0.76%, within threshold

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b38978b]

Summary: ✅


AI Review

Summary

This PR skips split_intersecting_parts_ranges_into_layers_final for FINAL read-in-order queries when a small hard LIMIT is expected to fit into one layer. The current revision fixes the earlier WHERE/unmerged-duplicates cases, but it still treats some non-AST filters as if the limit were hard and still relies on a whole-range average that is not a lower bound for the earliest FINAL layer, so I would keep this at request changes.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:1979] input_order_info->limit still is not a proof that the limit is hard when additional_table_filters are active. InterpreterSelectQuery derives the read-in-order limit from query.hasFiltration(), but settings-driven filters are parsed separately into query_info.additional_filter_ast and applied later as an Additional filter step above the source. A selective FINAL ... ORDER BY pk LIMIT N SETTINGS additional_table_filters = {...} query can therefore disable layering even though it still has to scan far past the first layer to find N visible rows, serializing the exact workload the old path parallelized.
    Suggested fix: zero the shortcut when query_info.additional_filter_ast is present, or more generally gate it on the absence of post-read filters, and add a focused regression test.

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:1979] input_order_info->limit also remains non-zero when apply_row_policy_after_final = 1 defers a non-sorting-key row policy (and possibly PREWHERE) after FINAL, because the limit is computed before deferFiltersAfterFinalIfNeeded rewrites the plan. That means a selective row policy can still turn layers off and make FINAL ORDER BY pk LIMIT N scan most of the table sequentially to find N visible rows.
    Suggested fix: zero the shortcut whenever deferred_row_level_filter or deferred_prewhere_info is present, and add a regression test with a deferred row policy plus a small LIMIT.

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:2004] [dismissed by author -- https://github.com/Disable split_intersecting_parts_ranges_into_layers_final for queries with FINAL that read in the order of the primary key #110431#discussion_r3604758804] rows_per_layer is a whole-range average over merged-part source rows, not a lower bound on the earliest layer's FINAL output. If duplicate-heavy unmerged updates are clustered at the beginning of the keyspace and the merged base part sits later, the first layer can emit far fewer than hard_limit rows even though merged_parts_rows / max_layers / new_parts.size() is large, so this shortcut serializes a workload that still benefits from parallel layers. I still consider this real because the current code never looks at the earliest PK span it is using as the predictor.
    Suggested fix: derive the bound from the actual first layer / earliest PK span, or keep layers for mixed merged+unmerged layouts.

Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 14, 2026
KochetovNicolai and others added 2 commits July 15, 2026 10:02
…er_limit_no_layers

The flaky check randomizes optimize_read_in_order; with 0 the read-in-order
optimization does not apply, the gate does not fire, and the small-limit query
splits into layers again, changing the first line of the test output.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110431&sha=59ee8d7ea1762e7a885bf00ec023a459123474c4&name_0=PR
PR: #110431

Co-Authored-By: Claude Fable 5 <[email protected]>
The query limit counts rows after the FINAL collapse, while the gate compared
it against source rows per layer. On heavily duplicated data (e.g. 3 fully
duplicated parts) a layer of 75000 source rows emits only 25000 rows, so a
limit of 50000 was misclassified as fitting into one layer and lost the
parallel FINAL merge. Every key appears at most once per part, so divide by
the number of parts to get a lower bound of the layer output and keep layers
unless the limit fits into one layer even under the worst-case duplication.

Addresses a review comment in #110431

Co-Authored-By: Claude Fable 5 <[email protected]>
@KochetovNicolai KochetovNicolai changed the title Small tuning for FINAL Disable split_intersecting_parts_ranges_into_layers_final for queries with FINAL that read in the order of the primary key Jul 16, 2026
An unmerged part may contain arbitrarily many versions of the same key
(e.g. inserted with optimize_on_insert = 0), so dividing source rows by the
number of parts is not a valid lower bound of a layer's post-FINAL output.
A part of non-zero level went through the merging algorithm (a background
merge or collapsing on insert - optimize_on_insert marks such parts with
level 1), so it contains a key at most once, or at most twice for
Collapsing engines. Count only rows of such parts in the bound; a group of
only unmerged parts never disables layering.

The stateless test now uses a merged base part with unmerged updates on
top, adds a regression case with duplicates inside unmerged parts, and the
performance test data is restructured the same way so the gate still fires
there.

Addresses a review comment.

Co-Authored-By: Claude Fable 5 <[email protected]>
query_task_size_limit carries the original query limit even when there is
filtering between the limit and the reading step. With a filter the query
consumes limit / selectivity rows, which is unknown at planning time: for
a rare-value filter the single merging stream processes most of the table
sequentially. Measured on a 48-core machine with a 16M-row table: a
1e-5-selectivity filter regressed from 0.08s to 0.75s, about 10x. Use
query_info.input_order_info->limit instead, which is non-zero only when
nothing filters the stream, so the skip applies only when the number of
rows to read is bounded by the limit itself. The unfiltered case keeps its
improvement (0.075s -> 0.025s on the same table). For filtered queries
with known-good selectivity the setting
split_intersecting_parts_ranges_into_layers_final = 0 remains available.

The stateless test uses filter-free queries for the gate cases and asserts
that a filtered small-limit query keeps layers; the performance test keeps
the filtered variants (including a rare-value filter) as controls.

Addresses a review comment.

Co-Authored-By: Claude Fable 5 <[email protected]>
: 1;

const size_t rows_per_layer = std::max<size_t>(
merged_parts_rows / max_layers / new_parts.size() / max_collapsed_rows_per_key_in_merged_part, 1);

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.

rows_per_layer is not a lower bound once FINAL can drop rows from an already merged part. merged_parts_rows still counts tombstones in ReplacingMergeTree(version, is_deleted) and negative-sign rows in CollapsingMergeTree, but FINAL removes those rows (readNonIntersectingWithEngineFilter already has to do that for the non-merge path, and 02490_replacing_merge_tree_is_deleted_column.sql covers the tombstone case with clean_deleted_rows = 'Never'). In a tombstone-/cancel-heavy merged part this expression can say the first layer has > LIMIT rows even though it emits few or zero rows, so the branch disables layering and serializes a query that still needs several layers. Can we either exclude engine modes with row-dropping semantics from this shortcut, or derive the bound from rows guaranteed to survive FINAL and add a regression test?

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.

Considered, and decided to accept the approximation rather than exclude these engines: delete tombstones and cancelling rows are normally a small fraction of the data, and requiring a strict survivor bound would turn the optimization off entirely for ReplacingMergeTree with is_deleted and for Collapsing engines — penalizing the common case to protect a pathological one (a merged part that is mostly tombstones). The approximation is now documented in the code, and the test covers these engines with a realistic tombstone fraction. If tombstone-heavy workloads turn out to matter in practice, a follow-up could respect an explicitly set split_intersecting_parts_ranges_into_layers_final = 1 as "always split".

…plit gate

FINAL may still drop some rows of merged parts: is_deleted tombstones kept
until cleanup, Collapsing rows cancelling across parts, rows masked by
lightweight deletes. A strict lower bound would exclude these engines from
the optimization entirely, while in practice such rows are usually a small
fraction of the data, so the estimate deliberately counts them and the
gate stays enabled for these engines. Documented in the code and covered
by test cases with a small fraction of tombstones and cancelling rows.

Addresses a review comment (deciding to accept the approximation).

Co-Authored-By: Claude Fable 5 <[email protected]>
: 1;

const size_t rows_per_layer = std::max<size_t>(
merged_parts_rows / max_layers / new_parts.size() / max_collapsed_rows_per_key_in_merged_part, 1);

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.

rows_per_layer is treated here as a lower bound on what the first FINAL layer can emit, but the layer splitter does not guarantee that. In PartsSplitter.cpp, splitIntersectingPartsRangesIntoLayers chooses borders from global source-row counts (getRowsCountAllParts / getMarkRows) across all selected parts, not from post-FINAL survivor rows in the earliest key range. With read_in_order we also skip the intersecting/non-intersecting split, so a mixed layout can still hit this path.

A concrete counterexample is a merged base part whose keys live later in PK order plus two optimize_on_insert = 0 update parts at the beginning of the keyspace. The first layer can then consist almost entirely of duplicate-heavy unmerged rows and emit only a handful of FINAL rows, while merged_parts_rows / max_layers / new_parts.size() is still large because it averages merged rows across the whole query range. In that case LIMIT N disables layering even though the query still needs later layers, turning a case that used to parallelize into the sequential merge path.

Can we either derive a bound from the actual earliest layer, or keep the layered path and add a regression test with skewed key ranges (duplicate-heavy unmerged prefix, merged rows later in PK order)?

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.

It is becoming too complicated for a small perf improvement PR.
Yes, we cannot predict how many unmerged rows in the part, but let's expect there are not many for now. Probably, we can improve it later when we see a use case.

@KochetovNicolai
KochetovNicolai marked this pull request as ready for review July 17, 2026 17:15
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR narrows the FINAL read-in-order pipeline to skip splitting intersecting ranges into layers when a small hard LIMIT is expected to be served by the first layer alone; the change is confined to that FINAL-with-limit path in the MergeTree reader. The only flagged row, ClickBench Q15 (+14.0%, 215->245ms), does not use FINAL and cannot be touched by this code, and the delta falls squarely within master's current variance band [191,275ms] — the deterministic within-envelope suppression is correct and it is left as not_sure. No query that actually exercises the changed path was flagged, so there is no evidence of a regression here.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 215 245 +13.9% <0.0001 This PR only changes the FINAL read-in-order-with-limit planning path; ClickBench Q15 uses no FINAL, so the +14.0% sits inside master's current variance band [191,275ms] as expected.

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.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 54dffac7-020c-41c7-bd26-4ac1ad087b2d
  • MIRAI run: 04a8aacc-9442-43a2-9514-cf0b80548cd1
  • PR check IDs:
    • clickbench_567059_1785179737
    • clickbench_567076_1785179737
    • tpch_adapted_1_official_567084_1785179737
    • tpch_adapted_1_official_567096_1785179737
    • tpch_adapted_1_official_567402_1785179740

@yakov-olkhovskiy yakov-olkhovskiy self-assigned this Jul 20, 2026
/// With a filter the query consumes limit / selectivity rows, and the selectivity is unknown here:
/// for a rare-value filter the single merging stream would process most of the table sequentially,
/// many times slower than the parallel layered merge.
const UInt64 hard_limit = query_info.input_order_info ? query_info.input_order_info->limit : 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.

input_order_info->limit is not sufficient proof that the read limit is hard. In InterpreterSelectQuery we set it from query.hasFiltration() before ReadFromMergeTree::deferFiltersAfterFinalIfNeeded moves row policies behind FINAL, so a query like SELECT ... FINAL ORDER BY pk LIMIT 10 under the default apply_row_policy_after_final = 1 still reaches this branch with hard_limit = 10 even when the row policy filters on a non-sorting-key column. In that case the row policy can discard almost every row after FINAL, but this shortcut disables layering anyway and recreates the selective-filter regression the previous revision just fixed: the single lazy merge can end up scanning most of the table to find 10 visible rows. Can we zero the shortcut whenever deferred_row_level_filter / deferred_prewhere_info is present (or otherwise derive the limit after deferral), and add a regression test with a deferred row policy plus a small LIMIT?

@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Jul 27, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jul 27, 2026
@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Jul 27, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jul 27, 2026
@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Jul 27, 2026
@KochetovNicolai
KochetovNicolai removed this pull request from the merge queue due to a manual request Jul 27, 2026
/// With a filter the query consumes limit / selectivity rows, and the selectivity is unknown here:
/// for a rare-value filter the single merging stream would process most of the table sequentially,
/// many times slower than the parallel layered merge.
const UInt64 hard_limit = query_info.input_order_info ? query_info.input_order_info->limit : 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.

input_order_info->limit is still not a proof that the read limit is hard. InterpreterSelectQuery derives it from query.hasFiltration(), which ignores settings-driven filters such as additional_table_filters; those filters are parsed into query_info.additional_filter_ast and added later as an Additional filter step above the source. So SELECT ... FINAL ORDER BY pk LIMIT 10 SETTINGS additional_table_filters = {'t_final_layers':'rare_predicate'} still reaches this branch with hard_limit = 10 even though the filter may discard almost every row after FINAL.

In that case this shortcut disables layering and serializes exactly the selective-filter workload the old path parallelized. Can we zero the shortcut whenever query_info.additional_filter_ast is present (or otherwise gate it on "no post-read filters") and add a focused regression test?

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 82.30% 86.30% +4.00%
Functions 91.70% 92.00% +0.30%
Branches 74.40% 78.40% +4.00%

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

Full report · Diff report

@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Jul 28, 2026
Merged via the queue into master with commit c10bd01 Jul 28, 2026
352 of 353 checks passed
@KochetovNicolai
KochetovNicolai deleted the final-skip-layers-split-in-order-limit branch July 28, 2026 12:17
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 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