Repository navigation
Disable split_intersecting_parts_ranges_into_layers_final for queries with FINAL that read in the order of the primary key - #110431
Conversation
…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]>
|
Workflow [PR], commit [b38978b] Summary: ✅
AI ReviewSummaryThis PR skips Findings
Final VerdictStatus: |
…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]>
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); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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)?
There was a problem hiding this comment.
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.
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (1 of 43)
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
|
| /// 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; |
There was a problem hiding this comment.
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?
| /// 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; |
There was a problem hiding this comment.
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?
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 33/33 (100.00%) · Uncovered code |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Queries with
FINALthat read in the order of the primary key (ORDER BYa prefix of the sorting key) with a smallLIMITno longer usesplit_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.
Version info
26.8.1.267(included in26.8and later)