Skip to content

Fix performance regression for Map subcolumns with PREWHERE - #107988

Merged
Avogar merged 6 commits into
masterfrom
fix-map-subcolumns-prewhere-regression
Jun 24, 2026
Merged

Avogar merged 6 commits into
masterfrom
fix-map-subcolumns-prewhere-regression

Conversation

@Avogar

@Avogar Avogar commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix performance regression for Map subcolumns with PREWHERE. Closes #107912. Caused by: #99200

Version info

  • Merged into: 26.7.1.25 (included in 26.7 and later)
  • Backported to: 26.6.1.1187, 26.5.4.13, 26.4.5.68, 26.3.17.15

After introducing bucketed Map serialization and Map subcolumn support
(`SerializationMapKeyValue`, `SerializationMapSize`), queries using
`optimize_functions_to_subcolumns` with Map columns (e.g. `tags['key']`
rewritten to `tags.key_key`) suffered a severe performance regression
when PREWHERE was enabled.

Root cause: `tryBuildPrewhereSteps` grouped PREWHERE conditions by their
logical column names (`required_columns`). Since each Map subcolumn has
a distinct name (e.g. `tags.key_k0`, `tags.key_k1`), each one was placed
into a separate PREWHERE step with its own reader, causing redundant
decompression and deserialization of the same underlying Map data.

Fix:
- Group PREWHERE conditions by physical storage column name
  (`required_storage_columns`) instead of logical subcolumn name.
  Resolve names via `ColumnsDescription::tryGetColumnOrSubcolumn` and
  `getNameInStorage`. This ensures all subcolumns of the same Map column
  share a single PREWHERE step and reader.

- Remove the `path.empty()` guard in `ISerialization` substreams cache
  functions so that `SerializationMapKeyValue` can cache the deserialized
  Map nested column at the top level, allowing multiple key-value
  subcolumns to share the data within one `readRows` call instead of
  each re-reading the same range.

- Revert the optimized sparse offsets cache in `SerializationSparse` to
  use the standard `addElementToSubstreamsCache`/`getElementFromSubstreamsCache`
  API, which is now correct with the `path.empty()` guard removed.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

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.

Here I reverted bad and unneeded changes (in my opinion) from #104513

@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3ae3e7d]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL IGNORED

AI Review

Summary

This PR fixes the Map subcolumn PREWHERE performance regression by sharing deserialized map data through the substream cache and grouping same-storage-column predicates before splitting PREWHERE into read steps. The cache-side change looks directionally sound, but the current grouping still changes explicit PREWHERE evaluation for adjacent Map key predicates, so I do not think this is safe to merge yet.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp:268] Explicit PREWHERE with multiple read steps relies on earlier filter steps removing rows before later predicate expressions are evaluated. This condition groups adjacent predicates whenever their required_storage_columns match, so PREWHERE tags['safe'] != '' AND toUInt64(tags['unsafe']) > 0 is evaluated in one step for the same Map storage column. Rows that the first predicate would previously filter out can now still reach the conversion, turning a successful query into an exception. Keep physical read sharing separate from predicate evaluation order, or only merge predicates when evaluating every expression on the unfiltered input is proven safe.
Tests
  • ⚠️ The new performance test only benchmarks all-true adjacent Map predicates, so it would not catch the explicit PREWHERE guard-order regression above. Please add a focused stateless test where the first Map key predicate filters out rows before a later expression on the same Map that would otherwise throw.
Final Verdict

Status: ❌ Block

Minimum required action: preserve explicit PREWHERE filter boundaries for adjacent predicates on the same Map, or otherwise prove and test that the shared-read implementation cannot evaluate guarded expressions on rows that should already have been filtered.

Avogar and others added 2 commits June 19, 2026 19:37
…reads

When `optimize_functions_to_subcolumns` rewrites `tags['k0']` to
`tags.key_k0`, each Map subcolumn gets a distinct logical column name.
The WHERE optimizer's `move_condition` grouped conditions by logical
column names (`table_columns`), so conditions on different Map
subcolumns were moved independently and could end up non-adjacent in
the PREWHERE list. This caused `tryBuildPrewhereSteps` to place them
into separate read steps, each redundantly decompressing the same
underlying Map data.

Fix: resolve column names to their physical storage names via
`ColumnsDescription::tryGetColumnOrSubcolumn` and `getNameInStorage`,
then group by `table_storage_columns` in `move_condition`. This ensures
all conditions on subcolumns of the same Map column are moved together.

Also remove the non-functional test `04330_prewhere_map_subcolumns_grouping`
(returned the same result on master) and add a performance test case
with interleaved Map and non-Map WHERE conditions.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
When conditions in explicit PREWHERE are interleaved (e.g. Map subcolumn
checks separated by a condition on another column), `tryBuildPrewhereSteps`
previously only grouped adjacent conditions with matching storage columns.
Non-adjacent conditions on the same Map column would end up in separate
read steps, causing redundant deserialization.

Replace adjacent-only grouping with a linear scan over existing groups so
that any condition matching an earlier group's `required_storage_columns`
is appended to that group regardless of position in the condition list.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Avogar and others added 2 commits June 22, 2026 19:38
Non-adjacent grouping could reorder predicates past intentional guards,
e.g. `PREWHERE tags['safe'] != '' AND value > 0 AND toUInt64(tags['unsafe']) > 0`
would pull the throwing conversion before the `value > 0` filter.

Revert to adjacent-only grouping in `tryBuildPrewhereSteps`. This is safe
because `MergeTreeWhereOptimizer` already groups subcolumns of the same
storage column together, so they arrive adjacent for the WHERE-to-PREWHERE
path.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…prewhere-regression

# Conflicts:
#	src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp
@antonio2368 antonio2368 self-assigned this Jun 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.50% 92.60% +0.10%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 138/139 (99.28%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

robot-clickhouse added a commit that referenced this pull request Jun 24, 2026
robot-clickhouse added a commit that referenced this pull request Jun 24, 2026
Cherry pick #107988 to 26.5: Fix performance regression for Map subcolumns with PREWHERE
robot-clickhouse added a commit that referenced this pull request Jun 24, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 24, 2026
fm4v added a commit that referenced this pull request Jun 24, 2026
Backport #107988 to 26.4: Fix performance regression for Map subcolumns with PREWHERE
fm4v added a commit that referenced this pull request Jun 24, 2026
Backport #107988 to 26.5: Fix performance regression for Map subcolumns with PREWHERE
Avogar added a commit that referenced this pull request Jul 1, 2026
Backport #107988 to 26.3: Fix performance regression for Map subcolumns with PREWHERE
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 26, 2026
The read step splitter ends a step at every condition that reports true from
isSuitableForShortCircuitArgumentsExecution, which is the only can-throw signal
available in the tree today. That predicate is documented as "throws OR is
computationally heavy", so conditions that are merely expensive, such as
startsWith and LIKE, also become step boundaries and each one then deserializes
the same Map data again.

The PR description measured this on 16 conjuncts over one Map column, 1 step
before and 16 after. Encode both shapes as performance queries next to the
`!= ''` shape from ClickHouse#107988 that stays in a single step, so the cost is reported
by the Performance Comparison check instead of living only in prose, and so a
future change to the boundary predicate shows up as a measured difference.

Verified on two Build-ID-checked binaries over a 200k row Wide part: master
(a45998f2e6fe1165) groups all three shapes into 1 step; this branch
(80934294df192fe2) keeps `!= ''` at 1 step and splits startsWith and LIKE into
16. Both binaries return 111040 rows for the two new shapes, so the split
changes cost only.

Co-Authored-By: Claude Fable 5 <[email protected]>
Avogar added a commit that referenced this pull request Aug 13, 2026
With the `m['key']` -> Map key subcolumn rewrite disabled by default there is no
reason to group PREWHERE conditions by physical storage column: without the
rewrite all `m['kN']` conditions reference the same column, so grouping by the
exact column set already places them into one read step.

Restore the pre-#107988 grouping in `MergeTreeWhereOptimizer` and
`tryBuildPrewhereSteps`. This also fixes the `CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN`
regression from #107988: storage-column grouping merged a guard condition and a
throwing expression over subcolumns of the same column into one read step, and
every condition of a step is evaluated on the unfiltered block, so the throwing
expression ran on rows the guard had rejected.

Verified with the repro from #111879 on pre-built binaries: master before #107988
returns a result, master with #107988 throws, and this branch returns a result
again. Improving subcolumn read sharing in PREWHERE is left for a separate change
that does not need backporting.

Tests:
- 04815: regression test for the `JSON` subcolumn guard with a throwing
  `CAST(tuple, 'Point')`.
- 04814: pin `optimize_map_element_to_subcolumn`, it is randomized in CI, so the
  test cannot rely on the default value.
- `map_subcolumns_prewhere` performance test: drop the setting opt-in so it
  measures the default path.

Closes: #111879
Related: #107988
Related: #111954

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ns-prewhere-regression

Fix performance regression for Map subcolumns with PREWHERE
pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Sep 27, 2026
…s guard

All conditions of one PREWHERE read step are evaluated on the same unfiltered
block, and the step filter is applied only afterwards, so a guard condition
cannot protect a later condition placed in the same step.

Since ClickHouse#107988 MergeTreeWhereOptimizer groups conditions by their physical
storage column, so a guard such as `payload.longitude IS NOT NULL` and a
throwing predicate over `payload.latitude` arrive adjacent and
tryBuildPrewhereSteps merges them into one step. The throwing expression then
runs on the rows the guard rejects, which fails the query with
CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN. Short circuit does not help because the
conversion is a prewhere DAG output, and adding more IS NOT NULL guards does
not help either since they are hoisted into the same step.

Commit 7572613 already reverted non-adjacent merging for the same hazard.
The comment it left behind claimed adjacent-only merging was safe precisely
because the WHERE optimizer makes such conditions adjacent; this is the
counterexample, so the comment is corrected.

The fix propagates a may_throw flag through the existing fillRequiredColumns
DFS, using the same isSuitableForShortCircuitArgumentsExecution predicate the
short circuit machinery uses. A condition that may throw always starts a new
read step, and the step preceding such a boundary is forced to materialize its
filter: a boundary alone is not enough, because a non-final step's need_filter
is otherwise just query_plan_merge_filters, and ReadResult::optimize applies a
step filter on its own only when fewer than 60% of the rows pass.

Conditions that cannot throw are still grouped, so the redundant read
optimization from ClickHouse#107988 is preserved; the read step counts for the query
shapes in tests/performance/map_subcolumns_prewhere.xml are unchanged.

Closes ClickHouse#111879
Avogar added a commit to groeneai/ClickHouse that referenced this pull request Oct 13, 2026
…zation

With `basic` serialization, reading the key subcolumn `m.key_<key>` of a
`Map` reads the whole column, so the rewrite gave nothing there, and
ClickHouse#107988 had to group PREWHERE conditions by the storage column to keep
several keys of one `Map` in one read step. That grouping also merged a
cheap subcolumn condition with an expensive condition on the rest of the
same column (ClickHouse#124535). The first version of this pull request worked
around it with a `Map` key special case in `tryBuildPrewhereSteps`,
which put generic PREWHERE code in charge of `Map` serialization details
and was wrong for `with_buckets`.

Gate the rewrite on the new `IStorage::hasBucketedMapSerialization`,
true for a `MergeTree` table if either `map_serialization_version`
setting is `with_buckets`, and forwarded by the storages that pass the
analyzed query to other tables (`Merge` requires all of them). The check
is in `storageAllowsTransformer`, so both passes of
`FunctionToSubcolumnsPass` agree. Explicit key subcolumns still work for
any serialization.

With that, `MergeTreeWhereOptimizer` and `tryBuildPrewhereSteps` group
conditions by their exact column set again, and `tryBuildPrewhereSteps`
no longer needs `ColumnsDescription`. The `may_throw` split and the
read-ahead of a split run stay.

Tests that assert the rewrite now pin both map serialization settings,
which clickhouse-test randomizes. The new `05340` covers the gate, and
`05339` gets the `with_buckets` case from the CI review.

Closes: ClickHouse#124535
Related: ClickHouse#124553

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 5, 2026
…n its subcolumn

Since ClickHouse#107988, tryBuildPrewhereSteps groups adjacent PREWHERE conditions
by the storage column they read, so that the keys of one Map, each of
which reads the whole Map, share one read step (ClickHouse#107912). The resolution
was type-blind: `j.kind` and `j`, two JSON paths, a Tuple element and the
whole Tuple, `m.size0` and `m.key_k1`, and keys of two Maps nested in one
Tuple all resolved to one storage column. A cheap subcolumn condition was
then merged with an expensive condition on the rest of the column, which
read the whole column for every row. On master a may-throw `toString(j)`
gets its own step (ClickHouse#111954), but its read-ahead, keyed on the same
comparison, reads `j` in step 0 anyway.

Key each input by the storage column and the substreams cache key of its
subcolumn path instead. A Map key subcolumn drops its trailing
MapKeyValue, so it keys as the Map that owns it (`(m, "")` at the top
level, as before; `(c, "%2Eleft")` for a Map inside a Tuple, so two
sibling Maps no longer share a step). The pair is used rather than a
concatenated string because the path rendering escapes tuple dots.

MergeTreeWhereOptimizer keeps grouping by storage column: that keeps a
guard ahead of a throwing condition on the same column. So with the
expensive condition written first the order is still kept.

Closes ClickHouse#124535

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Avogar added a commit that referenced this pull request Nov 10, 2026
Merge `backport/26.8/124553` and rebuild the change on it. The branch predates master's read step machinery, so instead of the master hunks:
- PREWHERE steps and the WHERE optimizer group conditions by exact column sets again: the storage column grouping of #107988 is reverted (keeping the `expensive` handling of this branch), and the `ColumnsDescription` parameter it added is removed from `tryBuildPrewhereSteps`, `getPrewhereActions` and `MergeTreeSelectProcessor`.
- `m['key']` is rewritten to `m.key_<key>` only if `IStorage::hasBucketedMapSerialization` is true (`MergeTree` with `with_buckets` in either map serialization setting; Proxy, MaterializedView, Alias, Buffer, Merge and MaterializedPostgreSQL forward it).
- Tests: 05339 and 05340 added; the existing tests that assert the rewrite pin `with_buckets`; edits to tests that do not exist on this branch are dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Avogar added a commit that referenced this pull request Nov 10, 2026
Merge `backport/26.9/124553` and rebuild the change on it. The branch predates master's read step machinery, so instead of the master hunks:
- PREWHERE steps and the WHERE optimizer group conditions by exact column sets again: the storage column grouping of #107988 is reverted (keeping the `expensive` handling of this branch), and the `ColumnsDescription` parameter it added is removed from `tryBuildPrewhereSteps`, `getPrewhereActions` and `MergeTreeSelectProcessor`.
- `m['key']` is rewritten to `m.key_<key>` only if `IStorage::hasBucketedMapSerialization` is true (`MergeTree` with `with_buckets` in either map serialization setting; Proxy, MaterializedView, Alias, Buffer, Merge and MaterializedPostgreSQL forward it).
- Tests: 05339 and 05340 added; the existing tests that assert the rewrite pin `with_buckets`; edits to tests that do not exist on this branch are dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Avogar added a commit that referenced this pull request Nov 10, 2026
Merge `backport/26.3/124553` and rebuild the change on it. The branch predates master's read step machinery, so instead of the master hunks:
- PREWHERE steps and the WHERE optimizer group conditions by exact column sets again: the storage column grouping of #107988 is reverted as it was backported to this branch, and the `ColumnsDescription` parameter it added is removed from `tryBuildPrewhereSteps`, `getPrewhereActions` and `MergeTreeSelectProcessor`.
- `m['key']` is rewritten to `m.key_<key>` only if `IStorage::hasBucketedMapSerialization` is true (`MergeTree` with `with_buckets` in either map serialization setting; Proxy, MaterializedView, Alias, Buffer, Merge and MaterializedPostgreSQL forward it).
- Tests: 05339 and 05340 added; the existing tests that assert the rewrite pin `with_buckets`; edits to tests that do not exist on this branch are dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport v26.4-must-backport v26.5-must-backport v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Map element access (map['key']) re-reads the whole map column once per distinct key — O(N) I/O for N keys

6 participants