Skip to content

Do not read a physical column as a map subcolumn when analysing skip indexes - #119457

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-shadow-column-read-as-map-subcolumn-in-skip-index
Sep 12, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-shadow-column-read-as-map-subcolumn-in-skip-index

Conversation

@groeneai

@groeneai groeneai commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Do not read a physical column as a map subcolumn when analysing skip indexes

Related: #119336
Related: #99200

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 wrong results when a table declares both a Map column m and a column named exactly `m.key_<key>` (dots are legal in column names), or has that name claimed by a subcolumn such as a Tuple element or a typed JSON path. Skip-index analysis read the name as the map's key subcolumn and pruned every granule whose map lacks <key>, so a mapKeys or mapValues index (ngrambf_v1, tokenbf_v1, sparse_grams, bloom_filter, text) dropped rows that matched the predicate.

Description

Skip-index conditions resolve a name shaped m.key_nokey to "the map m's element at key nokey" with a textual split (tryParseMapSubcolumnName) and no column list to check against. Where the name belongs to something else, mapKeys(m) was still probed for nokey and the granule pruned.

Reproducer:

CREATE TABLE t (m Map(String, String), `m.key_nokey` String,
                INDEX idx mapKeys(m) TYPE ngrambf_v1(3, 512, 3, 0) GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ({'abc' : 'x'}, 'hello');

SELECT count() FROM t WHERE `m.key_nokey` = 'hello'; -- 0, wrong
SELECT count() FROM t WHERE `m.key_nokey` = 'hello' SETTINGS use_skip_indexes = 0; -- 1

FunctionToSubcolumnsPass, which produces these names, already guards this via the storage snapshot. IMergeTreeIndex::getColumnsShadowingMapSubcolumns() derives the same set from the metadata_snapshot the index holds, and the three condition classes get it from their createIndexCondition factories. All five call sites fail safe: a shadowed name resolves to nothing, so the index does not apply.

Subcolumn names are flat, so the claimant need not be top-level: the set covers the metadata's columns and their subcolumns, because a Tuple element or typed JSON path named m.key_nokey claims the name just as a column does (both measured). A genuine key subcolumn is generated on demand, so it is absent there and still prunes.

Measured 0 before, 1 after: ngrambf_v1, tokenbf_v1, sparse_grams, bloom_filter (= and IN) and text, over mapKeys and mapValues; set was never affected.

Residuals, pre-existing and unchanged here: a JSON column j beside a Map column `j.m`, where j.m.key_nokey resolves under j as a dynamic path while the split reads map j.m (no enumerated set can cover a dynamic path); and Map columns a and a.key_b, unreproduced and behind the arrayElement rewrite #114150 puts under a default-off setting.


Workflow [PR]
Sync PR [sync-upstream/pr/119457]

groeneai and others added 3 commits September 11, 2026 08:06
…indexes

Dots are legal in column names, so a table may declare both a Map `m` and a
physical column named literally `m.key_nokey`. Skip-index conditions resolve a
name of that shape to "the map `m`'s element at key `nokey`" with a purely
textual split in `tryParseMapSubcolumnName`, having no table column list to
check it against. On such a table a predicate on the physical column was
analysed as a map-element predicate: the needle was replaced by the key text,
`mapKeys(m)` was probed for `nokey`, and every granule whose map lacks that key
was pruned. Rows whose physical column matched the predicate were dropped with
no error, and `count()` came back short.

The producer of these names already guards the same collision:
`FunctionToSubcolumnsPass` refuses to rewrite `m['k']` into a column reference
when the storage snapshot declares a column of the generated name. The index
conditions never received that column list, so they could not make the same
check. `IMergeTreeIndex::getColumnsShadowingMapSubcolumns()` derives it from the
`metadata_snapshot` the index already holds, and each of the three condition
classes takes it in its constructor from its own `createIndexCondition` factory,
the only path that builds them. `getAll()` is what the producer's lookup covers,
so a MATERIALIZED or ALIAS column of that name shadows too.

The `shadowing_columns` parameter is deliberately not defaulted, so every
present and future call site has to carry the check; a defaulted one would let
the next call site silently reintroduce the defect. All five sites fail safe: a
shadowed name yields no resolution, the index is not applicable to that atom,
and the query full-scans and answers correctly. Nothing pruned today stops being
pruned unless the table really declares a shadowing column.

Measured on a Debug build of master, `count()` with the index vs
`use_skip_indexes = 0`: 0 vs 1 before, 1 vs 1 after, for `ngrambf_v1`,
`tokenbf_v1`, `bloom_filter` (`=` and `IN`), and `text` over both `mapKeys` and
`mapValues`; `set` was never affected. Independent of
`optimize_functions_to_subcolumns`, because the failing predicate holds no
`arrayElement` to rewrite. A genuine key subcolumn of the same map, in the same
table, still prunes.

Co-Authored-By: Claude Opus 5 <[email protected]>
…lues branches

The regression test asserted only that each shadowed predicate returns its row.
That count is also correct whenever the skip index is absent from the plan for an
unrelated reason, so the test was one setting default away from asserting nothing:
`use_skip_indexes` is not randomized by `tests/clickhouse-test` today, but nothing
records that the arms depend on it. Pin it, and assert the plan directly: one row
carrying the index count for the shadowed name and for a genuine key subcolumn of
the same map, expecting `0 1`.

`EXPLAIN indexes = 1` emits no `Indexes:` section at all for the shadowed
predicate once it is fixed, so a filter for `Granules:` would have matched zero
rows and passed for any reason at all, including a broken EXPLAIN. Counting a
marker that is actually printed, on both sides of a single row, reddens if the
guard under-applies (left becomes 1) and if it over-applies (right becomes 0).

Two arms are added for indexes over `mapValues`, which reach the resolution
branch that probes the filter with the predicate's own value instead of the
deserialized map key: `MergeTreeIndexBloomFilterText` takes `key_index` from
`mapValues(m)` and leaves `const_value` as the needle, and
`MergeTreeIndexConditionBloomFilter` resolves `has_values_index` with an empty
key field and probes with `value_field`. Both were measured returning 0 before
the fix and 1 after, so neither arm was covered by the existing `mapKeys` ones.

Also sorts the `DataTypeMapHelpers.h` include into the block's alphabetical order.
The test is untagged, so it also runs in the ParallelReplicas stateless lane,
where the default profile sets `enable_parallel_replicas`,
`parallel_replicas_for_non_replicated_merge_tree` and a cluster with a local
replica. `tests/clickhouse-test` independently randomizes
`parallel_replicas_local_plan`, and at 0 the query gets no local read node at
all: `EXPLAIN indexes = 1` then reports no `Indexes:` section, so the `Granules:`
filter returns zero rows and the `Name: idx` counts read `0 0` instead of `0 1`.
Both plan assertions break against the fixed reference with no behaviour
regression. Measured on a server configured like that lane: 22 failures in 50
runs before this change, 0 in 50 after.

Pinned per statement rather than tagging the file `no-parallel-replicas`, which
would also stop the seven count arms from running in that lane. Those arms carry
the wrong-results contract this test exists for, and they are correct there:
measured 0 before the fix and 1 after, at both `parallel_replicas_local_plan`
values, so only the plan assertions need the setting held down. Same shape as
`04402_sparse_pk_index_analysis_truncated_isnull`, which pins the setting on its
own `EXPLAIN indexes = 1` queries for this reason, and
`05023_set_index_expression_widened_operand`, which pins it alongside a skip
index assertion built on the same `Name: <idx>` marker.

Both assertions stay exact and the reference file is unchanged, so the two
mutants that keep them honest still fail on opposite sides: neutering the guard
turns the left count into 1, and a coarse whole-table refusal turns the right
count into 0 and drops the `Granules:` row.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change cold against the PR contract; I adjudicated its findings
with my own. Everything below is about the test, not the guard.

⚠️ Oracle was one-sided (fixed). count() = 1 alone also passes whenever the index is absent
from the plan for an unrelated reason. Pinned use_skip_indexes = 1 and added a two-sided plan
assertion: the shadowed name must get no index, a genuine key subcolumn of the same map must still
prune.

⚠️ Two mapValues branches were unshipped (fixed). mapValues resolves through a different
branch in both bloom-filter classes and probes the filter with the predicate's value rather than the
map key. Covered now.

⚠️ Plan assertions were non-deterministic under parallel replicas (fixed). The test is untagged,
the lane's default profile enables parallel replicas, and the runner randomizes
parallel_replicas_local_plan; at 0 the read is planned entirely remotely, so EXPLAIN indexes = 1
reports no Indexes: section, the Granules: line disappears and the counts read 0 0. Measured on
a server configured like that lane: 22/50 runs failed before the pin, 0/50 after. Pinned
enable_parallel_replicas = 0 on those two statements only, keeping exact counts rather than
thresholds, so the seven count arms still run under the lane's settings (measured 0 before the fix
and 1 after, there too).

💡 Noted, not fixed. getColumnsShadowingMapSubcolumns() rebuilds its NameSet per
createIndexCondition(), i.e. per part per index on the runtime-filter path; it depends only on the
metadata snapshot, so it could be built once per index. No correctness impact - happy to change it if
you prefer.

Type variants of the shadowing column (Nullable, LowCardinality, FixedString, MATERIALIZED,
ALIAS, UInt32 map key) and tokenbf_v1 were measured and left out of the test: they share the
shipped code paths, and one case per scenario beats one per type.

@clickhouse-gh clickhouse-gh Bot closed this Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer @george-larionov, could you review this? Skip-index analysis read any name shaped m.key_x as a map element by a purely textual split, so on a table that declares both a Map m and a real column named m.key_x a predicate on that column was probed against the mapKeys/mapValues index and matching granules were pruned; the condition classes now receive the shadowing column names from the metadata snapshot they already hold and refuse that shape.

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [55953ff]

Summary: ✅


AI Review

Summary

This PR makes skip-index analysis respect real columns and subcolumns that shadow Map key-subcolumn names such as m.key_<k>, by threading the shadowing-name set from the metadata snapshot through every current parsing path in the touched skip-index conditions. I re-checked the prior bot findings against the current head, including the added Tuple and typed JSON coverage plus the “genuine key subcolumn still prunes” plan assertions, and I did not find any remaining correctness or coverage gaps in the changed surface.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 55953ff.

Metric Baseline Current Δ
Lines 88.90% 89.00% +0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 67/67 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 11, 2026
The shadowing set was built from the metadata's top-level columns, so it only
caught a declared column named `m.key_<k>`. Subcolumn names are flat, so the
claimant need not be top-level: in `t Tuple(m Map(String, String), `m.key_nokey`
String)` the flat name `t.m.key_nokey` resolves to the tuple element, and a typed
JSON path of that name does the same. Skip-index analysis kept reading those names
as key `nokey` of the map `t.m` and pruned every granule whose map lacks that key,
so the wrong-results defect this branch fixes survived one level down.

Build the set from `get(GetColumnsOptions(All).withSubcolumns())`, which adds
exactly the statically enumerated names a subcolumn can claim. A genuine Map key
subcolumn is generated per key on demand and is absent from that enumeration, so
it stays parseable and the index stays usable.

Measured on a debug build, count() over the tuple-element carrier returns 0 before
this change and 1 after, against an oracle of 1 with `use_skip_indexes = 0`; same
for a `JSON(m Map(String, String), `m.key_nokey` String)` typed path. A genuine key
subcolumn of a nested map still prunes: `Granules: 0/1` with `Name: idx` for
`t.m.key_zzz` when the map has no key `zzz`. The published head of this branch is
the negative control for the new test arm: it reddens that line and no other.
The test passed 50/50 in the ordinary lane and 50/50 in the ParallelReplicas lane
at both `parallel_replicas_local_plan` values.

The Tuple arm's count also passes if key subcolumns of a nested map stop being
indexable altogether, so it ships with a plan assertion on the same table:
`t.m.key_zzz` is claimed by nothing and the map has no key `zzz`, so the index must
be applied and must prune, expecting `1 1`. Both sides move: with a key the map
does hold, the granule count reads `Granules: 1/1` and the right value becomes 0;
on the shadowed name the index is gone from the plan and the pair reads `0 0`.

A per-name storage-snapshot resolution check, accepting only a positive
`SerializationMap::isKeyValueSubcolumn` resolution, was considered instead.
`ColumnsDescription::tryGetColumn` reaches a Map key subcolumn only with
`with_dynamic_subcolumns`, which the producer's own call does not set, so such a
check would refuse every genuine parse and silently disable the index; the
enumeration above already claims the names that shadow one.

Raised by clickhouse-gh[bot] at
ClickHouse#119457 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 11, 2026
groeneai and others added 2 commits September 11, 2026 16:26
clang-tidy's readability-container-contains is fatal in the arm_tidy build
(.clang-tidy sets WarningsAsErrors: '*'), and the helper added by this branch
compared find() against npos:

  src/DataTypes/DataTypeMapHelpers.cpp:456:24: error: use 'contains' to check
  for membership [readability-container-contains,-warnings-as-errors]

String is std::string and the project builds with C++23, where contains() is
specified as find() != npos, so this is the same predicate. The sibling parse
below keeps find(): it needs the position to split the name, and the check
there is on a stored value rather than a comparison against the call, which is
why tidy flags only the helper.

Reproduced and verified with the repo's own check set, not a narrowed one:
clang-tidy-22 -p build on the TU exits 1 with exactly that message before the
change and 0 after, and the five other src TUs this branch touches were clean
in both directions, so no other diagnostic is traded for this one. Test 05188
passes 10/10 against the rebuilt binary (build id 7ba0a65f, asserted on the
running server), confirming the guard this helper gates still behaves.

Co-Authored-By: Claude Opus 5 <[email protected]>
ColumnsDescription::addSubcolumns enumerates subcolumns by walking the type's
default serialization, so a Tuple element name is contributed by
SerializationTuple and a typed JSON path by SerializationObject. The two are
independent: the Tuple arm added earlier does not pin the typed JSON path
carrier that the changelog entry claims.

Measured on real servers, each arm identity-asserted with buildId():

  guard behaviour                          tuple arm  JSON arm
  pre-fix master                               0          0
  shadowing set from getAll()                  0          0
  set minus the typed JSON contribution        1          0
  this branch                                  1          1

Row three is a throwaway mutant that skips subcolumns rooted in an Object
column. It reddens the new count arm alone, so the arm is not redundant with
the Tuple arm; row two reddens both, so both arms are live.

A count arm alone would also pass if the guard over-refused and no key
subcolumn beneath a JSON column stayed indexable, which is invisible in a row
count, so the JSON carrier gets the same two-sided treatment as the Tuple one:
`j.m.key_zzz` resolves to String, is claimed by nothing, and must keep pruning.
A mutant that refuses every parse whenever the table has any shadowing name
turns that line from `1 1` into `0 0` while leaving the count arms green, so
the two mutants redden opposite sides.

Against this branch the test passes 50/50 randomized in the ordinary lane and
50/50 in a ParallelReplicas-lane server, and the new count arm reads 1 at both
parallel_replicas_local_plan values with parallel replicas in the plan.

The fixture stores only the shadowing path: dots separate JSON paths, so the
claiming path is a sub-path of the map path and the map cannot hold keys, which
is why the key probe misses.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 55953ff4e with master a10d277eb (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

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not bad.

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit 7c1ce7c Sep 12, 2026
174 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 27, 2026
…mn-identity-in-skip-index-analysis

ClickHouse#119457 landed on master meanwhile. It threads a NameSet of the names that
shadow a Map key subcolumn into the same parse sites this branch guards.
That set is subsumed by isKeySubcolumnOfMap: a key subcolumn is never
enumerated, so every enumerated claimant resolves either to a physical
column or to a subcolumn whose substream path does not end in
MapKeyValue, and is refused by the substream check anyway. The conflicts
are therefore resolved by replacing the set with the substream check: the
NameSet parameters and members of the three condition classes become the
metadata snapshot again, and getColumnsShadowingMapSubcolumns,
looksLikeMapSubcolumnName and the shadowing parameter of
tryParseMapSubcolumnName are removed. The 05188 test added by ClickHouse#119457
passes unchanged.

Master also added a sixth consumer of the parse,
MergeTreeIndexConditionText::tryGetMapElementKeyForIndexColumn, used by a
text index with the keyValuePairs tokenizer on the whole map. It has the
same defect for a dynamic JSON path (on master the indexed count is 0
against a use_skip_indexes = 0 oracle of 1), and it gets the same guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 28, 2026
ClickHouse#119457 made each bloom_filter, ngrambf_v1, tokenbf_v1, sparse_grams and text
index condition build and keep a set of every column and static subcolumn
named like a Map key subcolumn, which costs O(indexes x columns) on every
filtered SELECT. Look up the one parsed name in the table's columns instead.

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

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants