Skip to content

Restore Greedy read-in-order Plan - #116854

Merged
Michicosun merged 14 commits into
masterfrom
restore_greedy_read_in_order_plan
Sep 3, 2026
Merged

Michicosun merged 14 commits into
masterfrom
restore_greedy_read_in_order_plan

Conversation

@Michicosun

@Michicosun Michicosun commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

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

This patch restores the optimization application order to run read-in-order on 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]

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c7554d5]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: Found patch part A (min data version: B, max data version: C) that intersects mutation with version D (STID: 2781-4ebc) FAIL cidb
LLVM Coverage FAIL
Generate LLVM Coverage Diff Report FAIL cidb
Print Uncovered Code FAIL cidb Uncovered code analysis did not run: bash ci/jobs/scripts/generate_diff_coverage_report.sh failed (its output is on the Generate LLVM Coverage Diff Report result).
Docs examples FAIL
Documentation examples FAIL cidb

AI Review

Summary

This PR moves optimizeReadInOrder / optimizeDistinctInOrder ahead of projection selection to restore the greedy base-table plan for #116801, and it updates several tests around that new ordering. I cannot approve it as-is because the reordered pass flips readsInOrder before the projection selectors run, which changes the behavior of force_optimize_projection{,_name}, disables optimize_use_projection_filtering for in-order reads, and makes the new coverage mostly encode that broad projection suppression instead of proving the narrower fix.

Findings
❌ Blockers
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116854#discussion_r3880050497] [src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:412-421; src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp:84-85; src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:790-799] Running optimizeReadInOrder / optimizeDistinctInOrder before projection selection turns any base-table in-order opportunity into a hard projection veto. requestReadingInOrder sets readsInOrder, both projection selectors return immediately on that flag, and the end-of-pass checks then raise PROJECTION_NOT_USED / INCORRECT_DATA for queries where a projection is still valid. The same guard also makes preferred_optimize_projection_name unreachable because the normal selector narrows to the preferred projection only after canUseProjectionForReadingStep succeeds. The new SET optimize_read_in_order = 0 workarounds added in tests such as 04094 and 04653 are the same regression showing up in-tree. Suggested fix: keep "the base table can satisfy the required order" as a separate candidate property and only call requestReadingInOrder on the winning read after projection selection, or otherwise stop the readsInOrder veto from short-circuiting forced/named projection selection.
⚠️ Majors
  • [src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:414-421; src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp:84-85; src/Processors/QueryPlan/Optimizations/optimizeUseNormalProjection.cpp:528-569; tests/queries/0_stateless/04516_projection_index_in_read_pools.sql:89-143] The documented optimize_use_projection_filtering contract is lost for every in-order read. Once the early pass flips readsInOrder, optimizeUseNormalProjections returns before it can reach the filtering-only path in filterPartsAndCollectProjectionCandidates, so projection indexes stop pruning ranges even when the base table stays selected. 04516 now accepts 0 dropped marks in all in-order pools, which is the regression rather than proof that the behavior is correct. Suggested fix: keep the filtering-only path reachable when the base read is still the winner, even if that read can stream in order.
  • [src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:420-421; src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp:820-829; tests/queries/0_stateless/04909_distinct_projection_order_by_non_distinct_column.sql:10-15] Preliminary DISTINCT plans lose aggregate projections under default settings for the same reason: optimizeDistinctInOrder requests an in-order base read first, and the later aggregate-projection matcher then bails out on readsInOrder. The new 04909 workaround disables both optimize_read_in_order and optimize_distinct_in_order, so the PR no longer proves that SELECT DISTINCT ... ORDER BY ... shapes still use a valid projection after the fix. Suggested fix: compare DISTINCT aggregate-projection candidates before calling requestReadingInOrder, or carry the "base read can stream in order" fact separately until projection selection finishes.
Tests
  • ⚠️ [tests/queries/0_stateless/05048_projection_selected_over_read_in_order_limit.reference:10; tests/queries/0_stateless/05048_projection_selected_over_read_in_order_limit.sql:5-8] The new 05048 regression test asserts a base-table ReadFromMergeTree plan in a shape where the filter fixes grp, so the projection key (grp, ts) can still satisfy ORDER BY ts DESC. That pins the broad projection suppression from this PR, not the narrower contract "do not choose a projection that forces a full sort before the LIMIT." The focused proof here is "no full-sort fallback and correct bounded result", not "must read the base table."
Final Verdict

Status: ❌ Block

Minimum required actions: keep projection selection / forced projection settings / projection-index filtering reachable when a base-table in-order plan exists, preserve aggregate projection selection for DISTINCT under default settings, and tighten the new regression coverage so it proves the narrow #116801 contract instead of encoding the broad fallback.

LLVM Coverage Report

⚠️ No coverage measurement for commit c7554d5: bash ci/jobs/scripts/generate_diff_coverage_report.sh failed (its output is on the Generate LLVM Coverage Diff Report result).

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 28, 2026
│ Prefix sort description: ts DESC
│ Result sort description: ts DESC
│ Limit 200
└──ReadFromMergeTree (default.repro_proj_order)

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c7554d5c0 with master c064f38be (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

8 translation units recompiled, 25 s compile time in total, 8 of them have a recent master baseline.

Job report


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

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.

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.

@yariks5s
yariks5s added this pull request to the merge queue Aug 29, 2026
@yariks5s
yariks5s removed this pull request from the merge queue due to a manual request Aug 29, 2026
@yariks5s yariks5s self-assigned this Aug 31, 2026
@qoega
qoega added this pull request to the merge queue Aug 31, 2026
@qoega qoega self-assigned this Aug 31, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 31, 2026
@Michicosun

Michicosun commented Aug 31, 2026 •

Copy link
Copy Markdown
Member Author

04909_distinct_projection_order_by_non_distinct_column was committed after I updated all affected tests :(

@qoega

qoega commented Aug 31, 2026

Copy link
Copy Markdown
Member

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

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.

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

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.

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.

@Michicosun

Copy link
Copy Markdown
Member Author

clickhouse-gh All your comments looking into master code, we are restoring behaviour that we had in 25.5 before #103723, stop pinging me about changes.

@groeneai close everything that is not related and clear all unneeded comments.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

Those comments are not mine. They come from the clickhouse-gh app, posted by the Code Review job (ci/jobs/copilot_review_job.py). I do not operate it, I have no way to delete another account's comments, and I do not resolve threads or close anything on someone else's PR. What I can give you is why it keeps coming back, from that job's own procedure:

  • Each run submits a review with a new inline thread, and that is what notifies you. The AI Review block is a single comment edited in place, not reposted.
  • A silent thread resolution counts there as a dismissal, after which it stops replying on that thread (steps 4 and 6 in that file). qoega resolved one; the other four are still open.
  • Today's ping is a new thread at optimizeTree.cpp:418 for the finding whose earlier thread at :395 was already resolved, while the same run's summary still marks that finding [dismissed by author]. Step 5 says such findings stay in the summary and must not be migrated back to an inline thread, so that re-thread is a defect in the job rather than a call about your change.
  • There is no per-PR opt-out. The job is unconditional in the PR workflow (ci/workflows/pull_request.py:77), has no digest config, and skips only when there is no PR.

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.

@Michicosun
Michicosun added this pull request to the merge queue Sep 3, 2026
Merged via the queue into master with commit f1f88cf Sep 3, 2026
337 of 345 checks passed
@Michicosun
Michicosun deleted the restore_greedy_read_in_order_plan branch September 3, 2026 11:55
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 3, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 3, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 3, 2026
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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 3, 2026
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.
@clickgapai

Copy link
Copy Markdown
Contributor

@Michicosun @qoega @yariks5s — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

alexey-milovidov added a commit that referenced this pull request Sep 4, 2026
…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.
alexey-milovidov added a commit to niyue/ClickHouse that referenced this pull request Sep 8, 2026
…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.
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 15, 2026
vdimir added a commit that referenced this pull request Nov 17, 2026
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]>
vdimir added a commit that referenced this pull request Nov 17, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Projection selection ignores base-table read_in_order + LIMIT benefit, causing large regressions since 26.5

8 participants