Skip to content

Vectorize minmax index evaluation - #103526

Closed
EmeraldShift wants to merge 69 commits into
ClickHouse:masterfrom
EmeraldShift:optz-minmax
Closed

EmeraldShift wants to merge 69 commits into
ClickHouse:masterfrom
EmeraldShift:optz-minmax

Conversation

@EmeraldShift

@EmeraldShift EmeraldShift commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

The minmax evaluator iterates one minmax entry at a time, dispatching Field-variant comparisons via Range::intersectsRange / containsRange per leaf. The Field tag 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, like GRANULARITY 1 minmax 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 KeyCondition RPN into an ActionsDAG over min and max columns at condition-construction time. Evaluating the index for the whole part then becomes one ExpressionActions::execute over all minmax entries at once. AND/OR/NOT and per-leaf comparisons use the column engine's standard SIMD kernels and compile_expressions JIT. Unsupported RPN shapes (monotonic chains, space-filling curves, polygons, bloom filters, relaxed predicates, non-collapsed IN) 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 via readPODBinary straight into the typed column, skipping the Field round-trip and its variant-tag dispatch. Unsupported for Nullable, Decimal, String, DateTime64, UUID, IPs, etc.

Entries are read and evaluated in max_block_size chunks so memory stays bounded at O(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:

config μs in skip-index / query
baseline ~190,000
bulk (no JIT) ~42,000
bulk + JIT ~41,000

~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):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add an opt-in setting use_minmax_index_bulk_filtering that 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

  • Documentation is written (mandatory for new features)

The setting has sensible documentation, which is generated from code.

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.
@EmeraldShift EmeraldShift changed the title Optz minmax Speed up minmax index evaluation Apr 24, 2026
@EmeraldShift

Copy link
Copy Markdown
Contributor Author

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?

@EmeraldShift
EmeraldShift marked this pull request as draft April 24, 2026 22:36
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [29fb505]


AI Review

Summary

This 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 max_block_size. The current head addresses the earlier correctness issues I could trace from the discussion, but I still see one real observability bug and one uncovered sibling-path regression surface, so I would not merge it as-is.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:2768] IndexBulkFilteringEvaluatedGranules is incremented for every bulk-supporting index, not only the new minmax vectorized path. A query that uses a bulk set index and a scalar minmax fallback can still report the event as non-zero, so the new rollout/debug signal no longer proves that use_minmax_index_bulk_filtering actually engaged. Suggested fix: increment a minmax-specific event only on the minmax bulk path, or split generic and minmax-specific counters and use the latter in tests/docs.
Tests
  • ⚠️ The new chunked bulk loop in filterMarksUsingIndex is generic and now drives set skip indexes too, but the existing set bulk test (03633_set_index_bulk_filtering.sql) still fits in one default-sized chunk and never exercises readRange plus the chunk_begin + local_idx remapping. Add a small forced-multi-chunk TYPE set regression that checks bulk/scalar parity.
Final Verdict

⚠️ Needs changes before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 5, 2026
alexey-milovidov and others added 5 commits May 9, 2026 18:11
`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.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label May 23, 2026
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.
alexey-milovidov and others added 5 commits May 25, 2026 13:20
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @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.

04561_ie_join_storage_join failed with "The query succeeded but the server error '264' was expected" (the INCOMPATIBLE_TYPE_OF_JOIN hints). CIDB shows it failing on master (pull_request_number = 0, 12 times in the last 14 days) and on many unrelated PRs, so it is not caused by this PR, and I found no tracking issue for it.

The other red on this head, Stress test (amd_msan) "Sizes of nested column and null map of Nullable column are not equal after deserialization", is already tracked as #112213 with fix #112484 in flight — no action needed there.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

The fix is already merged: #113840 (@ PedroTadim, merged 2026-08-07T20:50:30Z, merge commit 7570b20ad2c7). It adds no-parallel-replicas to the test's Tags line, so there is no separate PR from me.

Mechanism: the test asserts that a Join-engine right side keeps the storage-join path, and its two serverError INCOMPATIBLE_TYPE_OF_JOIN arms depend on that path rejecting the join locally. Under parallel replicas the path is not taken at all, the plan routes through IEJoin, both ON sections join successfully (4 and 6 rows), and the not-routed counter reads 1 instead of 0. All three assertions invert together, which is why the runner reported it failing 3 out of 3 reruns rather than intermittently.

This head predates the fix, so the red is a pre-fix build: tests/queries/0_stateless/04561_ie_join_storage_join.sql is 1716 bytes at 0134011dfbd1b706bbda1f8d68643f32e9188b32 and 1932 bytes on master and on refs/pull/103526/merge, which already carries the tag. The row clears on the next run with no change needed on this branch.

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.

@EmeraldShift

Copy link
Copy Markdown
Contributor Author

This approach seems to be unnecessarily complicated due to how tricky it is to recover type information from Field and Range objects. I have a new attempt that tries to preserve the type information in the KeyCondition and hopefully is mucn more robust: #114008

alexey-milovidov and others added 3 commits August 9, 2026 09:59
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @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.

S3_ERROR No such key thrown — a part of 04630_merge_over_stale_packed_tmp_dir (t_merge_over_stale_packed, part all_1_1_0) fails to load on the S3 disk during the stress run: The specified key does not exist ... rwb-first-random-part/new-style-prefix/... with a filesystem-cache DOWNLOADING segment in the message. This escapes the benign background-download filters added in #108489/#112157. CIDB shows it is mass-flaky on master-based runs across ~20 unrelated PRs since 2026-08-07 (17 failures on 08-08 alone), which matches the test's introduction date, and it is unrelated to this PR's minmax changes. I found no tracking issue and no open fix.

The other two stress reds on this head are tracked elsewhere: the std::out_of_range logical error is #113841, and the Sizes of nested column and null map deserialization error is #112213 (fix in #112484).

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

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 MergeTreeIndexMinMax, KeyCondition, ConditionTemplate, MergeTreeIOSettings and Settings plus its own tests, nothing in the S3 disk, filesystem cache or temporary-directory cleanup.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @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: uuid != UUIDHelpers::Nil && getFirstLevelIdx(uuid) < uuid_map.size() in DatabaseCatalog::tryGetByUUID, reached from DatabaseReplicatedDDLWorker::checkParentTableExists (STID 2508-519e). Unrelated to this PR (Replicated-database DDL path); CIDB shows the same signature on unrelated PR #112788 on 2026-08-06. No tracking issue exists yet.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @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: Initiator received more initial requests than there are replicas: replica_num=0 (STID 8765-7cc2) on a fuzzed parallel-replicas query over merge('system', '^query_log$'). Unrelated to this PR (parallel-replicas coordinator path); CIDB shows the same signature on unrelated PR #102192 on 2026-08-08. No tracking issue exists yet.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

Both signatures are already owned, so no new PR from me here.

STID 2508-519e (tryGetByUUID, Stress test (amd_debug)) is fixed by #111928 (mine, open). ATTACH skips the non-APPEND refreshable-MV engine validation, so such a view can live in a Memory database with a Nil StorageID UUID; the refresh then writes that Nil into DDLLogEntry.parent_table_uuid and checkParentTableExists(Nil) trips the assertion.

I probed fix presence per build rather than inferring it from commit distance: the uuid == UUIDHelpers::Nil guard in DatabaseReplicatedWorker.cpp exists only on that PR's head, and is absent from both this carrier's sha and current master (control: checkParentTableExists appears 3 times in all three refs). So every branch cut from master keeps hitting this until #111928 lands, and merging master would not clear it. You are right that no tracking issue exists: the fix was already open when I found the defect, so the PR is the owner.

STID 8765-7cc2 (replica_num=0, AST fuzzer (amd_debug, targeted, old_compatibility)) is covered by your own #112849. I reported that on #102192 earlier today (#102192 (comment)): the modified_context->setSetting("enable_parallel_replicas", Field(0)) it adds in createChildrenPlans is unconditional, and enable_parallel_replicas is an alias of allow_experimental_parallel_reading_from_replicas, which is what canUseParallelReplicasOnFollower gates on.

This carrier is a cleaner instance than the one I analysed there, and it sharpens the mechanism: merge('system', '^query_log$') matches exactly one table, read twice, once per INTERSECT ALL arm. stream_id is the full table name (ReadFromMergeTree.cpp:795), so both arms key to the same coordinator and the second announcement is a repeat under one replica_num, hitting :223 here and :227 on other carriers from the same event. That confirms the same-stream_id double-arm reading and rules out the per-child fan-in explanation I gave first.

#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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@rschu1ze

Copy link
Copy Markdown
Member

#103526 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator

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. TextIndexUsedEmbeddedPostings is incremented at one site, and at parallel_replicas_local_plan = 0 only a follower can reach it. When the initiator has its answer and tears down connections, that follower loses its socket and ends as ExceptionWhileProcessing with Code: 210, so the probe's type = 'QueryFinish' discarded the only row holding the count. One predicate line, no engine change.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants