Skip to content

Fix Inconsistent KeyCondition behavior for wider-typed key comparisons - #109023

Merged
nihalzp merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-relaxed-exact-range
Jul 27, 2026
Merged

nihalzp merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-relaxed-exact-range

Conversation

@groeneai

@groeneai groeneai commented Jul 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111421
Related: #90461
Related: #108011

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

Fixes the recurring debug-only Inconsistent KeyCondition behavior logical error thrown from MergeTreeDataSelectExecutor::markRangesFromPKRange (the #90461 monotonicity canary), for the manifestation where the first primary-key column is compared against a wider-typed constant.

Requested by @alexey-milovidov on #108100, where the AST fuzzer mutated 04303_key_condition_ifnull_coalesce_boolean.sql's team_id = 1 (a UInt64 column) into team_id = toUInt256(1) and hit the assertion in Stress test (arm_debug). The same class was reported independently in #111421 (a composite (x, y, z) key with x = toUInt256(3)).

CI provenance: STID 5182-2f27, Stress test (arm_debug) on PR #108100, commit 1f4cb31a3007c75924ae0790f691c4b549772a08, fuzzed query SELECT count() FROM t_ifnull_keycond WHERE (team_id = toUInt256(1)) AND (k = 0). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108100&sha=1f4cb31a3007c75924ae0790f691c4b549772a08&name_0=PR&name_1=Stress%20test%20%28arm_debug%29

Root cause

KeyCondition::matchesExactContinuousRange() gates the exact continuous-range (implicit count projection) optimization. It classifies a key column as an exact POINT when the column's monotonic-function chain is strict.

Comparing a UInt64 key column against a wider-typed constant (toUInt256(...), toInt256, toUInt128, toInt128) inserts a widening CAST into that chain. The widening cast is genuinely strictly monotonic, so matchesExactContinuousRange marked the column POINT. But checkInRange applies the chain to the granule bounds via applyMonotonicFunctionsChainToRange, which forces the bounds closed. For a granule that straddles the key boundary, the closed-bound mapped range only partially matches, so checkInRange honestly reports can_be_false = true. That contradicts the POINT "exact continuous" promise, and the subsequent exact-range computation in markRangesFromPKRange finds an interior granule that can_be_false and throws the debug-only Inconsistent KeyCondition behavior canary.

This is compiled out under NDEBUG, so there is no behavior change in release builds. In release the broken exact range is dropped and read normally, so the count result stays correct (the wider-typed comparison just reads a couple more granules). Verified for both the #108100 single-key repro and the #111421 composite-key repro: the release count matches the native-typed comparison.

Fix

Only promote a key column to POINT in matchesExactContinuousRange when its monotonic-function chain is empty (a native key column). A non-empty chain, even a strict one, cannot promise exact continuity across boundary granules because the chain application forces closed bounds; treat such a column as a RANGE. This mirrors how the function already downgrades non-strict chains, and only disables the exact-range fast path for the affected queries (the pruning and results are unchanged).

Testing

tests/queries/0_stateless/04493_key_condition_wide_type_exact_range.sh reproduces the abort on a debug build without this change and passes with it. It covers the single-key = toUInt256/toInt256/toUInt128/toInt128/IN-set variants and the #111421 composite (x, y, z) key at index_granularity = 1 with range conditions; each returns the same count as the native-typed comparison.

Version info

  • Merged into: 26.8.1.235 (included in 26.8 and later)

matchesExactContinuousRange gates the exact continuous-range (implicit
count projection) optimization and classifies a key column as an exact
POINT when its monotonic-function chain is strict.

Comparing a key column against a wider-typed constant (e.g. a UInt64 key
vs toUInt256(...)) inserts a widening CAST into that chain. The widening
cast is genuinely strictly monotonic, so the column was marked POINT. But
checkInRange applies the chain to the granule bounds via
applyMonotonicFunctionsChainToRange, which forces the bounds closed. For a
granule that straddles the key boundary, the closed-bound mapped range
only partially matches, so checkInRange honestly reports can_be_false =
true. That contradicts the POINT "exact continuous" promise, and the exact
range computation in markRangesFromPKRange then finds an interior granule
that can_be_false and throws the debug-only "Inconsistent KeyCondition
behavior" logical error (the ClickHouse#90461 monotonicity canary, #ifndef NDEBUG).

Found by the AST fuzzer mutating 04303_key_condition_ifnull_coalesce_boolean.sql
(team_id = 1 -> team_id = toUInt256(1)) in Stress test (arm_debug) on
PR ClickHouse#108100 (STID 5182-2f27).

There is no behavior change in release builds (the branch is compiled out
under NDEBUG); the count result was already correct, the wider-typed
comparison just reads a couple more granules.

Fix: only promote a key column to POINT when its monotonic-function chain
is empty (a native key column). A non-empty chain, even a strict one,
cannot promise exact continuity across boundary granules because the chain
application forces closed bounds; treat such a column as a RANGE. This
mirrors how the function already downgrades non-strict chains and only
disables the exact-range fast path for the affected queries (pruning and
results are unchanged).

Related: ClickHouse#90461

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

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Gate Result
a Deterministic repro? Yes. On a debug build, clickhouse-local with a persisted MergeTree (index_granularity=4, team_id in {0,1,2}) aborts every time on SELECT count() ... WHERE team_id = toUInt256(1) AND k = 0. Test 04493 fires without the fix, passes with it.
b Root cause explained? Yes. Widening CAST (UInt64->UInt256) is strictly monotonic, so matchesExactContinuousRange marked the key column POINT. checkInRange applies the chain with forced-closed bounds, so a boundary-straddling granule honestly reports can_be_false=true, contradicting the POINT "exact continuous" promise -> markRangesFromPKRange throws the debug-only canary.
c Fix matches root cause? Yes. Only promote to POINT when the monotonic-function chain is empty; a non-empty chain (even strict) cannot promise exact continuity across boundary granules, so it stays a RANGE. Directly targets the mechanism in (b).
d Test intent preserved? / new tests added? Yes. New test 04493 covers the UInt256/Int256/UInt128/Int128/IN-set variants; existing 04303 and the PK/trivial-count/monotonicity/set-index suite still pass unchanged. The exact-range optimization still fires for native keys (verified 3/49 granules pruned).
e Demonstrated both directions? Yes. Identical debug binary + data: clean tree aborts (rc=134); with the fix returns the correct count 13. Verified via the clickhouse-test harness (FAIL on clean, OK with fix).
f Fix general, not a narrow patch? Yes. The guard is on the chain being empty, so it covers every wider-typed / monotonic-wrapped key comparison uniformly (both FUNCTION_IN_SET and FUNCTION_IN_RANGE branches), not just toUInt256.
g Generalizes across inputs (types/wrappers)? Yes. Verified correct for UInt256, Int256, UInt128, Int128, Int64, UInt32, Int8, IN-set, and a wider-typed second key column; range (>=/<=) forms also correct.
h Backward compatible? Yes. Optimizer-internal, compiled out under NDEBUG; no setting/format/wire change. Release-build results and pruning are unchanged (the wider-typed comparison reads a couple more granules, same as before).
i Invariants/contracts preserved? Yes. Restores the invariant that matchesExactContinuousRange only reports exact continuity when checkInRange's can_be_false is reliable, matching the documented contract on KeyCondition::relaxed and how non-strict chains are already downgraded to RANGE.

Session id: cron:clickhouse-worker-slot-3:20260701-061100

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @CurtizJ — could you review this? It fixes the debug-only Inconsistent KeyCondition behavior canary (#90461) for wider-typed key comparisons: matchesExactContinuousRange marked a key column an exact POINT when a widening CAST made its monotonic chain strict, but checkInRange forces the chain's granule bounds closed, so a boundary granule reports can_be_false and contradicts the exactness promise. The fix only treats a column as POINT when its function chain is empty (results and pruning unchanged; the branch is compiled out in release).

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [206a4a2]

Summary: ✅


AI Review

Summary

This PR narrows KeyCondition::matchesExactContinuousRange so only bare-key single-point constraints keep the exact continuous-range classification; wider-typed or otherwise wrapped key equalities are downgraded to RANGE, which avoids the debug-only Inconsistent KeyCondition behavior exception while leaving the underlying filtering logic unchanged. The added regression covers the original single-key repro, the composite-key repro from #111421, the mixed native-plus-cast case raised in review, and the descending-key variant. I did not find a remaining correctness or coverage gap on the current head.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 1, 2026
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1f4a77b

Every failure below has an owner. Only CH Inc sync is exempt. This PR touches only src/Storages/MergeTree/KeyCondition.cpp and one stateless test, so none of the failures is PR-caused.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (FUNCTION_THROW_IF_VALUE_IS_NON_ZERO on MutatePlainMergeTreeTask) flaky (benign #39174 background-mutation noise; intentionally-broken UPDATE ... throwIf(...) retried across the upgrade restart) #108651 (ours, open)
Mergeable Check, PR rollup of the Upgrade check red owned via #108651 (ours, open)

Session id: cron:our-pr-ci-monitor:20260701-120000

@qoega

qoega commented Jul 22, 2026

Copy link
Copy Markdown
Member

@groeneai update branch

groeneai and others added 2 commits July 22, 2026 17:48
…test

Extend the regression test with qoega's ClickHouse#111421 trigger: a composite (x, y, z)
key at index_granularity = 1 and a count() combining the wider-typed equality on
the leading key (x = toUInt256(3)) with range conditions on the rest, over a
multi-x dataset. This exercises the aggregate-projection exact-count path with a
mark layout fine enough to disagree with the analyzer's continuous-range claim,
which the existing single-key cases did not cover.

Without the KeyCondition fix this aborts in debug builds with the Inconsistent
KeyCondition behavior logical error; in release the broken exact range is dropped
and read normally, so the count stays correct (3).

Related: ClickHouse#111421

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

Copy link
Copy Markdown
Collaborator Author

Branch updated (merged current master, CI re-running). The stale Upgrade-check red was the flaky #39174 background-mutation noise from the old base, unrelated to this change.

I verified your #111421 repro against this fix on debug, release-emulation (throw disabled), and unfixed builds:

  • unfixed debug: SIGABRT at MergeTreeDataSelectExecutor.cpp markRangesFromPKRange, backtrace exactly your stack (filterPartsByPrimaryKeyAndSkipIndexes <- selectRangesToRead(find_exact_ranges=true) <- optimizeUseAggregateProjections).
  • with the fix: no abort, count() = 3.

On the release count: it is not a wrong result. count() for (x = toUInt256(3)) AND (y = 55) AND (5786 >= z) is 3 (rows (3,55,1235),(3,55,2791),(3,55,5786), all z <= 5786); the native-typed x = 3 and optimize_use_implicit_projections = 0 oracles also return 3. In release the assertion is compiled out, so the broken exact range is dropped and those marks are read normally, giving the correct count. So this is a debug/sanitizer abort, not a release data-correctness bug.

Your composite-key / index_granularity = 1 case exercised a mark layout the existing single-key test did not, so I added it to 04493_key_condition_wide_type_exact_range.sh.

@nihalzp nihalzp self-assigned this Jul 22, 2026
The regression only exercises the exact-count projection path (where the
debug abort fires) while optimize_use_projections and
optimize_use_implicit_projections default on. If either default flips, an
unfixed build reads normally and the test silently passes. Pin both settings
before the count queries in each clickhouse-local block, matching sibling
tests 04506 and 04508.

Also assert the wide-typed comparison is actually routed through the
exact-count projection with a discriminating
SELECT count() > 0 FROM (EXPLAIN ...) WHERE explain ILIKE
'%_exact_count_projection%' in each block, so the test fails if the optimizer
declines the affected mechanism instead of silently passing on the correct
count. Verified the assertion returns 1 with the projection path live and 0
when implicit projections are disabled.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
groeneai and others added 2 commits July 23, 2026 03:49
A key column can carry both a native exact-point atom (x = 3) and a redundant
widened-cast atom (x = toUInt256(3)) at once when the query is planned with the
old analyzer, which does not fold them (the new analyzer does). In that case
matchesExactContinuousRange pins the column to POINT via the native equality and
keeps it POINT despite the co-present cast atom.

This is safe: the native atom is a genuine exact point, and the equivalent
widening cast can only report can_be_false on the same boundary granules, so
after boundary trimming no interior granule is left non-exact. The exact-count
path stays live and returns the correct native count without the debug
Inconsistent KeyCondition abort. Add this case to 04493 (enable_analyzer = 0 to
keep both atoms) so the interaction is guarded against regression.

Also strengthen the existing wide-typed cases so they distinguish the fix from
reverted code in release builds too, where the debug abort is compiled out: the
fix demotes the leading key from POINT to RANGE, which forces generic-exclusion
index search instead of binary search. Assert 'generic exclusion search' via
EXPLAIN indexes = 1 for the wide-only equality and add a cast-wrapped IN case
(toUInt256(team_id) IN (toUInt256(1))) that actually populates the set-index
function chain, exercising the changed non-empty mapping.functions branch that a
bare-key IN does not reach.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The style check forbids describing the analyzer as "new" (it is enabled by
default since 24.3). Reword the comment to "the analyzer".
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7e73034

The PR-caused Style failure from the prior head (analyzer-wording rule in the 04493 test comment) is fixed on this head. The sole remaining failure is a pre-existing trunk flake, owned by an open fixing PR.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (Replicated-DB concurrent-ALTER race, regressed 2026-07-10; 634 distinct PRs / 30d, unrelated to this KeyCondition change) #111029 (external, open)

Session id: cron:our-pr-ci-monitor:20260723-113000

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 27, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 28, 2026
kolsha added a commit to kolsha/ClickHouse that referenced this pull request Jul 28, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Jul 31, 2026
…s key columns

`MergeTreeDataSelectExecutor::markRangesFromPKRange` throws the debug-only
`Inconsistent KeyCondition behavior` logical error when `matchesExactContinuousRange`
reports that the filter describes one continuous key range, yet the exact mark range
computed by the binary search still contains rows the filter rejects.

That check silently assumes the in-memory primary index resolves every key column the
filter references. A part can keep only a prefix of the key in memory - see the
`MergeTree` setting `primary_key_ratio_of_unique_prefix_values_to_skip_suffix_columns`
- and the key columns beyond that prefix are then analysed as constant coordinates
over the whole universe, or over the part's partition minmax bound, rather than from
per-mark values. A granule strictly inside the binary-search boundary can therefore
legitimately hold rows the filter rejects even though the condition itself really does
describe one continuous key range. The assertion fires on a plain
`WHERE a = 5 AND b = 3`, with no monotonic function and no reverse-sorted key column
involved:

    CREATE TABLE t (a UInt16, b UInt16, c UInt16) ENGINE = MergeTree ORDER BY (a, b, c)
    SETTINGS index_granularity = 4,
             primary_key_ratio_of_unique_prefix_values_to_skip_suffix_columns = 0.01;

    INSERT INTO t SELECT intDiv(number, 100), intDiv(number % 100, 10), number % 10 FROM numbers(1000);

    SELECT count() FROM t WHERE a = 5 AND b = 3;   -- SIGABRT on a debug build

Only `a` is kept in memory, so the binary search returns the marks for `a = 5`, and the
granules inside that boundary do contain rows with `b != 3`.

Restrict the check to the case where the in-memory index resolved the whole used key
prefix. It keeps firing for the widening-cast manifestation of ClickHouse#90461, which is what it
is actually catching in CI. Release builds are unaffected: the exact range is dropped
there already, and that is the correct outcome here too.

CI reports for this failure (`Logical error: Inconsistent KeyCondition behavior`,
STID 5182-2f27). The first one is the manifestation fixed here - its participating
conditions are `(column 0 in [5, 5]), (column 1 in [3, 3]), and, (column 0 in (-Inf, 100])`,
with no cast - while the other three are the widening-cast class already addressed by
ClickHouse#109023:

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=b59441bd06c2fcb6b103a30874528cc398afc723&name_0=MasterCI&name_1=Stress%20test%20%28arm_debug%29&name_1=Stress%20test%20%28arm_debug%29
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=859a9abe2597d0c2c26b898066a32a375ea6b62f&name_0=MasterCI&name_1=Stress%20test%20%28arm_debug%29&name_1=Stress%20test%20%28arm_debug%29
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=10116111a8db9ece9c215d65d7afa38d9f02ebdf&name_0=MasterCI&name_1=Stress%20test%20%28arm_debug%29&name_1=Stress%20test%20%28arm_debug%29
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=e7b490a6a1e7b00ceb20d0b23ba43fc64fca87d4&name_0=MasterCI&name_1=Stress%20test%20%28amd_debug%29&name_1=Stress%20test%20%28amd_debug%29

Related: ClickHouse#90461
Related: ClickHouse#109023

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov could you apply v26.6-must-backport to this PR? It expands to exactly 26.7 and 26.6, which are the two branches still aborting on the canary this PR fixed.

This fix is on master and on no release branch, so 26.7 and 26.6 keep aborting Stress test (amd_debug|arm_debug) on their own ReleaseBranchCI runs with Logical error: 'Inconsistent KeyCondition behavior' (STIDs 5182-2f27 and 5182-684a, both on both branches). Latest hits: 26.6 at 2026-08-04 21:09:50 UTC (sha 493d30c12145), 26.7 at 2026-08-02 22:59:45 UTC (sha 1399e12824d7).

Master went quiet exactly at the fix boundary. Keying on the message phrase over 14 days, with head_ref read explicitly because pull_request_number = 0 also matches release branches:

scope rows last hit
master 14 2026-07-27 09:54:19 (before this PR merged at 20:50:49)
26.7 12 2026-08-02 22:59:45
26.6 6 2026-08-04 21:09:50

The denominator matters, so here is the window where master carried this fix and nothing else for the family (2026-07-27 20:50:49Z to 2026-07-31 16:08:15Z, pull_request_number = 0, debug Stress only): master 0 hits over 1573 rows and 157 commits, while 26.7 fired 8 times and 26.6 3 times. So this fix alone is sufficient for what the release branches are hitting, and the asymmetry rules out the readings "the fix is insufficient" or "a new sub-signature appeared", either of which would have kept master red.

Effect and risk: the change only downgrades a key column from POINT to RANGE when its monotonic function chain is non-empty. It is conservative, so it can lose some pruning but never changes results. No settings and no serialization, so no SettingsChangesHistory.cpp entry is involved. The abort itself is debug-only, guarded by #ifndef NDEBUG, and the release path just drops the exact range, so there is no release-build wrong-results or crash consequence. The harm is that it reds each affected branch's Stress lane and masks real signal there.

I simulated the port with git merge-tree --write-tree --merge-base=693a303c1017 against each branch tip: clean on both 26.7 and 26.6, landing exactly the 3 files of this PR, with the guard present at both sites afterwards and the new test byte-identical to master's.

Two things I am deliberately not asking for. 26.5 and 26.3 carry the same unguarded line, but neither has fired: over 30 days they ran 1020 and 87 debug Stress rows across 102 and 87 commits with zero hits. 04612_reverse_key_index_analysis, which is named in 6 of the 18 release abort contexts, also does not exist on either branch; the other 12 contexts name no test, so I am not claiming to have identified the carrier for all of them. The label can reach further if you want defence in depth, but I am not requesting it. 25.8 has no canary site at all, so a backport there would fix nothing observable.

For completeness, #111964 is also unbackported. I am not asking for it here because its condition (t_unloaded, primary_key_ratio) appears in 0 of the 18 release abort contexts, and it conflicts on 26.6. I will raise it separately if it ever surfaces on a release branch. And this family is not closed on master: a third carrier over a LowCardinality key still reproduces there, tracked by my open #111050. So this fix works where it is present, which is the claim I am making, not that the canary is retired.

alexey-milovidov added a commit to RinChanNOWWW/ClickHouse that referenced this pull request Aug 6, 2026
Pull in the master fixes for the two unrelated CI failures on the previous head:
- ClickHouse#111991: fix test 04627_analyzer_compatibility_final_all_joined_tables with old analyzer
- ClickHouse#109023 / ClickHouse#111964: fix logical error `Inconsistent KeyCondition behavior`

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102194&sha=5086241c961abbe0a7cb89990fa1a0fee4c4939e&name_0=PR
PR: ClickHouse#102194

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai groeneai mentioned this pull request Aug 8, 2026
1 task done
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Oct 6, 2026
Antalya 26.6 Backport of ClickHouse#109023 - Fix Inconsistent KeyCondition behavior for wider-typed key comparisons
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-ci 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.

Logical error 'Inconsistent KeyCondition behavior' + release wrong count(): toUInt256 comparison on UInt64 PK

7 participants