Repository navigation
Skip a value-preserving narrowing cast in an index condition, and fix pruning for a cast into Bool - #116656
Skip a value-preserving narrowing cast in an index condition, and fix pruning for a cast into Bool#116656groeneai wants to merge 8 commits into
Conversation
…ange the value KeyCondition::applyMonotonicFunctionsChainToRange can skip applying a chain function when the function provably cannot change the Field. The gate, functionIsIntegerCastPreservingFieldRepresentation, decided this from the declared type widths alone, so a narrowing integer cast never took the fast path and every granule paid a full IFunctionBase::execute on a freshly built one-row const column. The minmax skip index is where that hurts. A minmax granule's Range holds plain deserialized Fields, so applyFunction takes its FieldRef::isExplicit branch straight into applyFunctionForField and structurally bypasses the whole-column memo below it: the conversion is re-executed per range endpoint, per chain function, per granule. Monotonicity is not enough to decide this, which is why the width proxy was there: ToNumberMonotonicity's shrink branch only requires both endpoints to sit in the same 2^bits block, and on a block above 0 every value shifts. The values, however, are in hand at the decision point, so test them: a narrowing cast is the identity exactly on endpoints that already fit the target type. Any endpoint that would truncate falls through to the existing application path, so the returned Range is unchanged for every input. The skip is taken only when both bounds are FieldRef::isExplicit. A real application advances the cached column alongside the threaded type, while a skip advances only the type, so skipping for a bound that references an index block would leave a later chain link reading a column of the previous physical type. Every consumer that carries the win has explicit bounds (minmax granules, partition values, statistics, part-level minmax); the one block-referencing path is the primary key, where the whole-column memo already amortizes the conversion. Reported by egor-click with the measurement on tests/performance/min_max_index_with_cast.xml. Related: ClickHouse#116580 Related: ClickHouse#55653 Co-Authored-By: Claude Opus 5 <[email protected]>
Bool is DataTypeUInt8 wearing DataTypeCustomFixedName, so its type id is TypeIndex::UInt8 and its size is 1. It therefore passed the integer-family and width tests in functionIsIntegerCastPreservingFieldRepresentation and was treated as a value-preserving conversion. It is not: a cast into Bool normalises every nonzero value to 1, at every source width. Measured on a minmax index over a UInt64 column with a Bool ALIAS, granule values 8..15 in one part and 300..307 in another: SELECT count() FROM t WHERE f = true returns 8 instead of 16, because the granule range [8, 15] is carried through unchanged and relabelled Bool, and 1 is not in [8, 15]. The same-size UInt8 -> Bool spelling returns 0 instead of 8 and does so on master as well, since the width test alone already accepted it. Both are fixed here by declining a Bool target outright unless the source is also Bool. Bool as a source still takes the fast path, and Bool is the only custom-named type over an integer base, so the exception is closed: the remaining registerSimpleDataTypeCustom entries are Geo types over Array and Tuple, which the family test declines already. The condition leads with hasCustomName() because isBool() is a getName() string comparison and getName() returns String by value, while this predicate runs once per chain function per granule. isBool(t) implies hasCustomName(t), so the extra term cannot change the result. Measured on the min_max_index_with_cast fixture, 21 interleaved rounds: without it the frozen query costs 1.0968x, with it 1.0000x. Two arms added to 04947, one per code path. Removing the guard reddens both and nothing else; moving it below the width test reddens only the same-size arm, which is why both arms are kept. The 585-cell differential sweep and the headline measurement are unchanged: 583 ms to 34 ms on the frozen query, output identical to master everywhere except the Bool target, where master silently drops matching rows. Also drops two comments that over-claimed what the width test proves.
Both Bool fixtures held only nonzero values, so `WHERE f = true` matched every row and the two `count()` arms returned 16 and 8 whether the index condition pruned correctly, pruned nothing, or was bypassed by a full scan. They pinned over-pruning only; nothing pinned that such a condition still prunes, so a later change that made the Bool atom unanalysable and fell back to a full scan would have left the whole file green. Add one all-zero part per table, which is the only prunable one, and one `EXPLAIN indexes = 1` assertion per width path. The two `count()` arms still read 16 and 8, since the new rows are false. The assertion keys on the statistics part pruner's line rather than the minmax index's: at default settings the all-zero part is dropped there first, so the skip index reports nothing left to do. Both pruners build a KeyCondition and reach applyMonotonicFunctionsChainToRange, so either one exercises the predicate under test. `sum()` rather than `count()` because a trivial-count plan can omit the read step entirely. Liveness: making a Bool chain link decline analysis altogether reddens exactly the two new arms and leaves both `count()` arms green, so they carry coverage the old arms cannot. Removing the Bool guard reddens all four; moving it below the width test reddens only the same-size pair, which is what shows the two width paths are not redundant. Test only; no change to src/.
The two `Granules` arms matched a string the statistics part pruner emits, not one from `i_f`. Automatic column statistics default to `basic, uniq_v2` and `addImplicitStatistics` applies them to every non-system table, so `t_bool_narrowing` and `t_bool_same_size` carry a `basic` statistic on `w`/`u` without declaring `STATISTICS`. `filterPartsByStatistics` runs ahead of skip indexes and dropped the all-zero part first, so the plan read `Statistics` `Granules: 4/5` followed by `Skip i_f` `Granules: 4/4`: the assertion matched the former, and `i_f` had nothing left to do. Dropping `INDEX i_f` would have left both arms green, which is the failure class they were added to close. `use_statistics_for_part_pruning = 0` ahead of the first of the two arms puts the pruning back on the index. It is a query-level setting, so it stays in effect for the rest of the file and covers both arms, and it beats runner injection. With it in place `i_f` itself reports `Granules: 4/5` and `Granules: 2/3`, so neither reference value changes; adding `use_skip_indexes = 0` reddens each arm, which is what shows it now measures the index. The pin also removes a non-determinism. `clickhouse-test` randomizes `auto_statistics_types`, yielding an empty value in 30% of runs and otherwise a random sample of the five types, so whether `basic` was present, and therefore which pruner emitted the matched string, varied from run to run. The arms passed either way, but an arm should measure one thing. Deliberate consequence: `t_bool_narrowing`'s `count()` arm precedes the `SET` and so keeps statistics pruning on, while `t_bool_same_size`'s follows it with statistics pruning off, giving one `count()` arm per consumer. Test only; no change to src/.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model, four rounds (engine: codex). 7 gate findings over
Session id: cron:clickhouse-review-slot-10:20260827-063800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260827-062000 |
|
Workflow [PR], commit [ef0b547] Summary: ✅
AI ReviewSummaryReviewed #116656 at Missing context / blind spots
Final VerdictStatus: ✅ Approve. No review changes required; remaining CI should complete before merge. |
|
cc @CurtizJ @alesapin, could you review this? It stops applying a narrowing integer cast per granule in an index condition when the analysed range endpoints already fit the target type, and it declines a cast into |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - eb4d579CI is fully finished at this commit. Two checks failed, and each has an owner.
Reports: Everything else at this commit is green: 178 praktika nodes, 150 Session id: cron:our-pr-ci-monitor:20260827-120000 |
…ing-cast-fast-path # Conflicts: # src/Storages/MergeTree/KeyCondition.cpp
Comment-only change: drop the comments that described the new code's own design (why hasCustomName is tested first, why a skip is cheaper, the narrowing branch narration) and keep the local invariants. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ing-cast-fast-path Master renamed `functionIsIntegerCastPreservingFieldRepresentation` to `functionIsCastPreservingFieldRepresentation` and extended it to `DateTime` / `toUnixTimestamp`; the narrowing-cast range check now lives in the renamed function and uses `is_uint_or_datetime` for the target signedness. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when a conversion to
Boolsits in aMergeTreeindex condition: granules whose values are all nonzero could be pruned away, so matching rows went missing silently. Reachable since 26.5 through aBoolALIASorCASTover an integer column that a minmax index or column statistics cover. Separately, a narrowing integer conversion is no longer applied for every granule when the analysed range endpoints fit the target type, which makes index analysis about 20x faster and the whole query about 17x faster on the reported workload.Description
Closes #116580, reported by @ egor-click with the measurement and a proposed patch; implemented here with two added preconditions.
The cost. A minmax index declared on
mortonDecode(2, z).1(UInt64) but queried through aUInt16ALIASputs an implicit_CAST(..., 'UInt16')in the index condition's function chain.KeyConditionalready skips a conversion that cannot change theField, butfunctionIsIntegerCastPreservingFieldRepresentationdecided that from the declared widths alone, so a narrowing cast never qualified and every granule paid a fullIFunctionBase::executeon a one-row const column.Why monotonicity is not enough.
ToNumberMonotonicity's shrink branch requires only that both endpoints sit in one2^bitsblock, and in a block above zero every value shifts. The endpoints are in hand at the decision point, so I test those instead: the cast is the identity exactly on endpoints that fit the target type. An endpoint that would truncate falls through to the existing application.Precondition 1. Both bounds must be
FieldRef::isExplicit: a real application advances the cached column alongside the threaded type, a skip advances only the type. The skip-index and statistics consumers have explicit bounds, as do the partition-minmax constant coordinates of unloaded primary-key columns; the in-memory primary-key index's block-backed bounds do not, and already amortise the application through the column cache.Precondition 2, the bug fix.
Boolis aUInt8with a custom name, so it reached the width test, yet a conversion intoBoolnormalises a nonzero value to 1. The same-width case is already wrong today, and the narrowing case would have become wrong here; one guard above the width test covers both.Widening casts are still skipped with no
isExplicittest, so a chain of three or more monotonic functions over a primary key reaches that divergence and throws aLOGICAL_ERROR; measured identically on master and on this branch, so it is pre-existing and left to a separate change. The report's two memoisation ideas are out of scope.Validation (click to expand)
Release build,
clang++-22, x86_64, same compiler and fixture both arms. Medians of 21interleaved rounds,
max_threads = 1; reproduced in a second session after a restart.SelectedMarks,read_bytesandmemory_usageare identical. The primary-key control's secondtimer read 1.25x, +15us on 320us, p10-p90 overlap.
ProfileEvents::FunctionExecutedoes notinstrument this path, hence the phase timer.
Correctness: 585 cells over 15 type pairs (narrowing, plus widening, same-size,
Nullable,LowCardinalitycontrols), 13 endpoint classes (block boundaries, 0, target min/max and one past,negative, open) and 3 consumer paths; all identical in result,
EXPLAIN indexes = 1and
SelectedMarks; 218 prune.Boolwas measured on three binaries with disjoint failuresets: before this change the same-width shape is wrong, without the guard both are, as shipped
neither; ground truth from a
Memorytable, both pruners off.Blast radius: all 10 index-adjacent perf tests, 0.654-1.050, answers identical wherever
deterministic (two
set_indexqueries are not; two more hit my harness's argv limit and did notrun);
minmax_index_insert0.988 covers writes.New test
04947_minmax_index_narrowing_cast, 13 arms, 50/50 green under randomization.Mutants: accepting every narrowing cast breaks 5 arms, never skipping leaves all 13 green, dropping
isExplicitfails only the primary-key arm, removing theBoolguard only its four arms, moving itbelow the width test only the same-width pair, and a declining
Boollink only the two pruning arms.Workflow [PR]
Sync PR [sync-upstream/pr/116656]