Repository navigation
Build bloom_filter indexes over mapKeys and mapValues from the map's own column when writing a part - #122420
Build bloom_filter indexes over mapKeys and mapValues from the map's own column when writing a part#122420groeneai wants to merge 10 commits into
bloom_filter indexes over mapKeys and mapValues from the map's own column when writing a part#122420Conversation
…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]>
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.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260926-083700 |
|
Workflow [PR], commit [806534a] Summary: ❌
AI ReviewSummaryThis PR rewrites direct Findings
Final Verdict |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (3 of 43)
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_officialFlagged queries (2 of 22)
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
|
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 40 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 3d92e91Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260926-223058 |
|
The
This is the class described in #122350 (comment), where the owner question is open. There is nothing to change in this PR. |
|
Fixing PR for the amd_release 3/6 perf red (is_valid_utf8 #0): #124676 |
…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}, {}); |
There was a problem hiding this comment.
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.
CI finish ledger - 806534aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 177 check runs completed and Session id: cron:our-pr-ci-monitor:20261012-203012 |
|
Fixing PR for the amd_release 2/6 perf red (like_perfect_affix_rewrite #0): #125531 |
…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
left a comment
There was a problem hiding this comment.
@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
|
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
The So I suggest closing this PR. Should I send a small query-side PR so that |
Yes, that looks much better. Extending indices usage and documentation is the way to go |
|
Acknowledged. I'll send a PR so that |
|
Opened #127482: |
Closes: #122232
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
bloom_filterskip index overmapKeys(m)ormapValues(m)is now built from the map's own keys or values column when a part is written byINSERTor by a mutation that rewrites the whole part. For a map withLowCardinalitykeys or values this avoids copying all of them, which lowers the peak memory of such anINSERT. The index format does not change.Description
A
bloom_filterindex overmapKeys(m)ormapValues(m)evaluated the function when a part was written. ForLowCardinalitykeys 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 keepsLowCardinality, for whichbloom_filterhashes 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 forINSERTand for mutations that rewrite the whole part. An output that ismapKeys(x)ormapValues(x)of aMapinput, read only bybloom_filterindexes, is replaced bygetSubcolumn(x, 'keys')orgetSubcolumn(x, 'values')under the same name. A granule's hashes do not depend on theLowCardinalitywrapper, 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, andArray(Nullable), whichbloom_filterrefuses.MATERIALIZE INDEXon 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_granularityget fewer, larger granules, and a block just abovemin_bytes_for_wide_partcan become a compact part.Peak memory of one 2M-row
INSERT(debug build,query_log.memory_usage): 872.8 -> 742.4 MiB with amapKeysindex (742.4 MiB with no index), 821.5 -> 742.4 MiB with amapValuesindex, 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
LowCardinality(FixedString(3))andUUID), with packed and unpacked skip indexes onINSERT, and through full-part mutations of compact and wide parts undermap_serialization_versionbasicandwith_buckets.optimize_on_insert, with projections, for a map inside aTuple, fortextindexes 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_insertcompares indexed and unindexed counts forLowCardinalityand 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 atextindex with a preprocessor, and next to a table column of the same name. Without the table-column exclusion, itsINSERT INTO t_namedfails withAMBIGUOUS_COLUMN_NAME. On master, its last two checks fail: with amapKeysand amapValuesindex, an INSERT takes 8.1x the memory of the same INSERT without them and aDELETEthat 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 abloom_filterindex overmapValuesofLowCardinality(Nullable(String))values, whichCREATErefuses, keeps refusingINSERTas on master.Workflow [PR]
Sync PR [sync-upstream/pr/122420]