Skip to content

Fix a set skip index over a Dynamic or Variant expression dropping every granule - #120780

Merged
al13n321 merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-set-index-dynamic-granule-range
Sep 23, 2026
Merged

al13n321 merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-set-index-dynamic-granule-range

Conversation

@groeneai

@groeneai groeneai commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115581

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):

Fixed a set skip index whose expression has type Dynamic or Variant, which includes an undeclared JSON path such as j.a, silently returning no rows for != and IS NULL. The index reported an unbounded range for such a granule, and index analysis read that as proof that a negated condition is false, so every granule was skipped.

Description

From the AST fuzzer (amd_release, oracle) TLP aggregate mismatch on #115581 (report); not caused by that PR.

Wrong results at default settings:

CREATE TABLE t (d Dynamic, s String,
                INDEX i1 d TYPE set(100) GRANULARITY 1, INDEX i2 s TYPE set(100) GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 4;
INSERT INTO t SELECT number, toString(number) FROM numbers(64);
SELECT count() FROM t WHERE d != 1048577 OR s = 'nope';  -- 0, not 64

With one index: secondary_indices_enable_bulk_filtering = 0.

An undeclared JSON path resolves to Dynamic, which setIndexValidator accepts. MergeTreeIndexSet builds each granule's Range from getExtremes, but ColumnVariant::getExtremes ignores its rows and returns Null() bounds, which Range reads as unbounded. containsRange is then vacuously true, so checkInHyperrectangle calls the atom definitely true, and a negated atom inverts that to definitely false: the granule is dropped before the exact evaluation. The default bulk path never reads the hyperrectangle, hence it survived.

The fix pushes Range::createWholeUniverse() for such a coordinate at both producers, so it cannot exclude a granule; other coordinates keep their ranges. Nothing on disk changes: the hyperrectangle is recomputed per read. minmax refuses these types at DDL; for set only the pre-check was unsound, so refusing would break working tables. A minmax index over Dynamic is still reachable through a hand-written ATTACH and drops granules for =; it is pre-existing and serializes its bounds, so I left it out, but can fold it in if you prefer.

05227_set_index_dynamic_granule_range covers Dynamic, Variant, present and absent JSON paths, a composite index and both routes; its negated and IS NULL arms return no rows on master, its positive-atom controls still prune on both. A unit test pins the range, which no query observes. The reported identity goes from 64 versus 0 to 64 versus 64.


Workflow [PR]
Sync PR [sync-upstream/pr/120780]

Version info

  • Merged into: 26.10.1.490-master (included in 26.10 and later)

An index column of type Dynamic or Variant, which an undeclared JSON path
such as j.a resolves to, took its per-granule Range from getExtremes.
ColumnVariant::getExtremes, which ColumnDynamic delegates to, ignores its
row range and returns Null() for both bounds, so the granule range became
Range(NULL, true, NULL, true).

That range is vacuous in Range arithmetic: a plain-Null bound is neither
< nor == any value, so every early return in intersectsRange and
containsRange fails and both report true. In checkInHyperrectangle a
contained key range means the atom is definitely TRUE on the granule, and
BoolMask::operator! turns that into definitely FALSE for a negated atom,
which returns before the exact evaluation and drops every granule whatever
the data. != and IS NULL therefore returned no rows at all.

The default bulk-filtering path never reads the hyperrectangle, which is
why this went unnoticed; a query with two useful skip indexes and a
disjunction, or secondary_indices_enable_bulk_filtering = 0, routes to the
pre-check and loses rows at otherwise default settings. It was found as a
TLP aggregate oracle mismatch reported by the AST fuzzer on ClickHouse#115581.

Push Range::createWholeUniverse() for such a coordinate at both producers
of set_hyperrectangle, the granule read path and the aggregator build path,
so the coordinate cannot exclude a granule while the other coordinates of a
composite index keep their measured ranges and the exact evaluation over the
stored set still decides. createWholeUniverse is used rather than the
type-aware helper, which would return the WithoutNull universe for Dynamic
and reintroduce the IS NULL half of the bug. Nothing on disk changes: the
hyperrectangle is not serialized, it is recomputed on every read.

Unlike minmax, the set index is not refused at DDL for these types: its
exact evaluation is correct, only the pre-check was unsound, and refusing
would break tables that work today without repairing existing ones.
Review round 1 asked for oracles that the round-0 test did not have. No
source change: MergeTreeIndexSet.cpp is byte-identical.

The aggregator half of the fix had no oracle. The granule range is never
serialized and there is no build-time granule cache, so an ordinary query
always rebuilds it in deserializeBinary and the aggregator's copy is never
read back. Deleting that hunk left every existing arm green.

It is not dead code: WhatIfEmpiricalEstimator builds granules with
createIndexAggregator() and calls mayBeTrueOnGranule on them directly, so
before the fix EXPLAIN WHATIF reports a 100% skip ratio for a hypothetical
set index over a Dynamic column that would in fact skip nothing. Case 10
asserts that estimate, modelled on 04408_hypothetical_index_partial_read,
and pins source: empirical so a fallback to the statistical or
applicability-only estimator cannot silence it. Verified at hunk level:
removing only the aggregator hunk makes exactly this line fail, and the
other 26 assertion lines stay green.

Three count-only arms could also survive a change that stops matching a
JSON subcolumn or a Variant column to the index, which is live right now,
so they gain a Granules: 16/16 plan oracle. The arm labelled bulk did not
pin its route: secondary_indices_enable_bulk_filtering is randomized, so in
half of CI runs it silently duplicated the granule arm.

Arity-1 Tuple(Dynamic) and Tuple(Variant(UInt64, String)) were measured
rather than assumed: both give Granules: 16/16 on the base and fixed
binaries, so no comparison atom is built for a tuple-typed index column at
any arity and no arm was added for them.

no-replicated-database is added because hypothetical indexes are
session-scoped and not replicated.
Review round 2 asked for a direct oracle on set_hyperrectangle. No source
change: MergeTreeIndexSet.cpp is byte-identical.

Nothing asserted what the granule range contains, although changing its
contents is the whole point of the fix. mayBeTrueOnGranule uses the
hyperrectangle only as a conservative pre-filter and otherwise falls through
to the exact scan over the stored set, which is ground truth, so widening a
measurable coordinate to the whole universe changes no query result and no
EXPLAIN granule count. A helper that answered false for every type would
leave every SQL assertion green. The property is not observable from SQL
either: the class emits no ProfileEvents and there is no counter for the
hyperrectangle.

The tests cover both producers of set_hyperrectangle for both kinds of
coordinate: a UInt64 column keeps the bounds measured from its values, and a
Dynamic column gets the whole universe, each asserted on the aggregator's
granule and again after a serializeBinary and deserializeBinary round trip,
which is the path a query takes when it reads the index from a part. The
last test builds a composite (Dynamic, UInt64) index from two blocks and
pins the per-coordinate alignment: the second block widens the measurable
coordinate to the union of both blocks while the Dynamic coordinate is
neither re-pushed nor widened.

Every bound is checked with its inclusion flags. The exclusive universe is
contained in the range an IS NULL atom carries and KeyCondition inverts that
mask, so a later switch to createWholeUniverseTypeAware, which returns the
exclusive universe for a non-Nullable type such as Dynamic, would again drop
every granule; asserting left_included and right_included makes that fail
here rather than in a row count.

Measured against the base source: the two Dynamic arms fail on both
producers while the measurable arms pass, and forcing the helper to false
reddens the measurable arms and the composite coordinate instead.
hasMeaningfulFieldExtremes recurses into children, so a Tuple(UInt64, Dynamic)
index column also gets the whole universe instead of measured bounds. Nothing
pinned that recursion: dropping it left every existing assertion green, because
ColumnTuple::getExtremes then writes Tuple Fields as the bounds, and no query
can see the difference (KeyCondition builds no granule-excluding atom for a
tuple-typed index column at any arity, so a SQL arm would assert nothing).
The granule bounds are only reachable from C++, which is where this belongs.
hasMeaningfulFieldExtremes rejects a Variant child as well as a Dynamic one,
and nothing pinned that half of the recursive condition: deleting only
`|| isVariant(child)` left all five existing unit tests and all 27 assertion
lines of the SQL test green, because the one nested arm is
Tuple(UInt64, Dynamic) so the isDynamic child arm still fires, and the Variant
arm of the SQL test is top level. Tuple(UInt64, Variant(UInt64, String)) is a
declarable index coordinate with the same pathology, since ColumnTuple's
getExtremes delegates per element to the ColumnVariant placeholder that
ColumnDynamic also delegates to, so the bounds become Tuple{0, Null} and
Tuple{9, Null} instead of the inclusive whole universe. As with the Dynamic
case, no query observes those bounds, so the assertion belongs in C++.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex), five rounds: 7 gate findings plus 8
from my own cold passes. The fifth round raised nothing from either source, and the 26-line source fix
has been byte-identical since the first round; every finding below is about test coverage or wording.

# Sev Finding Verdict Evidence / action
1 ⚠️ The build-path range has no oracle: deleting the aggregator hunk in MergeTreeIndexSet.cpp leaves every new arm green, and that range is consumed directly by empirical EXPLAIN WHATIF AGREE, fixed @ 3922331 WhatIfEmpiricalEstimator is its only live consumer and reported a 100% skip ratio for an index that skips nothing; a new EXPLAIN WHATIF arm covers it, and deleting only that hunk now moves exactly that assertion line
2 ⚠️ The negated and IS NULL arms assert counts only, so a change that stops matching the column to the index keeps them green AGREE, fixed @ 3922331 Narrowed: the plain Dynamic arm already had a Granules: 1/16 control. Added a Granules: 16/16 plan oracle to the plain Dynamic, JSON subcolumn and Variant arms
3 💡 The arm labelled bulk pins neither routing setting, so its route varies between runs AGREE, fixed @ 3922331 The arm now pins secondary_indices_enable_bulk_filtering = 1. Refused the second half: use_skip_indexes_on_data_read cannot route around the hyperrectangle, since the read-time path calls the same filterMarksUsingIndex
4 💡 The recursive wrapper branch of the type predicate has no regression coverage AGREE, fixed @ 3d4bff7 (raised twice, so not overridden) No SQL arm can reach it: Array(Dynamic), Map(String, Dynamic) and Tuple(UInt64, Dynamic) all report Granules: 16/16 and identical counts on both binaries, so no comparison atom reaches the pre-check. Once finding 8 added unit tests that read the granule range directly, a dedicated Tuple(UInt64, Dynamic) arm pins it, with a proof that deleting only the recursion reddens it and nothing else
5 ⚠️ The PR body claimed every test arm fails on master AGREE, corrected in the body Three arms are positive-atom controls that pass on both binaries by design: the pre-check never pruned this coordinate, so the surviving pruning comes from the exact evaluation over the stored set, which this change does not touch
6 ⚠️ The minmax sibling carrier was disposed of as a PR-body disclosure AGREE, body reworded A hand-written ATTACH bypasses minmaxIndexValidator, and WHERE d = 3 then returns 0 rows with Granules: 0/1; that is a positive-atom failure with an on-disk dimension this fix does not have, so the body now offers to fold it in rather than announcing the exclusion
7 💡 The composite arm covers only the order (d, k) DISAGREE The guard pushes exactly one range per coordinate in index order, so (k, d) measures coordinate 0 and widens coordinate 1 on the first block and skips it afterwards. No failure mode to assert. Round 2 asserts the two-coordinate case directly at unit level anyway
8 ⚠️ Nothing asserts what the granule range CONTAINS: if the type predicate returned false for every type, measurable coordinates would silently lose their measured bounds and every test output would still stay green AGREE, fixed @ db6d3b2 Confirmed, and there is no cheaper oracle: the class emits no ProfileEvents and there is no hyperrectangle counter, so the pre-check is not observable from SQL at all. Added direct bound assertions in gtest_index_set.cpp for both sides of the predicate at both producers, including the serialize/deserialize round trip and a two-block mixed (Dynamic, UInt64) index, with a both-directions mutation proof
9 💡 no-replicated-database is needed only by the EXPLAIN WHATIF arm but applies to the whole file Noted, not actioned True, but every arm exercises MergeTree skip-index granule ranges, which are database-engine agnostic, and splitting one case into its own file duplicates the whole preamble for no measured gain
10 💡 The EXPLAIN WHATIF arm does not pin secondary_indices_enable_bulk_filtering Noted, not actioned The hunk-level mutation proof plus 100 randomized runs is stronger evidence of liveness than a pin, and that table has no materialized index for bulk filtering to route
11 💡 The nested case pins Dynamic inside a wrapper but leaves the sibling nested Variant condition unpinned AGREE, fixed @ ed0df4f Deleting only the nested-Variant condition reddened nothing, yet Tuple(UInt64, Variant(...)) is declarable and has the same placeholder behaviour, since ColumnTuple::getExtremes delegates per element to the same ColumnVariant::getExtremes that Dynamic uses. A matching arm now pins it: deleting either condition of the recursive check reddens exactly its own arm

Also checked, unraised: the rows_to_read == 0 early return that skips set_hyperrectangle.clear() is
unreachable, because mayBeTrueOnGranule returns true on an empty granule before it reads the range.

Provenance, since the changelog category asserts it: the pre-check this fixes arrived in
7a27b10ef5a9a (2024-06-24) and first shipped in v24.7.1.2915-stable.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Review sessions: cron:clickhouse-review-slot-9:20260917-203900 (round 0),
cron:clickhouse-review-slot-8:20260918-023800 (round 1),
cron:clickhouse-review-slot-8:20260918-065800 (round 2),
cron:clickhouse-review-slot-49:20260918-082200 (round 3),
cron:clickhouse-review-slot-48:20260918-102000 (round 4)

@clickhouse-gh clickhouse-gh Bot closed this Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, twice over: two set indexes plus a disjunction returns 0 instead of 64 at default settings, and a single index does the same with secondary_indices_enable_bulk_filtering = 0.
b Root cause explained? ColumnVariant::getExtremes (which ColumnDynamic delegates to) ignores its row range and returns Null() for both bounds, so the granule Range is [NULL, NULL]. A plain-NULL bound is neither < nor == any value, so containsRange is vacuously true, checkInHyperrectangle calls the atom definitely true, and BoolMask::operator! inverts it to definitely false for != / IS NULL, dropping every granule before the exact evaluation.
c Fix matches root cause? Yes: the placeholder no longer becomes a range, at both set_hyperrectangle producers. No widened bound, no disabled setting, no guard at the drop site; the exact evaluation over the stored set still decides.
d Test intent preserved / new tests added? New 05227_set_index_dynamic_granule_range, 10 cases / 27 assertion lines: 3 Granules: 1/16 positive controls, 3 Granules: 16/16 plan oracles that also fail if the index stops being matched to that column, and one EXPLAIN WHATIF estimate that is the only oracle for the aggregator build path. Plus 5 unit tests in gtest_index_set.cpp asserting the granule range itself, which no query can observe because the range is only a conservative pre-filter. No existing test weakened.
e Both directions demonstrated? Yes. 11 of the 27 assertion lines return the wrong value on a pristine base build and the right one with the change, while the 3 controls are identical on both; Build-IDs differ (fbcc2905... base, f5841339... fix) and each server was asserted with SELECT lower(buildId()) before its results were used. The reported oracle identity goes from 64 versus 0 to 64 versus 64. Each of the three source hunks is pinned by its own mutation, and each of the four conditions in hasMeaningfulFieldExtremes separately: dropping only the isDynamic(child) disjunct fails exactly the Tuple(UInt64, Dynamic) test, dropping only isVariant(child) fails exactly the Tuple(UInt64, Variant(UInt64, String)) test, each leaving the other 5 unit tests green.
f Fix is general across code paths? Both producers fixed (granule read path and aggregator build path); grep confirms exactly two producers and one reader. Every other getExtremes consumer under src/Storages/ was classified by measurement: part-level minmax and minmax statistics cannot hold these types (Code: 549, Code: 708), patch-part pruning requires a minmax index and throws otherwise.
g Fix generalizes across inputs? Arms cover Dynamic, Variant, a JSON path present in every row, a JSON path absent from every row, a composite (d, k) index, !=, IS NULL, =, and both routes into the pre-check. NOT IN on Dynamic is refused by the function itself (Code: 43) and container-typed index columns build no comparison atom at any arity, so neither is asserted vacuously; the wrapper shape is covered where it is observable, by the Tuple(UInt64, Dynamic) and Tuple(UInt64, Variant(UInt64, String)) unit tests. Nullable(Dynamic) cannot exist.
h Backward compatible? Yes. No setting, no SettingsChangesHistory entry, and nothing on disk changes: serializeBinary writes only the row count and the columns, and the hyperrectangle is recomputed on every read, so old and new parts interoperate in both directions.
i Invariants and contracts preserved? The widened coordinate can only make the pre-check less selective, never more, so no granule that used to be read is now skipped (three controls assert the surviving pruning through EXPLAIN indexes = 1). set_hyperrectangle still gets exactly one entry per index column on every path, preserving its positional pairing with index_data_types. The skipped getExtremes call had no side effects and its result was unused.

Session id: cron:clickhouse-impl-slot-4:20260918-100600

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ed0df4f]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the set skip-index hyperrectangle for Dynamic/Variant-typed coordinates by substituting Range::createWholeUniverse() on both the write-time aggregator path and the read-time deserialization path, then adds focused SQL and unit coverage for the broken !=/IS NULL cases, the bulk-vs-granule split, the EXPLAIN WHATIF build path, and nested wrapper types. I did not find a correctness, compatibility, or coverage blocker in the current revision.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit ed0df4f.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 80.60% 80.70% +0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. label Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ed0df4f

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff CI-infrastructure: the job aborts with RuntimeError: CI logs cluster query failed in compare_symbols (ci/jobs/build_profile_diff_job.py:1375); 180 distinct PRs carry it today #118708 (mine, open)

Session id: cron:our-pr-ci-monitor:20260918-220128

@al13n321
al13n321 added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 6a2edb4 Sep 23, 2026
174 of 349 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
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-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants