Skip to content

Skip granules consumed by OFFSET when reading in order - #106578

Open
raimannma wants to merge 73 commits into
ClickHouse:masterfrom
raimannma:skip-granules-on-offset-read-in-order
Open

raimannma wants to merge 73 commits into
ClickHouse:masterfrom
raimannma:skip-granules-on-offset-read-in-order

Conversation

@raimannma

@raimannma raimannma commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #92671

When a MergeTree table is read in primary key order with an OFFSET, 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 setting query_plan_optimize_read_in_order_skip_offset (enabled by default) and only applies when it is safe to do so (forward read-in-order, no FINAL/PREWHERE/lightweight deletes/row policies/sampling/parallel replicas, and a safe ascending primary key).

Changelog category (leave one):

  • Performance Improvement

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

When reading a MergeTree table in primary key order with an OFFSET, skip reading the leading granules entirely consumed by the offset.


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

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
@raimannma
raimannma force-pushed the skip-granules-on-offset-read-in-order branch from 0affc21 to 65ce224 Compare June 5, 2026 17:04
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]>
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [59c936b]

Summary: ✅


AI Review

Summary

The PR skips leading granules consumed by OFFSET during forward ordered MergeTree reads, adjusts downstream limits and offsets, and preserves rows_before_limit_at_least. No remaining actionable findings were identified at 59c936bc2515f23e6a33d83d3fa02fda9753e404; the prior findings are addressed in the current code. Seven SQL regression tests matched their references, the missing-default and pending-mutation regressions passed, and 300 additional result comparisons matched. A local 50-million-row benchmark with OFFSET 45000000 returned identical results while reducing median elapsed time from 0.745 s to 0.00293 s.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 24, 2026
raimannma and others added 2 commits July 24, 2026 13:09
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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).

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1153 1010 -12.4% <0.0001 aggregation: This GROUP BY ... ORDER BY count query has no OFFSET and no read-in-order, so the new OFFSET-skip path never runs. The -12.4% median and CPU drop sit inside master's recent range.
⚠️ 34 not_sure 1148 998 -13.1% <0.0001 aggregation: This query aggregates and sorts by a computed count with no OFFSET, so the granule-skip optimization cannot apply. The -13.1% median is inside master's recent range and history is noisy.

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

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 54 -16.9% <0.0001 aggregation: TPC-H Q1 is a scan plus aggregation with no OFFSET, so the changed code path is not reached. The -16.9% (11 ms) shift is inside master's recent range on a noisy, fast query.
⚠️ 7 not_sure 81 63 -22.2% <0.0001 join_operator: TPC-H Q7 is a multi-join aggregation with no OFFSET, so the OFFSET-skip optimization never triggers. The -22.2% (18 ms) shift stays inside master's recent range.

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: 3b8cfc8f-3a1f-4cde-b6d7-cf9f3db04f3e
  • MIRAI run: ef6e321f-03ca-418b-9359-5407b9f2d2cf
  • PR check IDs:
    • clickbench_1162041_1791853684
    • clickbench_1162047_1791853684
    • clickbench_1162053_1791853684
    • tpch_adapted_1_official_1162064_1791853684
    • tpch_adapted_1_official_1162077_1791853684
    • tpch_adapted_1_official_1162640_1791853968

…_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]>
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]>
`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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 99/226 (43.81%) · Uncovered code

Full report · Diff report

raimannma and others added 2 commits August 4, 2026 16:25
`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]>
alexey-milovidov and others added 5 commits September 26, 2026 23:21
…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]>
…es-on-offset-read-in-order

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/Optimizations.h
#	src/Processors/QueryPlan/ReadFromMergeTree.h
… 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]>
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
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.
raimannma and others added 8 commits November 16, 2026 22:26
…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]>
@stresshouse

stresshouse Bot commented Nov 22, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — inconclusive across 29 queries analysed

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.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1007 1103 +9.5% <0.0001 aggregation: Q28 is a regex GROUP BY with no OFFSET or read-in-order, so the new OFFSET-skip step never fires. The +9.5% verdict is borderline because the two tests disagree.
⚠️ 32 not_sure 586 683 +16.6% <0.0001 aggregation: Q32 groups by (WatchID, ClientIP) with no OFFSET and no read-in-order, so the OFFSET-skip optimization does not apply. The +16.6% sits inside master's normal range for this query.
⚠️ 33 not_sure 828 940 +13.5% <0.0001 aggregation: 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 …
⚠️ 34 not_sure 844 946 +12.2% <0.0001 aggregation: 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.

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: f84750eb-cd11-4017-8b55-3b4e5549dc11
  • MIRAI run: 614d5656-a82d-4a91-a6ee-5f771087108c
  • PR check IDs:
    • clickbench_831896_1795372410
    • clickbench_831902_1795372411
    • tpch_adapted_1_official_831928_1795372411
    • tpch_adapted_1_official_831963_1795372411

This branch has not been deployed

No deployments
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... external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Skip granules based on the OFFSET for read in order

5 participants