Repository navigation
Conversation
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-13:20260610-193900 |
|
cc @ahmadov @CurtizJ - could you review this? When the indexed column is |
|
Workflow [PR], commit [108a64c] Summary: ❌
AI ReviewSummaryThis 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 Findings❌ Blockers
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. |
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
All other checks passed. Nothing in this PR's code path failed. Ready for review. |
Pre-PR validation gate (scope-extension update)This update extends the fix to the Hint-mode functions after @ qoega reported the same defect via
Session id: cron:clickhouse-worker-slot-2:20260612-075800 |
Pre-PR validation gate (commit df64f0e, mapValues fix)
Session id: cron:clickhouse-worker-slot-2:20260612-092500 |
|
CI fully finished on HEAD This HEAD adds the central nullable-haystack demotion ( No PR-caused failures. Ready for review. |
Ergus
left a comment
There was a problem hiding this comment.
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.
|
@groeneai The real issue is probably in When 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. |
|
@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 Fix: at that central virtual-column site, for a Nullable haystack I replaced the lossy cast with 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:
The |
Pre-PR validation gate (commit 4980a85, @Ergus redesign)
Session id: cron:clickhouse-worker-slot-6:20260615-135600 |
|
CI fully finished on HEAD
All four |
400afea to
91f1feb
Compare
|
Rebased onto current master (HEAD The conflict was mechanical only: master renamed Re-verified on the rebased binary (build id
|
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
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 |
91f1feb to
5b03f81
Compare
|
Rebased onto current master to resolve a fresh merge conflict. The only conflicting file was Verified master still carries the bug: the lossy Re-verified on the rebased binary (build id c4a32c4a): core repro |
CI finish ledger — 5b03f81Every 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
Session id: cron:our-pr-ci-monitor:20260626-160000 |
5b03f81 to
b603d9c
Compare
|
Rebased onto current master ( The conflict was mechanical: master reapplied "Text index postprocessor" (#108606), restoring the One test-only adjustment: the "direct read stays enabled" EXPLAIN assertion now also accepts Re-verified on the rebased binary (build id
|
edd316f to
b43a8bc
Compare
b43a8bc to
845d5bc
Compare
845d5bc to
921ec21
Compare
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260717-035300 |
921ec21 to
2a5bc55
Compare
Pre-PR validation gate (fixup 2a5bc55 — widened null-removing preprocessor)Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260717-054000 |
2a5bc55 to
99bb60a
Compare
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260717-063700 |
99bb60a to
912a5e4
Compare
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260717-115700 |
| return true; | ||
| } | ||
|
|
||
| return !isNullableOrLowCardinalityNullable(node->result_type); |
There was a problem hiding this comment.
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).
CI finish ledger — 912a5e4CI 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.
Session id: cron:clickhouse-maint-slot-11:20260717-200700 |
912a5e4 to
80ba335
Compare
| return lhs.virtual_column_name < rhs.virtual_column_name; | ||
| }); | ||
|
|
||
| /// Capture the original haystack and result type before preprocessing rewrites the node. |
There was a problem hiding this comment.
@groeneai The code comments are extremely verbose. Cut them to one quarter (at most) of their current length.
There was a problem hiding this comment.
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.
80ba335 to
108a64c
Compare
| const std::vector<SelectedCondition> & selected_conditions, | ||
| const ActionsDAG::Node * original_haystack) const | ||
| { | ||
| if (!original_haystack || !needApplyPreprocessor(function_name)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 94/105 (89.52%) · Uncovered code |
CI finish ledger - 108a64cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR's diff (text-index direct read NULL semantics). 30-day CIDB shows this signature on Session id: cron:our-pr-ci-monitor:20260726-050000 |
|
Replaced with #113332 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results from a
textindex on aNullable(orLowCardinality(Nullable)) column. A negated text-search predicate (NOT hasToken(col, 'x'), and likewisehasAllTokens,hasAnyTokens,hasPhrase,startsWith,endsWith,LIKE) no longer returns rows whose indexed value isNULL. The direct-read-from-text-index optimization materialized a non-Nullable0/1for such rows, losing theNULLthat the function returns, so negation wrongly kept theNULLrows.Description
Found by the AST-fuzzer correctness oracle (issue #106922, reproducible on default settings). The reporter later confirmed the same defect surfaces via
match,likeandhasPhrase(in addition tohasToken), on both fully and partially materialized (ngrams) text indexes.Root cause: the direct-read-from-text-index optimization reads a non-
NullableUInt8virtual column from posting-list membership. ANULLrow has no tokens, so it reads as0(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. This0then loses theNULLin both direct-read modes:Exactmode (hasToken/hasAllTokens/hasAnyTokens) fully replaces the function with the virtual column; the later cast toNullable(UInt8)only adds an all-false null map, soNOT 0 = 1keeps the row.Hintmode (hasPhrase/startsWith/endsWithand theLIKErewrites) buildsand(virtual_column, real_func); for aNULLrow that isand(0, NULL) = 0, soNOT 0 = 1keeps the row too.Fix: when the indexed (haystack) column is
Nullable/LowCardinality(Nullable), demote any non-Nonedirect read mode (ExactandHint) toNone, 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)andmapValuespaths (where the array value itself is neverNULL) are unaffected, and the non-Nullablefast 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 test02346_text_index_bug106922covershasToken/hasAnyTokens/hasAllTokens/hasPhrase/startsWith/endsWith/match/LIKEoverNullableandLowCardinality(Nullable)haystacks plus anngramspartially-materialized index, and fails on a binary without the fix. Existing text-index tests pass.