Repository navigation
Disable lazy FINAL under read-in-order and for early-exit LIMIT queries - #110576
Conversation
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]>
|
Workflow [PR], commit [ac466bf] Summary: ✅
AI ReviewSummaryThis PR disables lazy Findings
Tests
Final Verdict
|
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]>
… 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. |
There was a problem hiding this comment.
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?
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 39/42 (92.86%) · Uncovered code |
… 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.
…al-read-in-order-limit Disable lazy FINAL under read-in-order and for early-exit LIMIT queries
…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]>
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
04539_lazy_final_read_in_order_limit_disabledchecks the plan shape (InputSelectorpresence) for all six cases: filter-only (applies), read-in-order with and without limit (disabled), small bare limit (disabled), limitnot smaller than the selected rows (applies), limit above a full sort (applies), plus result equality with the optimization on and off.
lazy_finalstateless tests pass unchanged.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 100improves by28% (0.103s → 0.075s),
FINAL WHERE v = 7 ORDER BY k LIMIT 100by 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The lazy
FINALoptimization (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 aLIMITsmaller than the number of rows to read applies directly to the reading step, where the mandatory set-building pass would defeat early termination.