Skip to content

Optimize minmax skip index evaluation performance - #100366

Merged
alexey-milovidov merged 49 commits into
masterfrom
optimize-minmax-skip-index-eval
May 10, 2026
Merged

alexey-milovidov merged 49 commits into
masterfrom
optimize-minmax-skip-index-eval

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 22, 2026 •

Copy link
Copy Markdown
Member

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

Closes #55653

Changelog category (leave one):

  • Performance Improvement

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

  • Merged into: 26.5.1.501

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]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [178e3af]

Summary: ✅


AI Review

Summary

This PR optimizes minmax skip-index evaluation by adding fast paths in accurateEquals/accurateLess/accurateLessOrEqual, skipping redundant monotonic cast application when Field representation is preserved, avoiding Range copies in checkInHyperrectangle, and reusing MergeTreeIndexGranuleMinMax storage during deserialization. I did not find new correctness, safety, or compatibility issues in the current PR head, and prior inline concerns about Null/infinity semantics are addressed in code and covered with focused stateless tests.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ✅
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 22, 2026
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]>
Comment thread src/Common/FieldAccurateComparison.cpp Resolved
Comment thread src/Common/FieldAccurateComparison.cpp Resolved
@alexey-milovidov
alexey-milovidov marked this pull request as draft March 22, 2026 14:46
alexey-milovidov and others added 4 commits March 22, 2026 14:49
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]>
Comment thread src/Common/FieldAccurateComparison.cpp Resolved
alexey-milovidov and others added 12 commits March 29, 2026 00:12
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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.

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review May 9, 2026 15:38
Comment thread src/Common/FieldAccurateComparison.cpp Resolved
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 alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Overall, the change looks good. Only a few questions remain.

@alexey-milovidov alexey-milovidov self-assigned this May 9, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@EmeraldShift, this is an ad-hoc optimization for a narrow case. Your optimization will be useful regardless.

@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 80.00% (128/160) | lost baseline coverage: 9 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 10, 2026
Merged via the queue into master with commit c31e45e May 10, 2026
165 checks passed
@alexey-milovidov
alexey-milovidov deleted the optimize-minmax-skip-index-eval branch May 10, 2026 22:32
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 10, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Jun 6, 2026
`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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements 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.

Secondary index is slower than full scan

3 participants