Repository navigation
Restore Greedy read-in-order Plan - #116854
Conversation
…ble before projections selection
|
Workflow [PR], commit [c7554d5] Summary: ❌
AI ReviewSummaryThis PR moves Findings❌ Blockers
|
| │ Prefix sort description: ts DESC | ||
| │ Result sort description: ts DESC | ||
| │ Limit 200 | ||
| └──ReadFromMergeTree (default.repro_proj_order) |
There was a problem hiding this comment.
This reference over-specifies the first #116801 shape. Here grp is fixed by the filter, so the projection key (grp, ts) can satisfy ORDER BY ts DESC; the bad plan was the full-sort fallback after the projection rewrite hid that fixed key behind an ALIAS, not projection usage itself. Asserting ReadFromMergeTree (default.repro_proj_order) on the base table bakes in the broad projection suppression from this PR and will block the alias-side fix from using the better projection plan. This case should assert "no full-sort fallback / correct result" rather than pinning the base-table plan.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 25 s compile time in total, 8 of them have a recent master baseline. |
|
|
||
| -- Reading in order terminates early because of the LIMIT, so only the marks | ||
| -- before the matching one are guaranteed to be cut and dropped. | ||
| -- Read-in-order now runs before projection selection, and an in-order read declines |
There was a problem hiding this comment.
optimize_use_projection_filtering is documented as filtering part ranges even when the projection is not selected, but this new expectation accepts the opposite for every in-order read. With the new pre-pass, optimizeReadInOrder calls requestReadingInOrder first, then optimizeUseNormalProjections returns at canUseProjectionForReadingStep(reading) before it ever reaches filterPartsAndCollectProjectionCandidates, so the projection-index refiner never gets attached to MergeTreeReadPoolInOrder / MergeTreeReadPoolParallelReplicasInOrder. Please keep the filtering-only path alive when the base table stays selected instead of updating the test to expect zero dropped marks here.
|
|
|
lucky we have a merge queue :) |
| optimizeReadInOrder(frame_node, nodes, optimization_settings); | ||
|
|
||
| if (optimization_settings.distinct_in_order && !make_distributed_plan) | ||
| optimizeDistinctInOrder(frame_node, nodes, optimization_settings); |
There was a problem hiding this comment.
Running optimizeDistinctInOrder before the projection passes turns many SELECT DISTINCT ... plans back into ordinary base-table reads. buildInputOrderInfo(*distinct, ...) ends up calling ReadFromMergeTree::requestReadingInOrder, which flips readsInOrder(), and both projection optimizers then return at canUseProjectionForReadingStep(reading) (optimizeUseAggregateProjection.cpp:828, projectionsCommon.cpp:84) before they can compare any candidates. That is why this patch now has to pin optimize_read_in_order = 0 and optimize_distinct_in_order = 0 in 04909: under default settings, shapes like SELECT DISTINCT v * 2 FROM t_distinct_proj ORDER BY v SETTINGS optimize_use_projections = 1 stop using projection p even though the projection still satisfies the query. Please keep the "base read can stream in order" fact separate from the global readsInOrder() flag until projection selection is finished.
| [&](auto & frame_node) | ||
| { | ||
| if (optimization_settings.read_in_order && !make_distributed_plan) | ||
| optimizeReadInOrder(frame_node, nodes, optimization_settings); |
There was a problem hiding this comment.
Moving optimizeReadInOrder ahead of projection selection also changes the semantics of the named/preferred projection settings, not just the generic ranking. optimizeUseNormalProjections only narrows to preferred_optimize_projection_name after canUseProjectionForReadingStep succeeds (optimizeUseNormalProjection.cpp:347, :390-400), and the end-of-pass force_optimize_projection_name check in optimizeTree.cpp:794-799 likewise depends on some projection having been analyzed. Once this pre-pass flips readsInOrder(), every query whose base read can stream in order skips the selector entirely at projectionsCommon.cpp:84, so a usable named projection becomes unreachable and force_optimize_projection_name can fail with Projection <name> ... not used. Please keep the early "base read can satisfy ORDER BY" fact separate from the live readsInOrder() flag until projection selection has finished.
|
Those comments are not mine. They come from the
I can send a PR against that file so a finding whose thread has been resolved is not re-threaded on a later run. Say the word and I will. On #116801: #116835 is the alias fix you have been reviewing, and #116926 is the selection-level fix you asked for, whose decline branch is unreachable once this PR lands, as I noted on the issue. Both stay open unless you want #116926 closed. |
Since 26.5 the projection-on-fixed-key shape was planned as a reverse read of the projection; ClickHouse#116854 (merged 2026-09-03) runs read-in-order on the base table before projection selection again, so the same query now reads the base table in reverse order and the projection is not selected. The four counters in the first block therefore move from 1/1/0/1 to 1/0/1/1: the reverse read is unchanged, the projection step goes away and the base-table step appears. Measured on this tree, fix arm vs the same tree with this PR's src hunk reverted (build ids 2e96eb1f0f8dbb47 and 388167cacbbba085, server buildId() asserted on each arm): the first block is 1/0/1/1 on BOTH arms, so its new shape comes from ClickHouse#116854 and not from this change. The aliased-filter-column assertion is 1 on the fix arm and 0 on the reverted arm, and with this updated reference that assertion is the only mismatch the reverted arm produces, so the reference still fails without the alias unwrap.
The `mt_fixed_key` block stopped discriminating once ClickHouse#116854 restored read-in-order on the base table ahead of projection selection: its table key `(c, b)` serves `ORDER BY c DESC` on its own, so that query now reads the base table whether or not the alias is looked through, and the block cannot show the regression the issue reports. `mt_proj_only` keys the table on `a`, which cannot serve `ORDER BY c`, so the projection is the only read that can and only once its leading key `b` is seen as fixed by the `WHERE`. Measured on this tree against the same tree with this PR's src hunk reverted (build ids 2e96eb1f0f8dbb47 and 388167cacbbba085, server buildId() asserted per arm): `ReadType: InOrder` is 1 with the unwrap and 0 without it, while the projection step stays 1 on both arms, so the count attributes the in-order read to the projection rather than to a base-table read. Rows are [1,4,7,10,13] on both arms. Two of the fourteen assertions now fail without the unwrap, this one and the table-level `ALIAS` one; the rest are controls and results-and-order guards. Passes 10 of 10 runs at `--jobs 4`, so it is safe to run in parallel with itself and needs no tag.
|
@Michicosun @qoega @yariks5s — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
…rder pass `optimizeTreeSecondPass` runs `optimizeReadInOrder` on two traversals. The earlier one was added by #116854, so that read-in-order is applied before projection selection, and #115244 then narrowed its gate to `!make_distributed_plan`. Both landed on master on 2026-09-03 and came in with the last merge. For a non-distributed query that earlier traversal is therefore the one that converts the `SortingStep` to `FinishSorting`, and it runs before `pushLimitByIntoSort` has attached the `LIMIT BY` hint - so `preferMultipleStreamsForPushedDownLimitBy` saw no hint and did nothing. The later traversal does run after the hint is attached (the pre-order traversal visits the parent `LimitByStep` first), but by then the sorting is no longer `Full`, so `optimizeReadInOrder` returned immediately and never reached the request. `setPreferMultipleStreams` was consequently never called, and the per-part `PrefetchingConcat` collapsed the per-stream `LimitBySortedStreamTransform` prefilter to a single stream per part - the exact serialization that request exists to prevent. Handle an already converted `FinishSorting` instead of returning: its `prefix_description` is the read-in-order prefix it was converted with, and the hint the converting pass could not see is attached by the time the other pass visits the step. Whichever traversal converts the sorting, the other one applies the request, so the decision no longer depends on which pass gets there first. `findReadingStep` stops at a `UnionStep`, so the fan-out over union branches that the conversion already did is factored into `preferMultipleStreamsForPushedDownLimitByBelowSorting` and reused here. Caught by `04054_read_in_order_prefetching_concat`, assertion `order_by_limit_by_multi_part_no_prefetching`, which was the only failure in the `Fast test` run on `ceb1047271ad` (1 of 11358 executed tests). Measured on a 3-part table with `max_threads = 6`, before and after, everything else equal: direct table, `ORDER BY grp, key LIMIT 3 BY grp` before: `PrefetchingConcat` x 3, prefilter `LimitBySortedStreamTransform` x 3 after: no `PrefetchingConcat`, prefilter `LimitBySortedStreamTransform` x 6 `Merge` table, same query before: `PrefetchingConcat` 3, `LimitBySortedStreamTransform` 4 after: `PrefetchingConcat` 0, `LimitBySortedStreamTransform` 7 Both controls are unchanged by the fix and keep per-part prefetching, as they should: an `ORDER BY` suffix that is not covered by the read-in-order prefix (no per-stream prefilter runs, so there is nothing to protect), and `query_plan_push_limit_by_into_sort = 0` (no hint at all). The `Merge` route was affected identically but had no coverage - `04318_read_in_order_prefetching_concat_merge` exercised only the bare `LIMIT BY` shape, which reaches the reader through `optimizeLimitByInOrder` and was never broken. It now also covers `ORDER BY ... LIMIT BY` over a `Merge` table, whose `PrefetchingConcat` assertion fails without this fix.
…s not sort by Since ClickHouse#116854 the `read-in-order` optimization runs on the base table before projection selection. The base table of `04501_constant_column_after_filter_mergetree_write` was sorted by `time`, so it served `ORDER BY time` on its own and the `pageview_projection` projection was never picked, which made `force_optimize_projection = 1` throw `PROJECTION_NOT_USED`. Master adapted its own `05045` test the same way.
Resolve the conflict of the cherry-pick of #130893 to 26.8. The only conflict is modify/delete on `05049_projection_shorter_sort_prefix_than_pk.reference`: the test 05049 was added by #116854, which is not in 26.8, so the file stays deleted. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Resolve the conflict of the cherry-pick of #130893 to 26.3. The only conflict is modify/delete on `05049_projection_shorter_sort_prefix_than_pk.reference`: the test 05049 was added by #116854, which is not in 26.3, so the file stays deleted. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
This patch restores the optimization application order to run
read-in-orderon the base table before using projections that can benefit from in-order reading based on the initial table read-in-order.Fixes: #116801
Workflow [PR]
Sync PR [sync-upstream/pr/116854]