Skip to content

Skip constant ORDER BY columns when determining read-in-order direction - #94103

Merged
shankar-iyer merged 14 commits into
ClickHouse:masterfrom
matanper:fix-read-in-order-constant-column-direction
Jan 23, 2026
Merged

shankar-iyer merged 14 commits into
ClickHouse:masterfrom
matanper:fix-read-in-order-constant-column-direction

Conversation

@matanper

@matanper matanper commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

When ORDER BY includes a column that is constant due to WHERE clause, it should not affect the read direction decision. For example:

ORDER BY tenant, event_time DESC
WHERE tenant = '42'

Previously, 'tenant' would set read_direction=1 (ASC), causing 'event_time DESC' to fail direction matching. The query would use InOrder read instead of InReverseOrder.

After this fix, constant columns in ORDER BY are skipped when determining read direction. The effective ORDER BY becomes just 'event_time DESC', which correctly uses InReverseOrder.

This applies to both:

  • ReadInOrderOptimizer (old path)
  • optimizeReadInOrder query plan optimization (new analyzer)

Changelog category (leave one):

  • Performance Improvement

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

The read-in-order optimization now recognizes when ORDER BY columns are constant due to WHERE conditions, enabling efficient reverse-order reads. This benefits multi-tenant queries like `WHERE tenant='42' ORDER BY tenant, event_time DESC` which can now use InReverseOrder instead of requiring a full sort."

close #92755

Version info

  • Merged into: 26.1.1.774

When ORDER BY includes a column that is constant due to WHERE clause,
it should not affect the read direction decision. For example:

  ORDER BY tenant, event_time DESC
  WHERE tenant = '42'

Previously, 'tenant' would set read_direction=1 (ASC), causing
'event_time DESC' to fail direction matching. The query would use
InOrder read instead of InReverseOrder.

After this fix, constant columns in ORDER BY are skipped when
determining read direction. The effective ORDER BY becomes just
'event_time DESC', which correctly uses InReverseOrder.

This applies to both:
- ReadInOrderOptimizer (old path)
- optimizeReadInOrder query plan optimization (new analyzer)
Enhance the read-in-order optimization to recognize when ORDER BY columns
are effectively constant due to WHERE conditions. For example:

  SELECT * FROM events
  WHERE tenant = '42'
  ORDER BY tenant, event_time DESC
  LIMIT 5

The optimizer now correctly identifies that 'tenant' is constant and
determines the read direction from 'event_time DESC', enabling efficient
reverse-order reads from MergeTree.

This improvement applies to both query execution paths:
- ReadInOrderOptimizer (classic path)
- optimizeReadInOrder query plan optimization (analyzer path)

The optimization particularly benefits multi-tenant workloads where
queries filter by tenant but include tenant in ORDER BY for consistency,
as well as queries using row-level security policies that constrain
leading sort key columns.
@CLAassistant

CLAassistant commented Jan 13, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@matanper
matanper force-pushed the fix-read-in-order-constant-column-direction branch from d398f13 to 60aa2e5 Compare January 13, 2026 22:26
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jan 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [32ff797]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) failure
01455_shard_leaf_max_rows_bytes_to_read FAIL cidb IGNORED
Segmentation fault (STID: 2085-4579) FAIL cidb IGNORED
AST fuzzer (amd_ubsan) failure
Logical error: Cannot convert nested result of function A with type B to the expected result type C: D (STID: 4827-671c) FAIL cidb, issue ISSUE EXISTS
BuzzHouse (amd_debug) failure
Logical error: Node A with duplicate alias B does not exist in alias table. In scope C (STID: 3040-4746) FAIL cidb, issue ISSUE CREATED

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jan 13, 2026
@shankar-iyer shankar-iyer self-assigned this Jan 13, 2026
…iption

When an ORDER BY column is constant due to a WHERE clause, we should still
include it in the sort description but not let it determine the read direction.
The previous implementation skipped adding fixed columns entirely, causing
"SortDescription not a prefix" errors when the query's ORDER BY included
constant columns.
When an ORDER BY column is fixed (constant due to WHERE clause), we now:
1. Add it to the sort description (so optimization recognizes the match)
2. Don't let it set read_direction (so subsequent columns determine direction)
3. Default to ascending if all ORDER BY columns are fixed, but only if we
   actually matched key columns (key_pos > 0)

This fixes the regression where ORDER BY a WHERE a=1 stopped being optimized,
while preserving the fix for ORDER BY tenant, event_time DESC WHERE tenant='42'
to correctly use InReverseOrder from event_time DESC.

Also adds SET optimize_read_in_order = 1 to test to prevent flakiness from
random settings.
…INPUT nodes

After DAG merging, there can be multiple INPUT nodes with the same column name
(e.g., one from filter expression and one from SELECT). The fixed_columns set
would only contain one of them, but tryFindInOutputs might return a different
node, causing the check to fail intermittently.

The fix ensures all INPUT nodes with the same name are treated as fixed if any
one of them is identified as fixed from the filter expression.
@matanper

Copy link
Copy Markdown
Contributor Author

Hi, @shankar-iyer
I'm not sure how to reproduce the failing tests locally, do you have advice?

@shankar-iyer

Copy link
Copy Markdown
Member

Hi, @shankar-iyer I'm not sure how to reproduce the failing tests locally, do you have advice?

Thanks for the PR! For the ParallelReplicas failure of the new test, please add "SET parallel_replicas_local_plan = 1;" at the start of the test to give plan stability with parallel replicas. The other 2 failures don't look related to your PR. I will review the PR in a day or two,

@shankar-iyer

Copy link
Copy Markdown
Member

@matanper Something broken in CI in latest run I think, can you refresh to master and push? The CI run after that should be good.

@matanper

Copy link
Copy Markdown
Contributor Author

@shankar-iyer seems to still fail

@shankar-iyer

Copy link
Copy Markdown
Member

@shankar-iyer seems to still fail

The current run d8c481b should end good (#94278 was needed I think)

@shankar-iyer

Copy link
Copy Markdown
Member

CI run is clean, I will check the PR.

@shankar-iyer
shankar-iyer requested a review from Copilot January 22, 2026 09:49

Copilot AI left a comment

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.

Pull request overview

This PR fixes the read-in-order optimization to properly handle constant ORDER BY columns determined by WHERE clause conditions. Previously, when a column was constant (e.g., WHERE tenant='42'), it would incorrectly influence the read direction, preventing efficient reverse-order reads.

Changes:

  • Modified read direction determination to skip constant columns when setting the initial direction
  • Added logic to handle cases where all ORDER BY columns are constant
  • Extended fix to both ReadInOrderOptimizer (old path) and optimizeReadInOrder (new analyzer path)

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
src/Storages/ReadInOrderOptimizer.cpp Updated to skip constant columns when determining read direction and handle all-constant ORDER BY cases
src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp Added INPUT node consolidation for fixed columns and skips constant columns in direction determination
tests/queries/0_stateless/03789_read_in_order_constant_column_direction.sql Test verifying InReverseOrder is used when constant columns are present in ORDER BY
tests/queries/0_stateless/03789_read_in_order_constant_column_direction.reference Expected output showing both baseline and constant column cases use InReverseOrder

Comment thread src/Storages/ReadInOrderOptimizer.cpp Resolved
@shankar-iyer

Copy link
Copy Markdown
Member

Nothing much from the copilot review.

@shankar-iyer
shankar-iyer added this pull request to the merge queue Jan 23, 2026
Merged via the queue into ClickHouse:master with commit ec2891b Jan 23, 2026
125 of 128 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jan 23, 2026
@matanper
matanper deleted the fix-read-in-order-constant-column-direction branch January 23, 2026 12:58
alexey-milovidov added a commit that referenced this pull request Jan 24, 2026
…er optimization

PR #94103 introduced logic to skip "fixed columns" (columns that become constant
after WHERE filtering) when determining the read direction for read-in-order
optimization. For example, with `WHERE tenant = 'A' ORDER BY tenant, time DESC`,
the `tenant` column is fixed, so the read direction should come from `time DESC`.

However, with `parallel_replicas_local_plan`, each replica builds its own query
plan independently. Different replicas may have different `fixed_columns` sets
due to variations in filter pushdown or other optimizations. This causes
replicas to compute different read directions:

- Replica 1: identifies column X as fixed, skips it, gets direction from column Y
- Replica 2: doesn't identify X as fixed, gets direction from column X

When these directions differ (e.g., ASC vs DESC), replicas announce different
coordination modes (WithOrder vs ReverseOrder), causing the coordinator to throw:
"Replica N decided to read in WithOrder mode, not in ReverseOrder. This is a bug"

The fix: when parallel replicas are enabled, ignore fixed columns when determining
read direction. This ensures all replicas use the same deterministic direction
based on the first ORDER BY column, matching the behavior before PR #94103.

This is a conservative fix that disables the optimization only for parallel
replicas, preserving the improved behavior for single-node queries.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 16, 2026
Since ClickHouse#94103 a sorting key column fixed by the filter (`WHERE a = 1`)
and listed in `ORDER BY` does not determine the read direction. That change also disabled the virtual row for such
a column, and without the virtual row reading in order through an `INNER JOIN` is refused. So `WHERE a = 1 ORDER BY a, b`
over the key `(a, b)` was no longer read in order through an `INNER JOIN`.

If the read goes in the direction of the fixed column anyway, `ORDER BY` follows the sorting key as it is, and the
virtual row takes the column from the index like any other key column, as before that change.

Also do not skip the key column when only a function of it is fixed: `WHERE toDate(ts) = '2024-01-01' ORDER BY toDate(ts), b`
over the key `(ts, b)` returned rows in a wrong order.

Related: ClickHouse#94103

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

can be tested Allows running workflows for external contributors pr-performance Pull request with some performance improvements 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.

InReverseOrder not used when ORDER BY includes constant value (and under RLS)

6 participants