Skip to content

Properly fix primary key index analysis for reverse sorting keys - #111059

Merged
nihalzp merged 15 commits into
ClickHouse:masterfrom
nihalzp:reverse-key-index-analysis-fix
Jul 24, 2026
Merged

nihalzp merged 15 commits into
ClickHouse:masterfrom
nihalzp:reverse-key-index-analysis-fix

Conversation

@nihalzp

@nihalzp nihalzp commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Closes: #110275
Continuation of #110288.

The existing approach by swapping the left and right keys if a column is reversed is unsound, leading to incorrect hyperrectangles being created.

CREATE TABLE d (g String, r Enum8('poor'=1,'ok'=2,'great'=3))
ENGINE = MergeTree ORDER BY (g, r DESC) SETTINGS allow_experimental_reverse_key = 1;
INSERT INTO d VALUES ('manual','ok'),('manual','poor'),('novel','great'),('novel','great');
SELECT count() FROM d WHERE g = 'novel' AND r = 'great';  -- returned 0, correct is 2

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

Fix incorrect pruning from primary key index analysis on tables with a reverse (descending) sorting key (ORDER BY (g, r DESC)). A granule spanning a change of a leading key column followed by a descending key column could be pruned incorrectly, dropping matching rows.

Version info

  • Backported to: 26.7.2.15, 26.6.2.122

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [39c2c1a]

Summary: ✅


AI Review

Summary

This PR correctly threads reverse-key direction through planner-time KeyConditions, explicit PRIMARY KEY rebuilds, replica metadata refresh, and the JOIN runtime-filter pruning path. I did not find a remaining live mispruning bug in the current tree, but the newly fixed read-time runtime-filter path still has no regression coverage, so I’m requesting changes until that behavior is proven.

Tests
  • ⚠️ src/Storages/MergeTree/MergeTreeIndexReadResultPool.cpp:140 The PR fixes the reverse-key JOIN runtime-filter pruning path, but the new tests only cover planner-time primary-key analysis and replicated-metadata rebuilds. Add a focused stateless test that runs a runtime-filter-pruned join against a MergeTree table with ORDER BY (... DESC ...) and asserts enable_join_runtime_filters_index_analysis = 0 and 1 return the same result.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
@thevar1able

Copy link
Copy Markdown
Member

See also #110908 🙂

thevar1able added a commit that referenced this pull request Jul 20, 2026
Add a debug `chassert` in `KeyCondition::checkInRange` verifying its
contract: the boundary tuples must be physical boundaries in key order,
left not after right, with reversed (`DESC`) columns compared inverted.
The per-column boundary swap removed by the previous commit violated
exactly this contract, so the check would have caught the bug at the
API boundary.

Add `04612_reverse_key_index_analysis_shapes` with reverse key shapes
not covered by the earlier tests: a `DESC` first key column, two `DESC`
columns, NULLs (stored physically first on a `DESC` column), a part
without a final mark, a `DESC` key column not loaded in the in-memory
index, a middle `DESC` column skipped by the sparse analysis, an
explicit `PRIMARY KEY` clause, and granule-pruning effectiveness
checks. Scenarios ported from
#111059; the results match
that implementation's reference output exactly.

Related: #111059

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/KeyDescription.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.h Resolved
{
const auto & primary_key = metadata_snapshot->getPrimaryKey();
KeyCondition dynamic_key_condition(filter_dag, context, primary_key.column_names, primary_key.expression);
KeyCondition dynamic_key_condition(filter_dag, context, primary_key);

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 is the read-time JOIN runtime-filter pruning path that was still broken for reverse-sorted primary keys, but the new coverage never exercises it. 04612_reverse_key_index_analysis* only proves planner-time PK analysis and replicated-metadata rebuilds, so this call site can regress while the whole new suite still passes.

Please add a focused runtime-filter index-analysis case on a table with ORDER BY (... DESC ...) and compare enable_join_runtime_filters_index_analysis = 0 vs 1 results. The existing 04612_join_runtime_filters_index_analysis_multi_key_anti.sql harness already covers this feature on ascending keys and looks like the natural place to extend.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR will be backported to older versions where this path does not exist.

@groeneai Create a PR with this missing test coverage once this PR is merged.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do. Once this merges I will open a separate PR adding the missing test coverage on master and link it back here.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nihalzp done: #111777 adds the missing coverage for this JOIN runtime-filter index-analysis path on a reverse (DESC) primary key. Kept as a separate master-only PR since this path is not in the backport.

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 197/231 (85.28%) · Uncovered code

Full report · Diff report

@nihalzp nihalzp self-assigned this Jul 24, 2026
@nihalzp
nihalzp added this pull request to the merge queue Jul 24, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 24, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 24, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 24, 2026
Backport #111059 to 26.7: Properly fix primary key index analysis for reverse sorting keys
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 25, 2026
Add issue ClickHouse#111421 alexey-milovidov reverse-key case (ORDER BY (g, r DESC),
g = toUInt256(5)) to the 04493 regression. The matchesExactContinuousRange fix
is order-independent: a widening CAST leaves a non-empty function chain on the
leading key, so it is demoted POINT -> RANGE regardless of any column sort
direction. Verified this exact shape aborts in debug on master with ClickHouse#111059
without the fix and returns the native count (10) with it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Manerone pushed a commit to Manerone/ClickHouse that referenced this pull request Jul 28, 2026
Follow-up to ClickHouse#111059 requested by nihalzp: the reverse-key primary-key
index-analysis fix is backported to versions without the JOIN runtime-filter
read-time pruning path (MergeTreeIndexReadResultPool), so that path is not
covered by the backportable test 04612_reverse_key_index_analysis. This adds
the missing coverage on master only.

The enable_join_runtime_filters_index_analysis path builds a read-time
KeyCondition from a join's collected probe keys and prunes the probe-side
primary key. It must honor the key sort directions: before ClickHouse#111059 a DESC
primary-key column was analyzed as ascending, which inverts the value interval
and drops granules holding matching rows (on a set-index probe it aborts with
Invalid binary search result in MergeTreeSetIndex).

The test joins on reverse-sorted primary keys (DESC second, DESC leading, and
a single DESC column) and checks that the result with the feature on equals the
result with it off, and that pruning actually engaged (RuntimeFilterGranules
Considered and Dropped both greater than zero) so the equality is not vacuous.
nihalzp added a commit that referenced this pull request Jul 28, 2026
Cherry pick #111059 to 26.6: Properly fix primary key index analysis for reverse sorting keys
robot-clickhouse added a commit that referenced this pull request Jul 28, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 28, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 28, 2026
Backport #111059 to 26.6: Properly fix primary key index analysis for reverse sorting keys
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
Add issue ClickHouse#111421 alexey-milovidov reverse-key case (ORDER BY (g, r DESC),
g = toUInt256(5)) to the 04493 regression. The matchesExactContinuousRange fix
is order-independent: a widening CAST leaves a non-empty function chain on the
leading key, so it is demoted POINT -> RANGE regardless of any column sort
direction. Verified this exact shape aborts in debug on master with ClickHouse#111059
without the fix and returns the native count (10) with it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
Follow-up to ClickHouse#111059 requested by nihalzp: the reverse-key primary-key
index-analysis fix is backported to versions without the JOIN runtime-filter
read-time pruning path (MergeTreeIndexReadResultPool), so that path is not
covered by the backportable test 04612_reverse_key_index_analysis. This adds
the missing coverage on master only.

The enable_join_runtime_filters_index_analysis path builds a read-time
KeyCondition from a join's collected probe keys and prunes the probe-side
primary key. It must honor the key sort directions: before ClickHouse#111059 a DESC
primary-key column was analyzed as ascending, which inverts the value interval
and drops granules holding matching rows (on a set-index probe it aborts with
Invalid binary search result in MergeTreeSetIndex).

The test joins on reverse-sorted primary keys (DESC second, DESC leading, and
a single DESC column) and checks that the result with the feature on equals the
result with it off, and that pruning actually engaged (RuntimeFilterGranules
Considered and Dropped both greater than zero) so the equality is not vacuous.
@thevar1able thevar1able added v26.2-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Jul 31, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 31, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 31, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…nalysis-fix

Properly fix primary key index analysis for reverse sorting keys
robot-piglet pushed a commit to ytsaurus/ytsaurus that referenced this pull request Oct 5, 2026
Backport the KeyCondition/KeyOrder portion of ClickHouse/ClickHouse#111059.

Add a KeyDescription-based constructor and direction-aware lexicographic range decomposition. Preserve the existing ascending-only constructor; do not change MergeTree or CHYT callers.
commit_hash:0635f611128ee391a1e9db18bc5196de1130625f
robot-piglet pushed a commit to ytsaurus/ytsaurus that referenced this pull request Oct 5, 2026
Backport the KeyCondition/KeyOrder portion of ClickHouse/ClickHouse#111059.

Add a KeyDescription-based constructor and direction-aware lexicographic range decomposition. Preserve the existing ascending-only constructor; do not change MergeTree or CHYT callers.
commit_hash:0635f611128ee391a1e9db18bc5196de1130625f
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.4-must-backport v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Wrong result with filter push-down, ANY JOIN, CTE, and NOT IN

8 participants