Skip to content

Use skip indexes on Map keys/values subcolumns for m['key'] predicates - #127482

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:map-subcolumn-skip-index-element
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:map-subcolumn-skip-index-element

Conversation

@groeneai

@groeneai groeneai commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122420
Related: #122232

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A bloom_filter, text, tokenbf_v1 or ngrambf_v1 skip index declared on the keys or values subcolumn of a Map column (for example INDEX i m.keys TYPE bloom_filter) is now used for the same predicates as the same index on mapKeys(m) or mapValues(m), such as m['key'] = 'value' and mapContains(m, 'key'). For LowCardinality keys or values, a bloom_filter index on the subcolumn is cheaper to build than one on mapKeys(m) or mapValues(m).

Description

As discussed in #122420: an index on m.keys is built from the stored keys (for a 2M-row INSERT into Map(LowCardinality(String), LowCardinality(String)) peak memory 172.6 MiB vs 605.9 MiB with mapKeys(m)), but index analysis looked a map's keys/values index up only by the names mapKeys(m)/mapValues(m), so m['k'] = v, m['k'] IN (...) and mapContains(m, k) with optimize_functions_to_subcolumns = 0 did not use it.

IMergeTreeIndex::getMapSubcolumnIndexColumns maps mapKeys(m)/mapValues(m) to the index's own m.keys/m.values column, and the existing lookups in the bloom_filter, text and tokenbf_v1/ngrambf_v1 conditions use it. A column is mapped only if the index stores that input unchanged and a part builds it from the top-level Map column m. A dotted name can belong to another column: a part takes it from the shortest column prefix that has it as a subcolumn, so with j JSON(`m.keys` Array(String)) next to `j.m` Map(String, String) an index on j.m.keys holds the JSON path and must not be used for `j.m`['k']. Indexes on mapKeys(m)/mapValues(m) behave as before.

Docs: the MergeTree, Map and text index pages now describe indexes on the keys/values subcolumns.

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) and mapContains* predicates, a subcolumn index now selects the same granules as the mapKeys(m)/mapValues(m) one, with identical results. Not changed: has(mapKeys(m), k) with optimize_functions_to_subcolumns = 0, mapContainsKeyLike over tokenbf_v1/ngrambf_v1 with it set to 1, and tokenbf_v1/ngrambf_v1 still cannot be created on the subcolumns of a LowCardinality map.


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

groeneai and others added 2 commits October 22, 2026 19:59
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ❌ After a DDL drops the column that claimed P.keys when parts were written, old granules are read for P['k'] DISAGREE (separate PR) Master already reads the same index by name for mapContains(m, k) (rewritten to has(m.keys, k)) and has(P.keys, k); the gap is ALTER not rebuilding an index whose input changes source
2 ❌ tokenbf_v1/ngrambf_v1 reject LowCardinality map subcolumns DISAGREE (code), wording fixed Creatability is unchanged (same refusals on master); the changelog now limits the build-cost claim to bloom_filter and states the limitation
3 ❌ tokenbf_v1/ngrambf_v1 subcolumn index not used for m['k'] IN (...) DISAGREE (code), wording fixed A mapKeys(m) index of these types is not used for it either; the changelog no longer lists IN as an example
4 💡 Test lacks text IN/mapContainsValue and ngrambf_v1 cases DROPPED Checked by the local equivalence matrix (all types, both forms)
5 💡 sparse_grams shares the tokenbf_v1 condition, so it is also affected, but is not named in the changelog AGREE, noted It behaves like a sparse_grams index on mapKeys(m); not claimed because it was not measured

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@mintlify

mintlify Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 516895d.

Approve preview

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master every force_data_skipping_indices statement of the new test (20 of them, bloom_filter, text, tokenbf_v1) fails with INDEX_NOT_USED; a 2 map types x 5 index types x 15 predicates matrix shows 180 cells where an index on mapKeys(m)/mapValues(m) prunes and one on m.keys/m.values is not used.
b Root cause explained? The three map-aware index conditions find the index column holding map X's keys/values only by the name mapKeys(X)/mapValues(X); an index declared on the subcolumn has the column name X.keys/X.values, so it is never found although it holds the same elements.
c Fix matches root cause? Yes. The lookup also accepts the index's own X.keys/X.values column, but only when the index stores that input unchanged and a part computes it from the top-level Map column X. No setting, no special case per predicate.
d Test intent preserved / new tests added? New 05443_map_subcolumn_skip_index_element.sql; no existing test changed.
e Both directions demonstrated? Master: all 20 forced statements INDEX_NOT_USED. Fix: all pass, 100/100 randomized runs. Removing either half of the guard gives wrong results (0 rows instead of 64) for its schema; the JSON case of the test fails then.
f Fix is general across code paths? All 18 mapKeys/mapValues name lookups of the bloom_filter, text and tokenbf_v1/ngrambf_v1 conditions; no other index formats such names.
g Fix generalizes across inputs (params/datatypes/wrappers)? String and LowCardinality maps, Enum and FixedString keys, LowCardinality(Nullable(String)) values, absent keys and default values (m['zz'] = '' is not pruned), optimize_functions_to_subcolumns 0 and 1 (arrayElement and m.key_<k> forms).
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; indexes on mapKeys(m)/mapValues(m) select exactly the same granules as before; an existing m.keys index is used for more predicates with identical results.
i Invariants and contracts preserved? The mapping only redirects to a column of the same index header, so positions and types stay consistent; it is per-condition const state. A name claimed by another column (a JSON path, a Tuple element, a column literally named m.keys) or a stored x AS m.keys alias is never mapped.

Session id: cron:clickhouse-impl-slot-5:20261022-192300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @ahmadov @shankar-iyer, could you review this and add the can be tested label so CI runs? The bloom_filter, text and tokenbf_v1/ngrambf_v1 conditions found a map keys/values index only by the names mapKeys(m)/mapValues(m), so an index declared on m.keys/m.values was skipped for m['k'] = v; they now also accept the subcolumn column, only when the index stores it unchanged from the top-level Map column m.

@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [516895d]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR lets skip indexes on Map keys/values subcolumns serve predicates previously recognized through mapKeys/mapValues expressions. Four correctness blockers remain: the three existing findings still apply, and a newly identified key-substitution error can discard matching rows or reject valid queries.

Findings

❌ Blockers

  • src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp:1687 — Padded constants can hide missing-key matches. The map-equality guard compares a raw Field with the constant type's default. For m Map(String, String) containing only map('present', 'value'), m['missing'] = toFixedString('', 2) matches the scan, but the padded constant passes the guard and either mapped subcolumn index can eliminate the row. Use the actual equality semantics when checking the missing element's default, and normalize or decline incompatible probes. Existing finding.
  • src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:654 — A pattern matching the missing-key default must not become a key-presence requirement. With a tokenbf_v1 or ngrambf_v1 index on m.keys, m['missing'] LIKE '%' can lose rows: the guard compares the pattern literal to the default instead of evaluating the predicate on that default. The same issue applies to match with '^$', through both arrayElement and optimized subcolumn access. Decline extraction whenever the original predicate can match the missing element. Existing finding.
  • src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1311 — Text-index probes disagree with dictionary comparison. For Map(LowCardinality(String), String) with an array-tokenized text index on m.keys, mapContainsKey(m, toFixedString('hello', 10)) searches the dictionary for hello, but index extraction retains the five padding bytes and can discard the matching row. mapContainsValue with corresponding values has the same problem. Derive needle normalization from the actual element comparison, or decline extraction. Existing finding.
  • src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:654 — Extracted keys are incorrectly interpreted as value patterns. After substituting the map key for the original needle, extraction retains the original function. With ngrambf_v1(3, 4096, 3, 0), the key unhex('61625c256364') and value hello, m[unhex('61625c256364')] LIKE 'h%o' probes escaped-pattern n-grams absent from the stored literal key and can eliminate its row. A key [ is compiled as a regexp for a valid match predicate; multiSearchAny instead reaches safeGet<Array> with the substituted string. Build a literal key-presence condition directly after the missing-key safety check, in both map-access branches. New finding.
Tests
  • ⚠️ Add focused indexed-versus-scan regressions for padded FixedString equality on missing keys, patterns matching missing-key defaults, LowCardinality dictionary coercion for both map subcolumns, and literal keys containing pattern metacharacters. Include multiSearchAny to cover its array needle and both values of optimize_functions_to_subcolumns where supported. The new test covers ordinary predicates but does not exercise these failures.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary is available, so this run verified findings through current-code traces. At the reviewed head, CI skips the relevant builds and targeted stateless tests because the three earlier review threads remain unresolved; the passing fast test does not establish that these reproductions are fixed. Run the focused SQL regressions against a binary containing the fixes.
Final Verdict

Status: ❌ Block

Correct the four predicate-extraction errors and add focused regression coverage before merging.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 22, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 22, 2026
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))

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted) failure (STID 1611-37da, j.m.keys index in a merge): #127527

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 34f8e7a

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
AST fuzzer (amd_debug, targeted) / Logical error: Unexpected return type from A. Expected B. Got C. Action: (STID: 1611-37da) LOGICAL_ERROR in a merge, reproduces on master, not from this PR (it changes only the query-side index lookup): the fuzzer turned the t_json table of 05443 into a Map j.m next to a JSON j with a typed m.keys path, and OPTIMIZE builds the j.m.keys index from the other column (Expected Array(String). Got Array(LowCardinality(String))) #127527 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / same STID 1611-37da same message and shape as the row above #127527 (mine, open)
PR praktika rollup of the rows above #127527 (mine, open)

The Config Workflow / Pre Hooks failure is the earlier attempt stopped at the can be tested label; the current attempt passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261023-023006

@shankar-iyer shankar-iyer self-assigned this Oct 23, 2026
…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
Comment on lines +1300 to +1301
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));

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@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 Nov 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 41e367615 with master 96face4ae (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.

Object file sizes

13 object files changed (+33.34 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndices.cpp.o 203.13 KiB 219.52 KiB +16.39 KiB (+8.07%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 41e3676

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
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Unexpected return type from A. Expected B. Got C. Action: (STID: 1611-37da) LOGICAL_ERROR in a merge, reproduces on master, not from this PR (it changes only the query-side index lookup): same message as on the previous head, materialize(j.m.keys) Expected Array(String). Got Array(LowCardinality(String)) #127527 (mine, open)
La Casa Del Dolor (amd_debug) / Server shutdown shutdown hang, not from this PR (it does not touch merge selection): at the scheduled restart DDLWorker::shutdown waited for a fuzzed ON CLUSTER OPTIMIZE TABLE ... FINAL CLEANUP of a plain MergeTree, which waits in StorageMergeTree::selectPartsToMerge for running merges without checking query cancellation, so the server was force-killed after the 30 s stop window. First occurrence of this stack a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above #127527 (mine, open) and a fix task is created (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261106-190058

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for La Casa Del Dolor (amd_debug) / Server shutdown created: #129875

groeneai and others added 2 commits November 21, 2026 13:36
…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)))

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

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.

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. pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants