Repository navigation
Conversation
When a MergeTree table is read in primary key order with an OFFSET, the leading granules entirely consumed by the offset are read, merged and then dropped by the downstream offset step. This adds a query-plan optimization that, for forward read-in-order, drops the leading granules whose exact total row count does not exceed the offset (when each is strictly separated in primary key space from the remaining data) and reduces the downstream offset by the number of rows skipped. Gated by the new setting query_plan_optimize_read_in_order_skip_offset (default enabled). Applied only when it is safe: no FINAL, PREWHERE, lightweight deletes / row policies, sampling or parallel replicas, and a safe ascending primary key. Closes: ClickHouse#92671
0affc21 to
65ce224
Compare
Resolved a conflict in `QueryPlanOptimizationSettings.h` where master added `optimize_aggregation_in_order_limit` next to this branch's `read_in_order_skip_offset`; both members are kept. Moved the `query_plan_optimize_read_in_order_skip_offset` entry in `SettingsChangesHistory.cpp` from the `26.6` block to `26.7`, since master's development version moved on while this branch was open and `02995_new_settings_history.sh` only accepts versions after `26.6`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [59c936b] Summary: ✅
AI ReviewSummaryThe PR skips leading granules consumed by Final VerdictStatus: ✅ Approve |
Address two correctness gaps in the read-in-order OFFSET granule-skip optimization: - `ReadFromMergeTree::skipRowsForOffset` used physical granule row counts even when the reader removes rows after reading (lightweight-delete masks, on-the-fly `DELETE` mutations, patch-part deletes). At a granule boundary this could skip more visible rows than the `OFFSET` consumes. Bail out when any such reader-side delete filtering may apply. - `skipLeadingGranulesForOffset` proved the cut point on the full primary key, but read-in-order can merge on only a prefix of the sorting key (`used_prefix_of_sorting_key_size`), e.g. `ORDER BY a` on a table sorted by `(a, b)`. Granules strictly separated on the full key can still be tied in the merge order, so the separation test now compares exactly that prefix. Add stateless regression tests for both cases. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…offset-read-in-order
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds query_plan_optimize_read_in_order_skip_offset. When a MergeTree table is read in primary-key order with an OFFSET, it skips leading granules. It only runs when an OFFSET or LIMIT ... OFFSET sits above a forward read-in-order scan. None of the flagged queries match that shape: ClickBench Q33/Q34 group and sort by a computed count with no OFFSET, and TPC-H Q1/Q7 are aggregation and join queries with no OFFSET. All four improvements (-12.4%, -13.1%, -16.9%, -22.2%) are downgraded to not sure because every PR median sits inside master's recent range and history is noisy. The PR's actual benefit only shows up in its own perf test (read_in_order_skip_offset.xml). clickbenchFlagged queries (2 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_officialFlagged queries (2 of 22)
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
|
…_before_limit and arrayJoin Address two more correctness gaps in optimizeSkipOffsetForReadInOrder: - A LimitStep with always_read_till_end (exact_rows_before_limit) reads its source to completion so LimitTransform can report an accurate rows_before_limit_at_least. Granules skipped by the offset optimization never reach LimitTransform, so the count underreported by exactly the skipped rows. Bail out when always_read_till_end() is set, matching the guard already used in limitPushDown.cpp and optimizeTopK.cpp. - An ExpressionStep in the walk between the Limit/Offset and the read may contain an arrayJoin, which expands rows after they leave the read step. OFFSET then counts post-expansion rows, but the optimization was trimming source granules by pre-expansion row counts. Bail out when the expression's actions have an arrayJoin. Add stateless regression tests for both cases. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Addresses reviewer feedback on PR ClickHouse#106578: the previous cloud perf report only exercised queries without OFFSET, so it did not validate the optimization added by this PR. This test compares query_plan_optimize_read_in_order_skip_offset = 0 vs 1 for an in-order ORDER BY ... LIMIT ... OFFSET query on a large table. Locally on a 50M row table, skipping to OFFSET 45000000 dropped from ~0.6s to ~0.007s (about 80x) with the setting enabled. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…offset-read-in-order
An inner `LIMIT` cuts the prefix that an outer `OFFSET` sees, so dropping
leading granules below it can promote rows the inner limit would have
discarded. For a table with `index_granularity = 1` holding `0..9`,
SELECT k FROM (SELECT k FROM t ORDER BY k LIMIT 2) ORDER BY k LIMIT 2 OFFSET 1
returned `1, 2` instead of `1`: the walk reached the outer `OFFSET`, skipped
the first source row and left the inner `LIMIT 2` untouched.
`optimizeSkipOffsetForReadInOrder` now tracks the tightest `LimitStep` it
walks past and only applies the skip when that limit still covers
`offset + limit` of the target `LimitStep`. A pure `OffsetStep` keeps every
row after it, so no finite intermediate limit can cover it and the walk
bails out.
`master` is now 26.8, so `query_plan_optimize_read_in_order_skip_offset` sat in an already-released section and the Upgrade check reported it as missing from the settings changes history.
…icas `04613_read_in_order_skip_offset_prefix` compares the optimized plan's output against the unoptimized one. With the randomizer picking `optimize_read_in_order = 0` there is no read-in-order at all, so both sides fall back to a full sort whose ordering among rows tied on `a` is arbitrary and the comparison is no longer meaningful. Pin `optimize_read_in_order = 1` so the test exercises what it claims to. `04628_read_in_order_skip_offset_exact_rows_before_limit` reports `rows_before_limit_at_least` as 0 under parallel replicas regardless of this optimization, so tag it `no-parallel-replicas` as `01913_exact_rows_before_limit_full` already does.
A stateful function derives a row's result from the rows preceding it in its stream, so trimming leading granules changes what the surviving rows see. `rowNumberInAllBlocks` renumbers from the first row that survives the trimmed read, and `neighbor` and `runningDifference` also react to the changed block boundaries, since the reader no longer feeds the offset step the rows it drops. That makes the effect visible even when the stateful expression sits *above* the offset, which is where the final projection of an ordinary `ORDER BY ... LIMIT ... OFFSET` query ends up, so it is not enough to check only the `ExpressionStep`s the walk passes on its way to the offset. Bail out on a stateful function anywhere on the path from the reading step to the query root. Before this, `SELECT k, neighbor(k, -1) FROM t ORDER BY k LIMIT 2 OFFSET 3` on a table with `index_granularity = 1` returned `(4, 0)` instead of `(4, 3)` for its second row. Co-Authored-By: Claude Opus 5 <[email protected]>
…offset-read-in-order
`skipLeadingGranulesForOffset` proves the cut point on the raw key values from the primary index, but `optimizeReadInOrder` also keeps an in-order read for a monotonic transformation of the key, e.g. `ORDER BY toDate(ts)` on a table sorted by `ts`. Two granules can be strictly separated on `ts` and still be tied in `sort_description_for_merging`, so dropping the first one changes which tied rows survive the `OFFSET`. Require `sort_description_for_merging` to be exactly the leading `used_prefix_of_sorting_key_size` sorting-key columns, ascending and name-for-name. This also rejects the shapes where the merge description is not aligned with the key prefix - a key column fixed by `WHERE`, or an `ORDER BY` column that is not a key column - in which the separation test would have compared the wrong columns.
…offset-read-in-order
…offset-read-in-order
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 99/226 (43.81%) · Uncovered code |
…offset-read-in-order
`skipRowsForOffset` compared `input_order_info->sort_description_for_merging` against `used_prefix_of_sorting_key_size`, but `requestReadingInOrder` always builds the `InputOrderInfo` with an empty `SortDescription` - the merge order lives on the `SortingStep` above the read, not on the reading step. The guard could therefore never pass and the optimization never skipped a granule. Take the order the offset counts rows in from that `SortingStep` and pass it down. The analyzer qualifies column names in plan headers (`k` -> `__table1.k`), so resolve each sort column back through the `Expression` steps between the sorting and the read, following only alias chains down to an input. A monotonic transformation of the key (`ORDER BY toDate(ts)` on a table sorted by `ts`) resolves to a function rather than a read column and is still rejected, which is what the guard was aiming for. Also bail out when a second `SortingStep` is walked past: it re-orders the rows the offset sees, so the leading granules of the read are no longer the ones it consumes. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…fset-read-in-order Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es-on-offset-read-in-order # Conflicts: # src/Processors/QueryPlan/Optimizations/Optimizations.h # src/Processors/QueryPlan/ReadFromMergeTree.h
…offset-read-in-order
Master added the same accessor, so the merge declared it twice and the build failed: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106578&sha=9264e269a8ddce2f69a48c3ba45c14315d029d11&name_0=PR&name_1=Fast%20test
…offset-read-in-order
… read for trimmed ranges The OFFSET-skip read-in-order optimization only bailed out on functions that are not deterministic within the query, so it changed how many rows a stateful function (`aiEmbed`) or one with observable side effects (`sleepEachRow`) was evaluated on. Use `isSensitiveToEvaluationCount` instead. Automatic parallel replicas hands every read of the candidate plan the analysis of the same read in the single-replica plan, so reject the candidate when any read has ranges trimmed for the offset, not only the read instrumented for the statistics. The check now runs before the candidate plan is built.
…walk for trimmed reads Above the offset, a function sees the same rows whether the leading granules are skipped or not, so only the expressions below it need `isSensitiveToEvaluationCount`; the path to the root keeps checking for functions that depend on the rows before them or on the blocks. Detect trimmed reads in the plan walk that `considerEnablingParallelReplicas` already makes, and keep `sleepEachRow` below the sorting in the test.
Above the offset, skipping the leading granules still changes the chunks a function sees, which a per-block limit such as `function_sleep_max_microseconds_per_block` observes, so `isSensitiveToEvaluationCount` stays on the whole path.
…offset-read-in-order # Conflicts: # src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp
…offset-read-in-order # Conflicts: # src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp
… the settings history The setting is not in any release yet, and the current version is now 26.11.
`UNIQUE KEY` reads drop overwritten rows through a delete bitmap attached per read task, independently of the mutations snapshot, and `DeleteBitmapSnapshot::dropFullyDeadGranules` only removes wholly dead granules. A partially dead granule therefore overstated the rows the offset consumes, and the query returned rows that should have been skipped. ClickHouse#106578 (review) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…offset-read-in-order
A `UNIQUE KEY` INSERT writes the dense-index SST, which needs RocksDB, and the Fast test build has none (`SUPPORT_IS_DISABLED`).
`modernize-use-nodiscard` is enabled on master now.
…ends on the rows The reader computes the default of a column a part does not have (e.g. one added by `ALTER ADD COLUMN` after the part was written) on the blocks it reads, so it is in no `ExpressionStep` or `FilterStep` above the read, and a default like `rowNumberInBlock()` gave other values with the skipped granules. The defaults of the read columns are now checked like the steps above the read.
Without `exact_rows_before_limit`, LimitTransform counts the rows reaching it, and the rows the read skipped never did, so `LIMIT 3 OFFSET 40` over 100 rows reported 4 instead of a lower bound of at least 43. The optimization now records the skipped rows in `LimitStep`, and `LimitTransform` adds them to the counter.
…efault Resolving the defaults of the read columns while planning could throw for queries that worked (e.g. an experimental function in a default, which the reader allows), ran for every read in order, and did not follow defaults of other columns that a default reads. Instead, `skipRowsForOffset` now gives up when a selected part does not have a read column with a default: only then does the reader evaluate it.
…offset-read-in-order # Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.h
…default A pending `DROP COLUMN` or `CLEAR COLUMN` makes the reader ignore the values a part still has and compute the column's default on the blocks it reads, so a default like `rowNumberInBlock()` gave other values for the trimmed ranges. The earlier check only looked at whether the part has the column. Give up when the mutations snapshot has metadata or alter mutations and a read column has a default. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each skipped granule scanned the cursors of all parts twice, so with many parts and small granules the skipping took longer than reading the rows (1.49 s instead of 0.19 s with 1011 parts of `index_granularity = 64`). A min-heap of the active cursors by front value makes a step O(log parts); the same query takes 0.037 s now. Add a performance test with many parts. Also record the setting in the history of 26.12, the current version, so that `compatibility = '26.11'` disables it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
After the leading granules are skipped, an inner `LIMIT` or the limit of the `Sorting` below the `OFFSET` no longer sees the skipped rows, so it passed rows of the tail it would not have passed. The result was the same, but `rows_before_limit_at_least` added the skipped rows on top and could report more rows than the inner `LIMIT` can produce (21 for an inner `LIMIT 20`). Reduce those limits by the skipped rows, and take the limit of a `Sorting` into account in the check that an intermediate limit covers the `OFFSET`. Also use `VectorWithMemoryTracking` instead of `std::vector`, as the style check requires in `src/Processors/QueryPlan`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nules Use `std::priority_queue` as elsewhere in the file, drop the `active` flag of a cursor (`advance` returns whether the part has granules left), build the upper bound of a granule once and move it into the next front value, and push the current cursor back only when another part has a smaller front value. The query with 1011 parts in the performance test takes 0.009 s instead of 0.037 s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report
PR verdict: not_sure. 2 measured difference(s) not attributable to this PR. clickbench Q33: The measured difference cannot be attributed to this PR from the available source evidence. The PR adds optimizeSkipOffsetForReadInOrder (optimizeTree.cpp second pass), ReadFromMergeTree::skipRowsForOffset and skipLeadingGranulesForOffset in PartsSplitter.cpp. All of them need a forward read-in-order ReadFromMergeTree with an OFFSET above it. This query reads hits without input order through a hash aggregation and a LIMIT with offset 0, so the pass returns at the first check. The LimitTransform change only adds a one-time counter add at setup. The cause of the shift (an inherited master … clickbench Q34: The measured difference cannot be attributed to this PR from the available source evidence. Same plan shape as Q33: a hash aggregation on URL, then Sorting, then a LIMIT with offset 0, over a ReadFromMergeTree without input order. optimizeSkipOffsetForReadInOrder returns early, and skipRowsForOffset / skipLeadingGranulesForOffset are never called. The cause of the shift was not checked against the baseline hashes. clickbenchFlagged queries (4 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
|
Closes: #92671
When a
MergeTreetable is read in primary key order with anOFFSET, the leading granules entirely consumed by the offset are still read, merged and then dropped by the downstream offset step. This adds a query-plan optimization that drops those leading granules during reading and reduces the downstream offset accordingly. It is gated by the new settingquery_plan_optimize_read_in_order_skip_offset(enabled by default) and only applies when it is safe to do so (forward read-in-order, noFINAL/PREWHERE/lightweight deletes/row policies/sampling/parallel replicas, and a safe ascending primary key).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
When reading a
MergeTreetable in primary key order with anOFFSET, skip reading the leading granules entirely consumed by the offset.Workflow [PR]
Sync PR [sync-upstream/pr/106578]