Repository navigation
Optimize minmax skip index evaluation performance - #100366
Conversation
The evaluation of minmax skip indexes was extremely slow when the index expression involved type casts (e.g., mortonDecode(2, z).1 with a UInt16 alias). The bottleneck was in `applyMonotonicFunctionsChainToRange` which was called per-granule (~175K times), each time creating columns and executing functions via the full column execution machinery. Three optimizations: 1. Skip function application in monotonic chains when the function preserves Field representation (e.g., CAST between UInt types that all use UInt64 in Field). The monotonicity check already verifies values fit in the target type, so the Field values are unchanged. 2. Add fast paths to `accurateLess`, `accurateEquals`, and `accurateLessOrEqual` for common same-type comparisons (UInt64, Int64, Float64, Null), avoiding the expensive double visitor dispatch over the 24-type matrix. 3. Optimize `MergeTreeIndexGranuleMinMax::deserializeBinary` to update Range objects in-place on subsequent calls (when the granule is reused), avoiding vector clear/rebuild and Field copy-constructions. 4. Avoid copying Range in `checkInHyperrectangle` when there is no monotonic function chain (the common case). Benchmark on the reproducer from #55653 (1.4B rows, mortonDecode minmax index): skip index evaluation improved from 1.8s to 0.11s (16x), making it faster than the full scan (0.17s). #55653 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [178e3af] Summary: ✅ AI ReviewSummaryThis PR optimizes minmax skip-index evaluation by adding fast paths in ClickHouse Rules
Final Verdict
|
Test exercises the case from #55653 where the index expression type (UInt64 from `mortonDecode`) differs from the query condition type (UInt16 alias), causing a CAST in the monotonic function chain that is evaluated per-granule. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The `Null` Field type encodes three distinct sentinels: regular NULL, `-Inf`, and `+Inf`. The fast paths had two bugs: 1. `accurateEquals`: used `isNull()` comparison which treated `-Inf` and `+Inf` as equal. Fixed to compare both infinity flags. 2. `accurateLessOrEqual`: returned `true` unconditionally for Null pairs, making `+Inf <= -Inf` true. Fixed to check `!(right.isNegativeInfinity() && left.isPositiveInfinity())`. Also fixed cross-type Null handling to match the semantics of `!less(right, left)`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The `functionPreservesFieldRepresentation` check was too broad: it skipped function application for ANY function with compatible integer input/output types (e.g., UInt32 → UInt32). This is only correct for pure type conversion functions like `_CAST` and `toUInt*`/`toInt*`, where the Field value doesn't change when the function is monotonic. For arithmetic functions like `plus(x, 2)` with UInt32 → UInt32, skipping the application gave wrong key ranges, causing incorrect granule filtering in primary key and partition pruning. Fixed by checking the function name to ensure it's a type conversion. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ainToRange` The `functionIsIntegerCastPreservingFieldRepresentation` optimization incorrectly skipped function application for narrowing casts (e.g. UInt32 -> UInt16, Int32 -> Int16). While both source and target types use the same Field representation (UInt64 or Int64), narrowing casts truncate the value (e.g. `toUInt16(131072)` = 0), so the optimization must only apply to widening or same-size casts. This caused test `00653_verification_monotonic_data_load` to fail because granules with large values that should have matched after truncation were incorrectly skipped. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…d NaN Test exercises -Inf/NULL/+Inf ordering and NaN handling through minmax skip index range analysis on Nullable(Int64) and Nullable(Float64) columns. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… for Nullable types `getSizeOfValueInMemory` throws for Nullable types because they don't have a fixed size. Return false early when either type is Nullable since this optimization only applies to plain integer type casts. Fixes the failing test `04004_cast_nullable_monotonicity_key_condition`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…tionIsIntegerCastPreservingFieldRepresentation` The function called `getSizeOfValueInMemory` before checking that both types are integers, causing an exception for variable-length types like String, FixedString, and LowCardinality(String). Move the integer family check before the size comparison. Also fix incorrect expected output in test 04064 reference file. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The test `04064_minmax_index_null_inf_ordering` expected `WHERE val = nan` to return NaN rows, but in ClickHouse `NaN = NaN` evaluates to 0 (IEEE 754), so the query correctly returns no rows. Fix the reference file accordingly. Also fix minor typo in `MergeTreeIndexMinMax` comment. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
…ontent Avoid GitHub workflow scope rejection on push.
After merging master, restore the workflow file to master's current content to fix the `Check Workflows` CI failure.
… content Avoid GitHub workflow scope rejection on push.
The PR no longer needs to modify `.github/workflows/retry_infra_failures.yml` or `.github/workflows/auto_releases.yml`; restore them to match `master` so the PR's diff only contains the minmax skip-index optimization. Addresses the unresolved review comment "These changes are not relevant to the PR. Move them into a separate PR."
alexey-milovidov
left a comment
There was a problem hiding this comment.
Overall, the change looks good. Only a few questions remain.
|
@EmeraldShift, this is an ad-hoc optimization for a narrow case. Your optimization will be useful regardless. |
LLVM Coverage Report
Changed lines: 80.00% (128/160) | lost baseline coverage: 9 line(s) · Uncovered code |
`ConverterUUID::getBatch` reuses a member `PODArray<UUID> swapped_buf`, filling `buf[i].ptr = &swapped_buf[i]` before returning. The Parquet writer loop then feeds those pointers into `StatisticsFixedStringRef`, which keeps raw `const uint8_t *` `min`/`max`. After a page is flushed, `total_statistics.merge(page_statistics)` propagates these pointers into `total_statistics`. When the next batch of values exceeds the current capacity (e.g. after a low-density null run, where `data_count` swings from near 0 to near `write_batch_size`), `swapped_buf.resize(count)` reallocates and frees the prior buffer. The `total_statistics.min`/`max` pointers are now dangling. The next call to `merge` performs `memcmp(p, total_statistics.min, 16)` and reads from freed memory — heap-use-after-free, detected by AddressSanitizer in BuzzHouse with STID 1288-3e88. Switch `ConverterUUID::Statistics` to `StatisticsFixedStringCopy<16, false>`, which stores min/max as inline 16-byte arrays and copies bytes via memcpy on update/merge, eliminating the lifetime dependency. UUIDs are written big-endian and Parquet's UUID logical type compares as unsigned binary, so `SIGNED=false` is correct. Other Parquet converters using `StatisticsFixedStringRef` / `StatisticsStringRef` (e.g. `ConverterFixedString`, `ConverterString`, `ConverterEnumAsString`) point into the source column's stable storage (`column.getChars()`, the enum's name table) rather than an owned buffer that resizes between batches, so they are unaffected. Add a stateless regression test that triggers the bug pre-fix and passes post-fix: 100k Nullable(UUID) rows with clustered nulls, small `output_format_parquet_data_page_size`, custom encoder enabled. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100366&sha=f8d1795edeee81e2ec015f68c1a82721803c80f8&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29 PR with original sanitizer hit: ClickHouse#100366
The evaluation of minmax skip indexes was extremely slow when the index expression involved type casts (e.g.,
mortonDecode(2, z).1with aUInt16alias). The bottleneck was inapplyMonotonicFunctionsChainToRangewhich was called per-granule (~175K times), each time creating columns and executing functions via the full column execution machinery.Three optimizations:
Skip function application in monotonic chains when the function preserves Field representation (e.g., CAST between UInt types that all use UInt64 in Field). The monotonicity check already verifies values fit in the target type, so the Field values are unchanged.
Add fast paths to
accurateLess,accurateEquals, andaccurateLessOrEqualfor common same-type comparisons (UInt64, Int64, Float64, Null), avoiding the expensive double visitor dispatch over the 24-type matrix.Optimize
MergeTreeIndexGranuleMinMax::deserializeBinaryto update Range objects in-place on subsequent calls (when the granule is reused), avoiding vector clear/rebuild and Field copy-constructions.Avoid copying Range in
checkInHyperrectanglewhen there is no monotonic function chain (the common case).Benchmark on the reproducer from #55653 (1.4B rows, mortonDecode minmax index): skip index evaluation improved from 1.8s to 0.11s (16x), making it faster than the full scan (0.17s).
Closes #55653
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up the index analysis involving type casting and function application. Closes #55653.
Version info
26.5.1.501