Skip to content

NOT hasToken(<Nullable>, ...) over text-index direct-read returns rows whose value is NULL #106922

Description

@qoega

Wrong result: NOT hasToken over a Nullable(String) column with a text index returns the NULL rows — direct read from text index loses NULL semantics

Summary

With a text skip index on a Nullable(String) column, a query filtering by
NOT hasToken(str, '...') returns the rows where str IS NULL. Correct SQL
semantics: hasToken(NULL, '...') is NULL, NOT NULL is NULL, and a
NULL predicate filters the row out — which is exactly what happens when the
index is not used.

The culprit is the direct-read optimization
(query_plan_direct_read_from_text_index, enabled by default): it evaluates
hasToken from the index posting lists alone, where a NULL row simply has no
tokens, so the function result is materialized as 0 instead of NULL.
Negation then turns that 0 into 1. The same wrong result is expected for
the other text-search functions evaluated via direct read (e.g.
hasAllTokens/hasAnyTokens) under negation or any null-sensitive transform
(isNull(hasToken(...)) composed inside larger expressions, comparisons with
<=>, etc.).

Found by the AST-fuzzer correctness-oracle suite from PR
#99980: the TLP WHERE oracle
partitioned a seed from the text-index stateless tests into
p / NOT p / p IS NULL and the NULL rows showed up in two partitions
(69 mismatches in one fuzz batch).

Minimal repro

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');
-- default settings:                                  2 3 4   (WRONG: NULL rows 2 and 4 returned)
-- SETTINGS query_plan_direct_read_from_text_index=0: 3       (correct)
-- SETTINGS use_skip_indexes=0:                       3       (correct)

Reproduced on 26.6.1.1 (master 76c2edca2fd, release build) with
clickhouse local. Not dependent on compatibility (the fuzzer hit happened
to run with --compatibility=25.8, but the repro fires with defaults).

TLP view of the same inconsistency (rows 2 and 4 satisfy two disjoint
partitions simultaneously):

SELECT id FROM tab WHERE hasToken(str, 'hello')          -- 1 5
UNION ALL
SELECT id FROM tab WHERE NOT hasToken(str, 'hello')      -- 2 3 4  (wrong)
UNION ALL
SELECT id FROM tab WHERE isNull(hasToken(str, 'hello')); -- 2 4
-- 7 rows total; the table has 5.

Fix area

The direct-read-from-text-index planner optimization (the code behind
query_plan_direct_read_from_text_index,
src/Storages/MergeTree/MergeTreeIndexText* /
src/Processors/QueryPlan/Optimizations/ direct-read rewrite): when the
indexed column is Nullable, the function result column reconstructed from
posting lists must carry the null mask of the source column (NULL row →
NULL result, not 0). Alternatively, the rewrite must be disabled for
Nullable columns when the text-search function appears under a
null-sensitive parent (NOT, isNull, <=>, ...) — but propagating the
null mask is the correct general fix.

Original fuzzer hit (for reference)

2026-06-09 22:24:52, fuzz-lab interim fleet instance 14 (TSan build),
run dir tmp/fuzz_lab/runs/20260609-2141-76c2edca2fd/inst/14/
(mismatch_artifacts/run_1/ holds the full client log + seed shard).
TLP WHERE oracle: reference SELECT id FROM tab = 5 rows, partitioned
union = 7 rows, Only in partitioned: 2, 4.

Activity

  1. qoega commented on Jun 10, 2026

    @qoega
    MemberAuthor

    @groeneai could you please reproduce and fix this one? Repro is in the issue body — deterministic on master 76c2edca2fd, default settings.

  2. added
    fuzz
    sqlancer
    on Jun 10, 2026
  3. added
    comp-text-index
    on Jun 10, 2026
  4. groeneai commented on Jun 10, 2026

    @groeneai
    Collaborator

    Reproduced on master and fixed in #107078.

    Root cause: hasToken/hasAllTokens/hasAnyTokens use the Exact direct-read mode, which replaces the function with a non-Nullable UInt8 virtual column built from posting-list membership. A NULL row has no tokens, so it materializes as 0 (indistinguishable from a non-matching row); the later cast to Nullable(UInt8) only adds an all-false null map, so NOT 0 = 1 keeps the NULL row. The text index stores no per-row null map (NULL rows are skipped at build time), so it can't be reconstructed from the index alone.

    Fix: for a Nullable/LowCardinality(Nullable) indexed column, demote Exact to None so the real function is evaluated per row (granule pruning still applies). Added regression test 02346_text_index_bug106922 covering Nullable(String), all-NULL parts, LowCardinality(Nullable), preprocessor, and PREWHERE.

  5. qoega commented on Jun 12, 2026

    @qoega
    MemberAuthor

    Update: the same direct-read-from-text-index defect produces oracle mismatches via match, like, and hasPhrase — not only hasToken. Observed on the 02346_text_index_partially_materialized tables (tab_fully / tab_partially), so the fix should also cover partially-materialized text indexes (ngrams tokenizer in addition to splitByNonAlpha).

    Suggested scope:

    • hasToken, match, like, hasPhrase (and likely searchAny/searchAll)
    • Both full and partially-materialized text indexes
    • Same root cause as the original repro: posting lists materialize the function value as 0 for rows with no tokens (incl. NULL), so a negated predicate flips it to 1 and selects those rows.
  6. groeneai commented on Jun 12, 2026

    @groeneai
    Collaborator

    @qoega Confirmed and fixed for the expanded scope. You were right: the original fix only covered the Exact direct-read mode (hasToken/hasAnyTokens/hasAllTokens), but match/like/hasPhrase/startsWith/endsWith use the Hint mode, which builds and(virtual_column, real_func). For a NULL row that is and(0, NULL) = 0, so a negated predicate flips it to 1 and leaks the row, exactly as you observed.

    PR #107078 now demotes any non-None direct-read mode (Exact and Hint) to None for a Nullable/LowCardinality(Nullable) haystack, so the real function is evaluated per row (granule pruning still applies).

    Before/after on a Nullable(String) index (NULL rows are 2 and 4; reference is query_plan_direct_read_from_text_index=0):

    predicate before (default) after / reference
    NOT hasPhrase(str,'hello world') 2,3,4,5 3,5
    NOT endsWith(str,'world') 2,3,4,5 3,5
    NOT (str LIKE '%world') 2,3,4,5 3,5
    NOT match(str,'hello') 3 3

    Verified on both splitByNonAlpha and ngrams(3), and on a partially-materialized ngrams index (matching the tab_fully/tab_partially shape). The regression test 02346_text_index_bug106922 now covers all of these and fails on a binary without the fix.

    Note: standalone searchAny/searchAll are not functions in this build (only the multiSearch*/multiMatch* family), and those route through None mode already, so they were never affected. If you have an oracle repro that still mismatches after this update, please share the exact query + table definition and I'll dig in.

  7. added 3 commits that reference this issue on Jun 25, 2026
    91f1feb
    5b03f81
    b603d9c
  8. qoega commented on Jul 13, 2026

    @qoega
    MemberAuthor

    Reconfirmed still-open on today's master (fresh master + 1095 commits, tag 54200dd4a43, 2026-07-13). Minimal repro from the original issue still returns [2,3,4] (leaks NULL rows 2 and 4) with query_plan_direct_read_from_text_index=1 (the default), vs [3] with it off. So the fix expansion to cover Nullable direct-read is still needed. No urgency, just flagging it survived several master merges.

  9. added 11 commits that reference this issue on Jul 16, 2026
    f5290b3
    3c31780
    edd316f
    b43a8bc
    845d5bc
    921ec21
    2a5bc55
    99bb60a
    912a5e4
    80ba335
    108a64c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    comp-text-indexfuzzsqlancer

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions