Repository navigation
Conversation
…ent rewrite
In 26.3 we added bucketed serialization for the `Map` data type together with
an analyzer rewrite of `m['key']` into the Map key subcolumn `m.key_<key>`.
The bucketed serialization turned out imperfect and is being reimplemented as a
separate type. For regular (non-bucketed) `Map` serialization the rewrite can be
harmful (e.g. it complicates subcolumn size estimation) and gives no benefit.
Introduce a new setting `optimize_map_element_to_subcolumn` (default `false`)
that gates only the `{Map, arrayElement}` transformer in `FunctionToSubcolumnsPass`.
Other Map subcolumn optimizations (`mapKeys`, `mapValues`, `length`, `empty`)
keep following `optimize_functions_to_subcolumns`. The setting takes effect only
when `optimize_functions_to_subcolumns` is also enabled.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [186d612] Summary: ✅
AI ReviewSummaryThis PR reverts the PREWHERE physical-column grouping that caused Findings❌ Blockers
Final VerdictChanges requested: the advertised LLVM Coverage ReportMeasured on commit 186d612.
Changed lines: Changed C/C++ lines covered: 123/131 (93.89%) · Uncovered code |
After disabling the m['key'] -> m.key_<key> rewrite by default, the optimize_functions_to_subcolumns = 1 branches of this regression test no longer triggered the rewrite, so the post-aggregation guard it was written to cover was not exercised. Enable optimize_map_element_to_subcolumn so the test is meaningful again; results are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…analyzer The map element rewrite is now disabled by default, so: - Force enable_analyzer in 04814 (the rewrite is analyzer-only), fixing the old-analyzer CI failure. - Enable optimize_map_element_to_subcolumn in the map_subcolumns_prewhere perf test so it benchmarks the key subcolumn path instead of full Map scans. - Randomize optimize_map_element_to_subcolumn in BuzzHouse and clickhouse-test so fuzzing keeps exercising the rewrite. Co-Authored-By: Claude Opus 4.8 <[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]>
`04039_text_index_map_values_subcolumn` asserts `EXPLAIN indexes` for text indexes on `mapValues(m)` in the rewritten `m.key_<key>` form, and the `subcolumns=1` cases of `04546_map_element_duplicate_keys_first_match` pin the first-match behaviour of the key subcolumn reader (issue #111203). With the rewrite disabled by default both stayed on the `arrayElement` path and no longer covered what they were added for, so enable `optimize_map_element_to_subcolumn` there. This restores the configuration in which their references were generated, so the expected output is unchanged. Also pin `enable_multiple_prewhere_read_steps` in `04815`: with prewhere splitting disabled the whole PREWHERE is a single step, so no guard can protect a throwing condition, and the setting is randomized in CI. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`optimize_map_element_to_subcolumn` only narrows `optimize_functions_to_subcolumns`, so a single session-level SET is enough: the `subcolumns=0` cases keep the plain `arrayElement` path because that setting gates the whole pass. This also pins the value for the whole file, which the per-query clauses did not do - the file is not tagged `no-random-settings` and the setting is randomized in CI. Output is unchanged. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| { | ||
| condition_groups.back().push_back(node); | ||
| } | ||
| if (!condition_groups.empty() && nodes_info[condition_groups.back().back()].required_columns == node_info.required_columns) |
There was a problem hiding this comment.
This still leaves the same PREWHERE correctness hazard for the new default Map path. With optimize_map_element_to_subcolumn = 0, both m['type'] = 'geo' and CAST(m['lat'], 'Float64') > 0 collapse to the same {m} column set here, so they are merged into one read step and evaluated on the same unfiltered block. The cast then runs before the guard can drop non-geo rows, which is exactly the #111879 failure mode, just on full-Map reads instead of physical subcolumns.
We need some per-key distinction when the arrayElement(Map, const) rewrite is disabled, or these predicates must not be coalesced into one PREWHERE step.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units691 translation units recompiled, 5427 s compile time in total, 691 of them have a recent master baseline. |
The condition estimator rates the throwing `pointInPolygon` predicate as more selective than the `payload.longitude IS NOT NULL` guard that protects it (1000 vs 33000 rows), so `MergeTreeWhereOptimizer` orders it first and it lands in the first read step, where nothing has filtered the NULL rows yet. That hoisting is a separate hazard from the condition merging this test covers, it also reproduces without the reverted grouping, and `use_statistics` is randomized in CI, which is why the test failed there but never locally. Verified with the CI build of this branch: the test passes with the exact randomized settings of a failing run, and still fails on a pre-revert binary, so it keeps its regression signal. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…e-map-element-to-subcolumn-rewrite
…ation The `m['key']` -> `m.key_<key>` rewrite in `FunctionToSubcolumnsPass` only pays off when the `Map` column is serialized with buckets, because only then can one key be read without reading the whole column. With the regular serialization the subcolumn read still reads the whole `Map`, and the rewrite makes subcolumn size estimation harder for no benefit. Gate it on a new `IStorage::hasBucketedMapSerialization`, implemented in `MergeTreeData` from `map_serialization_version` and `map_serialization_version_for_zero_level_parts`, and forwarded by the storages that delegate the already-analyzed query to another table: `StorageProxy`, `StorageMaterializedView`, `StorageAlias`, `StorageBuffer` and `StorageMerge`. `Merge` requires every underlying table to qualify, like its neighbouring `supportsOptimizationTo*` overrides. The gate lives in `storageAllowsTransformer`, which both passes of the pass already consult, so the counting and the applying pass cannot diverge. This replaces the `optimize_map_element_to_subcolumn` setting added earlier in this pull request. A setting is not needed: whether the rewrite helps follows from the table, not from the query. Removing it also drops the `SettingsChangesHistory` entries, so nothing has to be said about `compatibility`, which makes this easier to backport. Reading `m.key_<key>` explicitly still works for any serialization, and query results are unchanged either way. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The tests that assert the rewrite now pin `map_serialization_version` and `map_serialization_version_for_zero_level_parts` to `with_buckets` in their DDL instead of enabling a session setting. That is deterministic even though `clickhouse-test` randomizes both, because the client only injects a MergeTree setting the `CREATE TABLE` does not already name. Most tables in `03989`, `04000` and `04040` already pinned them and needed no change. Two sections asserted that the rewrite applies with `basic` serialization, which is exactly what no longer happens: `03989` section 8 and `04000` section 4 now pin `basic` and assert that no rewrite occurs, plus the results. The `Memory` section of `04040` claimed to show that the bug it covers is in the analyzer rather than in serialization; the rewrite never fires for `Memory` now, so the section asserted nothing and is removed. `05218_map_element_to_subcolumn_bucketed_only` covers the gate: bucketed versus `basic` versus `Memory`, equal results either way, and the forwarding through `Merge`, `MaterializedView` and `Buffer`, including a `Merge` over one bucketed and one regular table, which must not rewrite. `04815` additionally pins `query_plan_optimize_prewhere` and `query_plan_merge_filters`: with either at `0` the outer `pointInPolygon` filter is not merged into the inner scan filter and the test passes without exercising the regression. `tests/performance/map_subcolumns_prewhere.xml` keeps measuring the default path, which is now full-`Map` reads, so its comments no longer describe the grouping of subcolumn conditions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The `still optimized` section asserts that the name-collision guard does not reject an ordinary rewrite. Three of its assertions are about `m['key']`, which is now rewritten only for tables with bucketed `Map` serialization, so they read `0` and the section no longer showed what it was written to show. `t_plain` pins both serialization versions, and the two tables carrying a `Map` under a `JSON` path and under a `Tuple` element move from `Memory` to a bucketed `MergeTree`. `Memory` never serializes with buckets, so the rewrite cannot fire there at all, and asserting `0` would be indistinguishable from the guard rejecting the rewrite, which is what this section exists to catch. Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114150&sha=d97eecc7c1d7fc9b087e12e1d8c41f8a9b9f055c&name_0=PR&name_1=Fast%20test #114150 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`StorageMaterializedPostgreSQL::read` hands the already-analyzed `SelectQueryInfo` to the nested `ReplacingMergeTree`, so the wrapper answers for that table, which is why it already forwards `supportsPrewhere`, `supportsSubcolumns` and `supportsOptimizationToSubcolumns`. `supportsOptimizationToTupleElementSubcolumns` needs no override because its `IStorage` default follows `supportsOptimizationToSubcolumns`, but `hasBucketedMapSerialization` defaults to `false`, so without forwarding it the wrapper suppressed the `m['key']` rewrite even for a bucketed nested table, and a `Merge` over such a table inherited that. No test: observing this needs a live PostgreSQL, the nested table is created by the engine so its `map_serialization_version` can only be set server-wide, and `convertPostgreSQLDataType` never produces a `Map`, so only the standalone table engine with a hand-declared `Map` column could reach it. Review comment: #114150 (comment) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Hi @Avogar could you add a comment about why was this closed? Just to get track of it? |
|
The original issue was closed by #111954, so the bug is fixed and this PR is not needed. I don't like both PRs, we need to improve PREWHERE conditions reordering/combinations in a general way, I wanted to do it, but don't have time for it at all, so I postponed it |
Closes: #111879
Related: #99200
Related: #107988
Related: #111954
Related: #107912
Description
In 26.3 we added bucketed serialization for the
Mapdata type together with an analyzer rewrite ofm['key'](internallyarrayElement(m, 'key')) into theMapkey subcolumnm.key_<key>, so that only the relevant bucket is read from disk. The rewrite was applied to everyMapcolumn regardless of how it is serialized.1. The rewrite is now restricted to bucketed
Mapserialization. Readingm.key_<key>is cheaper than reading the whole column only when the keys live in separate buckets. With the regular serialization the subcolumn read still reads the wholeMap, so the rewrite buys nothing and makes subcolumn size estimation harder.The decision follows from the table, not from the query, so it is gated on a new
IStorage::hasBucketedMapSerialization, implemented inMergeTreeDatafrommap_serialization_versionandmap_serialization_version_for_zero_level_parts. Storages that forward an already-analyzed query to another table answer for that table:StorageProxy,StorageMaterializedView,StorageAlias,StorageBufferandStorageMerge, the last requiring every underlying table to qualify, like its neighbouringsupportsOptimizationTo*overrides. The gate sits instorageAllowsTransformer, which both passes ofFunctionToSubcolumnsPassalready consult, so the counting and the applying pass cannot disagree.An earlier revision of this pull request used a new setting,
optimize_map_element_to_subcolumn, disabled by default. That setting is removed in favour of the storage gate: it asked the user a question they cannot answer better than the table can, and dropping it also drops theSettingsChangesHistoryentries, so there is nothing to say aboutcompatibilityand the change is easier to backport. Readingm.key_<key>explicitly still works for any serialization, and query results are unchanged either way.2. Revert of the PREWHERE grouping from #107988. That change made
MergeTreeWhereOptimizerandtryBuildPrewhereStepsgroup conditions by physical storage column instead of by the exact column set, so that severalm['kN']subcolumn reads share one read step. Its only purpose was to compensate for the rewrite; with the rewrite off for regularMapcolumns, allm['kN']conditions reference the same columnmand the original exact-column-set grouping already places them into one step.The grouping also introduced a correctness regression, #111879. All conditions of one read step are evaluated on the same unfiltered block, so a guard condition and a throwing expression over subcolumns of the same column — for example
payload.longitude IS NOT NULLand aCAST(tuple(...), 'Point')overpayload.latitude— became adjacent, were merged into one step, and the throwing expression ran on rows the guard had rejected.Note that this half is needed independently of the rewrite: #111879 is about
JSONsubcolumns, which the user writes directly, so no rewrite is involved and gating theMaprewrite cannot fix it.Measured with the repro from #111879 on pre-built binaries:
cd3c529cd3a)66666CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN66666Reverting instead of adding a new heuristic keeps this change small enough to backport. Improving subcolumn read sharing in PREWHERE will be done separately on
masterand does not need backporting; #111954 is superseded by this change.The serialization part of #107988 (
ISerializationcache keys, whole-map caching inSerializationMapKeyValue, theSerializationSparserefactor) is kept — it is unrelated to #111879 and still shares reads between subcolumns of the same column inside one read step.Expected performance comparison results
Tables using the default
basicserialization no longer rewritem['key'], so they read the wholeMapas before 26.3, and query shapes that look up map elements are slower than onmaster:get_map_valueand the shapes intests/performance/map_subcolumns_prewhere.xml. This is the intended consequence.tests/performance/map_bucketed_serialization.xmlpinswith_buckets, so it keeps measuring the key-subcolumn path and is unaffected by the gate, though it loses the read sharing the revert removes.Out of scope
With
enable_multiple_prewhere_read_steps = 0the whole PREWHERE is a single step, so no guard can protect a throwing expression and the repro still throws. This is pre-existing and unrelated: master before #107988 (cd3c529cd3a) already throws in that configuration.A guard and a throwing expression over the same column, rather than over two subcolumns of it, are still merged into one step by the long-standing exact-column-set rule, so that shape can still throw — for example
SELECT id, toUInt64(val) FROM t WHERE val != 'abc' AND toUInt64(val) > 50. That predates #107988 and is not a regression; it needs a separate fix.Tests
04815_prewhere_guard_throwing_expression_subcolumnsis the regression test for #111879; it pinsenable_multiple_prewhere_read_steps,optimize_move_to_prewhere,use_statistics,query_plan_optimize_prewhereandquery_plan_merge_filters, all of whichclickhouse-testrandomizes.05218_map_element_to_subcolumn_bucketed_onlycovers the gate: bucketed versusbasicversusMemory, equal results either way, and the forwarding throughMerge,MaterializedViewandBuffer, including aMergeover one bucketed and one regular table, which must not rewrite.The tests that assert the rewrite now pin
map_serialization_versionandmap_serialization_version_for_zero_level_partsin their DDL, which is deterministic even under randomization because the client only injects a MergeTree setting theCREATE TABLEdoes not already name. Two places asserted that the rewrite applies withbasicserialization and now assert the opposite: section 8 of03989and section 4 of04000.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
CANNOT_INSERT_NULL_IN_ORDINARY_COLUMNand similar errors raised when aPREWHEREguard condition and a potentially throwing expression, such as aCAST, read subcolumns of the same column, for example of aJSONorMapcolumn: such conditions are no longer grouped into a single read step. Rewritingm['key']into theMapkey subcolumnm.key_<key>now happens only for tables that usewith_bucketsMapserialization, where a single key can be read without reading the whole column. Query results are unaffected either way.Workflow [PR]
Sync PR [sync-upstream/pr/114150]