Skip to content

Do not use text index for has/mapContainsKey/mapContainsValue with an empty needle - #110094

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-empty-needle-has-map
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-empty-needle-has-map

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Closes: #110092

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 for has, mapContainsKey and mapContainsValue with an empty needle when a text index is present. Previously has(a, ''), mapContainsKey(m, '') and mapContainsValue(m, '') returned all rows instead of 0, because the empty needle tokenizes to an empty token list and an All-mode text search over zero tokens is vacuously true.

Description

The text index never indexes empty values. A needle that tokenizes to an empty token list produces an All-mode TextSearchQuery over zero tokens, which matches every row; since the text index condition can replace the real predicate evaluation (exact/direct read), the predicate returned all rows. With use_skip_indexes = 0 the results were already correct.

This extends the empty-needle guard added in #108340 (equals branch of MergeTreeIndexConditionText.cpp) to:

  • the has handler (text index over Array(String)),
  • the mapKeys/mapValues branch (mapContainsKey/mapContainsValue and their *Like variants).

When the tokenized needle is empty the index cannot serve the predicate, so we return false and fall back to a full scan with real evaluation. The guard is on the post-tokenization token list, so preprocessor/*Like needles that reduce to nothing are covered too.

Repro: https://fiddle.clickhouse.com/bf0c24a1-cb9b-4366-aad8-47bfa952e61a

… empty needle

The text index never indexes empty values, and a needle that tokenizes to an
empty token list produces an All-mode text search over zero tokens, which is
vacuously true. Because the text index condition can replace the real predicate
evaluation (exact/direct read), every row matched: has(a, ''),
mapContainsKey(m, '') and mapContainsValue(m, '') returned all rows instead of 0.

Extend the empty-needle guard added in ClickHouse#108340 (equals branch) to the has
handler and the mapKeys/mapValues (mapContainsKey/mapContainsValue and their
*Like variants) branch: when the tokenized needle is empty, bail out so the
predicate falls back to a full scan with real evaluation.

Closes: ClickHouse#110092

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. has(a,''), mapContainsKey(m,''), mapContainsValue(m,'') on a text index over Array(String)/mapKeys/mapValues return 8192 (all rows) with use_skip_indexes=1, 0 with use_skip_indexes=0.
b Root cause explained? Empty needle tokenizes to an empty token list. An All-mode TextSearchQuery over zero tokens is vacuously true; the text index condition replaces the real predicate (exact/direct read), so every row matches.
c Fix matches root cause? Yes. When the tokenized needle is empty, the has and mapKeys/mapValues handlers return false so the predicate falls back to a full scan with real evaluation, mirroring the #108340 equals guard.
d Test intent preserved / new tests added? Extended 02346_text_index_functions_with_empty_needle with has/mapContainsKey/mapContainsValue/*Like empty-needle cases, asserting index results equal use_skip_indexes=0, plus present/absent needle cases.
e Demonstrated both directions? Yes. Baseline binary: empty needle -> 8192 (wrong). Fixed binary: empty needle -> 0 (correct), non-empty needles unchanged.
f Fix general, not a narrow patch? Guard added at all needle-tokenizing sites: has handler, and make_map_function (covers mapContainsKey/mapContainsValue and the mapContainsKeyLike/mapContainsValueLike variants).
g Generalizes across inputs? Guard is on the post-tokenization token list, so preprocessor/*Like needles that reduce to nothing are covered, not just raw-empty strings. hasAnyTokens/hasAllTokens/hasAny/hasAll(empty element) already had their own guards and are unaffected.
h Backward compatible? Yes. Restores documented behaviour (0 rows); no setting/format change.
i Invariants preserved? Yes. Falls back to full-scan real evaluation, matching use_skip_indexes=0 and the equals branch contract.

Session id: cron:clickhouse-worker-slot-3:20260711-133600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @ahmadov for review. This mirrors the #108340 empty-needle equals guard, extending it to the has and mapKeys/mapValues (mapContainsKey/mapContainsValue and *Like) branches of MergeTreeIndexConditionText.cpp.

@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78808e0]


AI Review

Summary

This PR fixes the real empty-needle exact direct-read bug for has, mapContainsKey, and mapContainsValue on text indexes, and the new tokens.empty() bailouts in MergeTreeIndexConditionText match the existing "fall back to the scan when the index cannot prove the predicate" contract. I’m not approving yet because the new *Like regression cases still do not validate the additional stringLikeToTokens call sites the PR says it covers.

Tests
  • ⚠️ [tests/queries/0_stateless/02346_text_index_bug110092.sql:44-45] mapContainsKeyLike and mapContainsValueLike are still Hint-only in getDirectReadMode (src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:287-293), and empty-token hint queries are explicitly not converted to virtual columns (src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:314-317, src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:479-481). As written, these SQL cases still return 0 even if the new tokens.empty() guard at src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:855-863 is removed, because the original predicate is still evaluated. Please add a smaller focused test that can actually fail for the stringLikeToTokens callers in make_map_function (for example a unit/planner-level check that createTextSearchQuery refuses the empty-token mapContains*Like query), or stop claiming that this PR regression-covers the *Like path.
Final Verdict
  • Status: ⚠️ Request changes
  • Add proof for the mapContainsKeyLike / mapContainsValueLike branch touched by make_map_function; the current SQL regression only proves the exact direct-read has / mapContainsKey / mapContainsValue cases.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 11, 2026
…sion

The bad results only occur in the direct-read rewrite, not the ordinary
row-scan path. CI can run stateless tests with
query_plan_direct_read_from_text_index=0, in which the original predicate is
still evaluated and both buggy and fixed code return 0, so the test would not
catch a regression. Pin the setting on the index-on cases so the direct-read
path where the bug lives is exercised.

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

clickhouse-gh Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 14e520e

Every failure below has an owner (a fixing PR). None is PR-caused: this PR only edits tests/queries/0_stateless/02346_text_index_functions_with_empty_needle.sql (+ .reference), which touches neither the distributed-group-by path nor the Not-ready Set IN-family code.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel) / 01730_distributed_group_by_no_merge_order_by_long flaky (chronic; ~20 unrelated PRs + 4 master, 30d) #109456 (ours, open)
Stress test (amd_asan_ubsan) / Logical error: Not-ready Set is passed as the second argument (STID 0250-41a5) trunk logical error (chronic; 31 master + many unrelated PRs, 30d) #109722 (ours, open)
Mergeable Check / PR rollup of the above owned via #109456 / #109722
CH Inc sync - CH Inc sync (private, not actionable)

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

Comment on lines +30 to +33
SET use_skip_indexes = 1;
SELECT count() FROM tab WHERE has(arr, '');
SELECT count() FROM tab WHERE mapContainsKey(mp, '');
SELECT count() FROM tab WHERE mapContainsValue(mp, '');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This regression still only exercises the stringToTokens callers. The code change at src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:872-882 also touched the stringLikeToTokens branch for mapContainsKeyLike / mapContainsValueLike, and the PR description says those variants are fixed when the pattern reduces to an empty token list. Please add empty-pattern cases here, for example mapContainsKeyLike(mp, '') and mapContainsValueLike(mp, ''), with query_plan_direct_read_from_text_index = 1, so a regression in the *Like path cannot merge green.

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.

mapContainsKeyLike / mapContainsValueLike still are not covered by this regression in the way your latest comment claims. In MergeTreeIndexConditionText::getDirectReadMode they are Hint-only, not exact-read (src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:287-293), and empty-token hint queries are explicitly not converted to virtual columns (src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:314-317, src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:479-481). So the new cases at tests/queries/0_stateless/02346_text_index_bug110092.sql:44-45 still return 0 even if the tokens.empty() guard is removed from make_map_function, because the original predicate is still evaluated. The stringLikeToTokens callers you touched are still missing a fails-without / passes-with proof; this needs a smaller focused test (likely below SQL level) or the *Like coverage claim should be dropped.

Pin query_plan_direct_read_from_text_index=1 on the index-on cases and OR
each empty-needle predicate with a never-matching one so granule pruning no
longer masks the always-true virtual column. Without the fix these return all
rows; with it they return 0. Adds the has(mp,'') and mapContainsKeyLike/
mapContainsValueLike empty-pattern cases so the full changed exact-read
surface is covered.

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

Copy link
Copy Markdown
Collaborator Author

All three addressed in 78808e0.

The regression previously used plain predicates, which do not fail without the fix: granule pruning hides the always-true empty-needle virtual column in a simple predicate (both buggy and fixed return 0). The bug only surfaces once pruning cannot mask it, so each empty-needle case is now ORed with a never-matching predicate (id = 999999, out of range) and pins query_plan_direct_read_from_text_index = 1. Verified on a debug build: without the guard, has(arr, ''), has(mp, ''), mapContainsKey(mp, '') and mapContainsValue(mp, '') return 8192; with it they return 0.

Re-added the has(mp, '') case and added mapContainsKeyLike(mp, '') / mapContainsValueLike(mp, '') empty-pattern cases, all pinned direct-read=1, so the full changed exact-read surface (the stringToTokens and stringLikeToTokens callers of make_map_function, plus the has branch) is covered.

Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro Yes: has(arr,'') OR id=999999 with use_skip_indexes=1, query_plan_direct_read_from_text_index=1 returns 8192 pre-fix, 0 post-fix
b Root cause Empty needle tokenizes to zero tokens; the exact direct-read rewrite treats a zero-token All-mode search as always-true, returning all rows
c Fix matches cause tokens.empty() bail-out in make_map_function and the has branch so the original predicate is evaluated by a full scan
d Test intent preserved Test strengthened, not weakened: adds the OR form that actually catches the regression
e Both directions Confirmed: buggy build returns 8192, fixed build + reference return 0 on the same queries
f Fix general Covers all four make_map_function callers (has over Array/Map, mapContainsKey/Value) and the *Like variants
g Input matrix Empty needle over Array(String) and Map(String,String), keys and values, plain and Like; present/absent needle cases confirm the index still prunes
h Backward compatible N/A (test-only change plus an existing guard; no setting or format change)
i Invariants Direct-read result now agrees with the row-scan path for empty needles

Session id: cron:clickhouse-worker-slot-7:20260713-102500

@rschu1ze

Copy link
Copy Markdown
Member

Superseded by #110246

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Text index makes has(col, '') / mapContainsKey(m, '') / mapContainsValue(m, '') match all rows — empty needle is vacuously true

3 participants