Skip to content

Build bloom_filter indexes over mapKeys and mapValues from the map's own column when writing a part - #122420

Closed
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:map-subcolumn-skip-index-build
Closed

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:map-subcolumn-skip-index-build

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122232

Changelog category (leave one):

  • Performance Improvement

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

A bloom_filter skip index over mapKeys(m) or mapValues(m) is now built from the map's own keys or values column when a part is written by INSERT or by a mutation that rewrites the whole part. For a map with LowCardinality keys or values this avoids copying all of them, which lowers the peak memory of such an INSERT. The index format does not change.

Description

A bloom_filter index over mapKeys(m) or mapValues(m) evaluated the function when a part was written. For LowCardinality keys or values these functions return the full type, so the index input copied every key or value and every row was hashed. The map's own keys column keeps LowCardinality, for which bloom_filter hashes only each granule's distinct dictionary entries (hashWithColumnDistinct, by Michael Jarrett: 731f43fb707ac, 6c9ab487253ee, e581ff6f30d9f).

The change is in one place, getCombinedIndicesExpression, which computes the skip-index inputs for INSERT and for mutations that rewrite the whole part. An output that is mapKeys(x) or mapValues(x) of a Map input, read only by bloom_filter indexes, is replaced by getSubcolumn(x, 'keys') or getSubcolumn(x, 'values') under the same name. A granule's hashes do not depend on the LowCardinality wrapper, so each granule's index is byte-identical to master's and the query side is unchanged. Not rewritten: an output that the sorting key or an index of another type also reads, a nested call, a name that is also a table column, and Array(Nullable), which bloom_filter refuses. MATERIALIZE INDEX on a wide part keeps master's code (reading the subcolumn there made some mutations read up to 18% more), and so do merges (at most 5% gain in the patch author's runs).

Part sizing also counts the index input, which is now smaller: rows wide enough for adaptive granularity to cut granules below index_granularity get fewer, larger granules, and a block just above min_bytes_for_wide_part can become a compact part.

Peak memory of one 2M-row INSERT (debug build, query_log.memory_usage): 872.8 -> 742.4 MiB with a mapKeys index (742.4 MiB with no index), 821.5 -> 742.4 MiB with a mapValues index, and 3.35 -> 2.16 GiB on the OpenTelemetry exporter logs schema with its six such indexes.

Based on the analysis and patch by @ snelheidai in #122232.

Validation
  • Index files are byte-identical to master for 7 key/value type shapes (including LowCardinality(FixedString(3)) and UUID), with packed and unpacked skip indexes on INSERT, and through full-part mutations of compact and wide parts under map_serialization_version basic and with_buckets.
  • Query results and index files are the same as master's for Replacing, Summing, Coalescing, Aggregating, Collapsing and VersionedCollapsing tables with optimize_on_insert, with projections, for a map inside a Tuple, for text indexes with a preprocessor or postprocessor, and for a table column named like the expression (ordinary, DEFAULT, MATERIALIZED, ALIAS, EPHEMERAL, and renamed while a mutation is pending).
  • 05258_bloom_filter_map_keys_values_insert compares indexed and unindexed counts for LowCardinality and plain maps, after a compact-part mutation, with the expression shared by the sorting key or by indexes of other types, nested in a larger expression, in a text index with a preprocessor, and next to a table column of the same name. Without the table-column exclusion, its INSERT INTO t_named fails with AMBIGUOUS_COLUMN_NAME. On master, its last two checks fail: with a mapKeys and a mapValues index, an INSERT takes 8.1x the memory of the same INSERT without them and a DELETE that rewrites the part takes 6.6x, against 1.2x and 1.1x with this change.
  • 05259_bloom_filter_map_values_nullable_attach: an attached table with a bloom_filter index over mapValues of LowCardinality(Nullable(String)) values, which CREATE refuses, keeps refusing INSERT as on master.

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

groeneai and others added 5 commits September 26, 2026 03:41
…umn on insert

A bloom_filter skip index over mapKeys(m) or mapValues(m) evaluated the
function, which strips LowCardinality from the element type and copies
every key or value. When a part is written from a block (INSERT and every
mutation that rewrites the whole part), such an index expression output is
now replaced by getSubcolumn(m, 'keys') / getSubcolumn(m, 'values'), the
map's own column, aliased to the declared name. The replaced function node
is removed, because ExpressionActions executes every node of the DAG.

Only bloom_filter indexes are rewritten: a bloom_filter granule is built
from the type of the column it is given, and its bytes do not depend on a
LowCardinality wrapper, while set and text build for the declared type. An
output that the key or an index of another type also reads is kept, and so
is an expression nested in a larger one.

MATERIALIZE INDEX on a wide part and merges are unchanged: reading the
keys or values substream there changes what the mutation reads, and with
map_serialization_version = 'with_buckets' a mutation that reads the map
and its subcolumn together already fails on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A table column that no index expression references is carried in the
block next to the computed index input of the same name, and a block
holds equally named columns only with the same type. So a name that is
also a physical column of the table keeps the declared expression.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ap on insert

Every other check in 05258 compares an indexed count with an unindexed
one. Index files are byte-identical by design, so all of them also pass
on master, and they would keep passing if the subcolumn rewrite silently
stopped firing.

The new block inserts the same 100000-row map with 20 long keys per row
into a table without skip indexes and into one with a mapKeys and a
mapValues bloom_filter index, and requires the second INSERT's peak
memory_usage to stay below 1.5x the first. On master, both functions
materialize every key and value, and the ratio is 8.2-12.6x (20
randomized runs). With the rewrite it is 1.11-1.28x (150 randomized
runs: local disk with max_untracked_memory 1Mi and 4Mi, and S3 storage).

The pins keep both tables on the same part format and write buffers:
basic map serialization (with_buckets adds per-bucket streams),
min_bytes_for_wide_part = 0, one block and one part, and default
compress block sizes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ap in a mutation

The memory check covered only INSERT. A mutation that rewrites the whole
part executes the same skip-index expression through its own caller
(MutateAllPartColumnsTask), and no check in 05258 would notice if that
caller stopped using the rewritten expression.

The block now also runs an ALTER DELETE on both tables and compares their
MutatePart peak_memory_usage in system.part_log. The countIf columns turn
a missing or duplicated MutatePart row into a visible difference.

A mutation reads one granule per block. Both tables therefore pin
index_granularity = 131072 (more than the 100000 rows) and
index_granularity_bytes = 268435456, so each part is a single granule on
master too, and master's mutation copies all keys and values at once, as
its INSERT does. Both checks now use a 2x bound.

Measured with the shipped file under randomized settings: on master the
INSERT takes 6.2-8.5x and the mutation 5.0-7.5x the memory of the same
statement without the indexes (40 runs); with the rewrite 1.08-1.17x and
1.06-1.15x (160 runs: local disk with max_untracked_memory 1Mi and 4Mi,
S3, and a Replicated database). A randomized min_bytes_for_full_part_storage
between the two parts' sizes packs only the part without indexes, which
lifts the rewrite's ratios to about 1.45x and 1.40x.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the comment on the shared result column to its invariant and move it to the loop it explains; say that `set` and `text` are examples of index types that build for the declared type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Sep 26, 2026
@groeneai

groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

An independent model reviewed this before publication (engine: codex; 2 findings over 3 rounds). I also did three cold reviews of my own.

# Sev Finding Verdict Evidence / action
1 ⚠️ The tests cannot tell the write-time rewrite from master: every check in 05258 also passes on master AGREE, fixed @ a16ba7c Added a peak-memory check: an INSERT with a mapKeys and a mapValues index against the same INSERT without them. It fails on master. Not a marks or part-type count, which would follow the sizing effect in row 3
2 ⚠️ That check covers INSERT only, not the mutation that rewrites the whole part, which calls the same expression separately AGREE, fixed @ 1d8436d The same comparison for an ALTER DELETE, from system.part_log, on a one-granule table (a mutation reads one granule per block). It fails on master
3 ⚠️ Part sizing counts the index input, so wide rows get fewer, larger granules, and a block near min_bytes_for_wide_part or min_bytes_for_full_part_storage can become a compact or packed part. Byte identity holds per granule, not per part AGREE Description and changelog entry scoped to that. Measured on 1000-byte rows: 14 marks instead of 16, and a Compact part where master writes a Wide one when the threshold lies between the two sizes. No code change: sizing already counted the transient column
4 💡 A legacy ATTACHed table with a bloom_filter over mapValues of LowCardinality(Nullable(V)) values (rejected at DDL since e9b0f0e) would accept INSERTs whose parts then fail to merge, where master rejects the INSERT AGREE, fixed @ 3433ef1 Such an output keeps the declared expression, so the INSERT is refused as on master. Covered by 05259_bloom_filter_map_values_nullable_attach
5 💡 The comment on the index-type check names set and text as if they were every non-bloom_filter type AGREE, fixed @ e531fef The comment now calls them examples

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260926-083700

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [806534a]

Summary: ❌

job_name test_name status info comment
Integration tests (arm_binary, 1/4) FAIL
test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested FAIL cidb
test_storage_delta/test_writes_interop.py::test_write_to_table_with_unsupported_writer_feature_is_rejected FAIL cidb
Performance Comparison (amd_release, master_head, 2/6) FAIL Performance dashboard
like_perfect_affix_rewrite #0 FAIL dashboard
iceberg_suite_local_rw_features #5 unstable query history

AI Review

Summary

This PR rewrites direct bloom_filter inputs over mapKeys / mapValues to the map subcolumns so inserts and full-part rewrites avoid materializing large LowCardinality arrays. The main implementation looks sound for the straight-line cases, but there is still one mixed-DAG shape where the old mapKeys node stays live and the promised insert-memory reduction disappears.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeData.cpp:1733] Replacing only the top-level output does not help when the same mapKeys(m) / mapValues(m) node is still consumed inside another selected expression. In shapes like INDEX ic formatRowNoNewline('JSONEachRow', mapKeys(m)) next to INDEX ik mapKeys(m), removeUnusedActions keeps the original node alive for ic, so the insert still materializes the full Array(String) and the direct bloom_filter index loses the advertised peak-memory win.
Final Verdict

⚠️ Needs changes before merge: the mixed nested-expression case still defeats the optimization, so the performance contract is not yet upheld across the full changed surface.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. label Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

The only source change is in MergeTreeData.cpp: when bloom_filter skip indexes over mapKeys(m) or mapValues(m) are built on INSERT, merge or mutation, the PR now reads the map's own keys or values column instead of materializing LowCardinality elements. The rest of the PR is tests. All five flagged improvements (clickbench Q30 -13.2%, Q33 -8.5%, Q34 -8.9%; tpch_adapted_1_official Q1 -18.5%, Q7 -25.9%) are read-only SELECTs over tables without such indexes, so all five are downgraded to not sure. Q33 and Q34 also sit inside master's recent range, and the TPC-H deltas are only 12 to 21 ms on noisy queries. These benchmarks do not measure the PR's real target, INSERT cost into tables with map key/value bloom_filter indexes; the new map_keys_values_index_build performance test does.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 228 198 -13.2% <0.0001 This SELECT never builds the primary-key or skip-index expressions the PR changes, which run only on INSERT, merge and mutation. The -13.2% shift is not attributable to this diff.
⚠️ 33 not_sure 1134 1038 -8.5% <0.0001 The changed code is index-expression construction on the write path, and the hits table has no mapKeys/mapValues bloom_filter indexes. The -8.5% shift sits inside master's recent range on a noisy query.
⚠️ 34 not_sure 1140 1038 -8.9% <0.0001 Like Q33, this read-only GROUP BY never reaches the changed write-path code. The -8.9% shift is inside master's recent range on a noisy query.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 53 -18.5% <0.0001 TPC-H Q1 is a read-only aggregation over tables with no Map columns or map skip indexes, so the diff cannot touch it. The -18.5% is only 12 ms on a very noisy query.
⚠️ 7 not_sure 81 60 -25.9% <0.0001 TPC-H Q7 is a read-only join query that never builds key or skip-index expressions for insert or merge. The -25.9% (21 ms) shift is not attributable to this diff.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: b5ea642a-be40-49e7-a4bd-85b8b826d5f4
  • MIRAI run: 45a37ab2-3ae9-4b7b-bb2b-8d7063447ee7
  • PR check IDs:
    • clickbench_1079130_1791821381
    • clickbench_1079136_1791821381
    • clickbench_1079142_1791821381
    • tpch_adapted_1_official_1079153_1791821381
    • tpch_adapted_1_official_1079164_1791821381
    • tpch_adapted_1_official_1079175_1791821381

groeneai and others added 2 commits September 26, 2026 15:56
A bloom_filter index over mapValues(m) of LowCardinality(Nullable(T))
values has the declared type Array(Nullable(T)), which the index hashing
refuses. CREATE and ALTER reject such an index since e9b0f0e, and ATTACH
still loads it so that it can be dropped: every INSERT, merge and
mutation of the table fails until then.

The subcolumn m.values is Array(LowCardinality(Nullable(T))), which the
hashing accepts. Built from it, an INSERT succeeded while merges, which
build from the declared expression, kept failing, so the table collected
parts that could never be merged. Such an output now keeps the declared
expression, and the INSERT fails as it does on master.

05259 attaches such a table: its INSERT fails with the index and succeeds
once the index is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
05258: EXPLAIN draws the plan as a tree by default. With parallel
replicas the local read is a branch of a Union, so its index lines start
with a tree guide that trimLeft keeps, and the test failed in the
ParallelReplicas job. Strip the guides with the same regular expression
other tests use.

map_keys_values_index_build: the two OpenTelemetry INSERTs took 2.5 s and
5.3-6.7 s per run in the performance jobs, which flag any query above
2 s. Fill 250000 rows instead of 2000000. In a local A/B the INSERT with
the indexes still takes 23% less time than on master (0.74 vs 0.96 s).

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

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 806534a04 with master ef230ad3f (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3d92e91

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
Performance Comparison (amd_release, master_head, 3/6) / is_valid_utf8 #0 The shard's own report calls it slower and the dashboard confirmed_regression: client_time 0.0125 -> 0.0150 s (+20.1%). The query, SELECT isValidUTF8(materialize(repeat('a', 8))) FROM numbers(3000000), reads no table, and this PR changes only how text and bloom_filter skip indexes over mapKeys/mapValues are built. The previous head was about as slow on it (+17.6%), while in the last 14 days only 7 of 1155 amd runs had the new side more than 15% slower, 2 of them this PR's two heads a fix task is created (investigating at full effort, fixing-PR link to follow here)
Performance Comparison (amd_release, master_head, 4/6) / sparse_column_index_runs #4, array_first_last #7 dashboard-only confirmed_regression (+21.5%, +18.5%): the shard's own report flags neither query (4 too long only). The dashboard scored both without master history (C3 unavailable, so its 2% floor) ClickHouse/performance-comparison#5 (external): the dashboard's confidence scoring. That repository is not publicly readable, so its state cannot be measured from here
Performance Comparison (arm_release, master_head, 6/6) / optimize_time_filter_with_preimage #6, #4 dashboard-only confirmed_regression (+29.1%, +20.1%): the shard's own report calls #6 only unstable and #4 OK, and the dashboard scored both without master history (C3 unavailable). In the last 7 days the in-tree report called these queries slower on 68 and 46 other pull requests, and on master ClickHouse/performance-comparison#5 (external), the same owner as the row above
Mergeable Check, PR rollups, red only because of the rows above the owners of the rows above: a fix task is created, and ClickHouse/performance-comparison#5 (external)

Session id: cron:our-pr-ci-monitor:20260926-223058

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Performance Comparison (amd_release, master_head, 3/6) red on is_valid_utf8 #0 is code placement, not this change, and it hits most PR runs on recent master:

  • PR runs based on master ee0c20b9 (2026-09-26 07:07 UTC) or a later commit read a median +11.6% on this query (25 runs, 7 of them scored confirmed_regression by the dashboard), against +0.7% on the 77 PR runs on earlier bases since 2026-09-25 12:00 UTC. Master runs, which compare two official builds, stayed flat.
  • The per-row loop in FunctionStringOrArrayToT<ValidUTF8Impl, ...>::executeImpl, its callee DB::UTF8::isValidUTF8 and ColumnString::replicate have identical instructions in this build, in the official reference and in seven other PR builds, three of them slow and four fast. The job's CPU flame graphs put the extra time in that loop (self samples 19 -> 60).
  • Resolve JSON path presence and Dynamic variant serializations once per block in JSONAllPaths and JSONAllValues #122387 (mine) read +16.8% on base a32c4c20 and -0.7% on base b3087d24, with only a test file changed between its two heads.

This is the class described in #122350 (comment), where the owner question is open. There is nothing to change in this PR.

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the amd_release 3/6 perf red (is_valid_utf8 #0): #124676

groeneai and others added 3 commits October 12, 2026 12:18
…index-build

Conflict in getCombinedIndicesExpression with ClickHouse#123291, which made the key optional
and added a per-expression filter for the expressions computed after an INSERT
merges its block (getSkipIndicesExpression).

The helper now always takes the key plus a `compute_key` flag. The post-merge
caller passes the sorting key with compute_key = false: those columns are already
in the block, and the writer replaces a block column named like an index
expression with the recomputed result. Without the key names, a bloom_filter over
mapKeys(m) on a table ordered by mapKeys(m) would recompute the sorting key column
as Array(LowCardinality(...)) instead of its declared type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nserted block

With optimize_on_insert and a ReplacingMergeTree, the sorting key is computed before
the merge and the skip index expressions after it. A bloom_filter over mapKeys(m) then
shares its result column with the sorting key, which must keep its declared type: a
build that rewrote it to the keys subcolumn aborted on the first INSERT with
"Bad cast from type DB::ColumnLowCardinality to DB::ColumnString" while writing the
primary index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…alues indexes

A ReplacingMergeTree INSERT with optimize_on_insert computes the skip index expressions
after the engine merge, a separate path from the plain MergeTree INSERT. With the indexes
built from the map's own columns the INSERT needs 1.10x the memory of the same INSERT
without indexes; when that path materializes mapKeys/mapValues instead it needs 5.51x.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
String subcolumn = function_name == "mapKeys" ? "keys" : "values";
auto subcolumn_type = std::make_shared<DataTypeString>();
const auto & subcolumn_name = dag.addColumn(subcolumn_type->createColumnConst(0, subcolumn), subcolumn_type, subcolumn);
const auto & get_subcolumn = dag.addFunction(FunctionFactory::instance().get("getSubcolumn", context), {map, &subcolumn_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 only swaps the top-level output pointer for mapKeys / mapValues. If the same node is still used as a child of some other selected expression, removeUnusedActions keeps the original mapKeys(m) node alive and we still materialize the full Array(String).

A concrete example is the shape you already test in t_nested: INDEX ic formatRowNoNewline('JSONEachRow', mapKeys(m)) next to INDEX ik mapKeys(m). ik is rewritten to getSubcolumn, but ic still depends on the old mapKeys(m) node, so the insert has to build that large transient column anyway and the advertised peak-memory win disappears for this mixed DAG. I think this needs either (1) a rewrite of all uses of the shared node, or (2) an explicit exclusion for names whose mapKeys / mapValues node still has non-rewritten parents, plus a test that documents that limitation.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 806534a

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
Integration tests (arm_binary, 1/4) / test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested, test_storage_delta/test_writes_interop.py::test_write_to_table_with_unsupported_writer_feature_is_rejected not from this PR: both tests broke on master after the Spark 4.0 runner bump, and fail on about 60 PRs and on master since 2026-10-12 11:04Z #125456 (mine, merged 2026-10-12 20:32Z). The tested merge commit predates it
Performance Comparison (amd_release, master_head, 2/6) / like_perfect_affix_rewrite #0 dashboard confirmed_regression only (in-tree success): client_time 0.131 -> 0.159 s (+20.9%) for SELECT count() FROM tab WHERE str LIKE 'prefix%' with the rewrite off. The table has no Map column and no skip index, so the index-build change of this PR does not run there, and the same query on arm is unchanged. The dashboard's own 14-day history flags this query on 11 master runs as well, in both directions a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the rows above #125456 and the fix task above

All 177 check runs completed and Finish Workflow is green. The map_keys_values_index_build INSERT queries this PR targets are 17-38% faster on both architectures. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261012-203012

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the amd_release 2/6 perf red (like_perfect_affix_rewrite #0): #125531

valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Oct 13, 2026
…ance test

With `optimize_rewrite_like_perfect_affix=0`, every row of the fixture
matches, so `MatchImpl` calls the dispatched StringZilla `sz_find` once per
row, 10M times per query. On amd the cost of that call varies by 5-10%
between binaries and between server processes (the red run's extra CPU
samples are all in `sz_find_skylake`), so over 30 days the old/new ratio of
`#0` crossed 15% in 29 of 1,193 master-vs-master runs and 26 of 1,316 PR
runs (median 1.001), and reddened `Performance Comparison (amd_release,
master_head, 2/6)` on unrelated ClickHouse#122420 (+20.9%, +17.2% after restart).
`ClickHouse#2` behaves the same. The rewrite-on arms never crossed 15% on amd
(0 of 2,518, p99 1.109 / 1.081).

The harness compares the same query index across builds, never one arm
against another, so the `=1` arms are the detector for the rewrite: if it
stopped applying they would get 1.6x to 1.7x slower. The rewrite-off LIKE
path stays measured by the two `optimize_rewrite_like_perfect_affix = 0`
arms of `regexp_anchored_literal.xml` (0 runs above 12% in over 1,050 amd
runs each), and correctness by `03594_like_perfect_affix_rewrite_pass`.
Same shape as ClickHouse#122156.

The survivors renumber to #0/ClickHouse#1, so their learned thresholds reset to the
0.15 floor, which is above their p99.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@Algunenano Algunenano 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.

@groeneai This solution seems too complex and not scalable at all. Are we supposed to do something like this for all functions that might benefit? Seems like we need a better approach / architecture

@Algunenano Algunenano self-assigned this Oct 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

No, it should not be done per function, and the better approach already exists: a skip index can be declared on the subcolumn itself, with no write-side code.

On master (debug build, one INSERT of the 2M rows of Map(LowCardinality(String), LowCardinality(String)) from this PR's perf test, max_insert_threads = 1, median of 3), peak memory:

Index Peak memory
none 169.5 MiB
mapKeys(m) TYPE bloom_filter 605.9 MiB
m.keys TYPE bloom_filter 172.6 MiB
mapValues(m) TYPE bloom_filter 516.8 MiB
m.values TYPE bloom_filter 172.6 MiB

The m.keys index file is byte-identical to the mapKeys(m) one (same for values), and it works through merges and MATERIALIZE INDEX. has(mapKeys(m), x) and mapContains(m, x) already use it, because the analyzer rewrites them to read m.keys. m['k'] = v does not: the bloom_filter condition looks the index up only by the names mapKeys(m) / mapValues(m) (tryResolveMapIndexInfo).

So I suggest closing this PR. Should I send a small query-side PR so that m['k'] also uses an index on m.keys / m.values, or is the subcolumn index enough as it is?

@Algunenano

Copy link
Copy Markdown
Member

So I suggest closing this PR. Should I send a small query-side PR so that m['k'] also uses an index on m.keys / m.values, or is the subcolumn index enough as it is?

Yes, that looks much better. Extending indices usage and documentation is the way to go

@Algunenano Algunenano closed this Oct 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'll send a PR so that m['k'] also uses skip indexes declared on m.keys / m.values, together with documentation for skip indexes on map subcolumns, and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Opened #127482: m['k'] predicates now use bloom_filter/text indexes declared on m.keys / m.values, and the MergeTree, Map and text index docs describe indexes on these subcolumns.

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-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

2 participants