Repository navigation
Vectorize minmax index evaluation - #103526
EmeraldShift wants to merge 69 commits into
Conversation
Adds a performance test that measures wall-time cost of the minmax skip index evaluator in the two regimes where it tends to dominate: - A time-partitioned table with a minmax index on the partition-key column, exercised by range queries that fully cover interior partitions (the common observability shape). - A single wide part, optimized into one part, with two minmax indices on non-partition columns. Queries pass every granule or just above half, so per-granule evaluator cost surfaces without being diluted by data-scan work. Both tables use GRANULARITY 1 so there is one minmax entry per index_granularity rows, putting as many granules in front of the evaluator as possible. Reproduces the workload shape from issue ClickHouse#103292.
The existing minmax evaluator runs `Range::intersectsRange` and `Range::containsRange` per granule, each going through two variant-visitor dispatches on `Field`s whose tags are fixed for the entire query. When the skip index has to consider many granules (Observability, GRANULARITY 1, large parts), this Field dispatch dominates skip-index time and generalizes poorly to new column types. Lower the condition's RPN into a column-engine expression over paired (min, max) columns at condition-construction time. Bulk evaluation of a part becomes a single `ExpressionActions::execute` over those columns, producing "can-be-true" and "can-be-false" output columns per granule. Compare, AND, OR, NOT are delegated to the column engine's standard kernels, which are already SIMD-vectorized for the common numeric types and generalize to every type the column engine supports. The lowered DAG also benefits from `compile_expressions` JIT when the same condition shape is reused across queries. Unsupported RPN shapes (monotonic function chains, space-filling curves, polygons, bloom filters, relaxed predicates, non-collapsed IN_SET) leave the DAG unbuilt and the caller falls back to the generic per-granule path; this is safe for correctness and simply forgoes the speedup. Controlled by the new session setting `use_minmax_index_bulk_filtering` (default off). When the DAG cannot be built for a condition, the bulk path is skipped entirely so the caller doesn't pay bulk deserialization cost for no pruning benefit. Bulk filtering composes with `use_skip_indexes_for_disjunctions` when this index's own projected condition is a pure conjunction of leaves (no `OR` in the projected per-index RPN). In that case the disjunction-merge's bitset defaults of `true` coincide with the per-granule actual values that bulk's skipped callback path would have written, so precision is preserved. When the projected per-index condition itself contains an `OR`, bulk filtering is skipped for that index and the caller falls back to the generic per-granule path, which correctly populates the bitset. This covers the common observability shape `(time_range) AND (OR over another column)` without regressions.
The bulk minmax deserializer previously round-tripped each granule's min and max through `Field` before inserting into the typed column. For fixed-width numeric types (integers, floats, `Date`, `DateTime`, `Enum`) the on-disk representation is byte-identical to the `ColumnVector` container layout, so the `Field` layer is pure overhead: two virtual calls and a variant tag check per granule per column. Classify each index column at bulk-container construction. For the supported numeric families, read min and max directly into the typed column's backing storage. For `Nullable`, `Decimal`, `String`, `DateTime64`, `UUID`, `IPv4`/`IPv6`, and anything else, keep the existing `Field`-based path unchanged.
Bulk evaluation previously materialized every granule of a part into the bulk container before running the condition. On a wide multi-column minmax index over a multi-billion-row part this adds up to substantial working memory, and each call into the index reader pays dispatch overhead amortized only across one granule. Read and evaluate granules in chunks of up to `max_block_size`. Each chunk owns its own bulk container, which is released before the next chunk begins; working memory is bounded at `O(chunk_size × num_index_cols)` regardless of part size. A new bulk entry point on the index reader and a bulk override on the minmax bulk granules collapse the per-granule reader dispatch to per-chunk. The underlying compressed read buffer continues to stream decompressed blocks on demand; chunk boundaries are independent of block boundaries.
|
cc @alexey-milovidov since you've also been working on optimizing minmax indexes. My PR is pretty rough, but does it look like it's going in a good direction? |
|
Workflow [PR], commit [29fb505] AI ReviewSummaryThis PR adds an opt-in vectorized evaluation path for minmax skip indexes, threads it through analyze-time and runtime-filter skip-index analysis, and chunks bulk reads by Findings
Tests
Final Verdict |
`Enum8` stores values in `ColumnVector<Int8>` but was classified as `FastKind::U8`, so the fast-path `assert_cast<ColumnVector<UInt8>>` in `fastReadPair` could throw an exception at runtime when `use_minmax_index_bulk_filtering = 1` and an `Enum8` minmax index was read. Route `Enum8` to the `I8` fast path; `Enum16` was already correctly grouped with `I16`. Also drop two `std::move` calls that clang-tidy (`performance-move-const-arg`) flagged as no-ops because `ColumnWithTypeAndName` takes its arguments by const reference. CI report: ClickHouse#103526 AI review flagged the `Enum8` fast-kind misclassification. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The style check (`various_checks.sh`) flags any test that mentions `system.query_log` without a `current_database = currentDatabase()` filter. The test no longer queries `system.query_log` — earlier versions checked observability via `query_log`, but the test was rewritten to a parity-by-count structure. Update the `no-parallel-replicas` rationale to describe the actual reason (per-query SETTINGS toggling skip-index evaluation paths must take effect on the executing replica). CI report: ClickHouse#103526 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The new `MergeTreeIndexConditionMinMax` constructor calls
`tryBuildMinMaxActions` unconditionally during query analysis, even
when `use_minmax_index_bulk_filtering` is off. When a `KeyCondition`
range bound's `Field` does not match the index column's exact
`DataType` (e.g. a `UInt64`-tagged `Field` against a `Decimal64`
`DateTime64` column), `IDataType::createColumnConst` throws
`Bad get: has UInt64, requested Decimal64.` and fails the whole
query. Reproduced by `02439_merge_selecting_partitions` and
`01172_transaction_counters` reading `system.zookeeper_log` /
`system.transactions_info_log` with `event_time` predicates.
`addLiteral` now reshapes the `Field` via `convertFieldToType` so it
matches what `createColumnConst` expects, and bails out (returning
`nullptr`, which propagates a `{nullptr, nullptr}` from
`buildIntersectsAndContains`) when no representable value exists.
The constructor additionally wraps `tryBuildMinMaxActions` in a
catch-all so any unexpected lowering failure leaves
`minmax_actions` null and the per-granule scalar path runs - the
bulk path is a strict optimization and the scalar path is correct
on every shape.
Also adds `use_minmax_index_bulk_filtering` to
`SettingsChangesHistory.cpp` so `02995_new_settings_history` passes.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ConditionMinMax The catch is intentionally broad per the design comment above it (unsupported Field/Type combinations during DAG lowering must fall back to the per-granule scalar path rather than fail the query). Annotate it so the catch_all style check passes.
Workflow files in this branch were stale or had been deleted as a workaround for GitHub's workflow-scope check. Restoring them to match `master` so the PR diff no longer contains those unrelated changes.
…ingsChangesHistory.cpp` The new session setting `use_minmax_index_bulk_filtering` is not present in the `02995_settings_26_5_1.tsv` baseline (cut from `v26.5.1` pre-release), so the `02995_new_settings_history` test requires it to be registered under a version strictly greater than `26.5`. Move the entry from the `26.5` block to the `26.6` block to satisfy the check. Fixes the `Fast test/02995_new_settings_history` failure reported in ClickHouse#103526. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The bulk DAG path lowered the lower-bound intersection of a `FUNCTION_IN_RANGE` leaf into `greaterOrEquals(max, left)`. For a Float minmax granule that mixes finite values with `NaN`, the stored range is `[finite_min, NaN]` because `NaN` sorts last, and `greaterOrEquals(NaN, left)` is false. That made `intersects` false for lower-bounded predicates (`x >= c`, `x BETWEEN a AND b`), wrongly pruning a granule that still has matching finite values and producing wrong query results when `use_minmax_index_bulk_filtering = 1`. The scalar reference path `KeyCondition::checkInHyperrectangle` keeps such a granule: when only the granule max is `NaN` it forces `contains` to false but leaves `intersects` true. Mirror that in the DAG path by treating a `NaN` granule max as reaching any finite lower bound (only for Float index columns). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`MergeTreeIndexMinMax.h` is a relatively high-fanout header but only stores an `ExpressionActionsPtr` member. `ExpressionActionsPtr` is already forward-declared via the included `KeyCondition.h`, so the heavy `Interpreters/ExpressionActions.h` can move to the `.cpp` (which already includes it) to reduce rebuild surface for unrelated translation units. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Keep the workflow files at the previous fork-branch tip so the merge from master does not advance them, matching the existing pattern on this branch. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…constant folding Narrow the `catch` in `ConditionTemplate::generateForPartition` with an exception-code filter: `ABORTED`, `LOGICAL_ERROR`, `MEMORY_LIMIT_EXCEEDED`, `QUERY_WAS_CANCELLED`, `QUERY_WAS_CANCELLED_BY_CLIENT`, and `TIMEOUT_EXCEEDED` raised while folding partition constants now propagate instead of being silently downgraded to `generateUnsubstituted`. Expected query-evaluation failures (e.g. division by zero over a partition constant) still fall back. Co-Authored-By: Claude Fable 5 <[email protected]>
One skip-index granule can cover several PK-pruned mark ranges (`GRANULARITY > 1` with a fragmented primary-key selection). The scalar path deduplicates that case via `last_index_mark`, but the bulk loop started a fresh `readRange` per original range, seeking backwards and re-evaluating the same minmax granule, and `IndexBulkFilteringEvaluatedGranules` counted the repetitions. Merge overlapping `index_ranges` before chunking so every granule is read and evaluated exactly once, and map each surviving granule's data-mark span back to the original `ranges` with a single ascending cursor. Add `04817_minmax_bulk_filtering_overlapping_ranges`, which pins the unique-granule count via the profile event and checks bulk/scalar parity.
…umer With the default `use_skip_indexes_on_data_read = 1`, ordinary query-condition analysis never reaches `filterMarksUsingIndex` for minmax, so building the bulk `ActionsDAG` eagerly in the `MergeTreeIndexConditionMinMax` constructor was dead analysis work on every read of every minmax-indexed table once `use_minmax_index_bulk_filtering` is enabled. Defer the RPN lowering to the first `hasBulkFastPath` / `getPossibleGranules` call — i.e. to callers that can actually consume the bulk path (analyze-time filtering, the join runtime-filter pool). Guarded by `std::call_once` because one condition object is shared by concurrent per-part filtering threads. When the setting is off, no context is retained and the DAG is never built, keeping the disabled setting a true no-op.
…ck_size The bulk path hard-wired its chunk size to DEFAULT_BLOCK_SIZE while the documented contract said the entries are read and evaluated in `max_block_size` chunks. Thread the actual `max_block_size` setting into `filterMarksUsingIndex` via `MergeTreeReaderSettings`, so lowering the setting caps the per-query working set and raising it amortizes the path further. A zero value is clamped to 1 to keep the chunk loop advancing. Also document the chunking in the `use_minmax_index_bulk_filtering` docstring and pin the behavior with a test that splits a 100-granule index scan into 15 chunks and checks parity and the granule count. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103526&sha=0134011dfbd1b706bbda1f8d68643f32e9188b32&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.
The other red on this head, |
|
The fix is already merged: #113840 (@ PedroTadim, merged 2026-08-07T20:50:30Z, merge commit Mechanism: the test asserts that a This head predates the fix, so the red is a pre-fix build: CIDB matches: the last failure of this test anywhere is 2026-08-08 01:29:43Z, with 3461 OK and 0 FAIL since. The failures timestamped after the merge were pre-fix builds draining out. |
The style check requires extern setting declarations to match the setting's declared type; `max_block_size` is `NonZeroUInt64`. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103526&sha=0bc01f8dbf636f1db86cda8133173a5e43116a07&name_0=PR&name_1=Style%20check Co-Authored-By: Claude Fable 5 <[email protected]>
|
This approach seems to be unnecessarily complicated due to how tricky it is to recover type information from |
Partition constant folding in `ConditionTemplate::generateForPartition` is best-effort, but the previous `mustPropagateConstantFoldingException` denylist only propagated six codes, so resource and planner failures such as `TOO_LARGE_ARRAY_SIZE`, `CANNOT_ALLOCATE_MEMORY`, `TOO_MANY_ROWS_OR_BYTES`, or `TOO_DEEP_RECURSION` were still silently downgraded to `generateUnsubstituted`. Replace it with `isRecoverableConstantFoldingError`: only expected per-value evaluation failures (parse errors via `isParseError`, arithmetic and conversion errors, and functions rejecting the substituted constant) keep the fallback; every unclassified error now propagates (fail-close). Co-Authored-By: Claude Fable 5 <[email protected]>
The stateless runner randomizes `use_query_condition_cache`, and the cache key does not include `use_minmax_index_bulk_filtering` (or `log_comment`), so with the cache enabled a later bulk/scalar variant of the same predicate could reuse the earlier variant's skip-index result instead of exercising its own path, making the parity checks and the `IndexBulkFilteringEvaluatedGranules` probes vacuous. Pin the setting off in `03999`, `04302`, `04322`, `04498`, `04616` and `04817` (`04818` already had it). Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103526&sha=4a9f4c0238daf4c0265fae8bbf3b7a4c70508fe9&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.
The other two stress reds on this head are tracked elsewhere: the |
|
Two open PRs already own this victim:
So no separate PR is owed from me here. You settled the engine side yesterday (leave the reclaim as is, the test's part fabrication is the thing that was wrong), and these two cover the rest. On #112157 not covering it: that filter matches in-flight background-download misses, and here the blob is genuinely gone, so it correctly does not match. Unrelated to this PR from the file list rather than by agreement: this PR touches |
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103526&sha=7a1e3d36ba6a14de6b63fbb4b0f2f0fc4c4071c8&name_0=PR&name_1=Stress%20test%20%28amd_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. Logical error: |
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103526&sha=7a1e3d36ba6a14de6b63fbb4b0f2f0fc4c4071c8&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. Logical error: |
|
Both signatures are already owned, so no new PR from me here. STID 2508-519e ( I probed fix presence per build rather than inferring it from commit distance: the STID 8765-7cc2 ( This carrier is a cleaner instance than the one I analysed there, and it sharpens the mechanism: #112849 covers this in code but not in test; the reddening fixture I offered on #102192 still applies. |
| const MarkRange & index_range = index_ranges[i]; | ||
| /// Observable signal that the vectorized bulk path was actually taken for this | ||
| /// part (as opposed to silently falling back to the per-granule scalar path). | ||
| ProfileEvents::increment(ProfileEvents::IndexBulkFilteringEvaluatedGranules, chunk_end - chunk_begin); |
There was a problem hiding this comment.
IndexBulkFilteringEvaluatedGranules is being introduced here as the rollout/debug signal for the new minmax vectorized path, but this increment sits in the generic bulk_filtering branch. set indexes also return supportsBulkFiltering() = true, so a query that uses a bulk set index and a scalar minmax fallback will still report IndexBulkFilteringEvaluatedGranules > 0.
That means the event no longer proves that use_minmax_index_bulk_filtering actually engaged on mixed-index queries, even though the new tests/comments rely on it as a minmax bulk-vs-scalar signal. Could we either increment this only for MergeTreeIndexMinMax when the minmax bulk path is taken, or split it into a generic bulk counter plus a minmax-specific counter and use the latter for the new observability checks?
| return {res, read_hints}; | ||
| /// Fresh container per chunk so its columns' growth stays bounded by the | ||
| /// chunk size and the memory is released before the next chunk starts. | ||
| MergeTreeIndexBulkGranulesPtr chunk_granules = index_helper->createIndexBulkGranules(); |
There was a problem hiding this comment.
This new chunked loop is generic for every supportsBulkFiltering() index, not just minmax. set is the other current user, and its bulk container still depends on the caller-supplied granule_num / _granule_num bookkeeping to map surviving entries back to marks.
The existing set coverage (03633_set_index_bulk_filtering.sql) still fits in one default-sized chunk, so it never exercises the new readRange + chunk_begin + local_idx remapping path. Please add a small forced-multi-chunk TYPE set regression (for example with a tiny max_block_size) that checks bulk/scalar parity, so this generic refactor is proved for the sibling bulk implementation too.
|
Following up on my 08-01 lead here: the 02346 fix is up as #114338, and it is a test fix, not the counter move. The counter was never wrong for this flake. This also supersedes #112929, which @ rschu1ze closed on 08-10 preferring the increment stay where it decodes; that disposition stands and is unrelated to this mechanism. |
The minmax evaluator iterates one minmax entry at a time, dispatching
Field-variant comparisons viaRange::intersectsRange/containsRangeper leaf. TheFieldtag is fixed for the duration of a query but the dispatch happens per entry, and once an index has thousands of entries to evaluate per part, likeGRANULARITY 1minmax on a multi-tens-of-millions-of-rows part, that dispatch starts to dominate index-analysis time.This PR introduces two changes, both behind a new setting
use_minmax_index_bulk_filtering(default off):1. Vectorized evaluation via the column engine. Lower the index's
KeyConditionRPN into anActionsDAGoverminandmaxcolumns at condition-construction time. Evaluating the index for the whole part then becomes oneExpressionActions::executeover all minmax entries at once. AND/OR/NOT and per-leaf comparisons use the column engine's standard SIMD kernels andcompile_expressionsJIT. Unsupported RPN shapes (monotonic chains, space-filling curves, polygons, bloom filters, relaxed predicates, non-collapsedIN) fall back to the per-granule path.2. Native-width bulk deserialization. For fixed-width numeric types (Int/UInt 8/16/32/64, Float 32/64, Date, DateTime, Enum), the on-disk format is byte-identical to
ColumnVector<T>. The bulk deserializer can now read min/max pairs viareadPODBinarystraight into the typed column, skipping theFieldround-trip and its variant-tag dispatch. Unsupported forNullable,Decimal,String,DateTime64,UUID, IPs, etc.Entries are read and evaluated in
max_block_sizechunks so memory stays bounded atO(chunk × num_index_cols)regardless of part size.Performance test
using the schema from #103292 (1M-row single-part,
index_granularity = 1,GRANULARITY 1), pre-warmed cache, faster of two consecutive runs:~4.5× speedup.
The same per-entry speedup ratio applies at realistic production granularities; the absolute time saved scales with the number of minmax granules to check.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add an opt-in setting
use_minmax_index_bulk_filteringthat speeds up minmax skip-index evaluation using vectorized, columnar execution for common predicate shapes when analyze-time skip-index filtering is used (use_skip_indexes_on_data_read = 0).Documentation entry for user-facing changes
The setting has sensible documentation, which is generated from code.