Skip to content

Validate a Map key subcolumn by its substream path in skip-index analysis - #119591

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-map-key-subcolumn-identity-in-skip-index-analysis
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-map-key-subcolumn-identity-in-skip-index-analysis

Conversation

@groeneai

@groeneai groeneai commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #119617
Related: #119457

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 skip index over a Map column was consulted for a <map>.key_<key> predicate whose name does not belong to that map. Because dots are legal in column names, a JSON column j beside a Map column named `j.m` made j.m.key_<key> resolve to a dynamic path of j, while index analysis read it as a key of `j.m` and skipped the granule holding the matching row. A physical column, a Tuple element or another map sharing the name space had the same effect.

Description

A <map>.key_<key> name was split lexically at the first .key_, with no check
that it belongs to the map the index covers. Identifier resolution binds a dotted name through the
shortest matching column prefix. Where the two disagree, the index prunes the granule the
predicate matches and the query silently returns fewer rows. On 26.8.10.6, at default settings:

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

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

Here j.m.key_nokey reads dynamic JSON path m.key_nokey of j (toTypeName is Dynamic), not
the physical map the index covers.

The rewrite side validates the names it generates (canOptimizeToExpectedSubcolumn: the substream
marker, and that the subcolumn descends from the rewritten column), but a query can spell the name
itself, so this does not depend on optimize_functions_to_subcolumns. isKeySubcolumnOfMap asks the
same at the six skip-index call sites: resolve the name as the analyzer does, require a substream path
ending in Substream::MapKeyValue, and require its parent path to be this index's map, compared
structurally: two maps under one storage column can flatten to one name. Refusal is fail-safe. The
parser sits in src/DataTypes and cannot see the table's columns, hence one check per consumer.

Extended 03990_map_subcolumn_skip_index fails on master and passes here, with an in-range control
that keeps pruning; 20/20 randomized reruns green.

This replaces the enumerated name set of #119457 (mine, merged): key subcolumns are never
enumerated, so every name it refused is refused here too (its 05188 passes unchanged), plus the
dynamic path, which no set can reach.


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

groeneai and others added 2 commits September 11, 2026 22:39
…ysis

Skip-index analysis identified a `<map>.key_<key>` predicate name by splitting it
lexically at the first `.key_` marker, with no check that the name really belongs to
the map the index covers. Identifier resolution answers the same question
differently: it binds a dotted name through the shortest matching column prefix. When
the two disagree, the index prunes the granule the predicate actually matches and the
query silently returns fewer rows.

The reachable case needs no unusual setting. A table may legally hold a `JSON` column
`j` and a physical `Map` column named `j.m`, because dots are legal in column names
(`Nested` columns are exactly that). `j.m.key_nokey` then resolves to dynamic JSON
path `m.key_nokey` of `j`, while index analysis reads it as key `nokey` of map `j.m`
and probes that map's `mapKeys` index. The map does not hold the key, so the granule
is skipped:

    CREATE TABLE tdj (j JSON, `j.m` Map(String, String),
        INDEX idx mapKeys(`j.m`) TYPE ngrambf_v1(3, 512, 3, 0) GRANULARITY 1)
    ENGINE = MergeTree ORDER BY tuple();
    INSERT INTO tdj VALUES ('{"m.key_nokey":"hello"}', {'abc':'x'});
    SELECT count() FROM tdj WHERE j.m.key_nokey = 'hello';                    -- 0, wrong
    SELECT count() FROM tdj WHERE j.m.key_nokey = 'hello'
        SETTINGS use_skip_indexes = 0;                                        -- 1, correct

Ask the question the producer of these names already asks. The rewrite side
(`FunctionToSubcolumnsPass`) gates every subcolumn rewrite on
`canOptimizeToExpectedSubcolumn`, which resolves the name against the table and
requires the resolved subcolumn's substream path to be the expected substream. The
consumer side had no such gate. `isKeySubcolumnOfMap` adds it for the five skip-index
call sites: resolve the name through `ColumnsDescription::tryGetColumn` with
subcolumns enabled (the same shortest-prefix walk the analyzer uses), require a
subcolumn whose substream path ends in `Substream::MapKeyValue`, and require its
parent path to be the index's own map. Refusal is fail-safe: the atom stays unknown
and the index simply does not apply.

The parent binding compares substream paths structurally rather than by the name they
render to. A name comparison cannot separate two maps that flatten to the same
subcolumn name under one storage column, which is the same class of collision one
level up: a `Tuple` element named `x.Map(String, String)` and the `Map(String,
String)` element of a sibling `Variant` element `x` render identically, yet only one
of them owns the key. `bucket` is deliberately excluded from the comparison because a
bucket index is a Map-with-buckets read detail and not part of map identity.

This also covers the shapes an enumerated name set can reach (a physical column, a
`Tuple` element or a typed JSON path carrying the name) plus the one it cannot: a
dynamic JSON path is resolved on demand and is never enumerated, since
`Substream::MapKeyValue` is absent from `hasSubcolumnForPath`'s whitelist, so no key
subcolumn is enumerable at all.

`tryParseMapSubcolumnName` itself is left alone: it lives in `src/DataTypes` and must
not learn about `ColumnsDescription`, a `Storages` type.

Extends 03990_map_subcolumn_skip_index with the wrong-results shapes and an in-range
control that must keep pruning. Verified in both directions on a debug build, and
each clause of the guard is pinned by a mutation that reddens only its own arm.

Co-Authored-By: Claude Opus 5 <[email protected]>
Section 8 reached only three of the five places where a `<map>.key_<key>` name
is validated before it can select an index.
`MergeTreeIndexConditionText::traverseMapElementKeyNode` had no arm, so deleting
its guard left the whole suite green.

The arms already there cannot reach it. Each shadows the name with an untyped
`JSON` column, so the predicate's argument is `Dynamic` and `hasToken`,
`startsWith`, `notEmpty` and `=` all return `Nullable(UInt8)`; the function's
entry gate tests `isUInt8()` without `removeNullable` and refuses before the
guard is consulted. Over a physical `String` column the same predicates are a
bare `UInt8` and do reach it.

The new arm therefore carries the collision on a physical column with a `text`
index over `mapKeys`: unguarded, index analysis probes the map for key `nokey`,
does not find it, prunes the granule, and the count comes back 0 while the
`use_skip_indexes = 0` oracle says 1.
@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 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (3 rounds. One residual NOT fixed here: the same missing owner check exists in FunctionToSubcolumnsPass and is reachable without any index.)

Pre-publication review by an independent model (engine: codex, two rounds, one finding each) plus my
own cold pass in each round.

# Sev Finding Verdict Evidence / action
1 ⚠️ The text index's own mapKeys guard site (MergeTreeIndexConditionText.cpp:1828) had no test that fails if the guard is removed AGREE, fixed The earlier probes of that site all used the shadowed JSON table, where the argument is Dynamic, so the predicate is Nullable(UInt8) and the function's isUInt8() entry check refuses before the guard runs. Over a physical String column the same predicate is a bare UInt8 and does prune the matching row, so that arm was added and reddens on the parent commit.
2 ❌ FunctionToSubcolumnsPass validates a generated <map>.key_<key> name by its substream marker and result type, never by its owner, so the rewrite itself can bind to a different map AGREE, out of scope here Measured on both binaries: with j JSON(m Map(String, String)) beside a physical `j.m` Map(String, String), `j.m`['nokey'] reads '' at optimize_functions_to_subcolumns = 0 and json at 1 (the default), and the matching count() goes 1 to 0. Byte-identical on the parent commit and on this branch, and it reproduces with use_skip_indexes = 0, so it is a different layer and not what this changelog claims. The body no longer says the rewrite side validates this identity. Fixing it needs a different predicate (compare against the map the rewrite started from, not against an index's map), so it is left to its own change.
3 💡 The body claimed 150/150 randomized runs, a figure measured before the last test arm existed AGREE, fixed Corrected to the 20/20 actually measured on the test file that ships here.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding; there were none this time.

Also measured and deliberately not fixed here: with a physical column named like a JSON path
(`j.some.path` beside j JSON), a JSONAllPaths text index prunes the matching row too. That
is a different matcher and behaves identically on the parent commit and on this branch.

Session id: cron:clickhouse-review-self-slot-58:20260912-051700

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

groeneai commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @Ergus, could you review this? A <map>.key_<key> name was split at the first .key_ with no check that it belongs to the map the index covers, so when a JSON column or a physical column claims that name through shortest-prefix identifier resolution, the index pruned the granule holding the row the predicate matches. The five skip-index call sites now resolve the name the way the analyzer does and require its substream path to be a key of this index's own map, refusing otherwise.

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [043a2f5]

Summary: ✅


AI Review

Summary

This PR replaces the lexical map.key_<key> matcher with a structural isKeySubcolumnOfMap check at several skip-index call sites, which is the right invariant. However, the fix still leaves multiple pre-rewrite carriers matched only by the rendered column name, so the shortest-prefix collision from the PR description still produces silent false negatives for m['key'], whole-map mapContains* / has, and keyValuePairs mapContainsKeyValue queries. I would block this until those carriers are guarded too.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp:354, src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:651] The arrayElement carrier still resolves the skip index from first_argument.getColumnName() without proving that the argument owns that map. With j JSON(m Map(String, String)) beside a physical `j.m` Map(String, String), j.m['nokey'] still reads the JSON path while these branches probe the physical j.m index and can prune the matching granule when optimize_functions_to_subcolumns = 0. Suggested fix: run the same owner validation on the arrayElement carrier before tryResolveMapIndexInfo / getKeyIndex, and add a Section 8 regression for j.m['nokey'].
  • [src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp:1308, src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:629] The whole-map mapContains* / has branches are still keyed only by key_node.getColumnName(). A typed JSON path j.m can therefore still select the physical j.m mapKeys / mapValues index, so direct pruning remains wrong for mapContains(j.m, 'nokey'), mapContainsValue(j.m, 'hello'), and similar predicates. Suggested fix: validate the resolved map owner for whole-map carriers before accepting mapKeys({name}) / mapValues({name}), and add a Section 8 arm that compares those predicates against the use_skip_indexes = 0 oracle.
  • [src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1223, src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1986, src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:2071, src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:2249] The text-index condition still has the same rendered-name match in its pre-rewrite paths: whole-map mapContains* uses has_map_keys_column / has_map_values_column, traverseMapElementKeyNode accepts any Map whose printed name matches, and both keyValuePairs / mapValues arrayElement helpers still gate on getColumnName(). That leaves the PR's wrong-results bug reachable in the text index whenever the query spells j.m or j.m['key'] instead of j.m.key_<key>. Suggested fix: route every pre-rewrite map carrier through the same structural owner check and add matching Section 8 regressions.
  • [src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:2205] mapContainsKeyValue on the keyValuePairs tokenizer is another unguarded whole-map carrier: it only checks hasIndexForColumn(function_node.getArgumentAt(0).getColumnName()). With the same typed-JSON / physical-j.m collision, mapContainsKeyValue(j.m, 'nokey', 'hello') still reads the JSON path while the token lookup hits the physical index and can drop the matching row. Suggested fix: apply the same owner validation here and add a Section 8 arm for mapContainsKeyValue.
Tests
  • ⚠️ Add Section 8 regressions for j.m['nokey'], whole-map mapContains* / has, and mapContainsKeyValue under j JSON(m Map(String, String)) beside a physical `j.m` Map(String, String). The current matrix only pins the spelled j.m.key_nokey carrier, so all of the still-buggy pre-rewrite paths above stay green.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: extend the owner check to every remaining pre-rewrite map carrier (arrayElement, whole-map mapContains* / has, and mapContainsKeyValue) and add focused stateless regressions for those shapes.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 12, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 043a2f55e57c1fc399522bcc2d13fe7d4ebfcffd was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a71bab2

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
BuzzHouse (arm_asan_ubsan) / Logical error: AST subtree not found in children (STID 1218-27e6) LOGICAL_ERROR raised inside the server-side AST fuzzer's own safety-limit stripping: stripQuerySettings.cpp:140 calls IAST::reset on a SETTINGS slot the fuzzer has desynced from children. Nothing in this PR touches that path. 5 rows / 4 carrier PRs in 30 days, 0 master rows. #110394 (mine, open)
Mergeable Check Aggregator. Its own text is Failed: BuzzHouse (arm_asan_ubsan), so it carries no independent failure. #110394 (mine, open)
PR praktika workflow aggregator over the same job. #110394 (mine, open)

Run detail for this head: 154 checks green, 17 skipped, 3 failed as above, Finish Workflow
green at 12:51:28Z. The cancelled check-runs also visible on this head belong to the superseded
earlier attempts of the same workflow run, not to a separate result.

Session id: cron:our-pr-ci-monitor:20260912-133020

groeneai and others added 3 commits September 27, 2026 12:45
…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]>
A text index with the keyValuePairs tokenizer on a physical Map column
`j.m` beside a JSON column `j`: `j.m.key_nokey` binds to a dynamic path of
`j`, so the indexed count must equal the `use_skip_indexes = 0` oracle.
On master the arm prints 0 1 (the granule is pruned). Deleting the guard
at that site reddens exactly this line of 03990, and a guard that refuses
every name there reddens the existing direct-read line of
02346_text_index_keyvaluepairs_tokenizer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment-only: the same invariant in three lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai requested review from Ergus and rschu1ze September 27, 2026 13:15
/// function call or a `map.key_<serialized_key>` subcolumn reference.
std::optional<MapIndexInfo> tryResolveMapInfoFromNode(
const RPNBuilderTreeNode & key_node, const Block & header, const NameSet & shadowing_columns)
const RPNBuilderTreeNode & key_node, const Block & header, const StorageMetadataPtr & metadata_snapshot)

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.

metadata_snapshot only protects the parsed m.key_<key> branch here. The arrayElement carrier below still does tryResolveMapIndexInfo(first_argument.getColumnName(), ...) with no owner check, so the same shortest-prefix collision is still reachable when optimize_functions_to_subcolumns = 0.

A concrete repro is the typed-JSON case from Section 8 but written as j.m['nokey']: with j JSON(m Map(String, String)) beside a physical `j.m` Map(String, String) and an index on mapKeys of that physical column, the predicate reads the JSON path j.m, while this branch still probes the physical mapKeys index and can prune the matching granule. The same raw-name lookup is still present in MergeTreeConditionBloomFilterText::traverseTreeEquals, so both bloom-filter families need the owner check on the arrayElement carrier too, plus a stateless arm that pins the optimize_functions_to_subcolumns = 0 shape.

if (!header.has(fmt::format("mapKeys({})", map_column_name)))
return false;

if (!metadata_snapshot

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 closes only the rewritten m.key_<key> carrier. The pre-rewrite text-index paths still accept any column whose rendered name matches the indexed Map: traverseMapElementKeyNode keeps using required_column.name in its isMap(...) && header.has(mapKeys(...)) branch, and hasIndexForMapElementValue / tryGetMapElementKeyForIndexColumn still use function.getArgumentAt(0).getColumnName() for arrayElement.

That leaves wrong-results cases under optimize_functions_to_subcolumns = 0. With j JSON(m Map(String, String)) beside a physical `j.m` Map(String, String), predicates such as mapContains(j.m, 'nokey') or j.m['nokey'] = 'hello' can still consult the physical j.m text index even though they read the JSON path, and direct-read pruning can drop the matching row. The structural owner check needs to cover those non-rewritten carriers too, and Section 8 should add a stateless arm that exercises them.

@clickhouse-gh clickhouse-gh Bot added comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 27, 2026
/// function call or a `map.key_<serialized_key>` subcolumn reference.
std::optional<MapIndexInfo> tryResolveMapInfoFromNode(
const RPNBuilderTreeNode & key_node, const Block & header, const NameSet & shadowing_columns)
const RPNBuilderTreeNode & key_node, const Block & header, const StorageMetadataPtr & metadata_snapshot)

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.

Separate from the arrayElement carrier above, the whole-map mapContains* / has branches are still keyed only by the rendered column name. In MergeTreeIndexConditionBloomFilter this is the mapKeys({key_column_name}) / mapValues({key_column_name}) lookup, and MergeTreeConditionBloomFilterText does the same via column_name.

That leaves the same shortest-prefix collision reachable through non-rewritten whole-map predicates. With j JSON(m Map(String, String)) beside a physical `j.m` Map(String, String), mapContains(j.m, 'nokey') can still consult the physical j.m index even though the predicate reads the JSON path, so direct pruning can still drop the matching row. These carriers need the same metadata_snapshot-based ownership validation, and Section 8 needs a stateless arm that compares them to the use_skip_indexes = 0 oracle.

# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexText.cpp
if (!hasIndexForColumn(map_column_name))
return std::nullopt;

if (!metadata_snapshot || !isKeySubcolumnOfMap(metadata_snapshot->getColumns(), column_name, map_column_name))

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 hardens the rewritten m['key'] / m.key_<key> path, but the whole-map keyValuePairs carrier is still keyed only by the rendered name: MergeTreeIndexConditionText::traverseMapContainsKeyValueNode at src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:2205 only checks hasIndexForColumn(function_node.getArgumentAt(0).getColumnName()).

With j JSON(m Map(String, String)) beside a physical `j.m` Map(String, String) indexed by TYPE text(tokenizer = 'keyValuePairs'), mapContainsKeyValue(j.m, 'nokey', 'hello') reads the JSON path while this branch still probes the physical j.m index and can prune the matching granule. Please apply the same owner validation here and add a Section 8 arm for mapContainsKeyValue.

This branch has not been deployed

No deployments
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-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Skip index over a Map column j.m wrongly prunes granules when the predicate reads a JSON dynamic path j.m.key_<k> of a sibling JSON column j

2 participants