Skip to content

Fix wrong result from primary index analysis on a reverse sorting key - #110288

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-reverse-sorting-key-index-analysis-110275
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-reverse-sorting-key-index-analysis-110275

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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 a wrong result from primary key index analysis on tables with a reverse (descending) sorting key (allow_experimental_reverse_key). A granule spanning a change of a leading key column followed by a descending key column could be pruned incorrectly, dropping matching rows.

Description

Closes: #110275

Reported wrong result (returns 0 rows with query_plan_filter_push_down=1, 25 with =0). The push-down/ANY JOIN/CTE/NOT IN shape only relocates the filter; the actual bug is in primary index analysis over a reverse sorting key and reproduces with plain equality, no join or subquery:

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

Root cause: MergeTreeDataSelectExecutor swaps the left/right boundary values per reverse column before calling KeyCondition::checkInRange. That swap is correct only when a single key column varies within a mark range. When the range spans a change of a leading column, forAnyHyperrectangle's head/tail decomposition ([x1] x [y1..+inf) and [x2] x (-inf..y2]) needs the trailing value at the range begin for the head and at the range end for the tail; the swap routes them the wrong way, so the range on the descending column is inverted and a matching granule is pruned.

Fix: pass reverse_flags into KeyCondition::checkInRange and forAnyHyperrectangle (dense and sparse overloads), feed the raw storage-order begin/end tuples without swapping, and construct the value-space Range per column honouring its sort direction. Both use_lightweight_primary_key_index_analysis paths are covered.

Verified the fix locally (repro fixed in both directions), the new regression test 04512_reverse_sorting_key_index_analysis_wrong_result, and the existing reverse-key tests (03257_*, 03286_*, 03669_*) still pass.

…) sorting key

A granule that spans a change in a leading key column, followed by a
descending key column, was pruned incorrectly. The per-column left/right
swap in MergeTreeDataSelectExecutor is correct only when a single column
varies; across a leading-column change it inverts the head/tail
decomposition in forAnyHyperrectangle, so an equality/range on the
descending column could prune a matching granule (wrong result).

Thread reverse_flags into KeyCondition::checkInRange and
forAnyHyperrectangle (both dense and sparse overloads), feed the raw
storage-order begin/end tuples unswapped, and build the value-space range
per column honouring its sort direction.

Reproduces without any JOIN/subquery/filter-push-down; the issue's
push-down + ANY JOIN + CTE + NOT IN shape merely relocates the filter
onto the reverse-keyed table.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 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 ('manual','ok'),('manual','poor'),('novel','great'),('novel','great'); then SELECT count() FROM d WHERE g='novel' AND r='great' returns 0 (correct: 2) every time. No JOIN/subquery/push-down needed.
b Root cause explained? The executor swaps left/right boundary values per reverse column before KeyCondition::checkInRange. That swap is correct only when a single key column varies within a mark range. When the range spans a leading-column change (manual->novel), forAnyHyperrectangle builds head [x1] x [y1..+inf) and tail [x2] x (-inf..y2]; the head needs the trailing value at range begin, the tail at range end. The swap routes them the wrong way, so the novel tail gets r in (-inf, ok] instead of [great..+inf), and r='great' is pruned.
c Fix matches root cause? Yes. Removes the per-column swap in the executor (feed raw storage-order begin/end), threads reverse_flags into checkInRange/forAnyHyperrectangle (dense + sparse), and builds the value-space Range per column honouring sort direction — so head/tail decomposition is reverse-aware.
d Test intent preserved / new tests added? New regression test 04512_reverse_sorting_key_index_analysis_wrong_result (minimal equality/range cases, both lightweight-index paths, and the original issue's push-down + ANY JOIN + CTE + NOT IN shape). No existing test weakened.
e Both directions demonstrated? Yes. Fails without the fix (returns 0), passes with it (returns 2). Full regression .sql matches .reference.
f Fix is general across code paths? Yes. Fixed in forAnyHyperrectangle AND forAnySparseHyperrectangle (both use_lightweight_primary_key_index_analysis values), and the executor's loaded-column, unloaded-column (partition minmax), and last-mark (range.end==marks_count) branches are all made reverse-aware.
g Fix generalizes across inputs? Verified for point-equality, one-sided ranges (r>='ok', r<'ok'), and multi-column reverse keys. Existing reverse-key tests 03257_*/03286_*/03669_* (Int/String/projection reverse keys) still pass. Direction is derived generically from reverse_flags, independent of column datatype.
h Backward compatible? Yes. Pure correctness fix; no setting default, on-disk/wire format, or new validation change. reverse_flags is a defaulted (= {}) parameter, so non-MergeTree checkInRange callers are unaffected.
i Invariants and contracts preserved? Yes. left_keys/right_keys are documented as storage-order endpoints; the value-space Range construction upholds the head/tail fixed-point identity of forAnyHyperrectangle for both ascending and descending columns. An empty reverse_flags reproduces the exact prior all-ascending behavior.

Session id: cron:clickhouse-worker-slot-4:20260713-162100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai — could you review? This makes MergeTree primary index analysis (forAnyHyperrectangle / KeyCondition::checkInRange) reverse-key aware, replacing the per-column left/right swap in the executor that breaks across a leading-key-column change. Fixes wrong result #110275.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [280f646]


AI Review

Summary

This PR fixes reverse-sorting-key primary-index pruning by making KeyCondition interpret mark-range boundaries in storage order and by covering the previously reported last-mark Nullable corner case as well. I reviewed the current head and prior discussion, including the resolved bot thread, and I did not find a remaining correctness, safety, or compatibility issue in the changed code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 13, 2026
The reverse (DESC) sorting-key index-analysis fix widens the pruned range for
the reverse-keyed generic exclusion search (scenario E), so the pruning-off
case now reads 9/100 granules instead of 8/100. Reading one more granule is the
safe direction: the fix corrects the over-pruning class from ClickHouse#110275 and loses
no rows (count() stays 1 with pruning on, off, and no index).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the Fast test failure on 04356_partition_minmax_for_primary_key_pruning. Scenario E (reverse-keyed generic exclusion search, pruning off) now reads 9/100 granules instead of 8/100: this fix widens the pruned range for the reverse key, which is the safe direction (the 8/100 came from the same over-pruning the fix corrects). count() is unchanged (1 with pruning on, off, and no index), so no rows are lost. Updated the reference to 9/100.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0597a7e

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CH Inc sync - CH Inc sync (private, not actionable by us)

Finish Workflow and Mergeable Check are green; all functional/integration/stress checks pass on this head. The prior Fast test 04356 reference difference (PR-caused) was resolved in this commit (0597a7e).

Session id: cron:our-pr-ci-monitor:20260715-010000

…rk range

In the last mark range of a part without a final mark, the sparse path of
markRangesFromPKRange set equal_boundaries_mask[i] = isNullAt(range.begin),
assuming the right boundary is always +inf. For a descending (reverse) key
column the storage-order right endpoint is -inf, so the boundaries are never
equal there. Marking them equal collapsed the column to the point {NULL},
which caused both a false exclusion (WHERE n = 5 returned 0) and a wrongly
exact range (WHERE n IS NULL returned 4 out of 4 rows because the filter was
eliminated). Requires Nullable reverse key column, allow_nullable_key = 1 and
index_granularity_bytes = 0.

Also add test coverage for parts without a final mark, where the last-mark
+inf/-inf endpoints are actually exercised (adaptive parts have an index
entry at the end of the last granule, so the previous test never hit this
branch).

Related: ClickHouse#110288
Related: ClickHouse#110275
@fm4v

fm4v commented Jul 16, 2026

Copy link
Copy Markdown
Member

Pushed 1f1d4a5 with a fix for a residual wrong result in the code this PR touches, found while reviewing.

In the last mark range of a part without a final mark, the sparse path set equal_boundaries_mask[i] = isNullAt(range.begin), assuming the storage-order right boundary is always +inf. For a descending column it is now -inf, so the boundaries are never equal there. Marking them equal collapsed the column to the point {NULL}:

CREATE TABLE tn (n Nullable(Int32)) ENGINE = MergeTree ORDER BY n DESC
SETTINGS allow_nullable_key = 1, index_granularity = 2, index_granularity_bytes = 0;
INSERT INTO tn VALUES (NULL), (NULL), (NULL), (5);
SELECT count() FROM tn WHERE n = 5;      -- returned 0, correct is 1 (false exclusion)
SELECT count() FROM tn WHERE n IS NULL;  -- returned 4, correct is 3 (range wrongly exact, filter eliminated)

Both symptoms come from the same collapse (the point range makes can_be_true false for n = 5 and can_be_false false for n IS NULL). Pre-existing on master in both analysis paths; this PR already fixed the dense path, the commit fixes the sparse one and extends the test with index_granularity_bytes = 0 coverage — adaptive parts have an index entry at the end of the last granule, so the previous test never exercised the last-mark +inf/-inf endpoints at all.

groeneai and others added 2 commits July 16, 2026 22:39
The review flagged a possible empty Range(+Inf, value) for a descending
Nullable key when a mark boundary lands on NULL. NULL maps to +Inf and sorts
first for a descending column, so storage order is NULL, values..., i.e. no
interior mark can begin at a value and end at NULL. The empty range cannot
form. Add tests for the exact reported case (ORDER BY ts DESC, rows 4, 3,
NULL, index_granularity = 2) and a composite (a, n DESC) case with a NULL mark
boundary, covering both dense and sparse index analysis.

Related: ClickHouse#110288
Related: ClickHouse#110275

Co-Authored-By: Claude Opus 4.8 <[email protected]>
index_granularity_bytes=0 with the default min_bytes_for_wide_part
emits a stderr warning that Fast test rejects. Force Wide format by
also setting min_bytes_for_wide_part=0 (consistent with non-adaptive
granularity); mark boundaries and results are unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.00% 86.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.10% 78.10% +0.00%

Changed lines: Changed C/C++ lines covered: 122/124 (98.39%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks @fm4v, verified 1f1d4a5. Gating the last-mark equal-boundaries shortcut on !reverse_flags[i] is correct: for a descending key the storage-order right endpoint is -inf, so a real (or +inf/NULL) left value never equals it, and the previous unconditional isNullAt(range.begin) collapsed the column to {NULL}. Confirmed the new index_granularity_bytes = 0 (no final mark) coverage exercises the +inf/-inf endpoints the adaptive test never reached. Integrates cleanly with the dense-path fix here.

CI finish ledger - b612e41

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CH Inc sync - CH Inc sync (private, not actionable by us)

Finish Workflow and Mergeable Check green; all functional/integration/stress/fuzzer checks pass on this head. The earlier PR-caused Fast test failure on 04512 (non-adaptive-granularity warning to stderr) was fixed in b612e41 by pinning min_bytes_for_wide_part = 0 on the non-adaptive tables.

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

nihalzp commented Jul 17, 2026

Copy link
Copy Markdown
Member

@groeneai Check if it is fixed by #109901 or not,

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nihalzp checked: #109901 does not fix this. They are complementary fixes to different code paths.

Built a binary with only #109901's source changes (its 2-file KeyCondition.cpp monotonic-chain + MergeTreeDataSelectExecutor.cpp last-mark changes) on top of the same master merge-base, and ran the #110275-shape repro:

CREATE TABLE t_r (g String, r Enum8('poor'=1,'ok'=2,'great'=3))
ENGINE = MergeTree ORDER BY (g, r DESC)
SETTINGS allow_experimental_reverse_key = 1, index_granularity = 8192;
INSERT INTO t_r VALUES ('manual','ok'),('manual','poor'),('novel','great'),('novel','great');
SELECT count() FROM t_r WHERE g='novel' AND r='great';                          -- primary key
SELECT count() FROM t_r WHERE g='novel' AND r='great' SETTINGS use_primary_key=0; -- reference
binary #110275-shape (adaptive granularity, composite reverse key) #109901's own no-final-mark case (x>11 on ORDER BY x DESC, index_granularity_bytes=0)
#109901 only 0 vs 2 (wrong, granule pruned) 12 vs 12 (correct)
this PR (#110288) 2 vs 2 (correct) 12 vs 12 (correct)

Why they don't overlap: #110288 fixes the value-space range construction in forAnyHyperrectangle / forAnySparseHyperrectangle (the make_varying_range per-column direction swap for a reverse column), which is the bug that fires on a mark spanning a leading-column change under normal adaptive granularity. #109901 does not touch those functions; it fixes the last-granule infinity substitution in markRangesFromPKRange for parts with no final mark (index_granularity_bytes = 0). The only line in common is the last-mark equal_boundaries_mask[i] = !reverse_flags[i] && ... shortcut, which @fm4v already added here in 1f1d4a5.

So #110288 is still needed; it and #109901 fix disjoint reverse-key pruning bugs.

@nihalzp

nihalzp commented Jul 17, 2026

Copy link
Copy Markdown
Member

KeyCondition is not supposed be aware of direction of the ranges that is given to it. The contract is simple: checkInRange should get keys such that left_key <= right_key. Please fix it properly.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The left_key <= right_key contract already holds for every range this PR builds: make_varying_range produces Range(right_keys[i], left_keys[i]) for a reverse column, and since the storage-end value is the smaller one for a descending column, that range is well-formed (left <= right). What the flag drives is not the endpoint ordering, it is the decomposition of a multi-column mark that spans a change in a leading key column.

Concrete case from #110275 (ORDER BY (g, r DESC), one mark holds ('manual','ok'),('manual','poor'),('novel','great')):

  • correct decomposition is head g='manual' AND r <= 'ok', tail g='novel' AND r >= 'great'.
  • a direction-agnostic forAnyHyperrectangle always builds head r >= left (anchored at range begin) and tail r <= right (anchored at range end). For the descending r, both bounds come out inverted, so WHERE g='novel' AND r='great' maps to an empty/mismatched sub-range and the granule is pruned.

I built exactly the contract you describe (caller normalizes the storage endpoints so left_key <= right_key, checkInRange direction-agnostic, which is what master did before this PR) and ran the repro:

g='novel' AND r='great'  -> 0    (use_primary_key=0 -> 2)   WRONG
g='manual' AND r='poor'  -> 0                               WRONG

vs this PR:

g='novel' AND r='great'  -> 2
g='manual' AND r='poor'  -> 1

The reason no caller-side normalization fixes it: within one decomposition the trailing column appears in BOTH the head sub-range (lower-bounded, anchored at the begin value) and the tail sub-range (upper-bounded, anchored at the end value). For a descending column both of those need to flip direction, and they draw from different endpoints, so a single ordered [left, right] pair cannot encode it. The flip has to happen where the head/tail split is known.

If the specific thing you want removed is the per-call reverse_flags parameter, I can instead make the direction an intrinsic property of the KeyCondition, established at construction from the sort description (like the key columns and key expression already are), so checkInRange keeps taking storage-order keys and gains no new range-direction argument. Would you prefer that shape?

Resolve the conflict in `MergeTreeDataSelectExecutor` while preserving the PR storage-order boundary handling and the `reverse_flags` handoff to `KeyCondition`.

ClickHouse#110288
@nihalzp

nihalzp commented Jul 20, 2026

Copy link
Copy Markdown
Member

A more proper and cleaner fix here:

@nihalzp nihalzp closed this Jul 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

This PR fixes a correctness bug in MergeTree primary-key index analysis for reverse (descending) sorting keys, moving the reverse-column handling into KeyCondition; for ascending keys the logic is behavior-preserving. The two flagged ClickBench improvements (Q4 change_factor -21.6%, Q15 -19.3%) both fall inside master's current-era variance band and were correctly kept as no_change: ClickBench tables use only ascending keys, so the touched code path is never hit, and CPU time is essentially unchanged (Q4 2682.7 vs 2678.3 ms, Q15 2595.2 vs 2621.5 ms) even as the wall-clock median dropped. The envelope suppressions are consistent with the diff — no real performance impact from this change.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 75824827-753c-4c17-b811-5cbe23cc7e83
  • MIRAI run: 6e5a9676-626d-483c-af06-04e400dd7dc2
  • PR check IDs:
    • clickbench_440823_1784557846
    • clickbench_440837_1784557846
    • clickbench_440843_1784557846
    • tpch_adapted_1_official_440849_1784557846
    • tpch_adapted_1_official_440860_1784557846
    • tpch_adapted_1_official_440872_1784557846

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-bugfix Pull request with bugfix, not backported by default v26.4-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

4 participants