Skip to content

Disable lazy FINAL under read-in-order and for early-exit LIMIT queries - #110576

Merged
KochetovNicolai merged 7 commits into
masterfrom
disable-lazy-final-read-in-order-limit
Jul 22, 2026
Merged

KochetovNicolai merged 7 commits into
masterfrom
disable-lazy-final-read-in-order-limit

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Jul 15, 2026 •

Copy link
Copy Markdown
Member
Claude

The lazy FINAL replacement plan (hash aggregation over the sorting key plus a lazy column fetch) does not produce rows in any particular order, while the steps above may already rely on the reading step producing rows in sorting key order after optimizeReadInOrder converted them - in an experiment the result of such a query stayed ordered only by accident of execution, with no sorting transform left in the pipeline. Disable the optimization when the reading step reads in order, both for correctness and because the set-building phase reads all filtered rows before either branch can return the first row, defeating early exit.

For the same reason, disable it when a LIMIT smaller than the number of selected rows applies directly to the reading step's output (only Expression/Filter steps in between): such queries stop reading as soon as enough rows pass the filter. A limit above a stream-consuming step (full sort, aggregation) does not disable the optimization.

Testing

  • New test 04539_lazy_final_read_in_order_limit_disabled checks the plan shape (InputSelector presence) for all six cases: filter-only (applies), read-in-order with and without limit (disabled), small bare limit (disabled), limit
    not smaller than the selected rows (applies), limit above a full sort (applies), plus result equality with the optimization on and off.
  • All existing lazy_final stateless tests pass unchanged.
  • New performance test lazy_final_early_exit_limit (2 intersecting parts, 16M rows, query_plan_optimize_lazy_final = 1). Local comparison against the parent commit on a 48-core ARM machine: FINAL WHERE v = 7 LIMIT 100 improves by
    28% (0.103s → 0.075s), FINAL WHERE v = 7 ORDER BY k LIMIT 100 by 24% (0.132s → 0.101s) — the saved time is the set-building barrier, so the relative win grows with table size. A control query with a clustered filter and no limit,
    where lazy FINAL still applies, is unchanged (+3%, within threshold).

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

The lazy FINAL optimization (query_plan_optimize_lazy_final, disabled by default) is no longer applied when the query reads in the order of the sorting key, because its replacement plan does not produce rows in sorting-key order, while the plan above may already rely on that after the read-in-order optimization, which could result in incorrectly ordered results. It is also no longer applied when aLIMIT smaller than the number of rows to read applies directly to the reading step, where the mandatory set-building pass would defeat early termination.

image

The lazy FINAL replacement plan (hash aggregation over the sorting key plus
a lazy column fetch) does not produce rows in any particular order, while
the steps above may already rely on the reading step producing rows in
sorting key order after optimizeReadInOrder converted them - in an
experiment the result of such a query stayed ordered only by accident of
execution, with no sorting transform left in the pipeline. Disable the
optimization when the reading step reads in order, both for correctness
and because the set-building phase reads all filtered rows before either
branch can return the first row, defeating early exit.

For the same reason, disable it when a LIMIT smaller than the number of
selected rows applies directly to the reading step's output (only
Expression/Filter steps in between): such queries stop reading as soon as
enough rows pass the filter. A limit above a stream-consuming step (full
sort, aggregation) does not disable the optimization.

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

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ac466bf]

Summary: ✅


AI Review

Summary

This PR disables lazy FINAL for read-in-order plans and for several early-exit LIMIT shapes so the replacement InputSelector plan does not destroy ordering or force a full set-building pass when the ordinary pipeline could stop early. The remaining gap is that the new stack walk still treats every AggregatingStep as a full-stream consumer, but ClickHouse already has a default trivial GROUP BY ... LIMIT optimization that makes aggregation itself stop reading early, so one class of early-exit FINAL queries still keeps lazy FINAL enabled and loses the intended benefit.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeLazyFinal.cpp:411] The new "any other step consumes the whole stream" assumption misses AggregatingStep when max_rows_to_group_by is active. OptimizeTrivialGroupByLimitPass rewrites plain GROUP BY ... LIMIT queries to max_rows_to_group_by = limit + offset with group_by_overflow_mode = 'any', and AggregatingTransform then closes its input once that cap is reached. As a result, SELECT k FROM ... FINAL WHERE ... GROUP BY k LIMIT 5 still keeps lazy FINAL enabled and pays the full set-building pass even though the non-lazy plan stops after five groups.
Tests
  • ⚠️ Add a focused stateless EXPLAIN case for SELECT k FROM ... FINAL WHERE ... GROUP BY k LIMIT N with optimize_trivial_group_by_limit_query = 1, asserting that lazy FINAL is skipped just like the plain LIMIT and DISTINCT cases covered here.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 15, 2026
@KochetovNicolai
KochetovNicolai marked this pull request as ready for review July 15, 2026 15:43
Local perf.py comparison against the parent commit (48-core ARM machine,
release build, 2 intersecting parts, 16M rows):
- FINAL WHERE v = 7 LIMIT 100 (no ORDER BY): -28% (0.103s -> 0.075s)
- FINAL WHERE v = 7 ORDER BY k LIMIT 100 (read-in-order): -24% (0.132s -> 0.101s)
- control with clustered filter and no limit (lazy FINAL still applies): +3%, within threshold

Co-Authored-By: Claude Fable 5 <[email protected]>
DistinctTransform stops reading as soon as its pushed-down limit hint of
distinct rows is produced, so DistinctStep with a non-zero getLimitHint()
is an early-exit consumer and must disable lazy FINAL like a plain LIMIT.

arrayJoin inside an Expression/Filter step changes the number of rows, so
a limit above it is not comparable to the number of selected rows at the
storage level; stop the walk there and keep lazy FINAL, matching the guards
in optimizePrimaryKeyConditionAndLimit and lazy materialization.

Addresses review comments.

Co-Authored-By: Claude Fable 5 <[email protected]>
…azy FINAL walk

A LimitStep with always_read_till_end (set for exact_rows_before_limit and
some WITH TOTALS cases) reads the whole stream anyway, so it cannot stop
reading early and lazy FINAL remains useful there. Skip it in the walk,
matching the sibling guard in limitPushDown.

Addresses a review comment.

Co-Authored-By: Claude Fable 5 <[email protected]>
…queries

The read-in-order and small-limit gates fired before
trySplitNonIntersectingParts, so they also disabled the case when all
selected parts do not intersect by the primary key and the whole FINAL
read is replaced by a plain read. That replacement clones the query info
with the input order info, so it preserves both the reading order and the
early exit, and must stay enabled. The gates now only skip the partial
split (which mutates the reading step's analyzed result) and the
set-building plan when intersecting parts remain.

Addresses a review comment.

Co-Authored-By: Claude Fable 5 <[email protected]>
KochetovNicolai and others added 2 commits July 17, 2026 14:50
… walk

The DISTINCT limit hint is seeded from the query limit even when that
limit has always_read_till_end (exact_rows_before_limit or WITH TOTALS),
in which case the query reads the whole stream and the hint must not
disable lazy FINAL. Continue the walk above the DistinctStep to the
LimitStep and use the hint only when the limit allows to stop early,
the same exemption as for a plain limit.

Addresses a review comment.

Co-Authored-By: Claude Fable 5 <[email protected]>
…L walk

The DISTINCT transform stops reading once its limit hint of distinct rows
is produced even when the enclosing limit has always_read_till_end:
the planner seeds the hint regardless of exact_rows_before_limit, and
DistinctTransform calls stopReading unconditionally on reaching it.
Verified: SELECT DISTINCT ... LIMIT 5 with exact_rows_before_limit = 1
reads 262144 of 10M rows, the same as without the setting. So the query
does terminate reading early and lazy FINAL must be disabled for it -
revert the LimitStep confirmation added in the previous commit and treat
any non-zero hint as an early-exit carrier; if the hint seeding ever
starts to account for always_read_till_end, the walk follows
automatically. The plan test moves with this decision.

Addresses a review comment.

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

/// Find a LIMIT that applies directly to the reading step's output (only Expression/Filter
/// steps in between). Such a limit lets the query stop reading early, which the set-building
/// phase would defeat. Any other step consumes the whole stream and stops the search.

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.

AggregatingStep is another early-exit carrier here once max_rows_to_group_by is active. The default OptimizeTrivialGroupByLimitPass rewrites plain GROUP BY ... LIMIT queries into max_rows_to_group_by = limit + offset with group_by_overflow_mode = 'any' (src/Analyzer/Passes/OptimizeTrivialGroupByLimitPass.cpp:40-95), and AggregatingTransform then closes its input as soon as that cap is reached (src/Processors/Transforms/AggregatingTransform.cpp:886-888, src/Processors/Transforms/AggregatingTransform.cpp:968-995).

With the current "any other step consumes the whole stream" break, a query like SELECT k FROM t FINAL WHERE v = 7 GROUP BY k LIMIT 5 still keeps lazy FINAL enabled even though the non-lazy plan stops after five groups, so the set-building pass reads all filtered rows up front and defeats the same early-termination win this patch is trying to preserve.

Can we treat AggregatingStep with getParams().max_rows_to_group_by != 0 and getParams().group_by_overflow_mode == OverflowMode::ANY as another short-circuiting carrier here, and add a focused EXPLAIN test for that GROUP BY ... LIMIT shape?

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.10% 86.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 39/42 (92.86%) · Uncovered code

Full report · Diff report

@yakov-olkhovskiy yakov-olkhovskiy self-assigned this Jul 20, 2026
@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Jul 22, 2026
Merged via the queue into master with commit f46d1f2 Jul 22, 2026
349 of 350 checks passed
@KochetovNicolai
KochetovNicolai deleted the disable-lazy-final-read-in-order-limit branch July 22, 2026 14:27
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 22, 2026
alexey-milovidov added a commit that referenced this pull request Jul 24, 2026
… read-in-order

Master PR #110576 disabled the
lazy-FINAL partial split (the InputSelector shape) when the reading step
reads in order, so the previous anchor of this test became vacuous. The
full non-intersecting replacement still fires for in-order reads and still
reconstructs the reading step via createNonIntersectingPlan, which must
carry the read-in-order contract (copyReadInOrderContractFrom). Rework the
test to anchor on the full replacement with three disjoint parts (the
ReplacingSorted merge disappears while the read stays in order and
PrefetchingConcat stays absent), and additionally pin the new behavior
that intersecting parts under read-in-order keep the regular FINAL read
with no InputSelector.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…al-read-in-order-limit

Disable lazy FINAL under read-in-order and for early-exit LIMIT queries
pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Sep 29, 2026
…oint sorting key

`trySplitNonIntersectingParts` returns "not replaced" for a primary key the parts splitter
cannot compare (`isSafePrimaryKey`: `Nullable`, `Float*`, `BFloat16`, `Variant`, `Dynamic`,
`JSON`, also nested), for mixed `ASC`/`DESC` key columns, and when a full non-intersecting
replacement selects nothing. All three return before the checks that keep a direct read from
a text index (ClickHouse#106894) and a query that stops reading early (ClickHouse#110576) away from the
set-building plan, so `optimizeLazyFinal` built that plan anyway. Its read inherits the
`__text_index_*` column name from `getAllColumnNames` but not the index read tasks that
produce it: the filter drops rows, and when the `WHERE` repeats the `PREWHERE` predicate,
`set_plan.optimize` rewrites the copy to the same name and `createReadTasksForTextIndex`
throws `Column __text_index_... already added for reading`.

Apply the same two conditions right after the split. On every path that reaches the new
check with either condition true the reading step is still untouched, so the query keeps the
regular `FINAL` read, as it already does for a comparable key. The in-split checks stay, as
they must run before the partial split narrows the reading step. With both conditions false
the control flow is unchanged.

On 26.8.10.6, `SELECT count() FROM tab FINAL WHERE str = 'ccc'` with only
`query_plan_optimize_lazy_final = 1`, over a `ReplacingMergeTree` with a `Nullable(UInt64)`
sorting key and a text index on `str`, returns 0 instead of 1.

Found by `AST fuzzer (amd_debug, targeted, old_compatibility)` (STID 4792-5e4c) on
ClickHouse#122492:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122492&sha=f6b330abde632fb2c271eb66e098d4230b4a7004&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Tests: `02346_text_index_bug106809` gains a `Nullable`-key section (its `PREWHERE` + `WHERE`
row is 1 because `PREWHERE` is evaluated before `FINAL`), and
`04539_lazy_final_read_in_order_limit_disabled` gains `Float64`-key rows for both gates plus
a positive control.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default 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