Skip to content

Fix BAD_GET on whole-array comparison with a token-family skip index - #110057

Merged
rschu1ze merged 20 commits into
ClickHouse:masterfrom
groeneai:fix-110038-badget-array-token-index
Jul 29, 2026
Merged

rschu1ze merged 20 commits into
ClickHouse:masterfrom
groeneai:fix-110038-badget-array-token-index

Conversation

@groeneai

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 BAD_GET error when comparing an Array(String) column with an array literal (arr = ['x']) when the column has a text, tokenbf_v1 or ngrambf_v1 skip index. Such a comparison is now treated as a full scan by the index instead of failing the whole query.

Description

Closes: #110038

Token-family skip indexes (text, tokenbf_v1, ngrambf_v1) are supported on Array(String) columns for has/hasAny/hasAll, so their condition builders accept array-typed constants. Scalar-string functions (equals, notEquals, like, startsWith, ...) then called Field::safeGet<String>() on the array constant of e.g. a = ['x'], throwing Code: 170 ... Bad get: has Array, requested String. (BAD_GET) while BUILDING the index condition. The mere existence of the index made a valid query unexecutable; use_skip_indexes = 0 was the only workaround.

The fix guards both condition builders (MergeTreeConditionBloomFilterText::traverseTreeEquals and MergeTreeIndexConditionText::traverseFunctionNode): when the constant operand is an array but the function is not one of the array-consuming functions, the atom is treated as UNKNOWN (scan all granules) instead of throwing. Results are unchanged (verified against use_skip_indexes = 0), and the array functions the index does support continue to use it.

CI report for the fuzzer finding: #110038 (repro fiddle linked there).

An Array(String) column carrying a text/tokenbf_v1/ngrambf_v1 skip index
supports has/hasAny/hasAll, so the condition builders accept array
constants. But scalar-string functions (equals, notEquals, like, ...)
then called Field::safeGet<String>() on the array constant of e.g.
a = ['x'], throwing BAD_GET while building the index condition and
making a valid query unexecutable.

Treat an array constant for a function that cannot consume it as UNKNOWN
(scan all granules) instead of throwing.

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. CREATE TABLE t (a Array(String), INDEX idx a TYPE tokenbf_v1(256,2,0) GRANULARITY 1) ... ; SELECT count() FROM t WHERE a = ['x'] SETTINGS use_skip_indexes=1 throws Code: 170 BAD_GET every time on master; same for ngrambf_v1 and text.
b Root cause explained? The condition builders accept array constants (needed for has/hasAny/hasAll on Array(String)), but scalar-string functions (equals/notEquals/like/...) then call Field::safeGet<String>() on the array constant while building the index condition, throwing BAD_GET before the query runs.
c Fix matches root cause? Yes. Guards both builders: an array constant paired with a function that cannot consume it returns false (UNKNOWN → scan all granules) instead of reaching safeGet().
d Test intent preserved / new tests added? New test 04365 added. The array-consuming functions (has/hasAll/hasAny) still use the index; only the previously-throwing scalar path is redirected to a scan.
e Demonstrated in both directions? Yes. Baseline binary (Build ID ed24437) throws BAD_GET; fixed binary (85a6af) returns correct results matching use_skip_indexes=0.
f Fix is general, not a narrow patch? Yes. All three sibling index families fixed (tokenbf_v1, ngrambf_v1 in MergeTreeIndexBloomFilterText.cpp; text in MergeTreeIndexConditionText.cpp), each enumerating its full set of array-consuming functions.
g Generalizes across inputs? Guard is keyed on WhichDataType(value_type).isArray() + function name, so it covers any array element type and any scalar function; string/FixedString constants are unaffected and still use the index.
h Backward compatible? Yes. No format/setting change; only removes an erroneous exception, making previously-failing queries succeed.
i Invariants preserved? Yes. Returning false from an atom builder is the established "UNKNOWN, scan granules" contract already used elsewhere in these files; no RPN/index invariant is weakened.

Session id: cron:clickhouse-worker-slot-5:20260710-210200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @ahmadov — could you review? Small guard in the token-family index condition builders so a whole-array comparison (arr = ['x']) on an Array(String) column with a text/tokenbf_v1/ngrambf_v1 index falls back to a scan instead of throwing BAD_GET.

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1fed255]

Summary: ✅


AI Review

Summary

This PR hardens the text / tokenbf_v1 / ngrambf_v1 skip-index condition builders so whole-array predicates on indexed Array(String) columns fall back to a scan instead of throwing BAD_GET while building the index condition. The current tip also closes the earlier startsWith / endsWith gap in both builders, and the new regression test now exercises =, !=, startsWith, and endsWith for all three index families. I did not find any remaining correctness or coverage issues in the current diff.

Final Verdict
  • Status: ✅ Approve

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

groeneai commented Jul 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e326246 (corrected)

CI fully finished (Finish Workflow complete). Every failure below has an owner. None is caused by this PR (a text-index Array(LC(Nullable)) null-skip fix in MergeTreeIndexText.cpp; cannot affect AST-fuzzer optimizer stacks, ReplicatedDatabase alter, or a coverage-build server death).

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Logical error: Stream ... not found (STID 3190-5d8a) chronic trunk logical error (Variant/Dynamic/JSON subcolumn serialization; 5 PRs/0 master, 30d) a fix task is investigating at full effort (fixing-PR link to follow here)
AST fuzzer (amd_debug, targeted) / KeyCondition uses PREWHERE output (STID 4419-44a9) trunk logical error (10 PRs/0 master, 30d) #109267 (ours, open)
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter chronic flaky (48 PRs/9 master, 30d) #110030 (ours, open)
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) / 03915_exchange_tables_race + victims (00872, 02155, 02789, 03835, 04117, 04145, 04318, Unknown error; all one server-death event) server died (partial-result type-mismatch abort in the EXCHANGE-TABLES race is the crash contributor; the rest are health-check victims) #109747 (ours, on_review)
Sync - CH Inc sync (private, not actionable)

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

@rschu1ze rschu1ze assigned rschu1ze and unassigned Ergus Jul 13, 2026
Move the array-constant guard from a single blanket check into each
scalar-string case (equals, notEquals, like, hasToken, hasPhrase,
startsWith, endsWith, match, ...) that calls safeGet<String>() on the
whole constant, in both MergeTreeIndexBloomFilterText and
MergeTreeIndexConditionText. The array-consuming functions
(has(array)/hasAny/hasAll/multiSearchAny/hasAnyTokens/...) keep their
existing array handling.

Rewrite the regression test per review: single table `tab`, text index
first, drop the experimental setting and GRANULARITY 1, remove the
header block, and add the != and hasAny use_skip_indexes = 0 assertion
pairs.

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

This comment was marked as resolved.

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 Change -- text index to SELECT 'Text index'. Do the same for the corresponding comments for tokenbf_v1 and ngrambf_v1

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 Remove the comment in l. 800-804

@groeneai

This comment was marked as resolved.

…rray-token-index

# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexConditionText.cpp
Cover startsWith(a, [...]) / endsWith(a, [...]) with use_skip_indexes = 1
and = 0 for the text, tokenbf_v1 and ngrambf_v1 indexes. Those functions
accept Array operands via FunctionStartsEndsWith and had the same
safeGet<String>() BAD_GET failure mode as a = ['x'], which the previous
=/!= only cases did not exercise.

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

Copy link
Copy Markdown
Collaborator Author

@rschu1ze all review points addressed on 8c91b3e:

  • l.1-5 slob and allow_experimental_full_text_index removed; table renamed to tab; text index tested first; GRANULARITY 1 removed; SELECT 'Text index' markers; use_skip_indexes = 0 and hasAny scan cases added for all three; comment in MergeTreeIndexConditionText.cpp l.800-804 removed.
  • Point 10: replaced the per-case Array blacklist with a supported-type whitelist if (!value_data_type.isStringOrFixedString()) return false; in both condition builders.

Also addressed the bot finding: added startsWith(a, [...]) / endsWith(a, [...]) cases with use_skip_indexes = 1 and = 0 for text, tokenbf_v1 and ngrambf_v1. These functions take Array operands via FunctionStartsEndsWith and hit the same BAD_GET on master; verified locally that HEAD returns the correct count (equal to the scan result) and reverting the guards throws BAD_GET: has Array, requested String.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. startsWith(arr, ['x']) on a column with a text/tokenbf_v1/ngrambf_v1 index throws BAD_GET every time on master.
b Root cause explained? The scalar-string index-condition branches (equals/notEquals/like/startsWith/endsWith/match/hasToken/hasPhrase/has) call safeGet<String>() on the whole constant. A whole-array comparison supplies an Array constant, so safeGet<String> throws BAD_GET.
c Fix matches root cause? Yes. Each such branch early-returns UNKNOWN (scan) unless the constant is String/FixedString.
d Test intent preserved / new tests? Yes. New startsWith/endsWith Array-operand cases prove the whole-array contract for those functions; idx=1 result equals idx=0, so no wrong pruning.
e Demonstrated both directions? Yes. Reverting the guards -> BAD_GET; with the fix -> correct count.
f General, not narrow patch? Yes. Whitelist applied to every scalar-string branch in both MergeTreeIndexConditionText and MergeTreeIndexBloomFilterText; array-consuming functions (has/hasAny/hasAll/multiSearchAny) keep using the index.
g Generalizes across inputs? Whitelist gates on isStringOrFixedString, so Array/Map/Tuple/other non-string constants all fall to scan.
h Backward compatible? Yes. Only changes an error path into a correct scan; no format/setting change.
i Invariants preserved? Yes. Non-string constants that a scalar-string function cannot tokenize now yield UNKNOWN instead of a spurious throw.

Session id: cron:clickhouse-worker-slot-5:20260713-083300

@rschu1ze

Copy link
Copy Markdown
Member

@groeneai Stop pushing new commits, I will clean this PR up, then we can merge.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, no more commits from me. It is yours to clean up and merge. Thanks.

@rschu1ze

rschu1ze commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

@groeneai Fix the unrelated failure in 02346_text_index_parallel_replicas in a new PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. Investigating the 02346_text_index_parallel_replicas flakiness now; I will open a separate PR and post the link back here (or report findings if it turns out not to be actionable).

@groeneai

Copy link
Copy Markdown
Collaborator Author

@rschu1ze Fix opened: #111138. Root cause: the probe asserts TextIndexUsedEmbeddedPostings > 0, but that counter only increments in deserializeTokenInfo (a tokens-cache miss). Once the global TextIndexTokensCache is warm (a retry, a prior run, or another text index test), fillTokensFromCache serves the tokens and the counter stays 0, so the test reads 1 0 (which is why CI re-ran it 112/112 PASS). The PR sets use_text_index_tokens_cache = 0 so tokens are read from disk each run; reproduced 50/50 fail without it, 0/50 with it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 84719c8

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.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (SystemLog (system.metric_log): Failed to mark the rotated system log table as readonly, Code 229) trunk error-log leak, not PR-caused #111703 (external, merged 2026-07-24T17:24:53Z) - NOT on this branch (git merge-base --is-ancestor eb577ff401a3 84719c8d096861a3ed3988c5ad89407b91e3006a is false), so this build predates the fix; merging master will pick it up

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 586a46b

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.

This head is a plain master merge on top of the previously ledgered 84719c8d0968, so the
diff under review is unchanged. Neither red is in this PR's files. Fast test, Style check
and all four Bugfix-validation legs are green.

Check / test Reason Owner / fixing PR
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Logical error '!part.empty()' (STID 2735-47bf) coverage-shard death; 03915_exchange_tables_race is among the batch's UNKNOWN tests, and the reported !part.empty() text is the reporter picking the first Logical error match in the log (it matches an SQL comment in the passing 04367_lambda_arg_backquoted_dot_no_logical_error), not the aborting record #109747 (ours, open); root cause of the EXCHANGE-vs-SELECT race is fixed by #110048 (external, merged 2026-07-26), which is not yet an ancestor of this branch (issue #110133)
Stress test (arm_debug) / Inconsistent KeyCondition behavior (STID 5182-684a) debug-only monotonicity canary on a widened-type key comparison, markRangesFromPKRange (issue #90461) #109023 (ours, open)
Sync - CH Inc sync (private, not actionable)

Note on the merged #110048: this branch carries the hold label and its head is a
maintainer-pushed master merge, so I am not pushing a merge to pick it up. A later master
merge by the PR owner will.

Session id: cron:our-pr-ci-monitor:20260727-043000

@groeneai

Copy link
Copy Markdown
Collaborator Author

@rschu1ze New PR for the 02346_text_index_parallel_replicas flakiness: #112197. It supersedes #111138, which I closed.

#111138 was wrong and that concession stands. This one does not touch the tokens cache. It comes from the CI settings data: parallel_replicas_local_plan = 0 in 6 of 6 genuine flap rows over 60 days, against a 0.375 base rate for that value. With local_plan = 0 the initiator builds no local plan and does no index analysis, so TextIndexUsedEmbeddedPostings lands only on follower query_log rows, which is scheduling-dependent. The fix pins the setting to its own default, as three existing text index tests already do. The assertion and the reference are unchanged.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Update on the 02346_text_index_parallel_replicas flakiness I linked above: #112197 was closed, correctly, because pinning parallel_replicas_local_plan = 1 deletes the placement the test exists to cover. My own measurements also show that placement is not sufficient to cause the failure, so that PR was fixing the wrong thing. Details and my remaining question are in #112197 (comment). I have no replacement PR to link yet and will not open one until I can reproduce the failing direction.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c19c401

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
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / 00084_external_aggregation query-level Code 241 Query memory limit exceeded ... maximum: 286.10 MiB in AggregatingTransform; the runner's own rerun is clean (4/4 passed) #112054 (external, open)

Not PR-caused: this pull request is a skip-index/text-index change and does not touch the
aggregation path or any memory limit. The same query-level 241 signature is currently
firing across many unrelated pull requests on 00084_external_aggregation, which is
exactly the failure #112054 raises the headroom for. All 173 other checks are green.

Head c19c4011d829 is @ rschu1ze's own master merge, so I validated and ledgered only:
no push, no rebase, no master merge from me.

Session id: cron:our-pr-ci-monitor:20260728-163000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1fed255

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.

All 174 checks completed with no failures.

Check / test Reason Owner / fixing PR
- no failures -

Session id: cron:our-pr-ci-monitor:20260729-053000

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 hold Skip for auto-updating. pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BAD_GET on Array(String) column equality with an array literal when the column has a text/tokenbf_v1/ngrambf_v1 index

5 participants