Repository navigation
Fix performance regression for Map subcolumns with PREWHERE - #107988
Conversation
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]>
There was a problem hiding this comment.
Here I reverted bad and unneeded changes (in my opinion) from #104513
|
Workflow [PR], commit [3ae3e7d] Summary: ❌
AI ReviewSummaryThis PR fixes the Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Minimum required action: preserve explicit |
…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]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
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
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 138/139 (99.28%) | Lost baseline coverage: none · Uncovered code |
Cherry pick #107988 to 26.5: Fix performance regression for Map subcolumns with PREWHERE
Backport #107988 to 26.4: Fix performance regression for Map subcolumns with PREWHERE
Backport #107988 to 26.5: Fix performance regression for Map subcolumns with PREWHERE
Backport #107988 to 26.3: Fix performance regression for Map subcolumns with PREWHERE
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]>
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]>
…ns-prewhere-regression Fix performance regression for Map subcolumns with PREWHERE
…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
…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]>
…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]>
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]>
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]>
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]>
Changelog category (leave one):
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
26.7.1.25(included in26.7and later)26.6.1.1187,26.5.4.13,26.4.5.68,26.3.17.15