Repository navigation
Conversation
…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.
Internal second-model review: adjudication log (3 rounds. One residual NOT fixed here: the same missing owner check exists in
|
| # | 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 /
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
|
cc @CurtizJ @Ergus, could you review this? A |
|
Workflow [PR], commit [043a2f5] Summary: ✅
AI ReviewSummaryThis PR replaces the lexical Findings❌ Blockers
Tests
Final Verdict
|
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - a71bab2Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Run detail for this head: 154 checks green, 17 skipped, 3 failed as above, Session id: cron:our-pr-ci-monitor:20260912-133020 |
…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]>
| /// 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) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| /// 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) |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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.
Closes: #119617
Related: #119457
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when a skip index over a
Mapcolumn was consulted for a<map>.key_<key>predicate whose name does not belong to that map. Because dots are legal in column names, aJSONcolumnjbeside aMapcolumn named`j.m`madej.m.key_<key>resolve to a dynamic path ofj, while index analysis read it as a key of`j.m`and skipped the granule holding the matching row. A physical column, aTupleelement 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 checkthat 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:
Here
j.m.key_nokeyreads dynamic JSON pathm.key_nokeyofj(toTypeNameisDynamic), notthe physical map the index covers.
The rewrite side validates the names it generates (
canOptimizeToExpectedSubcolumn: the substreammarker, 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.isKeySubcolumnOfMapasks thesame 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, comparedstructurally: two maps under one storage column can flatten to one name. Refusal is fail-safe. The
parser sits in
src/DataTypesand cannot see the table's columns, hence one check per consumer.Extended
03990_map_subcolumn_skip_indexfails on master and passes here, with an in-range controlthat 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
05188passes unchanged), plus thedynamic path, which no set can reach.
Workflow [PR]
Sync PR [sync-upstream/pr/119591]