Skip to content

Fix text index on mapValues/mapKeys not used through a Distributed engine table - #109188

Merged
novikd merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-108874-text-index-mapvalues-distributed
Jul 9, 2026
Merged

novikd merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-108874-text-index-mapvalues-distributed

Conversation

@groeneai

@groeneai groeneai commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #108874

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 a text index defined on mapValues(map) or mapKeys(map) being silently not used when a table was queried through a Distributed engine table with the analyzer. The index was used for the local table and via cluster()/remote(), but a query through a Distributed engine table skipped it (and failed with INDEX_NOT_USED under force_data_skipping_indices).

Description

Reported in #108874. A text index on mapValues(attributes) (or mapKeys(attributes)) is used when querying the local MergeTree table and via cluster()/remote(), but silently not used when the same table is queried through a Distributed engine table with the analyzer.

Root cause: StorageDistributed only serializes the query to shards and never reads columns locally, but it inherited the default supportsOptimizationToSubcolumns() = supportsSubcolumns() = true. The Distributed table has no secondary indices in its own metadata, so the index-safety guard in FunctionToSubcolumnsPass (which refuses to rewrite columns required by a secondary index) never sees attributes as index-relevant on the initiator. The pass therefore rewrites mapValues(attributes) to the subcolumn attributes.values and serializes that form into the shard query, where it no longer matches the index defined on mapValues(attributes).

IStorageCluster (which backs cluster()/remote()) already returns false from supportsOptimizationToSubcolumns() for exactly this reason (commit 0c9926a7045d); StorageDistributed was 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):

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 this PR: Code 277 INDEX_NOT_USED. After: the index is used.
SELECT count() FROM logs_dist WHERE has(mapValues(attributes), '192.168.1.1')
  SETTINGS force_data_skipping_indices = 'attributes_vals_idx';

Added a regression test: 02346_text_index_bug108874.

Version info

  • Merged into: 26.7.1.701 (included in 26.7 and later)
  • Backported to: 26.6.2.89

…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]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM logs_dist WHERE has(mapValues(attributes), '192.168.1.1') SETTINGS force_data_skipping_indices = 'attributes_vals_idx' throws Code 277 INDEX_NOT_USED every time on master (2-shard cluster, enable_analyzer=1, enable_full_text_index=1).
b Root cause explained? Yes. StorageDistributed inherited the default supportsOptimizationToSubcolumns() = supportsSubcolumns() = true. The Distributed table has no secondary indices in its own metadata, so FunctionToSubcolumnsPass's index-safety guard never marks attributes as index-relevant on the initiator; it rewrites mapValues(attributes) to the subcolumn attributes.values and serializes that form to the shards, where it no longer matches the index defined on mapValues(attributes). Confirmed by capturing the shard query: Distributed path sent has(__table1.attributes.values, ...) while cluster() sent has(mapValues(__table1.attributes), ...); and optimize_functions_to_subcolumns=0 fixes it.
c Fix matches root cause? Yes. StorageDistributed::supportsOptimizationToSubcolumns() now returns false, so the pass no longer rewrites functions to subcolumns for a Distributed engine table. This directly targets the rewrite identified in (b).
d Test intent preserved / new tests added? New regression test 02346_text_index_bug108874 added; no existing test weakened. It asserts the index is used through local, cluster(), and Distributed-engine paths via force_data_skipping_indices (which throws INDEX_NOT_USED when the index is not used).
e Demonstrated in both directions? Yes. With the fix reverted (byte-identical to the original binary), the new test FAILS with INDEX_NOT_USED; with the fix it PASSES. Verified through the clickhouse-test harness.
f Fix is general, not a narrow patch? Yes. Audited all remote storages: IStorageCluster already returns false (same reason, commit 0c9926a7045d); StorageDistributed was the only remote storage still returning true. Fix covers both mapValues and mapKeys (verified) and any function-to-subcolumn rewrite, not just the one reported. Buffer/Merge/MaterializedView are not isRemote (they read locally, so the optimization is legitimate there).
g Fix generalizes across inputs? Yes. The change is at the storage-capability level, independent of the specific function/type. Verified mapValues and mapKeys both fixed; legitimate subcolumn optimizations (e.g. length(arr)) still fire shard-side (the shard re-runs the analyzer against the real table), so no optimization is lost for any input.
h Backward compatible? Yes. No setting default, on-disk/wire/replication format, or existing validation changed. The behavior change is: a query through a Distributed engine table now correctly uses skip indices that were previously missed (a strict improvement). No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. supportsOptimizationToSubcolumns() is a per-storage capability hint; returning false for a storage that never reads columns locally is exactly its contract (mirrors IStorageCluster). No data-structure, concurrency, or block-structure invariant is touched. Subcolumn optimization still happens on the shard where the physical read occurs.

Session id: cron:clickhouse-worker-slot-3:20260702-125700

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @novikd — could you review this? It fixes a text index on mapValues(map)/mapKeys(map) being silently skipped when a table is queried through a Distributed engine table with the analyzer. Root cause: StorageDistributed inherited supportsOptimizationToSubcolumns() = true, so FunctionToSubcolumnsPass rewrote mapValues(attributes) to the subcolumn attributes.values on the initiator and sent that to the shards, where it no longer matched the index. IStorageCluster already returns false here; this adds the same override to StorageDistributed.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [23b0ba6]

Summary: ✅


AI Review

Summary

This PR closes the original Distributed-table text-index miss and the follow-up wrapper leaks that were raised during review by making supportsOptimizationToSubcolumns fail closed or forward correctly through StorageDistributed, StorageProxy, StorageMaterializedView, StorageMerge, and StorageBuffer. I re-checked the current code and the changed test, and I did not find a remaining correctness, compatibility, or missing-wrapper issue in the patched paths.

Final Verdict

✅ No new findings in the current diff.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 2, 2026
Comment thread src/Storages/StorageDistributed.h Resolved
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]>
Comment thread src/Storages/StorageProxy.h Resolved
Comment thread src/Storages/StorageDistributed.h Resolved
… 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.
Comment thread src/Storages/StorageMerge.h Resolved
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]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in 50ad567. StorageBuffer now overrides supportsOptimizationToSubcolumns() to forward to the destination table (false when there is none), mirroring its supportsPrewhere() — so a Buffer over a Distributed destination fails closed just like StorageMerge/StorageMaterializedView.

Verified both directions against test_cluster_two_shards_localhost with a flushed Buffer over logs_dist:

  • Without the override: SELECT ... FROM logs_buffer WHERE has(mapValues(attributes), '192.168.1.1') SETTINGS force_data_skipping_indices = 'attributes_vals_idx' throws Code: 277 INDEX_NOT_USED (the initiator rewrote mapValues(attributes) before splitting, so the shard query lost the index).
  • With the override: returns the expected count, index used.

Regression 02346_text_index_bug108874 extended with mapValues/mapKeys buffer-over-dist cases.

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (StorageBuffer follow-up, click to expand)
# Question Answer
a Deterministic repro? Yes. Flushed Buffer(currentDatabase(), logs_dist, ...) over a Distributed destination; SELECT count() FROM logs_buffer WHERE has(mapValues(attributes), '192.168.1.1') SETTINGS force_data_skipping_indices='attributes_vals_idx' throws Code: 277 INDEX_NOT_USED on demand without the fix.
b Root cause explained? StorageBuffer::read()/getQueryProcessingStage() forward the already-analyzed query to the destination, but it inherited the IStorage default supportsOptimizationToSubcolumns() == supportsSubcolumns() == true. So FunctionToSubcolumnsPass rewrote mapValues(attributes) -> attributes.values on the initiator before the query was split; the shard query then carried a subcolumn that no longer matched the text index.
c Fix matches root cause? Yes. Adds the fail-closed supportsOptimizationToSubcolumns() override keyed off the destination table (mirrors supportsPrewhere()), so the initiator does not rewrite when the destination (e.g. Distributed) opts out.
d Test intent preserved / new tests added? Regression 02346_text_index_bug108874 extended with mapValues/mapKeys buffer-over-dist cases over a flushed Buffer on logs_dist, using force_data_skipping_indices so a missed index throws (proves the index is used).
e Both directions demonstrated? Yes. Without override: INDEX_NOT_USED (Build ID 02d29617…). With override: count 2, full test 5/5 pass (Build ID b6cb8a4a…).
f Fix is general across code paths? Yes. Completes the wrapper family: StorageDistributed (opt-out), StorageMerge/StorageMaterializedView/StorageProxy (forward), and now StorageBuffer (forward). No remaining IStorage-default wrapper over Distributed.
g Fix generalizes across inputs? Covered by the destination-forwarding design: the capability is whatever the destination reports, for any destination engine. Test exercises both mapValues and mapKeys.
h Backward compatible? Yes. Only tightens an in-memory capability flag used during analysis; no setting default, on-disk/wire format, or new data validation.
i Invariants and contracts preserved? Yes. Mirrors the existing supportsPrewhere() contract on the same class (fail closed when the destination is absent/unresolvable via getDestinationTable() which returns null, never throws for this purpose).

Session id: cron:clickhouse-worker-slot-5:20260702-163000

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 50ad567

Every failure below has an owner (a fixing PR). Neither failure is caused by this PR's diff (which only adds supportsOptimizationToSubcolumns() fail-closed overrides on StorageBuffer/StorageProxy/StorageMaterializedView/StorageMerge/StorageDistributed + a text-index regression test) — both are pre-existing trunk bugs the fuzzer/stress runs happened to hit on this branch.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Column ... already added for reading (STID 4792-5e4c) trunk bug (text-index virtual column re-added when make_distributed_plan re-runs optimizeTreeSecondPass) #108818 (ours, open)
Stateless tests (arm_asan_ubsan, azure, sequential) / AddressSanitizer (STID 0883-397d) + Server died trunk bug (0883 family: use-after-free reading String .size subcolumn across granules during merge) #109020 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260702-220000

@novikd

novikd commented Jul 3, 2026

Copy link
Copy Markdown
Member

@groeneai merge fresh master into the branch

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

@novikd merged fresh master (eb26de7) into the branch. New head: 320b49dec25dfd805ac19c2c9ef1194b76ba1f07. No conflicts; diff unchanged (9 files, +159/-0, no submodule drift). CI is re-running.

@groeneai

groeneai commented Jul 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 320b49d

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Column ... already added for reading (STID 4792-5e4c) trunk bug (text-index double-add via make_distributed_plan) #108818 (ours, open)
Stateless tests (arm_asan_ubsan, targeted) / Server died + Segmentation fault (STID 1367-3620), 03310_materialized_view_with_bad_select ERROR crash (ColumnString::doInsertRangeFrom -> MergeTreeDataPartWriterCompact compact-merge write; 0883 arm_asan_ubsan segfault family) #109020 (ours, open)

PR-caused gate: ZERO. This PR's diff is supportsOptimizationToSubcolumns() fail-closed capability overrides + a regression test; neither failure relates to it. Both are pre-existing trunk bugs, each isolated to this PR's fuzzer/targeted run by coincidence of the randomized surface. Same two families were owned on the prior head (50ad567) by the same open fixing PRs.

Session id: cron:our-pr-ci-monitor:20260703-210000

@novikd

novikd commented Jul 7, 2026

Copy link
Copy Markdown
Member

@groeneai merge fresh master into the branch

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

@novikd merged fresh master into the branch. New head: 23b0ba697e458c9cc0552a076335f3733ce7b71e (merge of prior head 320b49d + master 63e4476, no conflicts). Diff unchanged: 9 files, +159/-0, no submodule drift. CI is re-running.

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.70% 85.80% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 78.00% +0.10%

Changed lines: Changed C/C++ lines covered: 26/29 (89.66%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 23b0ba6

Every failure below has an owner: a fixing PR (ours or external). None is PR-caused (this PR's diff is supportsOptimizationToSubcolumns fail-closed capability overrides on Storage{Buffer,Distributed,MaterializedView,Merge,Proxy} + the 02346 regression test; none of the failures touch that code path).

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Column ... already added for reading (STID 4792-5e4c) trunk fuzzer (text-index double-add via make_distributed_plan) #108818 (ours, open)
Stateless tests (arm_asan_ubsan, azure, sequential) / Server died + Segmentation fault trunk crash (0883 MergeMutate merge-writer family; core.MergeMutate, MergedBlockOutputStream write path, not this PR's storage-proxy diff) #109020 (ours, open)
Performance Comparison (arm_release, master_head, 5/6) arm perf report-build Code-243 (all query rows success, no regression) #109397 (ours, open)
CH Inc sync private sync CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260707-233000

@novikd
novikd added this pull request to the merge queue Jul 9, 2026
Merged via the queue into ClickHouse:master with commit 3400dba Jul 9, 2026
677 of 685 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 9, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix text index on mapValues/mapKeys not used through a Distributed engine table

ClickGap verified: reproduced it with the script below on 26.5; tested 6 version(s) — 5 affected, 1 clean (see Affects); long-standing (not a recent regression); introducing PR not yet pinned.

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

  • Reproduces on every release line tested down to v25.12.11.4 (the oldest with a downloadable binary for this repro). The introducing change predates v25.12.11.4, so it can't be pinned from release binaries — this is a long-standing issue, not a recent regression. A maintainer with full git history can git blame the relevant file/line to find the exact change.

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3, 26.2, 26.1
  • Does NOT reproduce on: master
  • Backport needed: 26.5, 26.4, 26.3, 26.2, 26.1

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-distributed
Severity: P2

cc fix PR author: @groeneai


ClickGap · Finding: phase_d_pr109188

Triage metadata

  • Primary component: comp-distributed
  • Secondary components: comp-special-table-engines, comp-testing
  • Component owners (comp-distributed): @azat @alexey-milovidov

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 9, 2026
…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]>
Blargian pushed a commit to Blargian/ClickHouse that referenced this pull request Jul 10, 2026
…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]>
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 20, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 20, 2026
Backport #109188 to 26.6: Fix text index on mapValues/mapKeys not used through a Distributed engine table
alexey-milovidov added a commit that referenced this pull request Jul 21, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Jul 21, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Jul 21, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Jul 21, 2026
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]>
UnamedRus pushed a commit to UnamedRus/ClickHouse that referenced this pull request Aug 12, 2026
…ys not used through a Distributed engine table
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…4-text-index-mapvalues-distributed

Fix text index on mapValues/mapKeys not used through a Distributed engine table
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 1, 2026
…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.
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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Text index on mapValues(map) is silently not used when querying through a Distributed engine table (analyzer)

8 participants