Skip to content

Use projection if it will help with sorting - #103723

Merged
Michicosun merged 13 commits into
masterfrom
optimize_read_in_order_after_projection_use
May 1, 2026
Merged

Michicosun merged 13 commits into
masterfrom
optimize_read_in_order_after_projection_use

Conversation

@Michicosun

@Michicosun Michicosun commented Apr 29, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Slightly better query plan for projections in-order scan.

Version info

  • Merged into: 26.5.1.210

@clickhouse-gh

clickhouse-gh Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8195677]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Port is already connected, (header: [A]) (STID: 0996-3f42) FAIL cidb

AI Review

Summary

This PR improves projection selection by allowing equal-cost normal projections when their sort order can help ORDER BY, and moves read_in_order / distinct_in_order application to a post-projection traversal. I found one correctness-of-heuristic issue in the new sort-help predicate and one test coverage gap, so this should not be merged as-is.

Findings
  • ⚠️ Majors
    • [src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:1401-1427, src/Processors/QueryPlan/Optimizations/optimizeUseNormalProjection.cpp:248-260] wouldReadInOrderBeUseful is used to break ties for equal-cost projection candidates, but it does not mirror all applicability guards from optimizeReadInOrder (notably partitioned sorting guarded by reuse_storage_ordering_for_window_functions at optimizeReadInOrder.cpp:1444-1445). This can mark sort-order benefit as available when optimizeReadInOrder will later skip optimization, causing projection selection based on a benefit that cannot be realized.
      • Suggested fix: align wouldReadInOrderBeUseful with optimizeReadInOrder applicability checks (at minimum the partitioned-sorting guard, and any other early-return guards that affect applicability).
Tests
  • ⚠️ Add a stateless test that exercises the touched distinct_in_order path after projection rewrite (similar setup to 04109_*, but with DISTINCT), to lock behavior introduced by the new post-projection traversal in optimizeTreeSecondPass.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Make the new sort-order usefulness predicate consistent with actual read_in_order applicability checks.
    2. Add coverage for DISTINCT with projection rewrite + post-projection distinct_in_order optimization.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Apr 29, 2026
@azat azat self-assigned this Apr 30, 2026
@Michicosun
Michicosun force-pushed the optimize_read_in_order_after_projection_use branch from be943b9 to fbdea02 Compare April 30, 2026 07:23
@Michicosun Michicosun changed the title Optimize read in order after projection use Use projection if it will help with sorting Apr 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 97.64% (124/127) | lost baseline coverage: 2 line(s) · Uncovered code

Full report · Diff report

@Michicosun
Michicosun added this pull request to the merge queue May 1, 2026
Merged via the queue into master with commit e036292 May 1, 2026
323 of 326 checks passed
@Michicosun
Michicosun deleted the optimize_read_in_order_after_projection_use branch May 1, 2026 04:53
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 1, 2026
alexey-milovidov added a commit that referenced this pull request May 2, 2026
When `optimize_read_in_order` is the result of a normal projection being chosen
to satisfy `ORDER BY` (PR #103723), `requestReadingInOrder` is called on the
projection's read step. Projections typically have a single part, so any
non-trivial filter that hits all rows in that part triggers the PK-selectivity
guard, disabling read-in-order on the projection - which is the entire reason
the projection was chosen.

With a single selected part there is no inter-part parallelism to lose, so the
guard is meaningless there. Add `selected_parts > 1` to the precondition.

The 04053 regression test was a single-part insert, which now correctly skips
the guard. Switch it to four parts (with `SYSTEM STOP MERGES`) so it actually
exercises the multi-part case the optimization is meant for.

Test: tests/queries/0_stateless/04109_read_in_order_with_normal_projection.sql

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100377&sha=c0ff2228cf01cd7c1cb58cb1ac6ab8f2564d30b1&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
alexey-milovidov added a commit that referenced this pull request May 4, 2026
The previous guard `selected_parts > 1` was too broad: it disabled the
PK-selectivity check for any single-part scan, including large single-part
tables where reading via mark-range parallelism would still beat the
ordered single-stream path.

The original motivation for the carve-out was the normal-projection case
(PR #103723): when a projection is chosen to satisfy `ORDER BY`, calling
`requestReadingInOrder` on the projection's read step must still set up
in-order reading - otherwise the projection's own ordering is wasted.
Projection parts are detected by `AnalysisResult::readFromProjection`,
which is exactly the property we need.

Switch the precondition to `!readFromProjection` so that:
- projection-driven reads keep read-in-order regardless of PK selectivity;
- single-part non-projection scans with poor PK selectivity correctly fall
  back to parallel reading + sorting, matching the multi-part case.

Review: #100377 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ianton-ru pushed a commit to Altinity/ClickHouse that referenced this pull request Jul 13, 2026
…_order_after_projection_use

Use projection if it will help with sorting
alexey-milovidov pushed a commit to tuanpach/ClickHouse that referenced this pull request Jul 20, 2026
…ow expects

Projection metadata is re-derived from the projection query text at every
table load, so the believed column set of a projection can drift from the
stored column set of existing projection parts. Two native triggers: parts
written by <= 26.2 for a projection selecting an ALIAS column store only the
sort key (26.3+ derive the alias source as a physical projection column), and
ALTER TABLE ... MODIFY COLUMN re-pointing an ALIAS used by a projection is
allowed without a projection rebuild. Since 26.5 the planner also selects
normal projections for sorting without a filter (ClickHouse#103723, ClickHouse#104680), so a
plain SELECT reads the drifted part through the projection, fills the missing
column with the type default, and silently returns wrong data. Background
merges that merge projection parts directly read the same default fill and
bake the wrong values permanently into the merged projection part. The same
shape breaks aggregate projections: the aggregate-state column name embeds
the expanded alias (`sum(plus(b, 1))`), so a re-pointed alias leaves old
parts without the state column the metadata now expects and reads return
default aggregate states.

A column is missing legitimately only when it is a parent-table column the
parent part also lacks (added by `ALTER ADD COLUMN` after the part was
written) - the default fill is then correct and identical on either read
path. Everything else counts as drift: `analyzeProjectionCandidate` now reads
such parts from the base table (covers normal and aggregate projections;
virtual columns are exempt since the reading step provides them), and
`prepareProjectionsToMergeAndRebuild` rebuilds the projection from the merged
parent data instead of merging drifted projection parts directly (skipped
under `deduplicate_merge_projection_mode = 'ignore'`, mirroring the
expired-columns rule).

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
When `optimize_read_in_order` is the result of a normal projection being chosen
to satisfy `ORDER BY` (PR ClickHouse#103723), `requestReadingInOrder` is called on the
projection's read step. Projections typically have a single part, so any
non-trivial filter that hits all rows in that part triggers the PK-selectivity
guard, disabling read-in-order on the projection - which is the entire reason
the projection was chosen.

With a single selected part there is no inter-part parallelism to lose, so the
guard is meaningless there. Add `selected_parts > 1` to the precondition.

The 04053 regression test was a single-part insert, which now correctly skips
the guard. Switch it to four parts (with `SYSTEM STOP MERGES`) so it actually
exercises the multi-part case the optimization is meant for.

Test: tests/queries/0_stateless/04109_read_in_order_with_normal_projection.sql

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100377&sha=c0ff2228cf01cd7c1cb58cb1ac6ab8f2564d30b1&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The previous guard `selected_parts > 1` was too broad: it disabled the
PK-selectivity check for any single-part scan, including large single-part
tables where reading via mark-range parallelism would still beat the
ordered single-stream path.

The original motivation for the carve-out was the normal-projection case
(PR ClickHouse#103723): when a projection is chosen to satisfy `ORDER BY`, calling
`requestReadingInOrder` on the projection's read step must still set up
in-order reading - otherwise the projection's own ordering is wasted.
Projection parts are detected by `AnalysisResult::readFromProjection`,
which is exactly the property we need.

Switch the precondition to `!readFromProjection` so that:
- projection-driven reads keep read-in-order regardless of PK selectivity;
- single-part non-projection scans with poor PK selectivity correctly fall
  back to parallel reading + sorting, matching the multi-part case.

Review: ClickHouse#100377 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ow expects

Projection metadata is re-derived from the projection query text at every
table load, so the believed column set of a projection can drift from the
stored column set of existing projection parts. Two native triggers: parts
written by <= 26.2 for a projection selecting an ALIAS column store only the
sort key (26.3+ derive the alias source as a physical projection column), and
ALTER TABLE ... MODIFY COLUMN re-pointing an ALIAS used by a projection is
allowed without a projection rebuild. Since 26.5 the planner also selects
normal projections for sorting without a filter (ClickHouse#103723, ClickHouse#104680), so a
plain SELECT reads the drifted part through the projection, fills the missing
column with the type default, and silently returns wrong data. Background
merges that merge projection parts directly read the same default fill and
bake the wrong values permanently into the merged projection part. The same
shape breaks aggregate projections: the aggregate-state column name embeds
the expanded alias (`sum(plus(b, 1))`), so a re-pointed alias leaves old
parts without the state column the metadata now expects and reads return
default aggregate states.

A column is missing legitimately only when it is a parent-table column the
parent part also lacks (added by `ALTER ADD COLUMN` after the part was
written) - the default fill is then correct and identical on either read
path. Everything else counts as drift: `analyzeProjectionCandidate` now reads
such parts from the base table (covers normal and aggregate projections;
virtual columns are exempt since the reading step provides them), and
`prepareProjectionsToMergeAndRebuild` rebuilds the projection from the merged
parent data instead of merging drifted projection parts directly (skipped
under `deduplicate_merge_projection_mode = 'ignore'`, mirroring the
expired-columns rule).

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

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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