Skip to content

Fix primary key index analysis for reverse (DESC) sort key columns - #110908

Closed
thevar1able wants to merge 5 commits into
masterfrom
fix-reverse-key-index-analysis
Closed

thevar1able wants to merge 5 commits into
masterfrom
fix-reverse-key-index-analysis

Conversation

@thevar1able

@thevar1able thevar1able commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

forAnyHyperrectangle assumes all key columns are stored in ascending order. For a
reverse (DESC) key column, when the checked mark range spans more than one value of a
preceding key column, the edge hyperrectangles take the reversed column's boundary from
the wrong end of the range with the wrong direction. Depending on data layout this
causes overreads (the whole slice of the leading key value is selected) or silently
wrong results (binary search discards granules with matching rows); debug builds throw
the Inconsistent KeyCondition behavior exception.

CREATE TABLE t (org String, dt DateTime, id UInt64)
ENGINE = MergeTree ORDER BY (org, dt DESC, id);

-- org_a spans 2026-06-01 .. 2026-07-01; org_b only has dt >= 2026-06-10
INSERT INTO t SELECT 'org_a', toDateTime('2026-06-01') + intDiv(number * 2592000, 500000), number FROM numbers(500000);
INSERT INTO t SELECT 'org_b', toDateTime('2026-06-10') + intDiv(number * 1814400, 2000000), number FROM numbers(2000000);
OPTIMIZE TABLE t FINAL;

SELECT count() FROM t WHERE org = 'org_a' AND dt < toDateTime('2026-06-05');
-- returns 0 instead of 66667

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 wrong query results and excessive granule selection in primary key index analysis
for tables with reverse (DESC) sort key columns, when a range condition on the
reversed column is combined with a condition on a preceding key column.

Primary key index analysis mishandles reverse (`DESC`) sort key columns
when the checked mark range spans more than one value of a preceding key
column: `forAnyHyperrectangle` assumes all key columns are stored in
ascending order, and the per-column left/right boundary swap done in
`MergeTreeDataSelectExecutor::markRangesFromPKRange` takes the reversed
column's boundary from the opposite end of the range with the wrong
direction. Depending on the data layout this leads to overreads (the
whole slice of the leading key value is selected) or to silently wrong
results (binary search discards granules that contain matching rows).
On a debug build the built-in self-check catches the inconsistency with
the `Inconsistent KeyCondition behavior` exception.

The tests encode the correct behavior and are expected to fail until
the bug is fixed:
- 04538 checks result correctness for range predicates on the reversed
  column, with both index analysis representations.
- 04539 checks that granule selection narrows to the matching part of
  the slice instead of the whole slice.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c86cd69]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
04507_mvt_encode_state_serialize FAIL cidb
02345_implicit_transaction NOT_FAILED cidb
02499_monotonicity_toUnixTimestamp64 NOT_FAILED cidb
01147_partial_merge_full_join NOT_FAILED cidb
03707_statistics_cache NOT_FAILED cidb
01010_partial_merge_join NOT_FAILED cidb

AI Review

Summary

This PR fixes reverse-key primary-index analysis by passing physical boundary tuples plus per-column DESC metadata into KeyCondition, instead of swapping reversed-column bounds at the caller. The added stateless coverage exercises the main risk surfaces here: lightweight and legacy analysis, exact-range reads, unloaded key suffixes, NULL, NaN, multiple reversed columns, and pruning effectiveness. I did not find a remaining correctness or contract issue in the current patch, and the changelog metadata matches a user-visible bug fix.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Jul 17, 2026
@thevar1able thevar1able added pr-bugfix Pull request with bugfix, not backported by default and removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Jul 17, 2026
thevar1able and others added 3 commits July 20, 2026 17:16
`forAnyHyperrectangle` and `forAnySparseHyperrectangle` assumed that all
key columns are stored in ascending order, and
`MergeTreeDataSelectExecutor::markRangesFromPKRange` compensated by
swapping the left and right boundary values of every reverse (`DESC`)
key column. The swap produces a correct per-column value range only
while the preceding key columns are constant across the checked mark
range: it breaks the association between the boundary values and the
boundary tuples they came from, so the edge hyperrectangles of the
lexicographic decomposition took the reversed column's bound from the
opposite end of the range with the wrong direction. Depending on the
data layout this led to overreads (the whole slice of the leading key
value was selected) or to wrong query results (the binary search over
an exact continuous range discarded granules that contain matching
rows). On debug builds the built-in self-check caught the inconsistency
with the `Inconsistent KeyCondition behavior` exception.

Now the boundary tuples are passed to `KeyCondition::checkInRange`
physically, in key order, together with optional per-column reverse
flags, and the hyperrectangle decomposition itself maps the key-order
bounds of a reversed column to value bounds with the sides swapped: for
the range [ x1 y1 .. x2 y2 ] with reversed `y` the edge hyperrectangles
become [x1] x (-inf .. y1] and [x2] x [y2 .. +inf), and the virtual
end-of-part boundary of the last mark range is -inf instead of +inf.
When no key column is reversed, the flags are not passed and the
analysis is unchanged.

The granule count in the reference of
`04356_partition_minmax_for_primary_key_pruning` grows from 8 to 9 for
the reverse-key case without partition-minmax pruning: the previously
excluded granule at the boundary of two values of the leading key
column may genuinely contain matching rows, so the old exclusion was
unsound. With the pruning enabled the partition minmax bound still
excludes that granule and the count stays 8.

Test `04539_reverse_key_index_analysis_granules` now sets
`explain_query_plan_default = 'legacy'` so that the granule counts can
be parsed from `EXPLAIN indexes = 1` output.

Co-Authored-By: Claude Fable 5 <[email protected]>
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]>
The check added in the previous commit compared boundary values with
accurate Field comparison, under which NaN is unordered (every
comparison returns false), while the physical sort places NaN like
NULL. A Float key column containing NaN therefore failed the check and
debug builds aborted with
`Logical error: 'compareBoundaryTuples(left_keys, right_keys,
used_key_size, reverse_flags) <= 0'`.

Compare only values whose Field-level order provably matches the
physical sort order: give up on the tuple when a boundary value is NaN
or of a composite type that may contain NaN inside.

Add NaN coverage on ascending and reverse float key columns to
`04612_reverse_key_index_analysis_shapes`.

Co-Authored-By: Claude Fable 5 <[email protected]>
@thevar1able
thevar1able marked this pull request as ready for review July 20, 2026 17:05
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 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.20% 78.30% +0.10%

Changed lines: Changed C/C++ lines covered: 111/129 (86.05%) · Uncovered code

Full report · Diff report

@nihalzp nihalzp self-assigned this Jul 21, 2026
@nihalzp

nihalzp commented Jul 21, 2026

Copy link
Copy Markdown
Member

As discussed, closing in favor of

@nihalzp nihalzp closed this Jul 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants