Skip to content

Rewrite a Map element to the key subcolumn only for bucketed serialization, and revert the PREWHERE grouping change - #114150

Closed
Avogar wants to merge 15 commits into
masterfrom
disable-map-element-to-subcolumn-rewrite
Closed

Avogar wants to merge 15 commits into
masterfrom
disable-map-element-to-subcolumn-rewrite

Conversation

@Avogar

@Avogar Avogar commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

Closes: #111879
Related: #99200
Related: #107988
Related: #111954
Related: #107912

Description

In 26.3 we added bucketed serialization for the Map data type together with an analyzer rewrite of m['key'] (internally arrayElement(m, 'key')) into the Map key subcolumn m.key_<key>, so that only the relevant bucket is read from disk. The rewrite was applied to every Map column regardless of how it is serialized.

1. The rewrite is now restricted to bucketed Map serialization. Reading m.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 whole Map, 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 in MergeTreeData from map_serialization_version and map_serialization_version_for_zero_level_parts. Storages that forward an already-analyzed query to another table answer for that table: StorageProxy, StorageMaterializedView, StorageAlias, StorageBuffer and StorageMerge, the last requiring every underlying table to qualify, like its neighbouring supportsOptimizationTo* overrides. The gate sits in storageAllowsTransformer, which both passes of FunctionToSubcolumnsPass already 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 the SettingsChangesHistory entries, so there is nothing to say about compatibility and the change is easier to backport. Reading m.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 MergeTreeWhereOptimizer and tryBuildPrewhereSteps group conditions by physical storage column instead of by the exact column set, so that several m['kN'] subcolumn reads share one read step. Its only purpose was to compensate for the rewrite; with the rewrite off for regular Map columns, all m['kN'] conditions reference the same column m and 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 NULL and a CAST(tuple(...), 'Point') over payload.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 JSON subcolumns, which the user writes directly, so no rewrite is involved and gating the Map rewrite cannot fix it.

Measured with the repro from #111879 on pre-built binaries:

binary result
master before #107988 (cd3c529cd3a) 66666
master with #107988 CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN
this branch 66666

Reverting instead of adding a new heuristic keeps this change small enough to backport. Improving subcolumn read sharing in PREWHERE will be done separately on master and does not need backporting; #111954 is superseded by this change.

The serialization part of #107988 (ISerialization cache keys, whole-map caching in SerializationMapKeyValue, the SerializationSparse refactor) 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 basic serialization no longer rewrite m['key'], so they read the whole Map as before 26.3, and query shapes that look up map elements are slower than on master: get_map_value and the shapes in tests/performance/map_subcolumns_prewhere.xml. This is the intended consequence. tests/performance/map_bucketed_serialization.xml pins with_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 = 0 the 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_subcolumns is the regression test for #111879; it pins enable_multiple_prewhere_read_steps, optimize_move_to_prewhere, use_statistics, query_plan_optimize_prewhere and query_plan_merge_filters, all of which clickhouse-test randomizes. 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.

The tests that assert the rewrite now pin map_serialization_version and map_serialization_version_for_zero_level_parts in their DDL, which is deterministic even under randomization because the client only injects a MergeTree setting the CREATE TABLE does not already name. Two places asserted that the rewrite applies with basic serialization and now assert the opposite: section 8 of 03989 and section 4 of 04000.

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

Fixed CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN and similar errors raised when a PREWHERE guard condition and a potentially throwing expression, such as a CAST, read subcolumns of the same column, for example of a JSON or Map column: such conditions are no longer grouped into a single read step. Rewriting m['key'] into the Map key subcolumn m.key_<key> now happens only for tables that use with_buckets Map serialization, 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]

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [186d612]

Summary: ✅


AI Review

Summary

This PR reverts the PREWHERE physical-column grouping that caused #111879 and restricts the m['key'] to m.key_<key> rewrite to storages that report bucketed Map serialization. The JSON regression is fixed, but the current Map gate still leaves one correctness hole on the new default basic path and one supported configuration where the promised bucketed-only restriction is not actually enforced, so I would not merge it as written.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:420-447; src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp:194-200] Turning off the rewrite for basic Map serialization makes guarded Map element predicates collapse back to the same {m} column set, and both grouping passes still coalesce identical sets into one PREWHERE step. A query like m['type'] = 'geo' AND toFloat64(m['lat']) > 0 can therefore evaluate the cast on the unfiltered block again, which is the same exception pattern this PR says it fixes for Map columns. The new tests only prove “not rewritten” and “same result” for plain reads (03989, 04000, 05218); they do not cover the throwing PREWHERE case on a non-bucketed Map.
    Suggested fix: keep a per-key identity for arrayElement(Map, const) when building PREWHERE groups, or explicitly prevent multiple arrayElement(Map, const) predicates on a non-bucketed Map from being coalesced into the same read step.

⚠️ Majors

  • [src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp:1075-1079; src/DataTypes/DataTypeObject.cpp:173-180; src/Storages/MergeTree/MergeTreeSettings.cpp:396-397] [dismissed by author -- https://github.com/Rewrite a Map element to the key subcolumn only for bucketed serialization, and revert the PREWHERE grouping change #114150#discussion_r4027295448] hasBucketedMapSerialization() is only a table-level flag, but typed JSON(... Map ...) paths do not necessarily use that Map serialization. When propagate_types_serialization_versions_to_nested_types = 0, DataTypeObject::doGetSerialization() falls back to type->getDefaultSerialization() for typed paths, so j.m remains basic even on a table whose top-level map_serialization_version is with_buckets. storageAllowsTransformer() still rewrites j.m['k'], so the PR does not actually confine the optimization to bucketed Map serialization and the “full-Map read / harder size estimation” path survives in a supported configuration.
    Suggested fix: base the decision on the resolved subcolumn’s actual serialization, or fail closed for typed JSON(... Map ...) paths when nested serialization propagation is disabled, and add a regression for that setting combination.
Final Verdict

Changes requested: the advertised Map fix is incomplete on the new default basic path, and the bucketed-only gate is still false-positive for typed JSON Map paths in a supported configuration.

LLVM Coverage Report

Measured on commit 186d612.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 123/131 (93.89%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 10, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
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]>
@Avogar Avogar changed the title Add setting optimize_map_element_to_subcolumn to control the map element rewrite Disable the map element to subcolumn rewrite by default and revert the PREWHERE grouping change Aug 13, 2026
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-improvement Pull request with some product improvements labels Aug 13, 2026
Avogar and others added 2 commits August 13, 2026 18:59
`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)

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

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 186d612e7 with master e6019455e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

691 translation units recompiled, 5427 s compile time in total, 691 of them have a recent master baseline.

Job report

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]>
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
Avogar and others added 3 commits September 15, 2026 16:15
…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]>
@Avogar Avogar changed the title Disable the map element to subcolumn rewrite by default and revert the PREWHERE grouping change Rewrite a Map element to the key subcolumn only for bucketed serialization, and revert the PREWHERE grouping change Sep 15, 2026
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]>
Comment thread src/Storages/StorageMaterializedView.h Resolved
`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]>
@Ergus

Ergus commented Oct 2, 2026

Copy link
Copy Markdown
Member

Hi @Avogar could you add a comment about why was this closed? Just to get track of it?

@Avogar

Avogar commented Oct 2, 2026

Copy link
Copy Markdown
Member Author

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

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

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pointInPolygon: throwing CAST(tuple, 'Point') hoisted into PREWHERE ahead of its NULL guard (CANNOT_INSERT_NULL), regression from #107988

2 participants