Repository navigation
Conversation
A skip index can be declared on the `keys` or `values` subcolumn of a Map (`INDEX i m.keys TYPE bloom_filter`). It is built from the stored keys/values, which is cheaper than evaluating `mapKeys(m)` for every row (for a `Map(LowCardinality(String), LowCardinality(String))` 2M-row INSERT: 172.6 MiB peak memory vs 605.9 MiB with `mapKeys(m)`), and its granules hold the same elements. But the bloom_filter, text and tokenbf/ngrambf conditions find "the index column holding the keys (values) of map X" only by the name `mapKeys(X)` (`mapValues(X)`), so `m['k'] = v`, `m['k'] IN (...)`, `mapContains(m, k)` with optimize_functions_to_subcolumns = 0, etc. never used the subcolumn index. `IMergeTreeIndex::getMapSubcolumnIndexColumns` now maps `mapKeys(P)` / `mapValues(P)` to an index column `P.keys` / `P.values` of the same index, and the 18 existing name lookups go through `getMapIndexColumnName`, which returns today's name when there is no such column. A column is mapped only if: - the index has no `mapKeys(P)` / `mapValues(P)` column itself; - the index expression outputs the INPUT `P.keys` unchanged: a definition stored by an older server can hold `INDEX i (other AS `m.keys`)`, which is refused at CREATE/ALTER but replayed on load; - the part computes that input from the top-level physical Map `P`: a part resolves the name with `Block::findSubcolumnByName`, i.e. a column with that exact name, else the shortest column prefix having the rest as a subcolumn. With `j JSON(`m.keys` Array(String))` beside `` `j.m` Map ``, an index on `j.m.keys` holds the JSON path, so `` `j.m`['k'] `` must not use it. Dropping either guard returns wrong results (0 rows instead of 64) for the corresponding schema. The only type difference is that `m.keys` keeps `LowCardinality`, which the hashing / conversion code of every condition already strips. Docs: the `mergetree` page (source in registerStorageMergeTree.cpp), the `Map` page (DataTypeMap.cpp) and textindexes.mdx describe indexes on the `keys` / `values` subcolumns. Related: ClickHouse#122420 Related: ClickHouse#122232 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the isMapSubcolumnIndexColumn comment to the Block::findSubcolumnByName invariant and drop a comment restating the condition below it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings, then 1 on the re-review) plus my own review (2 nits).
Severity: ❌ blocker / |
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261022-192300 |
|
cc @ahmadov @shankar-iyer, could you review this and add the |
|
Workflow [PR], commit [516895d] Summary: ❌
AI ReviewSummaryThe PR lets skip indexes on Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ Block Correct the four predicate-extraction errors and add focused regression coverage before merging. |
| if (function_name == "equals") | ||
| { | ||
| if (auto map_info = tryResolveMapInfoFromNode(key_node, header, columns_shadowing_map_subcolumns)) | ||
| if (auto map_info = tryResolveMapInfoFromNode(key_node, header, columns_shadowing_map_subcolumns, map_subcolumn_index_columns)) |
There was a problem hiding this comment.
[P1] Preserve missing-key matches for padded FixedString constants
The new mapping routes existing m.keys/m.values indexes through the map-equality path, whose default-value guard compares raw Field values. toFixedString('', 2) contains two NUL bytes, whereas DataTypeFixedString::getDefault returns an empty string, so the guard below misses it. SQL equality nevertheless considers that constant equal to the empty String returned for a missing map key. The index then drops a granule that contains matching rows.
CREATE TABLE b
(
m Map(String, String),
INDEX i m.keys TYPE bloom_filter GRANULARITY 1
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO b VALUES (map('present', 'value'));
SELECT count() FROM b WHERE m['missing'] = toFixedString('', 2);
SELECT count() FROM b WHERE m['missing'] = toFixedString('', 2)
SETTINGS use_skip_indexes = 0;On the PR's CI binary these return 0 and 1, respectively. Changing the index to m.values also reproduces it, with either value of optimize_functions_to_subcolumns.
Before extracting either map index condition, recognize constants that compare equal to the missing element's default using the actual comparison semantics, including FixedString padding. Please add regression coverage for both subcolumns and optimizer settings.
There was a problem hiding this comment.
This is pre-existing on master with the same index declared on mapKeys(m) / mapValues(m) (0 vs 1 for m['missing'] = toFixedString('', 2), and for m['present'] = toFixedString('value', 6) over the values index, at both optimize_functions_to_subcolumns values); this PR only routes an m.keys / m.values index into the same guard and gives the same counts there. #107076 fixes that guard: with its change applied on top of this PR, every one of these queries returns the scan's count and the index still prunes.
| auto first_argument = key_function_node.getArgumentAt(0); | ||
| const auto map_column_name = first_argument.getColumnName(); | ||
| if (const auto map_keys_index = getKeyIndex(fmt::format("mapKeys({})", map_column_name))) | ||
| if (const auto map_keys_index = getKeyIndex(getMapIndexColumnName(map_subcolumn_index_columns, "mapKeys", map_column_name))) |
There was a problem hiding this comment.
[P1] Preserve rows when a pattern matches the missing-key default
This lookup now makes a keys-subcolumn index eligible for value predicates such as LIKE, but the guard above only checks whether the pattern literal equals the default. It does not check whether the predicate matches the default. For an absent key, m['missing'] is '', which satisfies LIKE '%'. Replacing the pattern with the map key below then probes for missing in the keys index and incorrectly eliminates the row.
CREATE TABLE t
(
m Map(String, String),
INDEX i m.keys TYPE tokenbf_v1(4096, 3, 0) GRANULARITY 1
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (map('present', 'value'));
SELECT count() FROM t WHERE m['missing'] LIKE '%';
SELECT count() FROM t WHERE m['missing'] LIKE '%'
SETTINGS use_skip_indexes = 0;On the PR's CI binary these return 0 and 1, respectively. The same failure occurs with ngrambf_v1(3, 4096, 3, 0), including match(m['missing'], '^$'). Both values of optimize_functions_to_subcolumns are affected.
Before replacing the original predicate with a key-presence condition, decline extraction whenever that predicate can match the missing element's default. Apply the guard to both the arrayElement and optimized map-subcolumn paths, and add focused LIKE/match regressions.
There was a problem hiding this comment.
This is pre-existing on master with the same index declared on mapKeys(m) (0 vs 1 for m['missing'] LIKE '%' over tokenbf_v1 and ngrambf_v1, and for match(m['missing'], '^$') over ngrambf_v1, at both optimize_functions_to_subcolumns values); this PR only routes an m.keys index into the same branch and gives the same counts there. #119336 fixes that branch: with its change applied on top of this PR, all of these queries return the scan's count.
|
Fixing PR for the AST fuzzer (amd_debug, targeted) failure (STID 1611-37da, j.m.keys index in a merge): #127527 |
CI finish ledger - 34f8e7aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Session id: cron:our-pr-ci-monitor:20261023-023006 |
…index-element # Conflicts: # src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp # src/Storages/MergeTree/MergeTreeIndexBloomFilter.h # src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp # src/Storages/MergeTree/MergeTreeIndexBloomFilterText.h # src/Storages/MergeTree/MergeTreeIndexConditionText.cpp # src/Storages/MergeTree/MergeTreeIndexConditionText.h # src/Storages/MergeTree/MergeTreeIndexText.cpp # src/Storages/MergeTree/MergeTreeIndices.cpp
| bool has_map_keys_column = hasIndexForColumn(getMapIndexColumnName(map_subcolumn_index_columns, "mapKeys", index_column_name)); | ||
| bool has_map_values_column = hasIndexForColumn(getMapIndexColumnName(map_subcolumn_index_columns, "mapValues", index_column_name)); |
There was a problem hiding this comment.
[P1] Match dictionary coercion before probing a mapped text index
This makes a text index on m.keys eligible for mapContainsKey with the optimizer disabled, but the text condition does not preserve the comparison semantics of LowCardinality elements. For LowCardinality(String), mapContainsKey goes through executeArrayLowCardinality and dictionaryIndexForConstant, which casts a FixedString needle to String and removes its padding. The index condition instead assigns NeedleAsTyped and leaves the padded needle unchanged at lines 1234–1235. With the array tokenizer, that probes a different token from the one stored for the matching key and can eliminate its row.
CREATE TABLE t
(
m Map(LowCardinality(String), String),
INDEX i m.keys TYPE text(tokenizer = array)
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (map('hello', 'value'));
SELECT count() FROM t
WHERE mapContainsKey(m, toFixedString('hello', 10))
SETTINGS optimize_functions_to_subcolumns = 0;
SELECT count() FROM t
WHERE mapContainsKey(m, toFixedString('hello', 10))
SETTINGS optimize_functions_to_subcolumns = 0, use_skip_indexes = 0;Both queries must return 1: the scan searches the dictionary for hello, while the mapped index searches for hello followed by five NUL bytes. The same mismatch applies to mapContainsValue with LowCardinality(String) values and an index on m.values. Normalize needles using the actual map element comparison semantics, or decline these index conditions, and add indexed-versus-scan coverage for both subcolumns. This finding is based on the current code trace; I could not execute the reproducer because no PR-head binary is available yet.
There was a problem hiding this comment.
This is pre-existing on master with the same m.keys / m.values text index: mapContainsKey, mapContains and mapContainsValue with a padded FixedString needle already return 0 instead of 2 at the default optimize_functions_to_subcolumns = 1 (and at both values with the index on mapKeys(m) / mapValues(m)), so this PR only adds the = 0 path to the same probe. #122086 keeps the trailing zero bytes in the FixedString to String conversion, and on its CI build the indexed and scan counts agree for all of these queries.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes13 object files changed (+33.34 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units305 translation units recompiled, 3218 s compile time in total, 305 of them have a recent master baseline. |
CI finish ledger - 41e3676Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261106-190058 |
|
Fixing PR for La Casa Del Dolor (amd_debug) / Server shutdown created: #129875 |
…index-element Master (ClickHouse#130814) matches a bloom_filter `mapKeys(m)` / `mapValues(m)` index by the structure of its expression in `findMapIndexPosition`, not by name. An index declared on `m.keys` / `m.values` is an INPUT node, so a plain merge would stop using it for `m['k']`, `mapContains*` and `has`. `findMapIndexPosition` now takes the subcolumn mapping: a mapped name resolves to the subcolumn index column, and an `arrayElement` map argument must be the table column itself, which is what `ExpressionMatcher::isSame` requires of the function index. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`optimize_functions_to_subcolumns` rewrites `m['k']` to the subcolumn `m.key_<k>` only for a table with bucketed Map serialization, and the runner randomizes `map_serialization_version`. Under `basic` the `= 1` queries took the same `arrayElement` path as the `= 0` ones, so the subcolumn-name branch of the index lookup was covered in about half of the runs. The tables now use `with_buckets`, and an EXPLAIN QUERY TREE check asserts the rewrite happens. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| auto first_argument = key_function_node.getArgumentAt(0); | ||
| const auto map_column_name = first_argument.getColumnName(); | ||
| if (const auto map_keys_index = getKeyIndex(fmt::format("mapKeys({})", map_column_name))) | ||
| if (const auto map_keys_index = getKeyIndex(getMapIndexColumnName(map_subcolumn_index_columns, "mapKeys", map_column_name))) |
There was a problem hiding this comment.
[Blocker] Probe extracted map keys as literals, not as value patterns
This enables the m.keys index for the branch that replaces const_value with the map key, but the branch keeps the original function_name. The later like/match handlers therefore interpret a literal key as a pattern. For example:
CREATE TABLE t
(
m Map(String, String),
INDEX i m.keys TYPE ngrambf_v1(3, 4096, 3, 0) GRANULARITY 1
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t SELECT map(unhex('61625c256364'), 'hello');
SELECT count() FROM t
WHERE m[unhex('61625c256364')] LIKE 'h%o'
SETTINGS optimize_functions_to_subcolumns = 0;
SELECT count() FROM t
WHERE m[unhex('61625c256364')] LIKE 'h%o'
SETTINGS optimize_functions_to_subcolumns = 0, use_skip_indexes = 0;Both counts must be 1. The stored key is the six bytes 61 62 5c 25 63 64, but stringLikeToBloomFilter treats its backslash as an escape and probes n-grams such as 61 62 25, which the stored key does not contain. This can discard the matching granule. There is also an exception case: match(m['['], '^h.*o$') reaches Regexps::createRegexp with [ as the regexp. Likewise, multiSearchAny(m['k'], ['hello']) replaces its array needle with a string and reaches safeGet<Array>.
After establishing that the original predicate cannot match a missing key, build a literal key-presence condition with stringToBloomFilter and return it directly. Apply this to the arrayElement and optimized subcolumn branches, with focused indexed-versus-scan tests. These examples are based on the current code trace; no PR-head binary is available for execution.
There was a problem hiding this comment.
This is pre-existing on master with the same index declared on mapKeys(m) (0 vs 1 for the escape-bearing key, Code: 427 for match(m['['], ...), Code: 170 for multiSearchAny(m['k'], ['hello']), both optimize_functions_to_subcolumns values); this PR only routes an m.keys index into that branch and gives the same results there. #119336 fixes that branch (a literal probe for the substituted key, no substitution for an array needle): with it applied on top of this PR, all three return the scan's count and the index still prunes.
|
Dear @shankar-iyer, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Related: #122420
Related: #122232
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
bloom_filter,text,tokenbf_v1orngrambf_v1skip index declared on thekeysorvaluessubcolumn of aMapcolumn (for exampleINDEX i m.keys TYPE bloom_filter) is now used for the same predicates as the same index onmapKeys(m)ormapValues(m), such asm['key'] = 'value'andmapContains(m, 'key'). ForLowCardinalitykeys or values, abloom_filterindex on the subcolumn is cheaper to build than one onmapKeys(m)ormapValues(m).Description
As discussed in #122420: an index on
m.keysis built from the stored keys (for a 2M-row INSERT intoMap(LowCardinality(String), LowCardinality(String))peak memory 172.6 MiB vs 605.9 MiB withmapKeys(m)), but index analysis looked a map's keys/values index up only by the namesmapKeys(m)/mapValues(m), som['k'] = v,m['k'] IN (...)andmapContains(m, k)withoptimize_functions_to_subcolumns = 0did not use it.IMergeTreeIndex::getMapSubcolumnIndexColumnsmapsmapKeys(m)/mapValues(m)to the index's ownm.keys/m.valuescolumn, and the existing lookups in thebloom_filter,textandtokenbf_v1/ngrambf_v1conditions use it. A column is mapped only if the index stores that input unchanged and a part builds it from the top-levelMapcolumnm. A dotted name can belong to another column: a part takes it from the shortest column prefix that has it as a subcolumn, so withj JSON(`m.keys` Array(String))next to`j.m` Map(String, String)an index onj.m.keysholds the JSON path and must not be used for`j.m`['k']. Indexes onmapKeys(m)/mapValues(m)behave as before.Docs: the
MergeTree,Mapand text index pages now describe indexes on thekeys/valuessubcolumns.Validation: the new test fails on master and passes 100/100 randomized runs. Over 2 map types, 5 index types and the
m['k'](=,IN,LIKE,notEmpty) andmapContains*predicates, a subcolumn index now selects the same granules as themapKeys(m)/mapValues(m)one, with identical results. Not changed:has(mapKeys(m), k)withoptimize_functions_to_subcolumns = 0,mapContainsKeyLikeovertokenbf_v1/ngrambf_v1with it set to 1, andtokenbf_v1/ngrambf_v1still cannot be created on the subcolumns of aLowCardinalitymap.Workflow [PR]
Sync PR [sync-upstream/pr/127482]