Skip to content

Fix skip index analysis of a JSON path named like a Map key subcolumn - #122184

Open
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:no-column-enumeration-per-skip-index-condition
Open

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:no-column-enumeration-per-skip-index-condition

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122150
Related: #122144
Related: #119457

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed wrong results of queries filtering by a path of a JSON column a named like a key subcolumn of a Map column a.b, such as WHERE a.b.key_k = 'x': a bloom_filter, ngrambf_v1, tokenbf_v1, sparse_grams or text index over the map skipped granules with matching rows.

Description

Name resolution tries the shortest prefix first, so beside a Map a.b a JSON column a claims a.b.key_k as one of its paths, and the predicate reads the JSON. tryParseMapSubcolumnName refused only columns and static subcolumns with that name, so skip indexes over the map read it as key k of a.b and pruned the granule when the map had no such key. Now the name is resolved as the reader resolves it and accepted only if it is read from the map's storage column. Test 05621.

Also replace the IsShadowingColumn callback from #122144 with the table's columns: the skip index conditions keep the StorageMetadataPtr, and tryParseMapSubcolumnName takes the ColumnsDescription and looks the name up directly.

tests/performance/skip_indexes_wide_table.xml (64 bloom_filter indexes, 1000 columns) guards against enumerating the table's columns per skip index condition again, which #122144 removed.


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

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 25, 2026
@groeneai

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

Two rounds of pre-publication review by an independent model (engine: codex), plus my own cold review of
the resulting code in each round. Round 1 raised one finding, on the tests and none on src/; it was
fixed, src/ did not change between the rounds, and round 2 returned no findings on the amended tests.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new memory test could pass even if skip-index analysis declined every predicate, since a condition that is alwaysUnknownOrTrue is discarded immediately and the eager-set build would then retain only one name set at a time AGREE in remedy, DISAGREE in claim, now fixed The claim does not hold for this fixture: each of the 128 indexes is over one of s1..s10 and the predicate carries an equals atom on each, so none is always-unknown, and the test does fail on the pre-fix binary at a measured ratio of 5.3. The underlying point was right, that the oracle rested on an unasserted precondition, so the test now pins it per arm with an EXPLAIN indexes = 1 count of participating indexes, in the same shape 05188 uses. Proven live by mutating the oracle's input rather than the binary: the real predicate yields 128, a predicate leaving no usable atom yields 0. On the pre-fix binary the pinned line is unchanged and only the memory line flips, so the pin measures the fixture and not the fix
2 💡 src/DataTypes/DataTypeMapHelpers.h keeps an #include <Core/Names.h> that the header no longer needs DISAGREE Deliberate, not an oversight. Dropping an include from a header risks transitive breakage across its 7 includers, cannot be shown safe without a full build, and buys nothing here. Happy to remove it if a reviewer prefers

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding. Seven further nits were wording and accuracy corrections I made to this PR's own description
before posting, two of them checkable against the diff: the net line now says it counts src/ only, and
the list of index kinds that never consult this name test now also names hypothesis.

One scope decision worth stating plainly: I did not add a tests/performance/ test. I swept the shape
space first, and every shape whose quartiles separate cleanly needs at least 25 KB of literal column
declarations, while every compact wide shape has overlapping quartiles and would be flaky. The measured
time arm is in the description instead, and the memory invariant is guarded deterministically by the
stateless test.

Session id: cron:clickhouse-review-slot-9:20260925-083004

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [376eba1]

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 fixes Map-key skip-index analysis by verifying resolved substream identity and passing metadata directly to index conditions. The added regression passes on head 376eba131639999bb12ee20bef541b60b0f76447. Three pre-existing correctness defects remain in the affected JSON and text-index matching paths; each reproducibly drops matching rows.

Findings

❌ Blockers

  1. JSON claimant validation confuses sibling subcolumns. MergeTreeIndexJSONSubcolumnHelper.cpp:97: with c Tuple(j JSON, `j.x` String) and a bloom_filter index on JSONAllPaths(c.j), inserting tuple(CAST('{}', 'JSON'), 'hit') makes WHERE c.j.x = 'hit' return 1 with indexes disabled and 0 with them enabled. Both subcolumns have storage name c, but different substreams. IN ('hit') also fails. Verify ancestry under the indexed JSON's resolved substream path.

  2. Text-index JSON matchers bypass claimant validation. MergeTreeIndexJSONSubcolumnHelper.h:50: JSON matcher calls in MergeTreeConditionBloomFilterText and MergeTreeIndexConditionText omit the optional metadata argument. For columns j JSON and a literal j.x String, inserting '{}', 'hit' makes WHERE j.x = 'hit' return 1 → 0 when enabling a JSONAllPaths(j) index of type text or tokenbf_v1. A text index on JSONAllValues(j) also fails for equality and IN. Require metadata and supply it at every caller in both condition classes.

  3. Text-index matching confuses literal column names with computed expressions. MergeTreeIndexBloomFilterText.cpp:1051: with m Map(String, String) and an indexed literal mapKeys(m) Array(String) column, inserting map('k', 'hit'), ['other'] makes WHERE m.key_k = 'hit' return 1 → 0 when enabling the index. Reproduced for both tokenbf_v1 and text, and for the analogous literal JSONAllPaths(m) column. Metadata validation of the predicate cannot establish what the index computed. Validate the index expression DAG, following the existing bloom_filter implementation.

Tests
  • ⚠️ Add focused stateless regressions for the three failures above, including JSON equality and IN and both text-index condition implementations. Fixes should preserve index use for genuine subcolumns.
Final Verdict

❌ Block. Fix these incorrect-pruning paths with regression coverage, or link explicit tracking issues for the inherited defects before approval.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 25, 2026
@groeneai
groeneai requested review from CurtizJ and ahmadov September 25, 2026 09:05
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 376eba131 with master c78b7b9d3 (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

20 object files changed (+7.94 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/DataTypeMapHelpers.cpp.o 59.55 KiB 81.62 KiB +22.07 KiB (+37.05%)

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.58, programs/clickhouse-keeper ×0.69 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.0 s +5.0 s (+250%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.93 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -1120.9 s (-7%) in total before that adjustment.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 437d1d8f-a8f1-4c57-8bd7-64251b29a209
  • MIRAI run: 262f5f63-9472-4d81-ba71-84e30fe45511
  • PR check IDs:
    • clickbench_2253342_1790612702
    • clickbench_2253347_1790612702
    • clickbench_2253354_1790612702
    • tpch_adapted_1_official_2253361_1790612702
    • tpch_adapted_1_official_2253377_1790612702
    • tpch_adapted_1_official_2253413_1790612703

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6c77e3d

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, 4/6) / bit_positions_to_array_big_int #1 dashboard-verdict red: client_time 0.2358 -> 0.2746 (+16.4%), confirmed_regression. Job info 5 too long; 1 confirmed regression(s) on the performance dashboard, so the shard's own report calls this query neither slower nor unstable, and CIDB carries no failing test row for it. Query #1 of that file is SELECT count() FROM numbers(1000000) WHERE NOT ignore(bitPositionsToArray(toInt128(-1) * toInt128(1 + number % 2))): it reads no table and the fixture declares no skip index, while this diff only removes a per-condition column enumeration inside bloom and text skip-index condition construction, so the changed code is never entered and the change only deletes work. CIDB flags the query slower on master itself as well as on unrelated pull requests. Rule 3d, measured at the tree the job actually built rather than at this head: format_utc_date_time from #121847 is present in that job's confirmed checkout 97b04909b37e, and the verdict fired anyway, so #121847 does not own this row ClickHouse/performance-comparison#5 (external, open): the dashboard's confidence scoring, which @ fm4v named on 2026-09-23 as where these verdicts are handled after #121847. That repository is not publicly readable, so its state cannot be measured from here
Performance Comparison (arm_release, master_head, 5/6) / json_to_string #1 dashboard-verdict red: client_time 1.3643 -> 1.6658 (+22.1%), confirmed_regression. Query #1 is SELECT sum(length(toString(payload))) FROM json_to_string_shared_data, whose table is ENGINE = MergeTree ORDER BY id with no skip index of any type declared in the fixture, so again this diff cannot reach it. CIDB flags the query slower on 17 distinct pull requests (36 rows) in 30 days, master included. The same shard also reports array_fill #3 as unstable, which is not the cause of the red: three other shards of this very run carry unstable queries and are green (amd 2/6 with 3, arm 2/6 with 1, arm 4/6 with 2) ClickHouse/performance-comparison#5 (external, open), the same owner as the row above
Performance Comparison (arm_release, master_head, 6/6) / bitmap_cardinality #1 dashboard-verdict red: client_time 0.3339 -> 0.4375 (+31.0%), confirmed_regression. Query #1 aggregates bitmapAndCardinality over numbers(2000), and the only table in the fixture is ENGINE = Memory, so no MergeTree skip-index analysis runs there at all. This is the broadest fixture of the three: CIDB carries 276 slower or unstable rows for it across 119 distinct pull requests in 30 days, 14 of them on master with no pull request involved ClickHouse/performance-comparison#5 (external, open), the same owner as the rows above
Mergeable Check, PR rollup rows with no independent failure of their own. Mergeable Check reports Failed: 3, matching exactly the three shards above ClickHouse/performance-comparison#5 (external, open), the same owner as the rows above

All 176 check runs completed (157 pass, 14 not selected, 5 red), Finish Workflow is green, and
CH Inc sync passed on this head, so no sync row is owed. Across CI as a whole this job-level
confirmed regression(s) on the performance dashboard verdict red 101 distinct pull requests on 110
commits in the last 24 hours.

No master merge is pushed for this, and that is measured rather than a preference: the one
ClickHouse-side fix in this family, #121847, is already in the tree that ran, so there is nothing to
pick up, and no repo-side repair for it is open either (no open pull request of its author touches
that gate), so the remaining half lives in the dashboard service and cannot be merged from here.

Session id: cron:our-pr-ci-monitor:20260925-150335

@rschu1ze rschu1ze 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 Remove all slop, make this fix as minimal and clean as it can get.

ClickHouse#119457 made each bloom_filter, ngrambf_v1, tokenbf_v1, sparse_grams and text
index condition build and keep a set of every column and static subcolumn
named like a Map key subcolumn, which costs O(indexes x columns) on every
filtered SELECT. Look up the one parsed name in the table's columns instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai force-pushed the no-column-enumeration-per-skip-index-condition branch from 6c77e3d to 30d258d Compare September 28, 2026 11:43
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 30d258d, now a single commit: the check is one ColumnsDescription::tryGetColumn lookup inside the existing tryParseMapSubcolumnName (no new function, no rename, src/ +35/-57), and the stateless test is replaced by tests/performance/skip_indexes_wide_table.xml.

@groeneai
groeneai requested a review from rschu1ze September 28, 2026 11:44
Comment thread src/DataTypes/DataTypeMapHelpers.cpp Resolved
…dex analysis

A subcolumn of an EPHEMERAL column is not readable, so `a.b.key_x` next to an EPHEMERAL
`a Tuple(b Tuple(key_x String))` still reads the map `a.b`, and the removed column census
did not refuse it. Keep that behaviour.

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

groeneai commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e2db640

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, 5/6) / join_squashing_blocks #0 dashboard confirmed_regression, client_time 0.116 -> 0.136 s (+17.2%), while the shard's own report does not flag the query (3 too long only). The query is select count() from ttt left join (select number from numbers(10)) r on x = number over a MergeTree table with no skip index and no filter, so no skip-index condition is built. The query is noisy on amd on its own: in 14 days it moved by more than 15% in 91 of 797 amd runs, 55 of them master-vs-master, and in none of 1680 arm runs #126173 (ours, open)
Performance Comparison (arm_release, master_head, 4/6) / least_greatest_const_columns #2 dashboard confirmed_regression, client_time 0.220 -> 0.263 s (+19.3%), while the shard's own report does not flag the query (4 too long, 1 faster). The query computes greatest over strings from numbers(5000000) and reads no table. In 14 days it moved by more than 15% in 34 of 1676 arm runs (9 master-vs-master) and in 97 of 799 amd runs (61 master-vs-master) #122784 (ours, merged)
Mergeable Check, PR rollups, red only because of the two shards above #126173 (ours, open) and #122784 (ours, merged)

All 146 check runs completed (109 passed, 35 not selected, 2 red), Finish Workflow is green and
CH Inc sync passed. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260928-200457

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the arm_release 4/6 perf red (least_greatest_const_columns #2): #122784

pull Bot pushed a commit to mikeyhodl/ClickHouse that referenced this pull request Sep 29, 2026
…columns performance test

`least_greatest_const_columns #2` returns the 256-byte constant `repeat('d', 256)` for every row, so
the result `ColumnString` grows its `chars` by power-of-two `realloc` up to 16 MiB per block. Whether
jemalloc grows that buffer in place or moves and copies it (`large_ralloc` -> `memcpy`) differs
between server processes, and in CI CPU profiles that copy is the only part of the query whose sample
count differs between the two servers. In 14 days the two servers differed by more than 15% in 94 of
775 amd and 23 of 1692 arm runs of this query, and in none for `#3`, which takes the same arguments
with `least` and returns the ~7-byte `toString(number)`.

Add a constant `'e'` that wins every row, so the result is one byte per row. The query still compares
`toString(number)` against the four 256-byte constants that are not materialized since ClickHouse#119108, and
still returns a constant argument.

Failing job: https://github.com/ClickHouse/ClickHouse/actions/runs/36432228454/job/109047348805
PR: ClickHouse#122184

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

groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the amd_release 5/6 perf red (join_squashing_blocks #0): #125278 (closed unmerged: the release binaries stay PIE). A fix task is moved to pending; the fixing-PR link will follow here.

@CurtizJ CurtizJ self-assigned this Oct 11, 2026
…on-per-skip-index-condition

# 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
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a4a94ea

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
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) not from this PR (it only changes how skip-index conditions look up Map subcolumn names): after the upgrade restart a background mutation keeps retrying on the empty part all_1_1_1_2 that DETACH PART leaves in 04653_mutation_rewrite_stale_part_column_type, and logs MutatePlainMergeTreeTask: Code: 47 ... Unknown expression identifier 'b' (UNKNOWN_IDENTIFIER). The same line failed this check on 76 other PRs in 30 days and on no master run #125293 (external, open)
Mergeable Check, PR praktika rollups of the row above #125293 (external, open)

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

Session id: cron:our-pr-ci-monitor:20261013-200005

@groeneai

groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the amd_release 5/6 perf red (join_squashing_blocks #0): #125949. Withdrawn: reds like this one were as common before PIE (PR side at least 15% slower in 1.9% of PR runs from Jul 1 to Sep 9, 1.4% since Sep 15), so PIE does not explain it. I will investigate it separately and post the result here. Per-query numbers: #125949 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Result for the amd_release 5/6 red (join_squashing_blocks #0): not caused by this PR or by PIE. The join's probe loop calls AddedColumns::appendFromBlock out of line for every matched row, and in about one build in 64 the linker places the callee where that call makes the query 17-20% slower; this happened at the same rate before PIE. The build of e2db640 has that placement and its reference build does not. Fixing PR: #126173, which removes the call when the join outputs no right-table column.

alexey-milovidov pushed a commit to JayPokale/ClickHouse that referenced this pull request Oct 19, 2026
…ight-table column

The hash join probe loops called the out-of-line AddedColumns::appendFromBlock
for every matched row. When the join outputs no column of the right table,
record_row_refs is false and the callee returned immediately, but the call
stayed in the loop, and its cost depended on where the linker placed the loop
and the callee: join_squashing_blocks #0/ClickHouse#1 ran 17-20% slower in about one
build in 64 (the amd_release reds on ClickHouse#122184 and ClickHouse#120758), and 1.4x slower in
some process starts.

Make appendFromBlock ALWAYS_INLINE so the record_row_refs test happens in the
loop, and keep the recording part, LazyOutput::addRef, out of line with
NO_INLINE: inlining its body into every probe loop made
hashjoin_low_cardinality_key #0 5-10% slower and pushed processMatch out of
line, even in loops where addRef never runs. Joins that record row refs keep
one call per match, to the same body as before.

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

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, 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.

@CurtizJ CurtizJ self-assigned this Nov 11, 2026
CurtizJ and others added 3 commits November 11, 2026 17:12
…tion-per-skip-index-condition

Master already replaced the per-condition census of names shadowing Map key subcolumns with a lazy
`IsShadowingColumn` callback (ClickHouse#122144), which is what this
branch did with a `StorageMetadataPtr`. Take master's version of the conflicting files and keep this
branch's behaviour for `EPHEMERAL` columns in `IMergeTreeIndex::getMapSubcolumnShadowingCheck`: a
subcolumn of an `EPHEMERAL` column is not readable, so it does not refuse the Map key subcolumn.

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

Replace the `IsShadowingColumn` callback that came from master
(ClickHouse#122144) with this branch's original approach:
each `bloom_filter`, `ngrambf_v1`/`tokenbf_v1`/`sparse_grams` and `text` index condition keeps the
`StorageMetadataPtr`, and `tryParseMapSubcolumnName` takes the `ColumnsDescription` and looks the
name up directly. Remove `IMergeTreeIndex::getMapSubcolumnShadowingCheck`.

A subcolumn of an `EPHEMERAL` column is not readable, so it again does not refuse the Map key
subcolumn, as tested in `05188_map_subcolumn_shadowed_by_physical_column`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
CurtizJ and others added 2 commits November 11, 2026 22:45
Name resolution tries the shortest prefix first, so beside a Map `a.b` a JSON column `a` claims
`a.b.key_zzz` as one of its paths, and a predicate on that name reads the JSON. `tryParseMapSubcolumnName`
refused only columns and static subcolumns with that name, so `bloom_filter`, `tokenbf_v1`, `ngrambf_v1`,
`sparse_grams` and `text` indexes over the map read it as key `zzz` of `a.b` and pruned granules whose
rows match. Resolve the name as the reader does and accept it only if it is read from the Map's storage
column.

Also count subcolumns of `EPHEMERAL` columns as claimants again, as master does: the analyzer binds the
name to them, with their type. Drop the `EPHEMERAL` case from `05188`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@CurtizJ CurtizJ changed the title Do not enumerate the table's columns for every skip-index condition Fix skip index analysis of a JSON path named like a Map key subcolumn Nov 11, 2026
Comment thread src/DataTypes/DataTypeMapHelpers.cpp Resolved
… key subcolumn

Two paths of one storage column can claim the same flat name: in
``c Tuple(`j.m` Map(String, String), j JSON(m Map(String, String)))`` the element answers `c.j.m`, while
the path `m` of the JSON element answers `c.j.m.key_k`. Both resolve to the storage column `c`, so
`tryParseMapSubcolumnName` accepted the JSON value as a key of the element map, and skip indexes over it
pruned matching rows. Accept the name only if its substreams path is the Map's path followed by
`MapKeyValue`, as `subcolumnDescendsFromColumn` does for rewrites.

Move `isSameSubstream` to `ISerialization`: `FunctionToSubcolumnsPass` and `DeltaLakeMetadataDeltaKernel`
had identical private copies.

PR: ClickHouse#122184
Review: ClickHouse#122184 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The two red Performance Comparison (arm_release, master_head, iceberg_local|iceberg_s3, 2/3) shards come from this PR's skip_indexes_wide_table.xml: the Iceberg configuration creates its table as Iceberg, and the ALTER ... ADD INDEX setup query fails with Code: 48. DB::Exception: Alter of type 'ADD_INDEX' is not supported by Iceberg storage (report). That configuration drops skip indexes anyway, so the test has nothing to measure there. One line in tests/performance/iceberg_skip_list.txt excludes it, as for text_index_partially_materialized.xml:

skip_indexes_wide_table.xml                              # ALTER ADD_INDEX

I have not pushed it because you are working on the branch; I can push it if you want.

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

LGTM

@CurtizJ
CurtizJ dismissed rschu1ze’s stale review November 13, 2026 16:24

Everything is good now.

CurtizJ and others added 3 commits November 13, 2026 16:27
…tion-per-skip-index-condition

Resolve conflicts with ClickHouse#130814: keep its expression
matching (`index_nodes`) and the `IsShadowingJSONSubcolumn` check, and keep passing the
`StorageMetadataPtr` instead of the removed `IsShadowingColumn` callback for Map key subcolumns.

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

Replace the `IsShadowingJSONSubcolumn` callback and `IMergeTreeIndex::getJSONSubcolumnShadowingCheck`
by a `ColumnsDescription` passed to `tryMatchJSONSubcolumnToIndex` and `tryMatchNodeToJSONIndex`,
as for Map key subcolumns: the `bloom_filter` condition already holds the metadata snapshot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
if (auto column = columns.tryGetColumn(options, String(name)))
{
auto json = columns.tryGetColumn(options, String(json_column));
if (!json || column->getNameInStorage() != json->getNameInStorage())

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] Verify the resolved substream of the indexed JSON

The relocated claimant check still accepts different subcolumns of the same storage column. With c Tuple(j JSON, `j.x` String), both c.j and c.j.x have storage name c, so this check accepts the sibling string as path x of the indexed JSON.

Reproduced with the current head's Fast test binary:

CREATE TABLE t
(
    c Tuple(j JSON, `j.x` String),
    INDEX idx JSONAllPaths(c.j) TYPE bloom_filter GRANULARITY 1
)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t SELECT tuple(CAST('{}', 'JSON'), 'hit');
SELECT count() FROM t WHERE c.j.x = 'hit' SETTINGS use_skip_indexes = 0;
SELECT count() FROM t WHERE c.j.x = 'hit' SETTINGS use_skip_indexes = 1;

The counts are 1 and 0, and EXPLAIN shows idx pruning the only granule. IN ('hit') also loses the row. Resolve the full name and verify that its substream path actually descends from the indexed JSON's path, as the Map helper now does, and add a stateless regression. This defect is retained from the moved implementation.

const String & json_function_name,
const JSONIndexArgumentTypes & json_argument_types,
const IsShadowingJSONSubcolumn & is_shadowing_subcolumn = {});
const ColumnsDescription * columns = nullptr);

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] Require metadata for every JSON-index matcher caller

The optional metadata parameter lets callers bypass claimant validation entirely. All JSON matcher calls in MergeTreeConditionBloomFilterText and MergeTreeIndexConditionText still omit it, including MergeTreeIndexBloomFilterText.cpp:430,595 and MergeTreeIndexConditionText.cpp:1321,2439,2491. Both condition classes now retain the metadata needed for the check.

For example, on the current head:

CREATE TABLE t
(
    j JSON,
    `j.x` String,
    INDEX idx JSONAllPaths(j) TYPE text(tokenizer = 'array') GRANULARITY 1
)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ('{}', 'hit');
SELECT count() FROM t WHERE j.x = 'hit' SETTINGS use_skip_indexes = 0;
SELECT count() FROM t WHERE j.x = 'hit' SETTINGS use_skip_indexes = 1;

The counts are 1 and 0: the predicate reads the physical string, while the index probes the absent JSON path. The same failure reproduces with tokenbf_v1(512, 3, 0) over JSONAllPaths(j), and with a text index over JSONAllValues(j) for equality and IN.

Make metadata mandatory and pass it through every JSON matcher call in both classes, with stateless coverage. This is an existing unsafe path retained by the API refactor; fixing the claimant check alone cannot cover these callers.

{
return std::make_shared<MergeTreeConditionBloomFilterText>(
predicate, context, index.sample_block, params, tokenizer.get(), getMapSubcolumnShadowingCheck(), collectJSONIndexArgumentTypes(*index.expression));
predicate, context, index.sample_block, params, tokenizer.get(), metadata_snapshot, collectJSONIndexArgumentTypes(*index.expression));

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] Validate the indexed expression in both text-index conditions

The strengthened Map-subcolumn check validates the predicate's source, but the text-index conditions still identify the indexed expression solely by its header name. A literal column named mapKeys(m) therefore passes the subsequent lookup even though its index contains unrelated data:

CREATE TABLE t
(
    m Map(String, String),
    `mapKeys(m)` Array(String),
    INDEX idx `mapKeys(m)` TYPE tokenbf_v1(512, 3, 0) GRANULARITY 1
)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (map('k', 'hit'), ['other']);
SELECT count() FROM t WHERE m.key_k = 'hit' SETTINGS use_skip_indexes = 0;
SELECT count() FROM t WHERE m.key_k = 'hit' SETTINGS use_skip_indexes = 1;

On the current head the counts are 1 and 0. Replacing the index type with text(tokenizer = 'array') also fails. Both implementations likewise lose rows when a literal JSONAllPaths(m) column is mistaken for the function's result.

Carry and validate the index expression DAG in both text-condition classes, following findMapIndexPosition and collectJSONIndexColumns in the bloom_filter implementation, and cover the Map and JSON variants together. This pre-existing failure remains reachable through the changed matchers even after supplying metadata and checking substream ancestry.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The three findings of the latest automated review reproduce identically on master before #130814, on the head of #130814, and on this head (count() is 1 without skip indexes and 0 with them in every listed variant), so this PR neither introduces nor fixes them. The claimant check added by #130814 compares storage columns only and is passed by the bloom_filter condition alone, and the tokenbf_v1/ngrambf_v1/text conditions still find the index by its header name (mapKeys(m)), which also loses the row for m['k'] = 'hit'. I can fix all three, here or in a separate PR, whichever you prefer.

@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 19, 2026

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. groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bloom/text skip index copies every column name per query: +20% on wide tables

3 participants