Skip to content

Do not raise "Inconsistent KeyCondition behavior" when the index lacks key columns - #111964

Merged
alexey-milovidov merged 4 commits into
masterfrom
fix-exact-range-unloaded-pk-columns
Jul 31, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
fix-exact-range-unloaded-pk-columns

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Related: #90461
Related: #109023
Related: #111421

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 one manifestation of the recurring debug-only Inconsistent KeyCondition behavior logical error (Logical error: Inconsistent KeyCondition behavior, STID 5182-2f27) thrown from MergeTreeDataSelectExecutor::markRangesFromPKRange.

Root cause

The check fires when KeyCondition::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.

It 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, instead of 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.

No monotonic function and no reverse-sorted key column are needed - a plain WHERE a = 5 AND b = 3 aborts a debug build:

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

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

The fix

Restrict the check to the case where the in-memory index resolved the whole used key prefix (used_key_prefix_size <= index->size()). Where it does not, the exact range is dropped, exactly as a release build already does - which is the correct outcome, since exactness genuinely cannot be proven from a truncated index.

Release builds are unaffected: the check is compiled out under NDEBUG, and the results were already correct there.

Relationship to #109023

These are two distinct root causes behind the same assertion, and both are needed.

Of the four CI reports below, the first 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. The other three are the widening-cast class ((_CAST(column 0) in ['5', '5'])), which #109023 fixes by demoting POINT to RANGE for a non-empty monotonic-function chain; that change cannot help here, because the chain is empty.

I sampled 15 further recent failures of this STID from CIDB: all 15 are the widening-cast class, so #109023 remains the high-volume fix. This PR does not touch it, and the canary still fires for that class after this change (verified on a debug build).

Not a regression from #111059

The stress-test hit rate for this STID jumped from ~1-3/day to 45 on 2026-07-24, the day #111059 merged, because the tables added by 04612_reverse_key_index_analysis.sql gave the AST fuzzer the right material to mutate. The underlying interaction is long-standing and independent of reverse-sorted keys: the minimal reproducer above uses an ascending key. The only pre-existing test using this setting, 02998_primary_key_skip_columns.sql, uses range conditions only - which never reach the exact-range path - and is tagged no-debug.

Testing

New test 04647_exact_range_unloaded_key_columns.sql, which asserts its own premise by comparing primary_key_bytes_in_memory against an identically shaped table without the setting.

  • Aborts the unmodified master server at its first query (clickhouse-test reports ClickHouse server died); passes with this change.
  • 20/20 runs with randomized settings.
  • 235 tests matching primary_key/key_condition/index_analysis/exact_range/implicit_projection/minmax run against both this branch and unmodified master on the same local server config: identical sets of 47 environment-related failures, no differences.
  • The file compiles clean with -DNDEBUG -Wunused-variable.

CI reports

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

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Version info

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

…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 #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
#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: #90461
Related: #109023

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

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [491a805]

Summary: ✅


AI Review

Summary

This PR narrows the debug-only exact-range consistency check in MergeTreeDataSelectExecutor::markRangesFromPKRange to cases where the in-memory primary index actually holds every key column referenced by the filter. That matches the existing release-build behavior, where truncated in-memory indexes already fall back to conservative exact_ranges handling, and the added stateless test covers the unloaded-suffix reproducer for both lightweight and non-lightweight primary-key analysis. I did not find any new correctness, compatibility, or test-coverage issues in the current head; the current PR CI report is also all green.

Final Verdict

✅ No blocking issues found.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only red job, Stress test (amd_debug), is the widening-cast manifestation of the same assertion, which this PR deliberately does not touch. From clickhouse-server.err.log of that run:

Inconsistent KeyCondition behavior: matchesExactContinuousRange() reported an exact continuous range, but the mark range [124, 150) (exact subrange [125, 149)) of part all_1_1_0 is not exactly continuous. ... Participating conditions: key condition (useful: true) (relaxed: false): (_CAST(column 0) in ['5', '5']), (column 1 in [900, +Inf)), and

The _CAST(column 0) wrapper is the signature of that second class - the fuzzed query is SELECT ... FROM t_big SAMPLE 1 / 2 WHERE (g = 5) AND (r >= 900), mutated from 04612_reverse_key_index_analysis.sql, and the used key prefix is fully loaded in memory there, so the narrowed condition added here correctly still lets the canary fire. The fix for that class is #109023 (demoting POINT to RANGE for a non-empty monotonic-function chain), which is still open; it is not on master yet, so this job stays red until it merges. The two changes are independent and both are needed.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111964&sha=faac6b8feefdbcc0ade259d64f231a372e6e96e3&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

Also merged master (the branch was 424 commits behind) and verified the merged result builds.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The single red job on the previous commit, AST fuzzer (amd_debug, targeted, old_compatibility), was again the widening-cast manifestation of the same assertion, not the unloaded-key-prefix one this PR fixes. From clickhouse-server.log of that run:

Inconsistent KeyCondition behavior: matchesExactContinuousRange() reported an exact continuous range, but the mark range [199, 300) (exact subrange [200, 299)) of part all_1_4_5 is not exactly continuous.

with the key condition (column 1 in [9223372036854775807, 9223372036854775807]), (_CAST(column 0) in ['2', '2']), and for the fuzzed query SELECT count() FROM t_exact_loaded__fuzz_0 WHERE (b = _CAST(9223372036854775807, 'Int64')) AND (a = toInt128(2)). The _CAST(column 0) wrapper is the signature of that class, and the table is t_exact_loaded, whose whole key stays in memory - so the narrowed condition added here correctly still lets the canary fire there.

The fix for that class, #109023, has since merged, so I merged master (the branch was 713 commits behind) to pick it up; the red should clear on the next run. All translation units of the merged result compile.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111964&sha=606490811fb9fc23b9a79fdcd55f525bc1c293a5&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only red job, Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel), is unrelated to this change. It fails on Logical error: Got read request from replica 2 for unknown stream ... inside ParallelReplicasReadingCoordinator::handleRequest, which then reports as Server died. This is the known STID 5217-5b3d:

Related: #110518
Related: #111689 (fix in progress, not merged yet)

Nothing in this PR touches parallel replicas — it only narrows a debug-only assertion in markRangesFromPKRange. Merged master (1147 commits) so the branch is current.

@groeneai, please pick up #110518 if #111689 has stalled.

@groeneai

Copy link
Copy Markdown
Collaborator

It has not stalled, and your PR's red is the exact case it fixes.

#111689 is approved (by you, on 2026-07-28) and MERGEABLE. What was holding it was two reds on
its own head, both unrelated to its diff and both now fixed on master: 01666_merge_tree_max_query_limit
(#112385, merged 2026-07-29 15:37) and the test_postgresql_replica_database_engine TSAN race
(#112381, merged 2026-07-29 01:39). Both merged after that head was built, so I have merged master
into the branch (370001dddc5716) to pick them up. The merge carries no source change of mine: the
added and removed lines of its diff are byte-identical before and after, and I rebuilt and re-ran
the regression test on the merged tree (output matches the reference, no abort). Your approval is
still live.

On your job: the aborting query in that run is
SELECT count() FROM mv WHERE id = 999999999 from
04493_create_or_replace_materialized_view_populate_keeps_subscription_concurrent.sh, and the
initiator's plan log for that query id shows
optimizeUseAggregateProjections: Exact count optimization is applied: 1 ranges with exact row count 1.
That is the first of the four short-circuit paths #111689 fixes: the exact-count optimization
replaces the initiator's ReadFromMergeTree with a prepared source, so initializePipeline never
runs and the empty-ranges announcement is skipped. The coordinator then has three log lines for the
whole query (create, snapshot replica, then the ignored announcement) and never registers a stream,
so replica 2's request throws. I reproduced your shape locally: on master's code the exact-count
branch sets has_parent_parts = false and announces nothing, and on the fixed build the same
materialized-view query returns cleanly even with the initiator/follower divergence forced.

So #111689 is the fixing PR for this red, not just for the issue. The signature is still live on
trunk (15 master hits in the last 7 days), so it is worth merging once its CI is green.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.70% +0.10%

Changed lines: Changed C/C++ lines covered: 2/2 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 31, 2026
Merged via the queue into master with commit 1c197bd Jul 31, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-exact-range-unloaded-pk-columns branch July 31, 2026 16:08
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 31, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants