Repository navigation
Skip constant ORDER BY columns when determining read-in-order direction - #94103
shankar-iyer merged 14 commits into
Conversation
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.
d398f13 to
60aa2e5
Compare
|
Workflow [PR], commit [32ff797] Summary: ❌
|
…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.
|
Hi, @shankar-iyer |
Thanks for the PR! For the ParallelReplicas failure of the new test, please add |
|
@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. |
…-in-order-constant-column-direction
…-in-order-constant-column-direction
|
@shankar-iyer seems to still fail |
The current run |
|
CI run is clean, I will check the PR. |
There was a problem hiding this comment.
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 |
|
Nothing much from the copilot review. |
ec2891b
|
Unfortunately, this PR introduced a bug: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=1ec9edcad6ecd8040cebe4c09487fb5bf219d725&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_ubsan%29&name_1=AST%20fuzzer%20%28amd_ubsan%29 I will try to fix or revert. |
…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]>
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]>
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:
Changelog category (leave one):
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
26.1.1.774