Skip to content

Fix MergeTreeSetIndex reporting a match for an out-of-domain range boundary - #113965

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-set-index-boundary-domain-overflow
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-set-index-boundary-domain-overflow

Conversation

@groeneai

@groeneai groeneai commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #102866
Related: #90461

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

The primary key index selects granules that cannot contain a match when an IN-set element is compared
against a range boundary pushed outside the key column's type.

On official release master, 1M rows, b always 255, default granularity:

CREATE TABLE t (a UInt64, b UInt8, c String) ENGINE = MergeTree ORDER BY (a, b, c);
INSERT INTO t SELECT number % 5, 255, toString(number) FROM numbers(1000000);
SELECT count() FROM t WHERE a = 1 AND b IN (0);   -- Granules: 25/123, reads 204800 rows
SELECT count() FROM t WHERE a = 1 AND b = 0;      -- Granules:  1/123, reads 0 rows

Both predicates are equivalent and answer 0, so results stay correct, but the IN form reads 25x more
granules. With b always 254 it is 1/123, identical to =: only a value at the key column type's
maximum is affected. A debug or sanitizer build also aborts, on an index consistency check that is
#ifndef NDEBUG. Found by CI, STID 5182-2f27, Stress test (amd_debug)
(report),
from MergeTreeDataSelectExecutor.cpp:2497.

Root cause. MergeTreeSetIndex::checkInRange stores each analysed boundary into a clone of the set's
own typed column, where ColumnVector::insert is push_back(static_cast<T>(...)).
Range::shrinkToIncludedIfPossible closes an excluded bound by incrementing the left (or decrementing the
right), guarding only against the Field's limits, not the column's. For a UInt8 key holding 255 the
excluded left bound (255, +inf) becomes [256, +inf), and 256 in a ColumnUInt8 becomes 0 - exactly
the set element. FUNCTION_IN_RANGE compares Fields directly and is immune.

Fix. FieldValue already carries +/-Infinity as a marker honoured by both comparators, so
FieldValue::update stores it instead of truncating. The direction follows the value's position: the
right-bound mirror exists too, a signed key at its minimum giving a bound below the domain. NOT IN does
not drop rows.

Validation. Selected granules fall 5/20 to 1/20. The regression test fails 12 of 12 runs on a pre-fix
debug build and 20 of 20 on a pre-fix release build, passes 50 of 50 on the fixed build, and four mutants
redden it.

Type-relative signature (pre-fix): only a boundary at the column type's own limit wraps
key type boundary in data set element pre-fix
UInt8 255 (max) 0 abort
UInt8 254 0 clean
UInt8 128 0 clean
UInt16 65535 (max) 0 abort
UInt16 65534 0 clean
Int8 127 (max) -128 abort
Int8 -128 (min) 127 abort (right-bound mirror)
Int16 -32768 (min) 32767 abort (right-bound mirror)
UInt8 0 (min) 255 clean, unsigned minimum equals the guard value

Also reproduced pre-fix and fixed: Date, DateTime, Enum8, Nullable(UInt8),
LowCardinality(UInt8), has([0], b), (a,b) IN ((1,0)), (a,b,c) IN ((1,0,'1')), and both
checkInRange overloads.

The four mutants: revert the guard; handle only the above-domain direction; make the fit test always
report "fits"; drop the Nullable unwrap.

…undary

MergeTreeSetIndex::checkInRange stores each analysed range boundary by inserting
it into a clone of the set's own typed column. ColumnVector::insert is
data.push_back(static_cast<T>(...)), so a boundary pushed outside that column's
domain was silently truncated back into it, where it could coincide with a set
element and make the atom report can_be_true for a hyperrectangle containing no
matching row.

The boundary leaves the domain in Range::shrinkToIncludedIfPossible, which turns
an excluded bound into an included one by incrementing the left or decrementing
the right. It guards only against the Field's Int64/UInt64 limits, not against
the eventual column's, which is correct for its own contract: it knows nothing
about the column type. So for a UInt8 key holding 255, the excluded left bound
(255, +inf) becomes [256, +inf), and 256 stored into a ColumnUInt8 becomes 0.
With b IN (0) that is exactly the set element, so the binary search yields
begin=0, end=1 and the atom answers can_be_true.

The equivalent FUNCTION_IN_RANGE atom is immune because it compares Fields
directly and never round-trips a bound through a typed column. That asymmetry
made the set atom select 5 of 20 granules where the range atom selected 1, and
the resulting over-wide range is what the exactness re-check in
MergeTreeDataSelectExecutor observed as a contradiction, aborting debug and
sanitizer builds with "Inconsistent KeyCondition behavior".

FieldValue already carries +/-Infinity in its `value` field as a marker while
`column` holds ordinary values, and both comparators already honour it. A bound
above the domain is, for comparison purposes, exactly +infinity, and one below it
-infinity, so this reuses that path instead of adding a concept. The direction is
derived from the value's position relative to the domain, because the right-bound
mirror exists too: a signed key at its minimum yields a bound one below the
domain (-129 for Int8, truncating to +127). Unsigned types are immune on that
side, since their minimum is 0, which equals the guard value in
shrinkToIncludedIfPossible.

Only Int64/UInt64 Fields are classified, which is exactly the set
shrinkToIncludedIfPossible adjusts, so Float and Decimal keys cannot reach this
state and are unaffected by construction. A Nullable key column keeps its values
in the nested column, whose type bounds the domain, so it is unwrapped first;
LowCardinality is already converted to a full column before the set index is
built.

The check is #ifndef NDEBUG, so release builds returned correct results and the
damage was CI signal loss: the abort killed the server mid-Stress-test, so the
rest of that job never ran, on pull requests unrelated to MergeTree. NOT IN was
measured not to drop rows: inverting the mask turns a too-permissive can_be_true
into a too-permissive can_be_false, and an exact can_be_false is only produced by
the at_most_one_element_range branch, which requires a degenerate range while the
truncation requires a non-degenerate one.

The regression test covers both bound directions, UInt8/UInt16/Int8/Int16, Date,
DateTime, Enum8, Nullable and LowCardinality wrappers, has(), tuple sets, and
both checkInRange overloads, with controls one below each type's maximum, for a
present set element, for the equivalent range atom, for a two-element set, and
for a single-column key whose exact-count optimization must be preserved.
The exactness check the test targets is #ifndef NDEBUG, so where it is
compiled out the thirteen count() witnesses cannot distinguish a fixed from a
broken set index: the defect only widens the analysed mark range while row
filtering still returns the right rows. The row cap is the only assertion left
that can redden there, and three randomized settings each defeat it.

use_query_condition_cache defaults on and is randomized 50/50. That cache
prunes granules before primary-key analysis, and the same predicate already
runs twice earlier in the test, so a warm entry satisfies the cap on cache
pruning alone. Measured on a build with the fix reverted: with the cache
enabled the row cap passes while the cache grows to three entries, with it
disabled the query correctly fails with TOO_MANY_ROWS.

parallel_replicas_index_analysis_only_on_coordinator defaults on, and under it
a follower skips index analysis and keeps all marks, which can exceed the cap
even with a correct set index. The runner enables parallel replicas for plain
MergeTree tables often enough for that to be a real flake rather than a
hypothetical one. Twenty-four other index tests combine a tight row cap with
exactly this pin.

optimize_use_projections and optimize_use_implicit_projections are randomized
at five percent each. Without the implicit count() projection nothing requests
exact ranges, so every witness reads no marks at all and passes whichever way
the set index behaves. Before this pin the reverted build passed two runs in
eight; after it, ten of ten runs fail as they should, and the fix passes ten of
ten plus fifty randomized runs.

The right-bound mirror had no assertion that could redden in a release build,
since its count() answers are correct either way. It now gets the same row-cap
pair as the above-domain witness, with the equivalent range atom beside it as
the control: on the reverted build the set form exceeds the cap while the range
form does not.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 3 findings adjudicated)

I ran an independent cold review plus a second-model review pass over this change before opening
it, then adjudicated every finding against the code. Round 1 produced two test-liveness findings I
agreed with and fixed; round 2 produced one I disagree with, recorded below with the refutation.

Round 1: 2 findings, both AGREED and fixed

❌ The single release-capable oracle was defeatable by the query-condition cache. The canary
that this bug trips is #ifndef NDEBUG, so in any build where it is compiled out the
count() -> 0 witnesses pass whatever the set index answers, and only the max_rows_to_read
pair can redden. That pair was defeatable: the query-condition cache prunes granules before
primary-key analysis (ReadFromMergeTree.cpp:2933 vs :2964), the same predicate runs earlier in
the test, and the setting is both on by default and randomized 50/50. Measured on a build with the
fix reverted: cache on, the oracle passes; cache off, Code: 158 TOO_MANY_ROWS. Fixed by pinning
use_query_condition_cache = 0.

❌ The row cap was not pinned against parallel-replica followers. Under the default
parallel_replicas_index_analysis_only_on_coordinator = 1 a follower skips index analysis and
keeps all marks (ReadFromMergeTree.cpp:2917-2925), which can exceed the cap even with the fix.
Fixed by pinning that setting to 0, the idiom 26 other tests use alongside max_rows_to_read.
I could not construct a follower on a single-node box, so this one rests on the source reading and
I am saying so rather than implying a measurement.

⚠️ Found while checking the above: a third randomized setting was voiding the whole test. With
optimize_use_projections = 0 (randomized off at 5%) nothing requests exact ranges, so every
witness and the row cap read zero selected marks and pass regardless. Before the pin, the
reverted build passed 2 of 8 runs; after it, 0 of 10, while the fixed build is 10 of 10 and 50 of
50 under full randomization. Pinned both that setting and its implicit sibling.

Round 2: 1 finding, DISAGREED

💡 Requested: also pin parallel_replicas_local_plan, parallel_replicas_support_projection
and optimize_aggregation_in_order
, on the ground that Parallel Replicas can make projection
optimization decline before exact ranges are requested. The mechanism is real
(projectionsCommon.cpp:89-101), but the test cannot reach it with Parallel Replicas active:

  • The test runner's only write of enable_parallel_replicas (clickhouse-test:1818) happens
    under automatic_parallel_replicas_mode = 2, which is mutually exclusive with task-based
    parallel replicas: Context::canUseTaskBasedParallelReplicas requires that mode to be 0
    (Context.cpp:8493), and buildContext zeroes enable_parallel_replicas outright when it is
    not (InterpreterSelectQueryAnalyzer.cpp:138-151). The runner's own comment agrees: that mode
    only collects statistics.
  • The one CI flavor that genuinely enables Parallel Replicas is ParallelReplicas, whose only two
    parameter sets are amd_llvm_coverage builds (job_configs.py:786,792). Those are
    CMAKE_BUILD_TYPE=None, i.e. RelWithDebInfo with NDEBUG defined, so the canary is compiled
    out and the count witnesses are already inert there by design. The assertion that does survive
    is the row cap, and for a SELECT * it never consults the projection path at all
    (has_projections is false, so the deferral at MergeTreeDataSelectExecutor.cpp:1238 is not
    taken). Its real exposure in that flavor is the follower path, already pinned in round 1.

So those three pins would be inert wherever the affected assertions are live. Unlike the four
settings I did pin, no measurement could show them load-bearing, so I am not adding them.

parallel_replicas_support_projection is also never touched by the test runner, so it cannot vary
under randomization in the first place.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (a UInt64, b UInt8, c String) ENGINE = MergeTree ORDER BY (a, b, c) SETTINGS index_granularity = 1; INSERT INTO t SELECT number % 5, 255, toString(number) FROM numbers(20); SELECT count() FROM t WHERE a = 1 AND b IN (0); aborts rc=134 every run on unmodified master, with the CI signature byte-identical: mark range [3, 8) (exact subrange [4, 7)), frames MergeTreeDataSelectExecutor.cpp:2497 <- :1079. No fuzzer, no stress harness, 20 rows.
b Root cause explained? Range::shrinkToIncludedIfPossible closes an excluded bound by incrementing the left (or decrementing the right), guarding only against the Field's Int64/UInt64 limits, not the column's. MergeTreeSetIndex::FieldValue::update then stores the bound with column->insert(x) into a clone of the set's typed column, and ColumnVector::insert is push_back(static_cast<T>(...)). For a UInt8 key holding 255, (255, +inf) becomes [256, +inf) and 256 truncates to 0, exactly the set element, so the binary search returns begin=0, end=1 and the atom answers can_be_true for a box with no matching row. The over-wide result is what the exactness re-check reports as a contradiction.
c Fix matches root cause? Yes, at the truncation site. FieldValue already carries +/-Infinity in value as a marker with both comparators honouring it, so the fix stores that marker for an out-of-domain bound instead of inserting. No bound widening, no tag, no dataset reduction, and the canary itself is untouched.
d Test intent preserved / new test added? New test 04812_key_condition_set_index_boundary_overflow (26 SELECTs, 24 asserted values, 12 tables). No existing test was weakened; the canary still fires for any genuine inconsistency (proved by the mutants in (e)).
e Demonstrated in BOTH directions? Yes, on dedicated servers with SELECT lower(buildId()) asserted equal to the binary's NT_GNU_BUILD_ID before every verdict. Base 17b3145b92166d92: [ FAIL ] Reason: server died. Fix abd93a9c207c7ce0: [ OK ], canary 0 on a freshly truncated log. Four mutants each redden it: revert the guard; handle only the above-domain direction (reddens the right-bound mirror arms); make the fit test always report "fits" (reddens the type-relative arms); drop the Nullable unwrap. Restoring the source rebuilt back to abd93a9c207c7ce0 byte-exactly.
f General across CODE paths? FieldValue::update has 6 call sites, all within the two checkInRange overloads, and both overloads have test arms (use_lightweight_primary_key_index_analysis 0 and 1) since they build ranges differently. Fixed at the storage primitive rather than guarded at the abort site, so the too-wide mark range is corrected too (5/20 to 1/20, matching the range atom). Range::shrinkToIncludedIfPossible was deliberately not changed: it operates on Fields with no knowledge of the eventual column type and is shared by every key-condition consumer.
g Generalizes across INPUTS? Both bound directions; UInt8/UInt16/Int8/Int16 at their own maximum and minimum, with one-below-the-limit controls proving the signature is type-relative and not keyed on 255; integer-backed Date, DateTime, Enum8; Nullable(UInt8) and LowCardinality(UInt8) wrappers; has([0], b); prefix and full-key tuple sets. Float32/Decimal32 are unaffected by construction, since shrinkToIncludedIfPossible only adjusts Int64/UInt64 Fields, and carry controls. Unsigned types are immune on the below-domain side because their minimum equals that function's guard value, so that arm uses a signed type.
h Backward compatible? No setting, no serialization, no on-disk format, no interface change: git diff --numstat reports 63 added and 0 removed lines in one file. check_settings_changes_history returns '' for this file list, with both its negative controls reddening. No SettingsChangesHistory.cpp entry is owed.
i Invariants and contracts preserved? The stored bound is now either an in-domain value or an infinity marker, which is exactly the state FieldValue already documents (isNormal / isPositiveInfinity / isNegativeInfinity), so both comparators are unchanged and no new state is introduced. The change is conservative in the safe direction: a bound above the domain compares greater than every element, one below it compares smaller, so the atom can only become tighter, never wider, and begin > end remains unreachable. Release results are unaffected; NOT IN was measured against full-scan ground truth over 6 shapes with the indexed and true counts agreeing in all 6, and it cannot drop rows because an exact can_be_false is only produced by the at_most_one_element_range branch, which needs a degenerate range while the truncation needs a non-degenerate one.

Regression evidence: 50 randomized runs of the new test plus 04303_key_condition_ifnull_coalesce_boolean
and 04612_reverse_key_index_analysis gave 150 of 150 [ OK ], counted per run. A scoped suite over
key_condition, set_index, index, projection, partition, merge_tree_index, 03604, 04303
and 04612, compared as reason-bucketed sets across 698 tests present in both arms, shows 0
only-in-fix failures and 0 only-in-base failures.

@groeneai groeneai mentioned this pull request Aug 8, 2026
1 task done
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @rschu1ze, could you review this? MergeTreeSetIndex::checkInRange stores each analysed range boundary by inserting it into a clone of the set's own typed column, so a bound that Range::shrinkToIncludedIfPossible pushed one past the column's domain (255 to 256 for UInt8) truncates back into it, lands on the set element, and reports a match for a range holding none, which the exactness re-check then reports as inconsistent and aborts debug builds. The fix stores the existing +/-Infinity marker instead of truncating, the same layer as 0139ea4.

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

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1f32988]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan, s3) FAIL
Hung check failed, possible deadlock found FAIL cidb

AI Review

Summary

This PR fixes MergeTreeSetIndex so out-of-domain range boundaries are treated as infinities instead of being truncated back into the set column type. I did not find a correctness issue in the implementation itself, but the PR metadata is currently wrong for a user-visible engine bug, and the reduced regression no longer proves the signed-minimum / Nullable branches that the new helper adds.

PR Metadata
  • Changelog category is incorrect. This is not a CI-only change; it fixes user-visible misbehavior in release builds, so Bug Fix fits better than CI Fix or Improvement.
  • A Changelog entry is therefore required, and ... does not satisfy that requirement.
  • Suggested Changelog category: Bug Fix
  • Suggested Changelog entry: Fixes primary-key analysis for INpredicates on MergeTree keys at type boundaries, avoiding extra granule reads in release builds andInconsistent KeyCondition behavior exceptions in debug builds.
Tests
  • ⚠️ tests/queries/0_stateless/04812_key_condition_set_index_boundary_overflow.sql:22 only exercises the unsigned above-domain UInt8 case. After the reduction, CI no longer pins the position < 0 mirror or the ColumnNullable unwrap added in compareToColumnDomain, and src/Interpreters/tests/gtest_merge_tree_set_index.cpp does not exercise out-of-domain bounds either. One extra focused check for either Int8 at its minimum or Nullable(UInt8) would close that proof gap without restoring the full matrix.
Final Verdict

Needs minor follow-up. The code change itself looks sound, but the PR should fix the changelog metadata and keep one focused regression for the remaining new branches before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 30/34 (88.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 1f32988 - the build was skipped, reused from cache, or predates profile upload.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 934f7156ab5e2a35b3b3cca7f13c1d02b8fbe4d3

CI is fully finished on this head and there are no failing checks.

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

Session id: cron:our-pr-ci-monitor:20260809-013000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 934f715

CI is fully finished on this head and there are no failing checks.

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

Correction to my previous comment: it printed the head as 934f7156ab5e2a35b3b3cca7f13c1d02b8fbe4d3.
That string is wrong past the first 12 characters - I abbreviated the sha and then padded it instead
of reading it back. The head this ledger covers is
934f7156ab5ef6b8e1d91557f1ea71570b9a5b0a, per gh pr view --json headRefOid. The result recorded
is unchanged.

Session id: cron:our-pr-ci-monitor:20260809-013000

@@ -0,0 +1,147 @@
-- { echo }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai Change the test into a single minimal reproducible example. Do not use term "witness". Do not reference C++ identifiers, e.g. function names in comments.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 1f32988. The test is now one table, one query, 22 lines instead of 147; "witness" is gone and no comment names a C++ identifier.

Two things I found while reducing it, both measured on this test:

The pins are load bearing. Column statistics record that the key column holds a single value, so statistics pruning rejects the predicate before the primary key index runs, and the runner materializes statistics on insert in 95% of runs. Without that pin a pre-fix debug build passed the test in 10 of 12 runs. With it: pre-fix debug fails 12 of 12, pre-fix release fails 20 of 20, fixed build passes 50 of 50 under full randomization. The other pins (query condition cache, parallel replica index analysis, implicit projection) are each the same kind of earlier-pruning or no-index-analysis path.

The row limit is now 1 rather than 4, so the test asserts the index selects exactly the one granule it should, not merely fewer than five.

One tradeoff worth your call: the single case covers the unsigned above-domain path only. The fix also handles the below-domain direction (a signed key at its minimum) and unwraps Nullable, and those two branches are no longer pinned by any test, so a later change could break them silently. I left it at one case because you asked for one. Say the word and I will add two more short queries for those branches.

@rschu1ze

Copy link
Copy Markdown
Member

@groeneai The repro

CREATE TABLE t (a UInt64, b UInt8, c String) ENGINE = MergeTree ORDER BY (a, b, c)
SETTINGS index_granularity = 1;
INSERT INTO t SELECT number % 5, 255, toString(number) FROM numbers(20);
SELECT count() FROM t WHERE a = 1 AND b IN (0);  -- aborts

worked just fine. Describe which problem you are trying to fix exactly.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@rschu1ze The abort needs a debug or sanitizer build: the consistency check it trips is under #ifndef NDEBUG, so a release build compiles it out. I re-ran your exact SQL just now on both:

  • debug master (26.8.1.1, git hash 604017b7): Received signal Aborted, Inconsistent KeyCondition behavior: ... the mark range [3, 8) (exact subrange [4, 7)) of part all_1_1_0 is not exactly continuous
  • release master (26.8.1.1080, official build from builds.clickhouse.com): returns 0, no abort

So "worked just fine" is expected on a release build. That precondition was missing from my description and I am fixing that.

The problem itself is observable without a debug build, and this is what I am fixing: the primary key index selects granules that cannot contain a match when the set element is compared against a boundary that was pushed outside the key column's type. On official release master, 1M rows, b always 255, default granularity:

SELECT count() FROM t WHERE a = 1 AND b IN (0)   -- Granules: 25/123, reads 204800 rows
SELECT count() FROM t WHERE a = 1 AND b = 0      -- Granules:  1/123, reads 0 rows

Both predicates are equivalent and both answer 0, so results stay correct, but the IN form reads 25x more granules. Control on the same release binary: with b always 254 instead of 255 the IN form is 1/123, identical to =. Only a value at the key column type's maximum is affected.

Mechanism: for b IN (0) the analysed range gets an excluded lower bound at 255, which is shrunk to 256, and 256 is then stored into a UInt8 to be compared with the set element, where it truncates back to 0 - the set element itself - so the index reports a possible match for every granule above it. In a debug build the exactness check then sees the contradiction and aborts.

I will reduce the test to a single minimal example as you asked and restate the description in these terms.

Requested by rschu1ze on the PR. The test covered thirteen type and
wrapper cases; one case is enough to guard the fix, and the extra cases
made it hard to read.

The kept case is the UInt8 maximum with a row limit. It is the strongest
single assertion available: on a debug build it trips the index
consistency check, and on a release build, where that check is compiled
out, it still exceeds max_rows_to_read because the primary key index
selects five granules instead of one.

The four pinned settings are load bearing, each measured on a pre-fix
build: without them the assertion passes whether or not the index is
right. index_granularity_bytes and min_bytes_for_wide_part are pinned so
the merge tree setting randomizer cannot collapse the twenty rows into a
single granule.

Comments no longer name C++ identifiers.
Column statistics record that the key column holds a single value, so
statistics pruning rejects the predicate before the primary key index
runs. The runner materializes statistics on insert in 95% of runs, which
made the assertion pass on a pre-fix build in 10 of 12 measured runs.
With the pin, a pre-fix debug build fails 12 of 12 and a pre-fix release
build 20 of 20, while the fixed build passes 50 of 50.

The row limit is also lowered from 4 to 1, so the test asserts the index
selects exactly the one granule it should rather than merely fewer than
five.

-- Every value of b is 255, so no granule can match: the index must select a single granule of one
-- row. Before the fix it selected five: a debug build aborted, a release build read too many rows.
SELECT count() FROM t_setidx WHERE a = 1 AND b IN (0) SETTINGS max_rows_to_read = 1;

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.

Reducing this to one query dropped the only CI coverage for the other two new branches in FieldValue::update: the position < 0 mirror and the ColumnNullable unwrap in compareToColumnDomain. The existing gtest_merge_tree_set_index cases do not exercise out-of-domain bounds at all, so with the current diff a future regression in either branch would still leave CI green.

Could you keep one additional focused check for either Int8 at its minimum or Nullable(UInt8)? That would keep the test small without bringing back the full matrix.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, and I checked rather than assuming: neither existing unit test case uses a bound anywhere near a type's limit, so you are right that with the current diff a regression in either of those two branches would leave CI green.

I raised the same gap in the thread above at 15:08Z and left the decision to @rschu1ze, since he asked for the reduction 24 minutes before your comment and adding cases back is his call. I would rather not re-expand the test while that question is open.

If he wants one more case, I would pick the signed key at its minimum over the Nullable one. It is the exact mirror of the direction already covered, and it needs nothing unusual from the table, whereas a Nullable key requires a non-default table setting to be created at all, so it would only pin that branch under an opt-in configuration.

Whichever is added has to carry the same settings as the existing query and be shown to fail without the fix. Without those pins the check is decorative: statistics pruning alone rejects the predicate before the index runs, which took a pre-fix build from failing 12 of 12 runs to failing 2 of 12.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026

This branch has not been deployed

No deployments
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 comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants