Skip to content

Fix text index direct read losing NULL semantics for Nullable columns - #107078

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-text-index-nullable-not-hastoken-106922
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-text-index-nullable-not-hastoken-106922

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

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 from a text index on a Nullable (or LowCardinality(Nullable)) column. A negated text-search predicate (NOT hasToken(col, 'x'), and likewise hasAllTokens, hasAnyTokens, hasPhrase, startsWith, endsWith, LIKE) no longer returns rows whose indexed value is NULL. The direct-read-from-text-index optimization materialized a non-Nullable 0/1 for such rows, losing the NULL that the function returns, so negation wrongly kept the NULL rows.

Description

Found by the AST-fuzzer correctness oracle (issue #106922, reproducible on default settings). The reporter later confirmed the same defect surfaces via match, like and hasPhrase (in addition to hasToken), on both fully and partially materialized (ngrams) text indexes.

Root cause: the direct-read-from-text-index optimization reads a non-Nullable UInt8 virtual column from posting-list membership. A NULL row has no tokens, so it reads as 0 (indistinguishable from a non-matching row), and the index stores no per-row null map (NULL rows are skipped at build time), so the mask cannot be reconstructed from the index alone. This 0 then loses the NULL in both direct-read modes:

  • Exact mode (hasToken/hasAllTokens/hasAnyTokens) fully replaces the function with the virtual column; the later cast to Nullable(UInt8) only adds an all-false null map, so NOT 0 = 1 keeps the row.
  • Hint mode (hasPhrase/startsWith/endsWith and the LIKE rewrites) builds and(virtual_column, real_func); for a NULL row that is and(0, NULL) = 0, so NOT 0 = 1 keeps the row too.

Fix: when the indexed (haystack) column is Nullable/LowCardinality(Nullable), demote any non-None direct read mode (Exact and Hint) to None, so the real function is evaluated per row. Granule-level pruning via the index still applies. The needle is always a non-null constant when direct read fires, so nullable-needle direct read, Array(Nullable) and mapValues paths (where the array value itself is never NULL) are unaffected, and the non-Nullable fast path is untouched.

Verified locally (debug build): every negated predicate now returns the same rows as SETTINGS query_plan_direct_read_from_text_index = 0; the regression test 02346_text_index_bug106922 covers hasToken/hasAnyTokens/hasAllTokens/hasPhrase/startsWith/endsWith/match/LIKE over Nullable and LowCardinality(Nullable) haystacks plus an ngrams partially-materialized index, and fails on a binary without the fix. Existing text-index tests pass.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On master fc73f46fae65, default settings: CREATE TABLE tab (id UInt32, str Nullable(String), INDEX idx(str) TYPE text(tokenizer='splitByNonAlpha')) ENGINE=MergeTree ORDER BY id; INSERT INTO tab VALUES (1,'hello world'),(2,NULL),(3,'foo bar'),(4,NULL),(5,'hello there'); SELECT id FROM tab WHERE NOT hasToken(str,'hello') ORDER BY id; returns 2 3 4 (wrong: NULL rows 2,4 leak); with SETTINGS query_plan_direct_read_from_text_index=0 returns 3 (correct).
b Root cause explained? hasToken/hasAllTokens/hasAnyTokens use TextIndexDirectReadMode::Exact, which fully replaces the function with a virtual column read from posting-list membership (a non-Nullable UInt8). A NULL row has no tokens, so it materializes as 0, indistinguishable from a non-matching row. The optimizer then casts the virtual column to Nullable(UInt8), but that only adds an all-false null map, so the lost NULLs are not recovered. NOT 0 = 1, so the NULL row is wrongly kept. The index stores no per-row null map (NULL rows are skipped at build time, row numbers stay aligned), so it cannot be reconstructed from the index alone.
c Fix matches root cause? Yes. When the indexed (haystack) column is Nullable/LowCardinality(Nullable), traverseFunctionNode demotes the Exact mode to None, so the real function is evaluated per row (preserving the NULL) instead of being replaced by the membership column. Granule-level pruning via the index still applies. Not a band-aid: it removes exactly the replacement step that drops the null mask.
d Test intent preserved / new tests added? New regression test 02346_text_index_bug106922 (.sql+.reference) added, covering Nullable(String), all-NULL part, LowCardinality(Nullable), preprocessor=lower, and PREWHERE; each negation query is checked against the same query with query_plan_direct_read_from_text_index=0. No existing test weakened.
e Both directions demonstrated? Yes. Without the fix the reproducer returns 2 3 4; with the fix it returns 3, matching the non-direct-read path. Debug trace confirmed the mode is demoted to None for a Nullable(String) haystack.
f Fix is general, not a narrow patch? Yes. The guard sits at the single mode-decision point (traverseFunctionNode) shared by all three Exact token functions (hasToken/hasAllTokens/hasAnyTokens) and both Nullable and LowCardinality(Nullable), in WHERE and PREWHERE. Sibling paths that were already correct are intentionally untouched: nullable-needle direct read (haystack non-null), Array(Nullable(String)) (array value never NULL), and mapValues(Map(..., Nullable)) (extracts non-null Array(String)) were all verified to behave the same with and without direct read.

Session id: cron:clickhouse-worker-slot-13:20260610-193900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @ahmadov @CurtizJ - could you review this? When the indexed column is Nullable/LowCardinality(Nullable), the Exact direct-read replacement for hasToken/hasAllTokens/hasAnyTokens materializes a non-Nullable 0/1 from posting-list membership, so a NULL row becomes 0 and NOT hasToken(...) wrongly keeps it. The fix demotes Exact to None for Nullable haystacks in traverseFunctionNode (the index has no per-row null map to reconstruct), so the real function runs while granule pruning still applies.

@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [108a64c]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: Invalid binary search result in MergeTreeSetIndex (STID: 3252-3a4a) FAIL cidb

AI Review

Summary

This PR replaces nullable text-index direct reads with a source-null-preserving wrapper and adds a broad regression matrix around preprocessors and materialization. The main direction is correct, but the current HEAD still leaves two supported preprocessor shapes returning different answers depending on whether the text index is materialized, so I do not think it is ready to merge.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeIndexTextPreprocessor.cpp:226] expressionRemovesSourceNull still classifies every non-null-propagating function by its declared result type. if and multiIf return the least supertype of their branches, so a supported preprocessor like if(isNull(str), '', str) or multiIf(isNull(str), '', str) stays Nullable(String) even though it maps every source-NULL row to a non-NULL string. removes_null therefore stays false, preserve_haystack_null re-adds if(isNull(str), NULL, vc), and NOT hasToken(str, 'hello') drops source-NULL rows on materialized parts while SETTINGS query_plan_direct_read_from_text_index = 0 keeps them. Classify branch-driven null removal by source-NULL behavior rather than by the outer result type, and add a regression for if / multiIf.
  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:554] The new needApplyPreprocessor gate leaves direct read enabled for raw-string siblings even though their postings probe is still built from preprocessed values via substringToTokens / stringLikeToTokens. With a supported preprocessor that can null out a matching non-NULL source value, materialized parts get false negatives, and under NOT they become false positives. Minimal trace: str Nullable(String), INDEX idx(str) TYPE text(tokenizer = ngrams(3), preprocessor = nullIf(str, 'hello world')), query NOT endsWith(str, 'world'). The materialized part sees row 1 as posting-membership 0 and keeps it, while SETTINGS query_plan_direct_read_from_text_index = 0 evaluates endsWith('hello world', 'world') = 1 and filters it. Either broaden the demotion to every direct-read path that consults preprocessed postings (equals, startsWith, endsWith, Hint LIKE, and similar), or rewrite those fallback predicates through the preprocessor too.
Final Verdict

❌ Request changes. The nullable wrapper fixes most of the reported cases, but the two preprocessor paths above still produce wrong results in supported queries.

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

Copy link
Copy Markdown
Collaborator Author

CI status — all failures triaged (commit 4ac4f34)

CI has fully finished (Finish Workflow / Mergeable green). The single red functional check is a pre-existing flaky test, not caused by this PR (which touches only src/Storages/MergeTree/MergeTreeIndexConditionText.{h,cpp} + a text-index regression test):

Check Failure Classification Disposition
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) 01090_zookeeper_mutations_and_insert_quorum_long differs Flaky — passed 6/6 on the in-job reproducibility rerun; hits 8 unrelated PRs (each 1×) in 30d; a ZK/quorum timing test unrelated to text-index code Tracked separately; not actionable on this PR

All other checks passed. Nothing in this PR's code path failed. Ready for review.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (scope-extension update)

This update extends the fix to the Hint-mode functions after @ qoega reported the same defect via match/like/hasPhrase and on partially-materialized (ngrams) indexes.

# Question Answer
a Deterministic repro? Yes. On default settings, over a Nullable(String) text index: SELECT id FROM t WHERE NOT hasPhrase(str,'hello world') returns 2,3,4,5 (NULL rows 2,4 leaked) vs the correct 3,5 with query_plan_direct_read_from_text_index=0. Same for NOT endsWith(str,'world') and NOT (str LIKE '%world'), on both splitByNonAlpha and ngrams(3) tokenizers.
b Root cause explained? Direct read materializes a non-Nullable UInt8 from posting-list membership; a NULL row has no tokens so it reads as 0. In Hint mode the predicate is and(virtual_column, real_func), and and(0, NULL) folds to 0, so NOT 0 = 1 wrongly selects the NULL row. (The previously-fixed Exact mode lost the NULL the same way: _CAST(0,'Nullable(UInt8)') adds an all-false null map.) The text index stores no per-row null map, so the mask cannot be reconstructed from the index.
c Fix matches root cause? Yes. The guard in traverseFunctionNode is broadened from "demote Exact→None" to "demote any non-None mode (Exact and Hint)→None" when the haystack column is Nullable/LowCardinality(Nullable). In None mode the real function is evaluated per row (identical to query_plan_direct_read_from_text_index=0, the verified-correct reference). Granule pruning via the index is preserved.
d Test intent preserved / new tests added? Regression test 02346_text_index_bug106922 extended to cover hasPhrase/startsWith/endsWith/match/LIKE over Nullable and LowCardinality(Nullable) haystacks, plus an ngrams partially-materialized index. Each negated query is checked against the same query with query_plan_direct_read_from_text_index=0. Positive predicates and the IS NULL/projection checks remain.
e Both directions demonstrated? Yes. On a binary with the Exact-only guard (no Hint fix) the test FAILS — it leaks NULL rows 2,4 at the hasPhrase/endsWith/LIKE/ngrams sections. With the fix the test output is byte-identical to the reference. Non-Nullable haystacks still use direct read and return correct results (fast path unaffected).
f Fix is general, not a narrow patch? Yes. The guard is keyed on haystack nullability and the direct-read mode, so it covers every direct-read function uniformly (all of getDirectReadMode's Exact and Hint results) rather than enumerating function names. Paths where direct read is correct are not demoted: nullable-needle, Array(Nullable) (array value never NULL), mapValues (produces Array(String)), and the non-Nullable haystack fast path. The LIKE dictionary-scan Exact path was probed in null-sensitive contexts (=0, IS NULL, OR, ifNull) and does not independently leak (it is declined under NOT by inversion pushdown), so it is left untouched per "no speculative changes".

Session id: cron:clickhouse-worker-slot-2:20260612-075800

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit df64f0e, mapValues fix)

# Question Answer
a Deterministic repro? Yes. m Map(String, Nullable(String)) + mapValues(m) text index, index_granularity = 128, 10000 rows (20 NULL map values). SELECT count() FROM tab WHERE NOT hasToken(m['k'],'needle') returns 9988 with direct read on vs 9968 with query_plan_direct_read_from_text_index = 0; the 20-row excess is exactly the NULL map-value rows (ids 0, 500, ..., 9500). ProfileEvents['TextIndexUseHint']=1 (non-bypassed Hint).
b Root cause explained? The nullable demotion ran right after getDirectReadMode(), but the mapValues / JSONAllValues / map-subcolumn branches re-set direct_read_mode = getHintOrNoneMode() afterwards, undoing it. In a non-bypassed Hint, fillColumn writes per-row posting membership, so a NULL map value reads as 0; the predicate becomes not(and(0, NULL)) = not(0) = 1 and the NULL row is wrongly kept.
c Fix matches root cause? Yes. The single demotion is moved to after all mode-assignment branches, so it is the final word on direct_read_mode and covers every Exact/Hint construction site including the re-promoted map paths (the "enforce it centrally before creating the virtual column" option). No per-site guards, no symptom band-aid.
d Test intent preserved / new tests added? New regression added to 02346_text_index_bug106922: a Map(String, Nullable(String)) mapValues section sized to keep the Hint non-bypassed (the only condition under which the bug manifests). Existing assertions unchanged; non-Nullable mapValues still uses the index (positive hasToken returns 12 with TextIndexUseHint=1).
e Both directions demonstrated? Yes, on Build-ID-pinned binaries. Pre-fix (d1e1b687): hasToken/hasPhrase return 9988, null-leak count 20 -> test FAILS. Fixed (f79357df): 9968, null-leak 0 -> test PASSES; 40/40 runs pass through clickhouse-test with randomization.
f Fix is general, not a narrow patch? Yes. The demotion now sits after all three re-promotion sites (mapValues, JSONAllValues, map-subcolumn), so it applies to every nullable-haystack Exact/Hint construction, not just the scalar path. It is the root-cause fix (re-promotion was overwriting the mode), not a guard at the crash site.

Session id: cron:clickhouse-worker-slot-2:20260612-092500

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD df64f0e7e5f7 (Finish Workflow + Mergeable Check both SUCCESS; 147 pass / 19 skip / 0 pending / 0 fail; CIDB shows zero FAIL/ERROR rows for this commit).

This HEAD adds the central nullable-haystack demotion (df64f0e), so the demotion is now the final word on direct_read_mode and covers every Exact/Hint construction site including the re-promoted mapValues / JSON / map-subcolumn paths flagged in the third bot review round.

No PR-caused failures. Ready for review.

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

This fix seems to disabled all direct read for any nullable column. That is not a correct approach because it may affect performance very strongly.

There should be another root cause somewhere else. Let's say that a nullable column when we remove the nullable wrapper, it must have empty entries in the null rows, so the index must have nothing in those rows, so no matches. When direct read fills the virtual column those rows must have 0 and negating them must be 1 as expected. This is not happening at the moment, so this fix is just a way around to hide the real problem.

@Ergus Ergus self-assigned this Jun 15, 2026
@Ergus

Ergus commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

@groeneai The real issue is probably in optimizeDirectReadFromTextIndex.cpp check these lines:

if (!function_node.result_type->equals(*replacement.node->result_type))
   replacement.node = &actions_dag.addCast(*replacement.node, function_node.result_type, "", context);

When hasToken(nullable_str, 'x') is replaced by the UInt8 virtual column, the types don't match, the function's result_type is Nullable(UInt8) (because the haystack is nullable), the virtual column is plain UInt8. So addCast wraps it as CAST(virtual_UInt8, 'Nullable(UInt8)'). That cast manufactures an all-false null map. Every row is declared non-null, so NULL rows become 0 with no way to distinguish them from genuinely non-matching rows.

This demoting to None in traverseFunctionNode prevents the virtual column from ever being created for nullable haystacks, which avoids the bad cast, but kills the optimization for all predicates rather than fixing the cast itself.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Ergus You're right on both counts, and your root cause is exact. Reworked the fix along the lines you described (pushed in 4980a85).

The defect was the type-mismatch cast in optimizeDirectReadFromTextIndex.cpp: with a Nullable haystack the predicate is Nullable(UInt8) but the virtual column is plain UInt8, so the mismatch path did CAST(vc, 'Nullable(UInt8)'). That cast adds an all-false null map, so a NULL row reads as a genuine 0 and NOT keeps it.

Fix: at that central virtual-column site, for a Nullable haystack I replaced the lossy cast with if(isNull(haystack), NULL, vc), which re-derives the haystack's own per-row null map (matching f(NULL, ...) = NULL). It keys on the haystack rather than posting-list membership, so it covers Exact, Hint and the mapValues re-promotion in one place. The haystack is picked as the non-constant Nullable argument, so equals(...) with the column on either side is handled too. For partial materialization the Exact default expression is coalesced with ifNull(real_func, 0) so the UInt8 column accepts the row and the outer wrap restores the NULL.

I removed the demote-to-None entirely, so direct read stays enabled for Nullable columns (your performance concern). Verified on a Nullable text-indexed column:

  • NOT hasToken(str, 'hello') returns the same rows with direct read on, with query_plan_direct_read_from_text_index = 0, and with use_skip_indexes = 0 (no divergence; NULL rows filtered as NOT hasToken(NULL, ...) = NULL).
  • EXPLAIN actions=1 still shows the __text_index virtual column being read, now wrapped in if(isNull(str), NULL, ...), so the optimization is not disabled.
  • 02346 fails on a binary with the lossy cast restored and passes with the fix.

The nullIf preprocessor case (plain-String source that becomes Nullable after the preprocessor) stays out of scope here, since the predicate type is non-nullable and gets no wrap; it is tracked separately.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 4980a85, @Ergus redesign)

# Question Answer
a Deterministic repro? Yes. str Nullable(String) with a text index, NOT hasToken(str, 'hello'): on a binary with the lossy CAST(vc, 'Nullable(UInt8)') restored, the NULL rows are wrongly kept (result includes ids 2,4); deterministic, no randomization needed.
b Root cause explained? The predicate over a Nullable haystack is Nullable(UInt8), but the text-index virtual column is plain UInt8. The type-mismatch path in optimizeDirectReadFromTextIndex.cpp did addCast(vc, Nullable(UInt8)), which manufactures an all-false null map. A NULL haystack row then reads as a genuine 0 indistinguishable from a real non-match, so NOT 0 = 1 keeps the row. (Root cause identified by @Ergus.)
c Fix matches root cause? Yes. At the central virtual-column site, for a Nullable haystack the lossy cast is replaced with if(isNull(haystack), NULL, vc), which carries the haystack's real per-row null map. It targets the cast itself rather than disabling the optimization. The prior demote-to-None workaround is removed.
d Test intent preserved / new tests added? Preserved. Existing 02346 cases unchanged. Added a "direct read stays enabled" assertion: EXPLAIN confirms the __text_index virtual column is still read and is guarded by isNull(haystack), so a regression that falls back to a full scan (losing the optimization) is caught.
e Both directions demonstrated? Yes. Negative binary (lossy cast restored): 02346 FAILS. Fix binary (6F5273C8): 02346 PASSES, 10/10 with randomization on. NOT hasToken on the Nullable column agrees across direct-read-on / direct-read-off / full-scan.
f Fix is general, not a narrow patch? General. The wrap is at the single central virtual-column construction site, so it covers Exact, Hint and the mapValues re-promotion uniformly (it keys on the haystack, not posting-list membership). Haystack detection picks the non-constant Nullable argument, so equals(...) with the indexed column on either side is handled. Partial materialization is covered via ifNull(real_func, 0) on the Exact default expression.

Session id: cron:clickhouse-worker-slot-6:20260615-135600

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD 400afeaa6d2e (Finish Workflow SUCCESS 2026-06-15T20:23:41Z; only CH Inc sync private mirror still pending, non-gating; >20 min ingestion buffer). The 4980a85 cast-fix redesign + the 400afea stale-comment update all carried through. No PR-caused failure. Disposition of each red:

Check / test Class Disposition
Stateless tests (amd_tsan, flaky check) "Server died" + "Scraping system tables" infra Chronic Fast/flaky-check server-health-death class (76 hits / 20 unrelated PRs / 3d). The changed test 02346_text_index_bug106922 ran OK 722× across every alive flaky batch (each "Failed: 0, Passed: 50") — our new/changed test is NOT flaky; the job-level death is the dead-server victim, not our test.
Stress test (amd_msan) LOGICAL_ERROR 'removed' (STID 2508-2c54) chronic trunk Assertion in DatabaseCatalog::dropTablesParallel (DatabaseCatalog.cpp:1564), msan stress-teardown. 3 master serverfuzz hits / 30d; tracked separately. Unrelated to this PR (text-index direct-read only).
Unit tests (amd_llvm_coverage) -FunctionsStress "Backup checksum should not be zero" chronic trunk Known FunctionsStress flake (167 hits / 59 PRs / 30d); fix in flight. Unrelated to this PR.
Mergeable Check / PR aggregators Reflect the above non-PR-caused reds.

All four @Ergus/clickhouse-gh[bot] review rounds are resolved on this HEAD: the lossy addCast(UInt8 -> Nullable(UInt8)) all-false-null-map was replaced with if(isNull(haystack), NULL, value) at the central virtual-column site (direct read stays enabled), and the stale demotion-era test comment was updated. No PR-caused failure remains.

@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from 400afea to 91f1feb Compare June 25, 2026 11:43
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased onto current master (HEAD 91f1febcf19) to resolve the merge conflict; the PR is mergeable again.

The conflict was mechanical only: master renamed need_preprocess_function -> need_transform_function and preprocessTextIndexFunction -> processTextIndexFunction in optimizeDirectReadFromTextIndex.cpp. No logic changed. The fix is byte-for-byte the same if(isNull(haystack), NULL, virtual_column) cast-fix from the redesign (Ergus's diagnosis): the lossy addCast(UInt8 -> Nullable(UInt8)) all-false null map is still on master, and this PR replaces it at the central virtual-column site. Direct read stays enabled for Nullable columns.

Re-verified on the rebased binary (build id 218843df):

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 91f1feb (post rebase)

CI has fully finished (Finish Workflow + Mergeable Check passed; last check 2026-06-25 15:37). This PR fixes text-index direct-read NULL semantics; the single red is an unrelated chronic deadlock. Every red check has an owner; only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_asan_ubsan) / Hung check failed, possible deadlock found deadlock (chronic shutdown-deadlock family: 976 hits / 433 PRs / 327 master in 30d) #105905 / #101680 (ours, open)
Mergeable Check / PR — rollup of the red above
CH Inc sync — CH Inc sync (private, not actionable by us)

The fix (nullable-haystack demotion at all Exact construction sites + isNull guard) + 02346 regression test are green; @ Ergus's CHANGES_REQUESTED was addressed in the rebased commit. Ready for re-review.

Session id: cron:our-pr-ci-monitor:20260625-170000

@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from 91f1feb to 5b03f81 Compare June 26, 2026 11:43
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased onto current master to resolve a fresh merge conflict.

The only conflicting file was optimizeDirectReadFromTextIndex.cpp: master commit 208ee06df4f ("Revert 'Text index postprocessor'") renamed need_transform_function back to need_preprocess_function and processTextIndexFunction back to preprocessTextIndexFunction. Resolution kept master's names and re-injected this PR's original_haystack capture above the preprocess call; everything else auto-merged. No logic change: the cpp net line-set is byte-identical pre/post rebase (62 lines each). Diff vs master is still the same 3 files (+397/-1).

Verified master still carries the bug: the lossy addCast(virtual UInt8 -> Nullable(UInt8)) (all-false null map) is still present on master, so this fix is still needed.

Re-verified on the rebased binary (build id c4a32c4a): core repro NOT hasToken(str, 'hello') on a Nullable text-indexed column returns only [3] across direct-read / query_plan_direct_read_from_text_index=0 / use_skip_indexes=0; 02346_text_index_bug106922 passes 30/30 with randomization; EXPLAIN actions=1 shows the __text_index virtual column is still read (direct read stays enabled) and the if(isNull(haystack), NULL, ...) guard is present.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5b03f81

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
Stress test (amd_msan) / Logical error 'Equal values are not contiguous' (STID 2508-348f, ColumnString::getEqualRangeEndAssumeSorted) trunk crash (latent unsorted-input feed into the sort primitive, surfaced under msan stress; #107078's text-index diff has no causal link) #108568 (ours, open)
Bugfix validation (functional tests) transient infra server-start death (Start ClickHouse Server FAIL; server exited 115 ~4s after launch, err.log never created, the changed test never ran; 4 unrelated PRs hit the same job-level FAIL in the same 11:44-11:54 UTC window) a fix task is created (investigating at full effort — fixing-PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260626-160000

@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from 5b03f81 to b603d9c Compare June 30, 2026 11:36
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased onto current master (33af86ef8f9) to resolve the merge conflict; PR is MERGEABLE again. HEAD is now b603d9c8396.

The conflict was mechanical: master reapplied "Text index postprocessor" (#108606), restoring the need_transform_function / processTextIndexFunction names in optimizeDirectReadFromTextIndex.cpp. The fix logic is byte-for-byte unchanged (the added-line set is identical pre/post rebase): the lossy addCast(UInt8 -> Nullable(UInt8)) is still replaced at the central virtual-column site with if(isNull(haystack), NULL, vc), so direct read stays enabled for Nullable columns and the per-row null map is restored.

One test-only adjustment: the "direct read stays enabled" EXPLAIN assertion now also accepts str IS NULL because current master renders isNull(str) in that operator form in the EXPLAIN actions dump. The assertion still verifies the guard is present (it is not weakened).

Re-verified on the rebased binary (build id 2e938339, server hash b603d9c8396):

  • Core NOT hasToken(<Nullable>, ...) over text-index direct-read returns rows whose value is NULL #106922: SELECT id FROM t_null WHERE NOT hasToken(str,'hello') returns only [3] across all three paths (direct read default, query_plan_direct_read_from_text_index=0, use_skip_indexes=0); NULL rows are filtered.
  • 02346_text_index_bug106922: 10/10 PASS with randomization on.
  • EXPLAIN actions=1: __text_index virtual column INPUT present (direct read on) and NOT if(str IS NULL, NULL, CAST(__text_index... AS Nullable(UInt8))) wrap present.

@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from edd316f to b43a8bc Compare July 17, 2026 02:07
@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from b43a8bc to 845d5bc Compare July 17, 2026 03:17
@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from 845d5bc to 921ec21 Compare July 17, 2026 04:46
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. str Nullable(String) + preprocessor = ifNull(str,''), rows (1,'hello'),(2,NULL),(3,'foo'), NOT hasToken(str,'hello'): default [3] vs fallback [2,3]. Also coalesce/assumeNotNull and the partial-materialization (part before ALTER ADD INDEX + part after) case.
b Root cause explained? preserve_haystack_null keyed off source result-type nullability and wrapped with isNull(source). A null-removing preprocessor makes the effective haystack non-Nullable, so the rewritten fallback evaluates a source-NULL row to 0, not NULL; the source-keyed wrapper wrongly reintroduced NULL on materialized parts only, giving a materialization-dependent result.
c Fix matches root cause? Yes. removesNull() detects that the preprocessor's effective output (applied to the real Nullable source) is non-Nullable; !preprocessorRemovesNull(...) is ANDed into preserve_haystack_null, so the wrapper is skipped exactly for null-removing preprocessors. No wrapper -> the plain virtual-column value (0) is the correct consistent answer.
d Test intent preserved / new tests added? New section in 02346_text_index_bug106922: ifNull (with partial + full materialization), coalesce, assumeNotNull, plus the nullIf still-demotes guard. Existing cases unchanged.
e Both directions demonstrated? Yes. pre-fix 74d2ffb9: new test FAILS (rows 2/12 dropped, isNull wrap present). fixed 35837a2b: exact reference match; default==recheck everywhere; partial/full-materialize agree.
f Fix is general across code paths? Central at preserve_haystack_null (Exact/Hint/mapValues share it). Scoped to needApplyPreprocessor functions, matching the sibling preprocessorCanIntroduceNullOnNullableHaystack guard; raw-string siblings evaluate the source value and are unaffected.
g Fix generalizes across inputs? Covered ifNull/coalesce/assumeNotNull (null-removing), nullIf (null-producing, still demotes), plain Nullable (still preserves NULL, direct read on), and Nullable(FixedString)+widening CAST (kept, from the prior round). Detection is type-based on the effective output, not a per-function allowlist.
h Backward compatible? N/A. No setting/format/default change; the change only affects a query-plan optimization to produce the same result as the non-optimized path.
i Invariants and contracts preserved? Yes. The invariant is direct-read result == non-direct-read result across every part regardless of materialization state; the fix restores it for null-removing preprocessors while keeping direct read enabled (granule pruning intact).

Session id: cron:clickhouse-worker-slot-1:20260717-035300

@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from 921ec21 to 2a5bc55 Compare July 17, 2026 05:51
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup 2a5bc55 — widened null-removing preprocessor)

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. str Nullable(String), preprocessor CAST(ifNull(str, ''), 'Nullable(String)'), rows (1,'hello'),(2,NULL),(3,'foo'), NOT hasToken(str, 'hello'): pre-fix direct read [3], fallback [2,3] (deterministic).
b Root cause explained? Yes. removesNull() compared the preprocessor's final declared result type; ifNull removes null then the outer CAST(..., 'Nullable(String)') widens back to Nullable, so removes_null stayed false, preserve_haystack_null stayed true, and the if(isNull(source), NULL, vc) wrapper re-added NULL for source-NULL rows on materialized parts.
c Fix matches root cause? Yes. removesNull() now peels the widening wrappers (shared peelWideningWrappers: ALIAS + CAST/_CAST/toNullable) off the effective output before the nullability check, so the inner ifNull is seen and removes_null becomes true.
d Test intent preserved / new tests added? Yes. Added a widened null-removing regression (direct read stays on, consistent answer) and a widened null-producing counter-case (CAST(nullIf(...), ...) still demotes). Existing cases unchanged.
e Demonstrated both directions? Yes. Build 35837a2b fails (row 2 dropped, isNull wrap applied); Build 12cef89f passes ([2,3] == fallback, wrap suppressed, direct read on).
f Fix general, not a narrow patch? Yes. introduces_null and removes_null now share one peel helper, so both null-introduction and null-removal detection handle widening wrappers uniformly (CAST/_CAST/toNullable/ALIAS).
g Generalizes across inputs? Yes. Verified ifNull/coalesce/assumeNotNull (null-removing) and nullIf (null-producing), each plain and wrapped in an outer widening CAST; peel stops at the inner null-producing function so no false negative.
h Backward compatible? Yes. Behavior change only widens where direct read is kept enabled (a correctness+perf improvement); no setting default, on-disk/wire format, or new-validation change.
i Invariants preserved? Yes. Direct read is only kept enabled when the effective post-preprocessor haystack is provably non-Nullable for source-NULL rows; the deterministic fallback predicate result is unchanged, so materialized and unmaterialized parts agree.

Session id: cron:clickhouse-worker-slot-1:20260717-054000

@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from 2a5bc55 to 99bb60a Compare July 17, 2026 07:24
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. preprocessor = lower(toNullable(str)), Nullable(String) haystack, EXPLAIN actions = 1 ... NOT hasToken(str, 'hello') with query_plan_direct_read_from_text_index = 1: pre-fix reads_virtual_column = 0 every run.
b Root cause explained? canIntroduceNull() was keyed off the declared result type via peelWideningWrappers(), which peels only CAST/_CAST/toNullable. A null-propagating function (lower, useDefaultImplementationForNulls() == true) stops the peel; its widened Nullable type is read, so introduces_null becomes true. That disables replaceFunctionsToVirtualColumns() for hasToken/hasAllTokens/hasAnyTokens/hasPhrase on a Nullable haystack and drops direct read for a supported preprocessor.
c Fix matches root cause? Yes. introduces_null now comes from expressionCanSynthesizeNull(): peel widening wrappers, recurse through null-propagating functions (reached via FunctionToFunctionBaseAdaptor, as in KeyCondition.cpp), treat any remaining Nullable node as null-synthesizing. Directly targets propagation-vs-synthesis.
d Test intent preserved / new tests added? Existing 02346 cases unchanged and passing. New case preprocessor = lower(toNullable(str)) asserts reads_virtual_column = 1 and direct read == fallback. The nullIf widened counter-case still demotes.
e Demonstrated both directions? Yes, Build IDs pinned. Pre-fix 12CEF89F: reads_virtual_column = 0. Fixed BD03F9C7: reads_virtual_column = 1, direct read [3] == fallback [3]. Full 02346 diffs clean against the reference.
f Fix general, not a narrow patch? Yes. The predicate is generic over all null-propagating functions (lower, upper, concat, substring, ...), not special-cased to lower. Genuine synthesizers (nullIf, if(..., NULL, ...), *OrNull, coalesce, ifNull) keep their useDefaultImplementationForNulls() == false and stay classified as synthesizing.
g Generalizes across inputs / type wrappers? Yes. Widening (CAST/_CAST/toNullable) is peeled; propagating functions recurse into every argument; LowCardinality(Nullable) handled via isNullableOrLowCardinalityNullable. Unknown/opaque shapes conservatively fall through to "synthesizing" (safe demotion).
h Backward compatible? Yes. No setting/format/wire change. Only widens when the direct-read optimization is allowed to fire; results are identical either way (this was a performance-only regression).
i Invariants and contracts preserved? Yes. The direct-read null-map wrapper if(isNull(source), NULL, vc) still preserves the source null map for Nullable haystacks; removesNull() is unchanged. The guard only stops falsely disabling the optimization; it never enables direct read where a real null-synthesizing preprocessor would be invisible to the source-keyed null map.

Session id: cron:clickhouse-worker-slot-0:20260717-063700

@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from 99bb60a to 912a5e4 Compare July 17, 2026 12:08
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. str Nullable(String), preprocessor = lower(CAST(ifNull(str,''),'Nullable(String)')), NOT hasToken(str,'hello') over (1,'Hello'),(2,NULL),(3,'Foo'): direct read returns [3], fallback returns [2,3] on pre-fix bd03f9c7.
b Root cause explained? removesNull() peeled only widening casts then read the outer node's declared type. For lower(CAST(ifNull(str,''),...)) the outer lower is null-propagating and declares Nullable(String), so removes_null stayed false, preserve_haystack_null re-added if(isNull(str),NULL,vc), and direct read dropped the source-NULL row (evaluates to 0 -> NOT keeps it in the fallback).
c Fix matches root cause? Yes. removes_null now = expressionRemovesSourceNull() which peels widening wrappers AND recurses through null-propagating functions (removes null iff every arg does), so the inner ifNull is detected and the wrap is suppressed.
d Test intent preserved / new test added? Yes. New 02346 case for the lower(ifNull(...))-on-Nullable shape; full prior reference matches byte-for-byte (only new case appended). No assertions weakened.
e Demonstrated both directions? Yes. Pre-fix bd03f9c7: [3] vs [2,3], isnull_wrap_count=1. Fix 87087596: [2,3]==[2,3], reads_virtual_column=1, isnull_wrap_count=0.
f Fix general, not narrow? Yes. Symmetric to the canIntroduceNull()/expressionCanSynthesizeNull() fix; both null-INTRODUCING and null-REMOVING sides now classify the effective expression, covering the wrapper family (CAST/toNullable/lower/upper/...).
g Generalizes across inputs/wrappers? Yes. lower(CAST(ifNull(...),...)) removes null; lower(toNullable(str)) does not (recurses to plain Nullable source); CAST(nullIf(str,''),...) stays null-producing. Matrix covered by 02346 cases.
h Backward compatible? Yes. Purely tightens a classification used to suppress an incorrect NULL wrap on already-supported preprocessor shapes; no setting/format/default change.
i Invariants preserved? Yes. Direct-read null-map contract upheld: the virtual column's effective null map matches the source function semantics on all parts (materialized and not); expressionRemovesSourceNull is conservative (unknown/opaque shapes -> treated as Nullable -> wrap kept).

Session id: cron:clickhouse-worker-slot-3:20260717-115700

return true;
}

return !isNullableOrLowCardinalityNullable(node->result_type);

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.

expressionRemovesSourceNull still misses explicit null-removing preprocessors whose declared result stays Nullable. A supported shape like preprocessor = if(isNull(str), '', str) maps every source NULL row to a non-NULL string, so NOT hasToken(str, 'hello') should keep that row just like SETTINGS query_plan_direct_read_from_text_index = 0 does. Here if is not null-propagating, its return type is still Nullable(String), and this line returns false, so preserve_haystack_null re-adds if(isNull(str), NULL, vc) and drops the row again once direct read is enabled.

Please classify if/multiIf-style preprocessors by their source-NULL behavior rather than only their declared result_type, and add a regression around if(isNull(str), '', str) (or an equivalent widened form).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 912a5e4

CI has fully finished (Config Workflow + Finish Workflow: success; last check completed 17:39:40 UTC; 154 success / 18 skipped / 1 failure). Every failure below has an owner: a fixing PR, a full-effort fix task, or the CH-Inc sync exemption.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, flaky check) — "Start ClickHouse Server" Pre-existing trunk TSAN startup data race, NOT PR-caused. Server aborts at startup (signal 6) so our changed test 02346_text_index_bug106922 never runs. Write DynamicDelay::rotateToMin() (DynamicDelay.cpp:69) from DiskLocalCheckThread::run() races the main-thread read DynamicDelay::getCurrentDelay() (DynamicDelay.cpp:49) from DiskLocalCheckThread::startup(). None of the raced files are touched by this PR; the other three flaky-check variants (amd_asan_ubsan, amd_debug, amd_msan) all pass. #110783 (external, open)

Session id: cron:clickhouse-maint-slot-11:20260717-200700

@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from 912a5e4 to 80ba335 Compare July 21, 2026 11:43
return lhs.virtual_column_name < rhs.virtual_column_name;
});

/// Capture the original haystack and result type before preprocessing rewrites the node.

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 The code comments are extremely verbose. Cut them to one quarter (at most) of their current length.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done. Trimmed the null-preservation comments from 55 to 13 lines (about a quarter); the full rationale stays in the commit message. Comment-only change, logic unchanged (108a64c).

With a text skip index on a Nullable (or LowCardinality(Nullable)) column,
queries like NOT hasToken(str, 'x'), NOT hasAllTokens(...) and
NOT hasAnyTokens(...) wrongly returned rows whose indexed value is NULL.

hasToken(NULL, 'x') is NULL and NOT NULL is NULL, so a NULL row must be
filtered out (which is what happens when the index is not used). The
direct-read-from-text-index optimization replaces these functions with a
virtual column read from posting-list membership. That column is a plain
UInt8: a NULL row has no tokens, so it materialized as 0, indistinguishable
from a non-matching row. When the original predicate is Nullable (because the
haystack is Nullable), the type mismatch path added CAST(virtual_column,
'Nullable(UInt8)'), which manufactures an all-false null map: every row is
declared non-NULL, so the lost NULLs are not recovered and NOT 0 = 1 kept the
NULL row.

Fix the cast site. For a Nullable haystack, wrap the replacement as
if(isNull(haystack), NULL, virtual_column): the haystack's own null map drives
the result, matching f(NULL, ...) = NULL. This keeps direct read enabled
(granule pruning still applies) and covers Exact, Hint and the mapValues
re-promotion uniformly because it keys on the haystack rather than the
posting-list membership. The haystack is located as the non-constant Nullable
argument, so comparisons like equals that carry the indexed column on either
side are handled too.

For partial materialization the Exact-mode default expression evaluates the
real function for non-materialized granules; coalesce it to 0 with
ifNull(real_func, 0) so a NULL row can be inserted into the UInt8 virtual
column, and let the outer wrap restore the NULL.

The if(isNull(haystack), ...) guard keys on the source column, so it cannot see
NULLs a preprocessor introduces from a non-NULL source value (e.g. a text index
with preprocessor = nullIf(str, '')): the '' row is non-NULL in the source but
NULL after the preprocessor. Left enabled, direct read reads 0 from posting-list
membership for such a row in a materialized part while an unmaterialized part
evaluates the fallback predicate to NULL, so a negated predicate keeps or drops
the row depending on which parts have the index materialized -- an intra-query
inconsistency. Detect such a preprocessor (its output is Nullable when applied
to a non-nullable input) and disable direct read on a Nullable haystack in that
case, so every part evaluates the deterministic fallback predicate. This is
narrow: direct read stays enabled for a Nullable column without a null-producing
preprocessor.

Scope that preprocessor demotion to the functions whose fallback predicate is
actually rewritten through the preprocessor (hasToken, hasAllTokens, hasAnyTokens,
hasPhrase). Raw-string siblings (equals, startsWith, endsWith, LIKE) evaluate the
original source value on the fallback path, so a str = '' row gets the same verdict
in a materialized and an unmaterialized part and there is no NULL divergence to
justify disabling direct read for them. The guard keys on the haystack node rather
than the predicate result type, so a plain String haystack with a nullable needle
(the result type is Nullable but the haystack is not) also keeps direct read.

A plain (non-Nullable) String source combined with the same null-producing
preprocessor remains a separate, pre-existing issue: the fallback recheck path
force-casts the Nullable predicate back to UInt8 and throws, which is a distinct
product-semantics decision tracked separately and not addressed here.

Extends 02346_text_index_bug106922 with NOT hasToken/hasAllTokens/hasAnyTokens,
LIKE/ILIKE, Hint-mode and Map(String, Nullable(String)) mapValues regressions,
a null-producing-preprocessor case (scalar and partially materialized) that
pins the deterministic behavior, plus an assertion that the virtual column is
still read directly and guarded by isNull(haystack) for a Nullable column, so a
regression that falls back to a full scan is caught, and an endsWith case on a
Nullable haystack with a null-producing preprocessor that asserts direct read stays
enabled for the raw-string sibling. The test is tagged long
because it exercises many index shapes and is heavy under sanitizer flaky-check.

Narrow the preprocessor null-introduction test itself. A Nullable declared
result type is not enough: a pure type-widening preprocessor such as
CAST(str, 'Nullable(String)') or toNullable(str) declares Nullable yet can never
turn a non-NULL row into NULL (CAST throws on a genuine conversion failure rather
than producing NULL). Only functions that synthesize NULL from a non-NULL value
(nullIf, if(..., NULL, ...), accurateCastOrNull, *OrNull) matter. Since the
constant actions run the preprocessor on a non-nullable String, peel the
type-widening CAST/_CAST/toNullable wrappers off the output node and treat the
preprocessor as null-introducing only if what remains is still Nullable. This
keeps direct read enabled for accepted shapes like Nullable(FixedString) with
preprocessor = CAST(str, 'Nullable(String)') instead of an unconditional slow-path
regression, while still demoting a genuinely null-producing preprocessor (even one
wrapped in an outer widening CAST, since the peel stops at the inner nullIf).

A null-REMOVING preprocessor (ifNull(str, ''), coalesce(str, ''), assumeNotNull(str))
is the opposite case: it strips the source nullability, so the effective haystack is
non-Nullable and the rewritten fallback predicate evaluates a source-NULL row to 0, not
NULL. Keying the null-map wrapper on the source null map would reintroduce NULL for those
rows on materialized parts while the default-expression/unmaterialized path keeps 0 -- a
materialization-dependent result. Detect this (the preprocessor's effective output, applied
to the real Nullable source, is non-Nullable) and skip the wrapper: direct read stays
enabled and the plain virtual-column value (0 for those rows) is the correct, consistent
answer on every part.

As with the null-introduction test, the declared output type alone is not enough: a
null-removing expression widened back to Nullable, e.g. CAST(ifNull(str, ''),
'Nullable(String)') (an accepted shape), declares Nullable yet still maps every source-NULL
row to a non-NULL value. Peel the type-widening CAST/_CAST/toNullable/alias wrappers off the
effective output node first, so the inner ifNull is seen and the wrapper is still suppressed.
The peel stops at a genuinely null-producing inner function (CAST(nullIf(str, ''),
'Nullable(String)') stays classified as null-producing), so it does not misfire.

Closes: ClickHouse#106922

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

canIntroduceNull() derivation: classify the effective expression, not just the declared
result type. A null-propagating preprocessor over a widened source (e.g. lower(toNullable(str)),
where lower uses the default Nullable handling) declares Nullable but only propagates the source
nullability -- it never synthesizes NULL from a non-NULL value. Keying canIntroduceNull() off the
declared type flagged it as null-producing, which disabled replaceFunctionsToVirtualColumns() for
hasToken/hasAllTokens/hasAnyTokens/hasPhrase on a Nullable haystack and silently dropped the direct-
read optimization for a supported preprocessor (a performance regression correct-result tests cannot
catch). introduces_null now comes from expressionCanSynthesizeNull(): peel pure type-widening
wrappers, recurse through null-propagating functions (useDefaultImplementationForNulls() == true,
reached via FunctionToFunctionBaseAdaptor), and treat any remaining Nullable node as null-
synthesizing. Regression added for preprocessor = lower(toNullable(str)) asserting the virtual column
is still read.

removesNull() derivation: mirror the canIntroduceNull() change for the null-REMOVING side. A
null-removing preprocessor can be wrapped in a null-propagating outer function, e.g.
lower(CAST(ifNull(str, ''), 'Nullable(String)')): the inner ifNull maps every source-NULL row to a
non-NULL '', and lower merely propagates that (already non-NULL) value, so the effective haystack is
never NULL even though the outer lower node declares Nullable(String). Keying removes_null off only
the peeled outer node's declared type left it false, so preserve_haystack_null re-added
if(isNull(str), NULL, vc) and direct read dropped the source-NULL row that the non-direct-read
fallback keeps (a wrong-result / materialization divergence). removes_null now comes from
expressionRemovesSourceNull(): peel type-widening wrappers, and for a null-propagating function
(useDefaultImplementationForNulls() == true) it removes source null iff EVERY argument does, else it
removes null iff its declared result is non-Nullable. So lower(CAST(ifNull(str,''),'Nullable(String)'))
removes null (wrapper suppressed) while lower(toNullable(str)) does not. Regression added asserting
the source-NULL row is kept under NOT and isNull_wrap_count = 0 for the lower(ifNull) shape.
@groeneai
groeneai force-pushed the groeneai/fix-text-index-nullable-not-hastoken-106922 branch from 80ba335 to 108a64c Compare July 21, 2026 14:46
const std::vector<SelectedCondition> & selected_conditions,
const ActionsDAG::Node * original_haystack) const
{
if (!original_haystack || !needApplyPreprocessor(function_name))

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 gate is still too narrow. needApplyPreprocessor excludes raw-string siblings such as equals, startsWith, endsWith, and the Hint LIKE path, but those searches still build their postings probe through substringToTokens / stringLikeToTokens, which call preprocessor->processConstant and therefore consult the preprocessed index contents.

That means a supported preprocessor which can turn a matching non-NULL source value into NULL still produces wrong results on materialized parts. Concrete trace: str Nullable(String), INDEX idx(str) TYPE text(tokenizer = ngrams(3), preprocessor = nullIf(str, 'hello world')), rows (1, 'hello world'), (2, 'foo'), (3, NULL), query SELECT id FROM tab WHERE NOT endsWith(str, 'world') ORDER BY id. The materialized part stores no tokens for row 1, so the Hint becomes not(if(isNull(str), NULL, and(0, endsWith(str, 'world')))) = 1 and row 1 is kept. With SETTINGS query_plan_direct_read_from_text_index = 0, row 1 is filtered because endsWith('hello world', 'world') = 1.

Please either broaden this demotion to every direct-read path that consumes preprocessed postings, or rewrite those raw-string fallback predicates through the preprocessor too.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed the mechanism is real: substringToTokens and stringLikeToTokens both call preprocessor->processConstant, so the raw-string and LIKE Hint probes do consult preprocessed index contents, and a preprocessor that maps a matching non-NULL source value to NULL can diverge between materialized and unmaterialized parts.

I am not applying a further guard change in this round. This is one of a long series of change-requests iterating the per-expression source-NULL classification of an arbitrary preprocessor (nullIf, widened CAST, lower(toNullable(str)), if(isNull(str), '', str), and now the raw-string postings path). An earlier request asked to scope the demotion out of the raw-string siblings; broadening it back disables direct read for more predicates on nullable haystacks, which is the performance concern in the standing CHANGES_REQUESTED review. Whether to keep tightening a per-expression NULL classifier or instead preserve the real null map on the virtual column (the direction raised in that review) is a design decision for a human reviewer rather than another automated round, so I am capping automated iteration here.

Open items in this guard family for a reviewer:

  • raw-string / LIKE postings path (this thread)
  • if(isNull(str), '', str) classification (unaddressed thread above)

@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 94/105 (89.52%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 108a64c

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
Stress test (arm_debug) / Logical error: Invalid binary search result in MergeTreeSetIndex (STID 3252-3a4a) trunk logical error in the set-index binary search, chronic across the fuzzer/stress jobs #107586 (mine, merged 2026-07-22T00:40Z) - this job ran 2026-07-21 18:19Z, ~6 h before the merge, so the build predates the fix
Sync - CH Inc sync (private, not actionable by me)

Not caused by this PR's diff (text-index direct read NULL semantics). 30-day CIDB shows this signature on
master and on ~20 unrelated PRs, all before #107586 landed.

Session id: cron:our-pr-ci-monitor:20260726-050000

@Ergus

Ergus commented Aug 7, 2026

Copy link
Copy Markdown
Member

Replaced with #113332

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.

4 participants