Skip to content

Text index looks through positive boolean wrappers - #110024

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/text-index-positive-boolean-wrapper-110012
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/text-index-positive-boolean-wrapper-110012

Conversation

@groeneai

@groeneai groeneai commented Jul 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #110012

Changelog category (leave one):

  • Improvement

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

The text (full-text) skip index now prunes granules for a supported search predicate even when it is wrapped in a positive boolean comparison, so hasToken(s, 'x') = true, hasToken(s, 'x') != false, hasToken(s, 'x') IN (true) and hasToken(s, 'x') IS TRUE use the index like the bare hasToken(s, 'x') instead of scanning every granule. Such wrappers are common in SQL generated by BI tools and ORMs.

Description

The text skip-index condition builder recognized a supported atom (hasToken, equals, LIKE, ...) as prunable only as a bare conjunct. When the same atom was wrapped in a semantically-equivalent positive boolean comparison the inner atom node was treated as the index column, header.has() failed, no index condition was built, and the query read every granule. Results were always correct; only pruning was lost.

traverseAtomNode now looks through positive boolean wrappers by recursing into the atom:

  • atom = true / true = atom
  • atom != false
  • isNotDistinctFrom(atom, true) (this is also the desugaring of atom IS TRUE)
  • atom IN (only-truthy-consts)

Only positive wrappers are handled. A positive wrapper selects a row exactly when the atom is true (under WHERE three-valued logic NULL and false rows are excluded in every case, so this holds for Nullable atoms too), hence the atom's granule mask remains a necessary condition and pruning stays sound. Negative wrappers (= false, != true) map to the negated atom, whose NOT-of-a-granule-mask is always can-be-true and gives no pruning benefit, so they are declined. Non-boolean right-hand sides such as = 5 are left to row-level evaluation.

The recursed atom's direct-read mode is forced to None: the wrapper node is not shaped [haystack, needles], so the direct-read / preprocessor rewrite (which assumes that shape) must not run on it. Granule pruning is mode-independent (driven by the RPN function type), so pruning is fully restored, and the bare inner atom node is still optimized for direct read independently.

Regression test 04365_text_index_positive_boolean_wrapper asserts via EXPLAIN indexes = 1 that every positive wrapper prunes to the same single granule as the bare atom, that negative and non-boolean wrappers do not prune, and that results are unchanged.

Repro from the issue: https://fiddle.clickhouse.com/33bc89bf-a740-450a-a1c8-26e7c3c59ba5


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

The text skip-index condition builder recognized a supported atom
(hasToken, equals, LIKE, ...) only as a bare conjunct, not when wrapped
in a semantically-equivalent positive boolean comparison, so
`hasToken(s, 'x') = true` full-scanned while bare `hasToken(s, 'x')`
pruned.

traverseAtomNode now looks through `atom = true`, `atom != false`,
`isNotDistinctFrom(atom, true)` (both argument orders, including the
`IS TRUE` desugaring) and `atom IN (only-truthy-consts)` by recursing
into the atom. Only positive wrappers are handled: a positive wrapper
selects a row exactly when the atom is true, so the atom's granule mask
stays a necessary condition and pruning is sound. Negative wrappers
(= false, != true) map to the negated atom, whose NOT-of-a-mask is
always can-be-true (no pruning benefit), and are declined.

The recursed atom's direct-read mode is forced to None because the
wrapper node is not shaped [haystack, needles]; granule pruning is
mode-independent, so pruning is fully restored while the bare atom node
is still optimized for direct read independently.

Closes: ClickHouse#110012

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. EXPLAIN indexes = 1 on a text-indexed table: bare hasToken(s,'rare') prunes to Granules: 1/128; = true / != false / IN (true) / IS TRUE all full-scan (128/128, index not even listed). On demand, every run.
b Root cause explained? traverseAtomNode handled a supported atom only as a bare conjunct. For equals(hasToken(...), true) it took the inner hasToken(...) node as the index column; header.has() fails on it, so no RPNElement is built and the whole predicate is FUNCTION_UNKNOWN -> no pruning -> full scan.
c Fix matches root cause? Yes. New traversePositiveBooleanWrapper detects positive boolean wrappers and recurses into the atom so the SAME RPNElement the bare atom builds is produced. No band-aid (no widened bounds, no no-random-* tag).
d Test intent preserved / new tests added? New test 04365_text_index_positive_boolean_wrapper (EXPLAIN indexes=1 subquery + ILIKE form): asserts positive wrappers prune identically to the bare atom, negative/non-boolean wrappers do NOT prune, and results are unchanged. No existing test weakened; 115 existing text-index tests still pass.
e Both directions demonstrated? Yes. Same binary tree: baseline (Build ID d3ba55) -> wrapped forms 128/128; with fix (Build ID d7b7e3) -> wrapped forms 1/128; = false stays 128/128 in both.
f Fix is general across code paths? Yes. The look-through recurses through the single traverseAtomNode entry, so it works for EVERY supported atom (hasToken, equals, LIKE, hasAnyTokens, ...), not just hasToken. Both argument orders handled.
g Fix generalizes across inputs? Handles all positive spellings: = true, != false, IN (only-truthy), isNotDistinctFrom(atom,true) / IS TRUE, both operand orders; boolean constants recognized as Bool/UInt64/Int64/Float64 0/1. Negative wrappers (= false, != true) and non-boolean RHS (= 5) correctly decline. Sound for Nullable atoms (WHERE 3-valued logic excludes NULL/false).
h Backward compatible? Yes. Pure optimization: only adds granule pruning that was already valid; results unchanged in all cases (verified). No setting, format, or default change.
i Invariants and contracts preserved? Yes. Recursion forces the atom's direct_read_mode = None because the wrapper node is not shaped [haystack, needles], so the direct-read/preprocessor rewrite (which assumes that shape) never runs on the wrapper. Granule pruning is mode-independent, so pruning is fully restored; the bare atom node is still optimized for direct read independently. Positive-wrapper soundness: the atom's granule mask stays a necessary condition.

Covered SHA: 2e2e6a2858fce8c559190b2940f34c320ff38b66
Session id: cron:clickhouse-worker-slot-1:20260710-155100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @ahmadov for review: this teaches the text-index condition builder to look through positive boolean wrappers (hasToken(s,'x') = true etc.) so pruning is not lost. Fix is in MergeTreeIndexConditionText::traverseAtomNode + a new 04365 EXPLAIN-indexes regression test.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai look at other skip indexes, primary key and partition pruning on these cases.

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bbd2133]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
Build ClickHouse FAIL
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

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

Copy link
Copy Markdown
Collaborator Author

@PedroTadim checked all of them with EXPLAIN indexes = 1 on master. Results for the four positive wrappers around a prunable atom:

predicate PK minmax bloom_filter partition set index
atom = true prunes prunes prunes prunes prunes
atom IS TRUE full scan* full scan* full scan* full scan* prunes
atom != false full scan full scan full scan full scan prunes
atom IN (true) full scan full scan full scan full scan prunes

Two distinct mechanisms:

  • PK, minmax, bloom_filter, partition all build their condition through KeyCondition/RPNBuilder. = true prunes only because the analyzer constant-folds X = true to bare X before KeyCondition sees it. IS TRUE, != false, IN (true) survive as real function nodes, hit no atom_map entry, and fall through to Condition: true (full scan). So the KeyCondition family shares exactly the blindness the text index had.
    • *IS TRUE is already handled by my open Support index pruning for IS NOT DISTINCT FROM and IS TRUE #110006 (adds isNotDistinctFrom to atom_map + tryRewriteIsTrueCondition), which fixes PK, minmax, bloom_filter and partition in one place since they share KeyCondition.
    • The remaining KeyCondition gap is != false and IN (only-truthy). I will extend the same shared layer to peel those (natural sibling of the IS TRUE rewrite), so it is fixed once for all four paths rather than per index.
  • set index does not go through KeyCondition for this; it evaluates the stored per-granule value-set against the actual filter expression, so it already prunes every wrapper form (verified above). No change needed.

Net: this PR (#110024) stays scoped to the text index (separate condition builder). PK/minmax/bloom_filter/partition are covered at the KeyCondition layer by #110006 (IS TRUE) plus a follow-up for != false / IN (true). set is already fine.

groeneai and others added 2 commits July 10, 2026 19:07
index_granularity_bytes = 0 disables adaptive granularity; when CI randomizes
min_rows/min_bytes_for_wide_part the server logs a Warning about it, and Fast
test (send_logs_level=warning) fails on any stderr. index_granularity = 1
alone already gives one row per granule, so a large non-zero
index_granularity_bytes keeps the granule counts stable without the warning.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The negative "no prune" assertions checked that every Granules line reads
128/128. In the merged-with-master Fast test build, primary-key / constant
folding prunes hasToken(s,'rare')=false, !=true and =5 independently of the
text index, so a Granules line was not 128/128 and the assertions flipped to
0. Assert on the text skip index by name (Name: idx) instead: positive
wrappers apply it and prune to one granule, negative and non-boolean wrappers
do not apply it. This isolates text-index behavior from unrelated pruning and
is stable across randomized settings. Reference unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…upport nullIn

Two review-comment fixes for the positive-boolean-wrapper handling:

1. The wrapper query is stored in None mode (so the wrapper node is not
   direct-read-rewritten), but TextSearchQuery::getHash includes direct_read_mode,
   so the bare inner atom -- optimized independently by the direct-read pass in its
   original mode -- missed the all_search_queries lookup and lost its direct read /
   hint. Keep the original-mode child query in a new RPNElement::extra_search_queries
   (registered in all_search_queries, ignored by pruning) so both representations exist.

2. Recognize nullIn / globalNullIn, the forms the analyzer rewrites IN / globalIn to
   under transform_null_in = 1. The truthy-only set check already rejects NULL members,
   so the soundness argument is unchanged.

Regression cases added: nullIn pruning, IN (true,false) declines under null_in, and
the bare/=true/IN(true) direct-read virtual column is present.

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

Copy link
Copy Markdown
Collaborator Author

Both addressed in ddb3d72.

1. direct_read_mode = None breaking the child-node optimization. Right. The wrapper query has to stay None for pruning, but the bare child atom is optimized independently by the direct-read pass, which reconstructs it in its original mode (Exact for hasToken), and getHash includes direct_read_mode, so the None-mode query missed the all_search_queries lookup and the child lost its direct read / hint. Fixed with two representations: the None-mode query drives pruning as before, and a new RPNElement::extra_search_queries holds the original-mode child query, registered in all_search_queries for replaceToVirtualColumn but excluded from pruning and all_search_tokens. (TextSearchQuery::patterns is not copy-constructible, so I re-traverse the atom for the second representation rather than cloning.) Verified on EXPLAIN actions=1: hasToken(s,'x') = true now yields both Granules: 1/128 and the __text_index_idx_... virtual column, same as the bare atom. Before the fix the virtual column was absent.

2. transform_null_in = 1 -> nullIn / globalNullIn. Added both to the wrapper recognition. Soundness is unchanged: the loop still rejects any set element that is not an explicit truthy boolean, so NULL members bail out. Added a transform_null_in = 1 regression asserting IN (true) prunes to 1/128 and gets the direct-read column, plus IN (true, false) under null_in still declines.

Repro was confirmed both directions on a local build: baseline (4971790) missed the child direct-read column on = true and did not apply the index for IN (true) under transform_null_in = 1; with the fix both work. Robust across the index-relevant randomized settings (use_skip_indexes_on_data_read, secondary_indices_enable_bulk_filtering, query_plan_direct_read_from_text_index, query_plan_text_index_add_hint, prewhere, query-condition-cache).

@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 77.90% 77.90% +0.00%

Changed lines: Changed C/C++ lines covered: 100/119 (84.03%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ddb3d72

CI fully finished (Finish Workflow complete). The earlier Fast-test failure was PR-caused and is fixed on this head (Fast test passes now). The sole remaining failure is a pre-existing flaky test with an owner.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / 04401_distributed_with_fill_const_to_scalar flaky (serialize_query_plan + WITH FILL on distributed; ~5% on master, ~16 unrelated PRs) #110060 (ours, open)
Sync - CH Inc sync (private, not actionable)

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ddb3d72

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
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / 04401_distributed_with_fill_const_to_scalar flaky (trunk test, ~5% master fail rate under randomized prefer_localhost_replica=0 + serialize_query_plan=1; 13 master + 35 unrelated PRs in 30d; not this PR's diff) fixing PR #110060 (ours, on_review)
Mergeable Check / PR rollup of the above owned via #110060

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

@rschu1ze rschu1ze added the hold Skip for auto-updating. label Jul 13, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Needs clarification

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, holding this PR. I will not push more code here until the direction on #110012 is settled.

Agreed the interesting questions are best answered on the issue: which index types besides text and bloom lack positive-boolean-wrapper look-through today, which functions besides hasToken, and whether this should be one shared normalization (fold X = true / X != false / X IN (only-truthy) once, before the pruning paths consume the RPN) rather than per-index shortcuts. I will post that survey with EXPLAIN indexes = 1 evidence (including a check of your bloom-filter IN case) on #110012 and follow whatever central-vs-per-index decision you and @PedroTadim reach.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for ea7b0ba

Every failure below has an owner. All three are one root cause: this branch no longer compiles against current master.

Check / test Reason Owner / fixing PR
Fast test build error, 3 compile errors in MergeTreeIndexConditionText.cpp fixed in this PR (blocked on the hold label, see below)
Build (arm_tidy) same 3 compile errors (clang-diagnostic-error) fixed in this PR (blocked on the hold label, see below)
Finish Workflow consequence only: the build failed, so 151 downstream jobs were DROPPED and no Bugfix validator ran resolved by fixing the build

Finish Workflow reports "No per-arch Bugfix Validation job validated the bug". That is not a test-design problem: the three functional and unit validators are DROPPED because Fast test and Build (arm_tidy) died first, so the new test was never measured on master HEAD. The two integration validators are SKIPPED, which is correct, since this PR adds no integration tests.

Root cause: a semantic conflict with master, not a bad merge

The head commit is a plain Merge branch 'master'. It resolves cleanly, and each side compiles on its own, but the combination does not.

At this branch's merge base, TextSearchQuery::getHash returned a SipHash and direct_read_mode was a public field, so master's own call sites read getHash().get128(). The three lines I added in July were written against that API.

PR #109886 (Optimize text index analysis) then changed it: getHash now returns UInt128 directly, the fields are private, and the hash is precomputed in the constructor with the comment "Fields are immutable after construction, otherwise the precomputed hash becomes stale."

So:

  • :197 getHash().get128(): mechanical, getHash already returns a UInt128. Master's sibling line is now all_search_queries.find(query_hash).
  • :773 / :785: not mechanical. My change deliberately mutates direct_read_mode after construction, which is exactly what the new invariant forbids, and the invariant is load-bearing here: initializeHash folds direct_read_mode into the hash, and replaceToVirtualColumn looks the query up by getHash(). Mutating the field would leave the hash stale and silently break the child-atom direct-read lookup that the earlier review round added extra_search_queries to preserve. The correct fix is to construct a new TextSearchQuery with the intended mode rather than to add a setter or friend the class.

Why I am not pushing the fix

This PR carries the hold label and I said on 2026-07-13 that I would not push more code here until the direction on #110012 is settled. I am keeping that commitment: the :773/:785 fix is a change to the wrapper mechanism itself, not a mechanical rebase, and #110012 is still open on whether this should be per-index at all or one shared normalization. Rewriting the mechanism now is the "patch 1, patch 2, ... patch N" churn that was objected to.

I have not written the fix yet, only diagnosed it, precisely because the shape of the :773/:785 half depends on that decision. If the preference is simply to get the branch green in the meantime, say so and I will push the minimal compile fix on its own.

Session id: cron:clickhouse-maint-slot-13:20260728-234502

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 4, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bbd2133

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
Build (arm_tidy) / Build ClickHouse PR-caused compile error: MergeTreeIndexConditionText.cpp:209 no member named 'get128' in 'wide::integer<128, unsigned int>', plus :866 and :878 'direct_read_mode' is a private member of 'DB::TextSearchQuery' a fix task is created (remedy already measured, held while the hold label is on this PR; fixing-commit link to follow here)
Fast test / Build ClickHouse PR-caused: the same three compile errors, hit in the fast-test build step a fix task is created (same owner as the row above)
Finish Workflow / Post Hooks Consequence of the build failure: both per-arch Bugfix validation jobs report DROPPED (Dropped due to previous failure [Build (arm_tidy)]), so no validator ran a fix task is created (discharged by the same build fix)

147 further jobs dropped behind the build, so this head carries no stateless, integration or fuzzer coverage.

Head bbd21331685a is a Merge branch 'master' commit rather than a push of mine (my last commit on this branch is ddb3d72ba9ce, 2026-07-10). The root cause is unchanged from the earlier ledger on this PR (#110024 (comment)): #109886 made TextSearchQuery's fields private and getHash() return UInt128 directly, so my lines need a freshly constructed query instead of a post-construction write to direct_read_mode, which feeds the precomputed hash. I am not pushing that fix while the hold label is on this PR and the central-versus-per-index question on #110012 is open.

Session id: cron:our-pr-ci-monitor:20260908-053039

@ahmadov ahmadov self-assigned this Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

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

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-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... groeneai-origin-unknown PR origin: unclassified (legacy task) hold Skip for auto-updating. 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 condition does not look through positive boolean wrappers — hasToken(s, 'x') = true scans all granules while bare hasToken(s, 'x') prunes

5 participants