Repository navigation
Fix text index on mapValues/mapKeys not used through a Distributed engine table - #109188
Conversation
…gine table A text index defined on mapValues(map) or mapKeys(map) was used for a local MergeTree table and via cluster()/remote(), but silently NOT used when the same table was queried through a Distributed engine table with the analyzer, failing with INDEX_NOT_USED under force_data_skipping_indices. StorageDistributed only serializes the query to shards and never reads columns locally, but it inherited the default supportsOptimizationToSubcolumns() = true. The Distributed table has no secondary indices in its own metadata, so FunctionToSubcolumnsPass on the initiator rewrote mapValues(attributes) to the subcolumn attributes.values and serialized that form to the shards, where it no longer matched the index expression. IStorageCluster (cluster()/remote()) already returns false here for the same reason; StorageDistributed was the missing case. The shard re-runs the analyzer against the real underlying table, so legitimate subcolumn optimizations still happen shard-side where the physical read occurs. Closes ClickHouse#108874. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260702-125700 |
|
cc @CurtizJ @novikd — could you review this? It fixes a text index on |
|
Workflow [PR], commit [23b0ba6] Summary: ✅
AI ReviewSummaryThis PR closes the original Final Verdict✅ No new findings in the current diff. |
A database with lazy_load_tables = 1 wraps each table in a StorageTableProxy. StorageProxy forwarded supportsSubcolumns() to the nested storage but not supportsOptimizationToSubcolumns(), which fell back to the IStorage default (tied to supportsSubcolumns() == true). A proxy around Distributed therefore re-advertised true, so FunctionToSubcolumnsPass rewrote mapValues(attributes) to a subcolumn on the initiator before serializing the shard query, and the text index defined on mapValues/mapKeys was missed again for a lazy-loaded Distributed engine table even after StorageDistributed opted out. Forward supportsOptimizationToSubcolumns() through the proxy to the nested storage. Extend the regression test with a lazy_load_tables = 1 case. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… Merge StorageDistributed and StorageProxy already opt out of the subcolumn optimization so a text index on mapValues/mapKeys is not lost through a Distributed engine table. Two more wrapper storages still tied the capability to the IStorage default (supportsSubcolumns() == true): - StorageMaterializedView::readImpl forwards the already-analyzed query tree to the target table without rebuilding it, so a MV whose target is Distributed could still rewrite mapValues(attributes) -> attributes.values on the initiator. Forward supportsOptimizationToSubcolumns() to the target. - StorageMerge over a Distributed child could serialize attributes.values to the shards. Add a fail-closed override that returns false if any child table opts out (same traverseTablesUntil pattern as supportsPrewhere). Extends 02346_text_index_bug108874 with MV-over-Distributed and Merge-over-Distributed cases (mapValues and mapKeys), asserting the index is used via force_data_skipping_indices.
StorageBuffer read() and getQueryProcessingStage() forward the already-analyzed query to the destination table, so it must not let the initiator rewrite functions to subcolumns when the destination opts out (e.g. Distributed). It kept the IStorage default (supportsOptimizationToSubcolumns() == supportsSubcolumns() == true), so a Buffer over a Distributed destination still rewrote mapValues(attributes) / mapKeys(attributes) before the query was split, and the shard query missed the text index (or threw INDEX_NOT_USED under force_data_skipping_indices). Add the fail-closed override mirroring supportsPrewhere(): forward to the destination, false when there is none. Extends the regression to a flushed Buffer over logs_dist. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Fixed in 50ad567. Verified both directions against
Regression |
Pre-PR validation gate (StorageBuffer follow-up, click to expand)
Session id: cron:clickhouse-worker-slot-5:20260702-163000 |
CI finish ledger — 50ad567Every failure below has an owner (a fixing PR). Neither failure is caused by this PR's diff (which only adds
Session id: cron:our-pr-ci-monitor:20260702-220000 |
|
@groeneai merge fresh master into the branch |
…-text-index-mapvalues-distributed
|
@novikd merged fresh master ( |
CI finish ledger — 320b49dEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
PR-caused gate: ZERO. This PR's diff is Session id: cron:our-pr-ci-monitor:20260703-210000 |
|
@groeneai merge fresh master into the branch |
…-text-index-mapvalues-distributed
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 26/29 (89.66%) · Uncovered code |
CI finish ledger — 23b0ba6Every failure below has an owner: a fixing PR (ours or external). None is PR-caused (this PR's diff is
Session id: cron:our-pr-ci-monitor:20260707-233000 |
3400dba
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRFix text index on mapValues/mapKeys not used through a Distributed engine table ClickGap verified: reproduced it with the script below on Reproduction-- Requires a running server with a 2-shard cluster and the analyzer.
SET enable_full_text_index = 1, enable_analyzer = 1;
CREATE TABLE logs
(
attributes Map(String, String),
INDEX attributes_vals_idx mapValues(attributes) TYPE text(tokenizer = 'array') GRANULARITY 1
) ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE logs_dist AS logs
ENGINE = Distributed('test_cluster_two_shards_localhost', currentDatabase(), logs, rand());
INSERT INTO logs VALUES ({'ip': '192.168.1.1'});
-- Before #109188: Code 277 INDEX_NOT_USED (text index on mapValues silently
-- skipped through the Distributed table). After #109188: returns 2 (index used).
SELECT count() FROM logs_dist WHERE has(mapValues(attributes), '192.168.1.1')
SETTINGS force_data_skipping_indices = 'attributes_vals_idx';Bisect
Affects
Suggested next stepThe fix has landed on master; the affected release branches above still need the backport. Component: cc fix PR author: @groeneai ClickGap · Finding: Triage metadata
|
…ression test The buggy rewrite only fires via name != '' -> notEmpty(name) -> name.size, which requires optimize_empty_string_comparisons enabled. clickhouse-test randomizes this setting; when it flips to 0 the query stays a plain notEquals and the test would pass even on a pre-ClickHouse#109188 binary, defeating the regression guard. Pin it so the reproducer is deterministic under random-settings CI. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…olumns on Distributed) Fixed by ClickHouse#109188 (StorageDistributed::supportsOptimizationToSubcolumns now returns false). This adds the reproducer from the issue as a stateless test. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Backport #109188 to 26.6: Fix text index on mapValues/mapKeys not used through a Distributed engine table
26.4 does not have #109188, which makes `StorageMerge` and `StorageDistributed` opt out of the `optimize_functions_to_subcolumns` rewrite. When the test runner randomizes that setting to 1, `mapValues(attributes)` in PREWHERE is rewritten to the subcolumn `attributes.values`, which `Merge` rejects with `ILLEGAL_PREWHERE`: "Table expression logs_merge does not support column attributes.values in PREWHERE". Pin the setting to 0 so the predicate keeps the function form that matches the text-index expression, as in the original repro. Verified against the arm_release binary of this PR: the unpinned test fails with `ILLEGAL_PREWHERE` under `optimize_functions_to_subcolumns = 1`, the pinned test matches the reference. Failing check: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111095&sha=7cc36ee3705fc895035c88523cc7a4553e8dd41e&name_0=BackportPR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%2C%201%2F2%29 Co-Authored-By: Claude Fable 5 <[email protected]>
26.3 does not have #109188, which makes `StorageMerge` and `StorageDistributed` opt out of the `optimize_functions_to_subcolumns` rewrite. When the test runner randomizes that setting to 1, `mapValues(attributes)` in PREWHERE is rewritten to the subcolumn `attributes.values`, which `Merge` rejects with `ILLEGAL_PREWHERE`. Pin the setting to 0 so the predicate keeps the function form that matches the text-index expression, as in the original repro. Same fix as on backport/26.4/110710 (PR #111095), where it was verified against the PR's arm_release binary: the unpinned test fails with `ILLEGAL_PREWHERE` under `optimize_functions_to_subcolumns = 1`, the pinned test matches the reference. Co-Authored-By: Claude Fable 5 <[email protected]>
26.5 does not have #109188, which makes `StorageMerge` and `StorageDistributed` opt out of the `optimize_functions_to_subcolumns` rewrite. When the test runner randomizes that setting to 1, `mapValues(attributes)` in PREWHERE is rewritten to the subcolumn `attributes.values`, which `Merge` rejects with `ILLEGAL_PREWHERE`. Pin the setting to 0 so the predicate keeps the function form that matches the text-index expression, as in the original repro. Same fix as on backport/26.4/110710 (PR #111095), where it was verified against the PR's arm_release binary: the unpinned test fails with `ILLEGAL_PREWHERE` under `optimize_functions_to_subcolumns = 1`, the pinned test matches the reference. Co-Authored-By: Claude Fable 5 <[email protected]>
26.6 does not have #109188, which makes `StorageMerge` and `StorageDistributed` opt out of the `optimize_functions_to_subcolumns` rewrite. When the test runner randomizes that setting to 1, `mapValues(attributes)` in PREWHERE is rewritten to the subcolumn `attributes.values`, which `Merge` rejects with `ILLEGAL_PREWHERE`. Pin the setting to 0 so the predicate keeps the function form that matches the text-index expression, as in the original repro. Same fix as on backport/26.4/110710 (PR #111095), where it was verified against the PR's arm_release binary: the unpinned test fails with `ILLEGAL_PREWHERE` under `optimize_functions_to_subcolumns = 1`, the pinned test matches the reference. Co-Authored-By: Claude Fable 5 <[email protected]>
…ys not used through a Distributed engine table
…4-text-index-mapvalues-distributed Fix text index on mapValues/mapKeys not used through a Distributed engine table
…olumns on Distributed) Fixed by ClickHouse#109188 (StorageDistributed::supportsOptimizationToSubcolumns now returns false). This adds the reproducer from the issue as a stateless test. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ression test The buggy rewrite only fires via name != '' -> notEmpty(name) -> name.size, which requires optimize_empty_string_comparisons enabled. clickhouse-test randomizes this setting; when it flips to 0 the query stays a plain notEquals and the test would pass even on a pre-ClickHouse#109188 binary, defeating the regression guard. Pin it so the reproducer is deterministic under random-settings CI. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…bcolumnsPass IStorage::supportsOptimizationToSubcolumns reads like a flag, but wrapper storages answer it by traversing what they wrap. StorageMerge overrides it with a full traverseTablesUntil over every child table (added by b2be878, PR ClickHouse#109188), traverseTablesUntilImpl re-creates the database iterators on every invocation, and DatabaseTablesSnapshotIterator holds the table map by value, so each call also copies it. FunctionToSubcolumnsPass reads that predicate from getTypedNodesForOptimization and getTypedNodesForChainedOptimization, which are reached from four per-query-tree-node call sites, and it reads it before the function name is consulted (the name check happens later in enterImpl). A query with N function nodes over a Merge table with T children therefore paid N traversals of T tables even when no function is rewritable. The rewritable set is 13 names and includes neither position nor multiIf, so the merge_table_large_query perf test (1504 position calls over 500 children) performed roughly 750k child visits for a rewrite that can never fire. Analysis became O(query-tree nodes x child tables) where it used to be O(nodes). The answer is a property of the storage, so this memoizes it in an unordered_map<const IStorage *, bool> held by each visitor, i.e. for the lifetime of one pass run. TableNode holds the StoragePtr by value and no updateStorage caller runs inside a query tree pass, so the key cannot be recycled mid-run; nothing is cached across queries or DDL, so there is no invalidation story. All twelve carriers of the predicate are pure reads of storage configuration, so only the number of computations changes, never the answer. Measured on one Debug binary with the perf test's own fixture, flipping optimize_functions_to_subcolumns (QueryAnalysisMicroseconds, medians of 5 interleaved runs): before, 90807 us with the pass off vs 403557 us with it on (4.44x); after, 99388 vs 99853 (1.005x). The same query over a plain MergeTree does not move on either build (1.07x / 1.02x), and the query result is byte-identical in all four cells. A 28-cell matrix over Array, Nullable, LowCardinality, LowCardinality(Nullable), Map, Tuple, String, empty array and count(), against both a supporting and an opting-out Merge, is identical on both builds. The new stateless test asserts that the memoized answer equals a fresh one on both the supporting and the fail-closed arm, including two storages whose answers differ within one query, an empty match set, and a Merge over a Merge. Because it is a semantics-preservation test it is green with and without this change, so its liveness was established by mutation: a mutant that ignores the cache key and a mutant that always reports support are both caught. DistanceTransposedPartialReadsPass reads the same predicate per node but checks the function name first, requires a UInt64 constant precision, and is gated on optimize_qbit_distance_function_reads, so it cannot exhibit this blow-up and is left alone. Not copying the table map in DatabaseTablesSnapshotIterator would help all traverseTablesUntil callers, but it changes a documented snapshot semantic in every database engine and is a separate concern. PR ClickHouse#109188 was backported to 26.6.2, so 26.6.2+ and 26.7+ carry the regression. Closes ClickHouse#113202.
Closes: #108874
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a text index defined on
mapValues(map)ormapKeys(map)being silently not used when a table was queried through aDistributedengine table with the analyzer. The index was used for the local table and viacluster()/remote(), but a query through aDistributedengine table skipped it (and failed withINDEX_NOT_USEDunderforce_data_skipping_indices).Description
Reported in #108874. A
textindex onmapValues(attributes)(ormapKeys(attributes)) is used when querying the localMergeTreetable and viacluster()/remote(), but silently not used when the same table is queried through aDistributedengine table with the analyzer.Root cause:
StorageDistributedonly serializes the query to shards and never reads columns locally, but it inherited the defaultsupportsOptimizationToSubcolumns() = supportsSubcolumns() = true. TheDistributedtable has no secondary indices in its own metadata, so the index-safety guard inFunctionToSubcolumnsPass(which refuses to rewrite columns required by a secondary index) never seesattributesas index-relevant on the initiator. The pass therefore rewritesmapValues(attributes)to the subcolumnattributes.valuesand serializes that form into the shard query, where it no longer matches the index defined onmapValues(attributes).IStorageCluster(which backscluster()/remote()) already returnsfalsefromsupportsOptimizationToSubcolumns()for exactly this reason (commit0c9926a7045d);StorageDistributedwas the missing case. This PR adds the same override.Because the shard re-runs the analyzer against the real underlying table (with full index metadata), legitimate subcolumn optimizations still happen shard-side where the physical read actually occurs, so there is no lost optimization.
Reproducer (needs the analyzer and a 2-shard cluster):
Added a regression test:
02346_text_index_bug108874.Version info
26.7.1.701(included in26.7and later)26.6.2.89