Repository navigation
Bulk minmax index filtering (2) - #114008
EmeraldShift wants to merge 77 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.
`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]>
These changes to CI workflow / infrastructure files were unrelated to the purpose of this pull request and were introduced accidentally (stale base branch). Restoring them to match `master`.
… columns The bulk-filtering fast path in `tryBuildMinMaxActions` excluded only directly-`Nullable` index columns via `isNullable`. A `LowCardinality(Nullable(T))` index column slipped through, because `isNullable` is false for it, but comparisons over it still produce a `Nullable(UInt8)` mask. `getPossibleGranules` then does `assert_cast<const ColumnUInt8 &>` on the resulting `ColumnNullable`, raising `Bad cast from type DB::ColumnNullable to DB::ColumnVector<char8_t>`. Use `isNullableOrLowCardinalityNullable` so such columns also fall back to the generic per-granule path, which preserves NULL semantics correctly. Found by the AST fuzzer: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103526&sha=f685fa7010a505a85f1b2dc850de7bc9e78d5228&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A non-nullable `LowCardinality(Float)` minmax index still uses the bulk fast path, but the `NaN` correctness handling was gated on `WhichDataType(column_type).isFloat()`, which is false when the type is wrapped in `LowCardinality`. As a result the `intersects_lower` OR-with-`isNaN` adjustment was skipped, and a `[finite_min, NaN]` granule was wrongly pruned for a lower-bounded predicate (the bulk path disagreed with the generic per-granule path). Unwrap `LowCardinality` with `removeLowCardinality` before the `isFloat` check. Also rename the regression test accordingly and extend it with a `LowCardinality(Float64)` `NaN` parity case. Reported by Bugbot on ClickHouse#103526 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The chunked bulk-filtering path advertised `O(chunk × bytes_per_granule)` working memory, but it accumulated one `size_t` per surviving granule in `global_survivors` for the whole part before emitting any `MarkRange`. For unselective predicates that pass most granules — a target workload of this feature — that vector grows with the part size, reintroducing the per-part memory term the chunking was meant to remove (hundreds of MB on a multi-tens-of-millions-granule part). Fuse the two passes: emit and merge `MarkRange`s directly as each chunk's survivors come back. Survivors arrive in ascending global granule order (ranges processed in order, chunks tile each range in order, and `getPossibleGranules` returns chunk-local indices ascending), so the `res.back().end` merge stays valid and the result is identical. This also removes the `global_survivors` vector and the `global_granule_base` / second-pass bookkeeping. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…when off - Initialize the variables flagged by `cppcoreguidelines-init-variables` (`intersects_upper`/`intersects_lower`/`contains_upper`/`contains_lower` pointers and the `is_null` flag in the bulk deserializer). - Gate the `ActionsDAG` lowering in `MergeTreeIndexConditionMinMax` on the `use_minmax_index_bulk_filtering` setting, so the default-off path no longer pays the RPN walk, function lookup, DAG construction and `ExpressionActions` allocation during query analysis. Addresses the review comment about the disabled setting not being a true no-op. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The minmax bulk path was gated by `indexConditionHasOnlyConjunctions`, which returns false whenever the index condition's RPN contains any `FUNCTION_OR` — including an OR over columns the index does not cover. With the default `use_skip_indexes_for_disjunctions = 1`, this disabled bulk filtering for the common observability shape `t >= c AND (v < a OR v > b)` (minmax index on `t`), which is exactly this feature's target workload. The disjunction-merge path leaves the partial-disjunction bitset at its `true` default for positions the bulk path owns. That default matches what per-granule evaluation would have written precisely when none of the index's own leaves sits inside a cross-index OR. Replace the gate with `KeyCondition::everyDisjunctionIsOverUnownedLeaves`, which walks the RPN and returns true unless some `FUNCTION_OR` crosses an owned leaf. A pure conjunction still qualifies (it is a strict superset of `hasOnlyConjunctions`), and so does a foreign disjunction whose OR is built only from `FUNCTION_UNKNOWN` / constant leaves. The `t >= c AND (v < a OR v > b)` shape now keeps `t`'s index on the bulk path while `mergePartialResultsForDisjunctions` still resolves the foreign OR via the other indexes' bitset positions, so the answer is unchanged. A genuine cross-index OR such as `t < a OR v > b` still falls back to the scalar path. Add the `IndexBulkFilteringEvaluatedGranules` profile event so path selection is observable (and cannot silently regress to scalar), and a regression test that asserts both answer parity and the bulk/scalar path taken for each shape. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After merging master, the build broke in `MergeTreeIndexMinMax.cpp` because `ActionsDAG::addColumn` no longer accepts a single `ColumnWithTypeAndName` and now takes `(ColumnConstPtr column, DataTypePtr type, std::string name, bool is_deterministic_constant)`. Additionally `IDataType::createColumnConst` returns `MutableColumnConstPtr`, which no longer implicitly converts to a `const ColumnPtr` inside `ColumnWithTypeAndName`. Pass the constant column, type and name directly to `addColumn`, moving the mutable const column into the immutable `ColumnConstPtr` parameter. This fixes the `Fast test`, `arm_tidy` and all eight `Build` jobs, which were failing on the same compile error. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The benchmark queries ran with the default `use_minmax_index_bulk_filtering = 0`, so they only measured the legacy per-granule scalar evaluator and never validated the new vectorized, columnar path this PR adds. Run each query twice via a `bulk` substitution: with the setting `0` (legacy path) and `1` (new path), following the established pattern for off-by-default optimization settings (e.g. the `enable_add_distinct_to_in_subqueries` perf test). On a server that predates the setting the `= 1` variants are reported as partial and measured only on the side that supports them. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…inmax` disjunction check An atom folded to `ALWAYS_FALSE` for a `minmax` index (e.g. `a = 0.5` with `a UInt8`) is still `FUNCTION_UNKNOWN` in the template RPN, and the scalar evaluator reports its `false` into the partial-disjunction bitset. `everyDisjunctionIsOverUnownedLeaves` treated it as unowned, so bulk filtering was allowed and left the bit at its `true` default, losing the pruning of the disjunction in `mergePartialResultsForDisjunctions`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged The only red on All review threads are resolved. @Ergus, the |
|
🕵 Merged All review threads are resolved, and CI on the previous head was green. @Ergus, your |
|
🕵 Merged Neither red check on
@groeneai, investigate these failures and provide a fix in a separate PR: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114008&sha=d3a6b309dda60b5440509ef875b8dd7f96458cd0&name_0=PR&name_1=Code%20Review and https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114008&sha=d3a6b309dda60b5440509ef875b8dd7f96458cd0&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%201%2F6%29. If a fix is already in progress, link it here. All review threads are resolved. @Ergus, your |
|
Neither red needs a new PR. Run 41779571465 was created on 2026-11-04 05:29Z, and its re-run on 2026-11-06 still executed that day's merge commit. Both reds come from that old tree, and neither shows up in runs created later.
The run for |
|
🕵 @groeneai, thanks for tracing both reds to the pre-#129463 / pre-#129279 tree. No new PR is needed, as you said. The @Ergus, your |
`DecimalComparison` brings both sides of a comparison to the common decimal scale and throws when that does not fit, e.g. for a `DateTime64(9)` key and a `UInt64` bound above `INT64_MAX`. The scalar `Range` comparison handles any bound and prunes the part, so bulk filtering threw where the scalar path did not. When the comparison would rescale a decimal (including `DateTime64` and `Time64`), convert the constant exactly to the key type and compare in it. Decline bulk lowering when the constant is not representable in the key type, because then either the constant or the key bounds would be rescaled, and the latter may overflow depending on the data. A finer-scale `DateTime64` bound now falls back as well, so `04771_minmax_bulk_typed_bounds` expects that. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `use_skip_indexes_for_disjunctions`, bulk filtering did not write the partial-disjunction bits of the marks it rejected. A later scalar index could restore such a mark by merging ranges across a seek gap, and the final `mergePartialResultsForDisjunctions` kept it, because the bits of the bulk index stayed at their `true` default. Not bridging gaps in the bulk index itself did not prevent that. Now a granule rejected by bulk filtering reports `false` for every atom owned by the condition. Bulk filtering is used with disjunctions only when every owned atom is reached from the root through `AND` only (`NOT` is evaluated to `true` by the final merge), so these bits make the final merge exclude the mark. The rejection is a proof that the whole filter is false on the granule, so reporting `false` for all owned atoms is sound. Bulk filtering merges seek gaps again. The new test also covers the `DECIMAL_OVERFLOW` case from the previous commit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
The only red check on the previous head was the review-threads gate. @Ergus, your |
… in the gtest After the exact-conversion guard (`comparisonMayRescaleDecimal` / `tryConvertFieldToTypeExact`), a `DateTime64(4)` bound that is not exactly representable at the key scale 3 no longer uses the bulk path, so `TypedBoundsMatchScalarRangeEvaluation` failed on `DateTime64_cross_scale`. Mark that case as expecting fallback and add `Decimal64_cross_scale_exact` and `DateTime64_cross_scale_exact` cases with exactly representable bounds to keep bulk coverage of cross-scale comparisons. Co-Authored-By: Claude Opus 5.5 <[email protected]>
For a `Decimal` key compared with a `Decimal` of a different scale, `KeyCondition` adds a cast to the common type to the monotonic chain for strict comparisons, so the bulk path is not used even for an exactly representable bound. The `DateTime64_cross_scale_exact` case keeps the cross-scale bulk coverage. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`master` bumped the version to 26.12 after the 26.11 branch was cut, so the new setting is first available in 26.12. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged
CI on the previous head was green and all review threads are resolved. @Ergus, your |
|
📊 Cloud Performance Report ✅ AI verdict: No query in clickbench or tpch_adapted_1_official shows a confirmed change. Only clickbench Q28 was flagged, as a borderline -5.6% (1062 ms to 1002 ms), and it stays not_sure because the two tests disagree and run-to-run noise was high on both sides. This PR changes how minmax skip indexes filter marks, mostly behind the new use_minmax_index_bulk_filtering setting, which is off by default. Q28 is a regex GROUP BY on Referer with no selective filter, so it has no plausible link to the changed code. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
`master` enabled the `modernize-use-nodiscard` clang-tidy check, so every `Build (arm_tidy)` shard failed on the const accessors added by this pull request: `KeyCondition::everyOwnedLeafIsUnderConjunctionsOnly`, `supportsBulkFiltering`, `bulkFilteringPreservesPartialDisjunctions`, `getPossibleGranules`, `createIndexBulkGranules` and `MergeTreeIndexBulkGranulesMinMax::size`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114008&sha=b306ed49d57973b08898e0ab346e4f5da011b504&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 ClickHouse#114008 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged
All review threads are resolved. @Ergus, your |
Related: #103526
Minmax skip indexes currently deserialize and evaluate granules one at a time. On tables whose parts contain many minmax granules, this
Field/Rangedispatch can dominate index analysis.This adds an optional columnar path.
KeyConditionrecords exact typed direct comparisons, then the minmax index lowers supported RPN expressions to anActionsDAGover paired min/max columns. The reader processes bounded chunks and uses native-width deserialization for numeric, date, datetime, and enum columns.Unsupported types and condition shapes continue to use scalar evaluation. This includes nullable inputs, transformed comparisons, and synthesized ranges. Tests cover mixed types,
NaN, negation, disjunctions, fallback behavior, and chunk boundaries.use_minmax_index_bulk_filteringcontrols the new path and defaults tofalse. On the workload from the linked issue, it reduced minmax index filtering time from 196 ms to 59 ms.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up minmax data-skipping indexes by evaluating granules in vectorized batches.
Workflow [PR]
Sync PR [sync-upstream/pr/114008]