Skip to content

Fix text index over-pruning for a NUL-padded FixedString constant - #112868

Open
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-padded-string-constant
Open

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-padded-string-constant

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 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 too few rows being returned when a query filters a column covered by an ngrambf_v1, sparse_grams or text skip index with a FixedString constant or IN element. The probe was built from bytes the comparison ignores, so a granule holding a matching row was skipped. This covers has, mapContainsKey, mapContains, mapContainsValue, a String constant carrying a NUL tail, and constants that end inside a UTF-8 sequence.

Description

On 26.8.18.2, has(v, toFixedString('VALUE0', 10)) over an ngrambf_v1 index on Array(FixedString(8)) returns 0 rows instead of 1.

Master's convertConstantToIndexDomain and #118972 already cover the IPv6, typed map key and padded text needle cases, so this PR keeps only the rest. Against master 9f7ed316 the fixture differs in 36 of 69 cells (oracle = unindexed Log twin):

  • has, mapContainsKey, mapContains, mapContainsValue, has(mapKeys(m), ...) with a constant wider than a FixedString(N) element, key or value: 1/0. Only equals, notEquals, hasAny and hasAll were normalized.
  • s = 'VALUE0\0\0\0\0' on FixedString(8): 1/0, the trim was keyed on the constant's type.
  • A constant or IN element ending inside a UTF-8 sequence, e.g. toFixedString(concat('VALUE', unhex('C2')), 8) (also at full width, 6) against a stored 'VALUE' || unhex('C200'), on ngrambf_v1, sparse_grams and a text index with ngrams or sparseGrams: 1/0. These tokenizers clamp the last gram to the buffer end, and String = FixedString compares zero padded.

normalizeConstantForIndexDomain wraps master's converter: for a FixedString(N) column it trims and re-pads the constant to N; for a widthless column it declines when equals, notEquals or IN would probe a constant ending mid-sequence. It is used by every arm of traverseTreeEquals and by prepared-set elements. On the text index the type-only tokenizerSplitsAtZeroByte becomes the shared per-value tokensSurviveTrailingNuls (asciiCJK and icu keep master's answer), and the decline no longer requires padding to trim, so 05223 now expects INDEX_NOT_USED for a full-width needle on array, splitByString and a preprocessor.

The fixture passes. 363 of the 367 stateless tests using these index types give output identical to master 9f7ed316; the other four are the two edited tests and two tests newer than that build, which pass. Both edited tests pass 25 randomized runs each.


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

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 5 rounds, 10 substantive findings, 8 agreed and fixed, 2 disagreed with evidence

An independent model reviewed this change against the repository review guidelines, in five
rounds, each re-reviewing the full scope. The table lists every finding that changed the code
or was refuted on the merits; rounds also produced confirmations that required no action. My
adjudication of each, with the evidence I verified it against.

# Severity Finding Verdict
❌ 1 blocker the trim is not token-preserving for a non-UTF-8 tail AGREE, fixed
❌ 2 major IPv6 index domain trimmed AGREE, fixed
❌ 3 major completeness guard also declines tokenbf_v1 AGREE, fixed
⚠️ 4 major optimize_functions_to_subcolumns randomization bypasses the direct map branch AGREE, fixed
⚠️ 5 major wide-constant cells asserted on the answer only, never on the granule count AGREE, fixed
⚠️ 6 major four further answer-only success cells, including every sparse_grams one AGREE, fixed
💡 7 nit changelog names tokenbf_v1 although no tokenbf_v1 cell was ever wrong AGREE, fixed
💡 8 nit helper comments carry derivations rather than invariants AGREE, fixed
⚠️ 9 major Direction D pins a known-wrong answer DISAGREE, see below
⚠️ 10 major trimming may be unsound for sparse_grams, whose emission is not a sliding window DISAGREE, see below

1. Non-UTF-8 tail. NgramsTokenizer::nextInString steps by UTF8::seqLength and clamps
its final token to the buffer end, so a value ending inside a declared sequence yields a
shorter final gram than the same bytes followed by padding. The trimmed probe was then not a
subset of the granule's tokens and skipped a matching granule, i.e. the very wrong-results
class this change exists to fix. Localized by enumerating 2.2M byte combinations: 502970
unsound cases all had a trimmed value that was not sequence-complete, and 0 were unsound when
it was, so that predicate is sufficient. Fixed by declining the widthless case otherwise.

2. IPv6 index domain. bloomFilterIndexTextValidator admits IPv6, and DataTypeIPv6
is not DataTypeFixedString, so the normalization took the widthless branch and trimmed. But
FunctionsComparison intercepts IPv6 against FixedString(16) before any common-type
resolution and compares all 16 raw bytes, which is also exactly what the granule tokenizes.
Any address with trailing zero bytes therefore lost pruning. Fixed by resolving the target
width from IPv6 as well, plus a granule assertion.

3. tokenbf_v1 decline. SplitByNonAlphaTokenizer advances one byte at a time and never
consults UTF8::seqLength, so it has no final-gram clamp and the trim is token-preserving for
it unconditionally. The guard from finding 1 was applying to every widthless index without
consulting the tokenizer, so tokenbf_v1 declined where it previously pruned. Fixed by
requiring sequence-completeness only for the gram tokenizers, and a non-ASCII-tail
tokenbf_v1 assertion now pins it.

4. Setting randomization. The stateless runner randomizes
optimize_functions_to_subcolumns, and mapContainsKey is rewritten to has(map.keys, ...),
so on about half of all runs the cells labelled as covering the direct map branch were
covering a different one. The specific setting is now pinned on those cells only;
randomization is left on everywhere else.

5 and 6. Answer-only assertions. This is why finding 2 was invisible. A decline returns
false from the arm, the atom becomes unknown, and the skip index then removes nothing, so
every answer-only cell still reads its correct answer and cannot distinguish an exact probe
from a declined atom. Round 2 found the map granule rows used an exact-width constant, where
padding is the identity, while the affected cells use a wider constant; round 3 found four
more success cells with the same blindness, including both sparse_grams cells and the
LowCardinality ones, and one arm with no granule row at all. Ten granule rows were added
across the two rounds, each proven load-bearing by a mutation that makes the arm decline
rather than by one that merely removes the normalization: on non-adversarial fixtures a
wrongly re-encoded probe still prunes, so a decline is the alternative a later reader would
actually write.

9. Direction D, disagreed. The finding is right that the pinned value is the wrong answer:
for a Map(String, FixedString(8)), an absent key yields the 8-byte zero default, which
compares equal to a 3-byte zero constant, so the oracle answer is 64 rather than 0. But the
requested remedy, deleting the row, is the riskier option. That value is produced by the
absent-key default-match guard, a separate root cause tracked separately, and this row is the
only assertion proving this change leaves that cell bit-identical to the current behaviour. An
all-zero constant is precisely the shape this change's trim path handles, so a later widening
of the helper into that guard would otherwise be undetectable. The row stays, with its comment
saying explicitly that the pinned value is the wrong answer and is pinned only as a scope
guard.

10. sparse_grams soundness, disagreed. Raised in round 4 because sparse_grams does not
emit a sliding window: SparseGramsImpl::consume selects grams through a hash-driven convex
hull over the whole buffer, so shortening the buffer could in principle change which grams are
emitted rather than only clamping the last one, and the completeness guard alone would then not
be sufficient. It is sufficient, and the reason is structural: getNextPosition clamps with
std::min(end - data, ...), so the buffer end enters the position walk only when a lead byte's
declared sequence overruns it, which is exactly the case the guard rejects. For a
sequence-complete value the position walk of the trimmed value is a prefix of the stored
value's, identical substrings feed identical hashes, and the hull evolves identically.
Verified by exhaustive enumeration over an alphabet of ASCII, UTF-8 lead and continuation
bytes: 682248 sequence-complete cases with 0 violations of the subset property, against 451312
violations of 516120 for values that are not sequence-complete, so the guard is load-bearing
rather than vacuous. Repeated under six unrelated hash functions with the same result, since
the hull's control flow is hash-driven.

Also verified independently rather than accepted: all 21 tokenization sites in the condition
were enumerated and each unedited one has a stated reason for exclusion (hasToken cannot take
a FixedString needle; every *Like, startsWith, endsWith, multiSearchAny and match
site builds a substring probe, where trimming would be unsound in the other direction;
notEquals has its containment inverted, so a wider probe is conservative there; the IN path
reads already-coerced set bytes). The tokenizer-kind switch is exhaustive over the tokenizer
enumeration and the three reachable kinds are pinned by the index creator's own
allowed-tokenizer set.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Gate Answer
(a) Deterministic repro? Yes. One clickhouse local run of the new test prints 47 differing rows on a baseline built from this branch with only the source file reverted, and 0 with the fix. Not a probabilistic repro.
(b) Root cause explained? Yes. traverseTreeEquals tokenizes the constant's raw Field bytes, which carry FixedString padding, while the granule tokenizes the stored value, so probe and granule tokenize different byte strings. Which bytes each predicate actually compares was measured per predicate and element type, not assumed.
(c) Fix matches root cause? Yes. The probe is normalized to the bytes the executing function compares, at the point where the probe is built. Not a widened bound: the normalized constant is a separator-boundary prefix of every matching value and a bloom filter is a subset test, so the probe is conservative by construction. No assertion weakened, no optimization disabled.
(d) Test intent preserved / new tests added? Yes. No existing test modified. A new 113-row test covers correctness against unindexed oracles, no-pruning-lost granule counts, exactness on adversarial shared-gram fixtures, rows asserting that a declined constant still reads every granule, and out-of-scope invariance. Every row is mutation-tested; two rows were caught vacuous by a mutation and re-expressed before shipping, and six further granule rows were added because a decline answers every query correctly, so an answer-only row cannot tell an exact normalized probe from a declined atom.
(e) Demonstrated in BOTH directions? Yes. 47 rows differ on the reverted-source baseline and all pass with the fix. Every assertion is reddened by at least one mutation of the shipped tree, and the mutations that see the granule rows are declines rather than reverted normalizations, because a wrongly re-encoded probe still prunes a non-adversarial fixture. A further arm built from the previous round's source reddens exactly the two rows that round regressed, which is how both pruning-loss regressions were localized.
(f) General across CODE paths? Yes. All five arms that tokenize a raw string constant are fixed (array, scalar has, scalar equals, both map branches); every other arm in the function is enumerated with a reason for exclusion. The carrier set is closed by registration: MergeTreeIndices.cpp binds ngrambf_v1, tokenbf_v1 and sparse_grams to one creator, so sparse_grams is covered too. tokenbf_v1 is a provable no-op with a pinning row.
(g) Generalizes across INPUTS? Yes. Rows for String, FixedString(N), LowCardinality(String), LowCardinality(FixedString(N)), Array of each, and both Map(FixedString, String) and Map(String, FixedString). Array(LowCardinality(...)) is rejected by the index validator, so no row is possible. Boundary constants covered: empty and all-NUL, shorter than the n-gram length, exact width, wider, and wider with genuine content, which declines. Byte-level inputs covered too: a value whose tail is a UTF-8 lead byte, where trimming the padding would shorten the last n-gram, is declined rather than probed with a non-subset filter.
(h) Backward compatible? Yes. Only which granules are read changes. No on-disk format change, no serialization version, no setting or default, so SettingsChangesHistory.cpp needs no entry. Existing indexes keep working: they are already tokenized with the padded stored bytes, which is the side that was correct.
(i) Invariants and contracts preserved? Yes. The probe-versus-granule subset invariant is now established rather than violated. The helper mutates a local copy, so no Field is modified in place; it has no path that leaves a half-normalized value; both decline paths return before the filter is consumed, so no partially built filter escapes; the probe-token-subset invariant is now checked rather than assumed for a widthless index, which is what the trim can otherwise break; and index_data_types is indexed only with a position the call site already dereferenced for out.key_column, so no empty-optional dereference is introduced on any branch.

Build: NINJA_RC=0, 0 FAILED: lines, Build ID moved from the pre-edit binary. Style check clean for the touched file. Tag-free 50 of 50 randomized runs pass. A/B sweep over the 47 stateless tests that use these index types, with the baseline built from this branch with only the source file reverted and each arm measured against a server restarted on its own binary: coverage asserted symmetric (47 ran in both arms, none only in one), 0 regressions, 1 improvement, and 8 failures shared by both arms that are missing-ZooKeeper and missing-S3-policy in the local sandbox.

One mutation, normalizing the mapContainsValueLike arm, leaves the suite green. That is structural rather than a weak assertion: mapContainsValueLike requires a String pattern and rejects a FixedString one at analysis, so the branch is unreachable for every constant shape whose bytes could differ. A separate row still pins that the arm keeps pruning.

Session id: cron:clickhouse-review-slot-8:20260801-060002

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer @tiandiwonder, could you review this? A text bloom-filter skip index tokenized a FixedString constant including its NUL padding, which the executing comparison does not compare, so the probe filter was built over tokens the granule never saw and a granule holding a matching row was pruned away.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79d5598]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Reviewed #112868 at 79d55981e797f592cbea61818ba7f030e7ec8d74, including all prior discussion and the current affected implementations. The change prevents false-negative pruning for padded FixedString comparisons and incomplete UTF-8 tails across the bloom-filter and text indexes. Previous correctness and buffer-padding findings are addressed. The conservative splitByString behavior is an accepted optional follow-up. No new blocker or major findings; no new inline comments.

Missing context / blind spots
  • ⚠️ Full CI on the current head remains limited by existing unresolved review threads. Both affected regression tests passed 100 targeted ASan runs on 9bdeb680d1f58ddff24055d5314a12f318a1fd36; the only subsequent change renames the new test pair from 05332 to 05866, without changing its contents. See the targeted ASan report. Full CI should complete after the existing discussion gate is cleared. No local tests were run in this CI job.
Final Verdict

Status: ✅ Approve

No required code changes identified. Existing CI and discussion gates still apply.

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

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

PR-caused CI failures on 67c6a37, fixed in 760e3cd

1. Build (arm_tidy): real compile break, mine.

MergeTreeIndexBloomFilterText.cpp:343:23: error: enumeration value 'Japanese'
not handled in switch [clang-diagnostic-switch,-warnings-as-errors]

ITokenizer::Type declares Japanese inside #if USE_MECAB, so the switch I added,
which deliberately omits default: so the compiler flags unhandled values, is
non-exhaustive only where MeCab is enabled. That is why arm_tidy was the single red
build while every other build was green.

The fix adds the arm under the same guard. It returns true alongside the other
clamping kinds because japanese is not in this index's allowed_tokenizers
(Ngrams, SplitByNonAlpha, SparseGrams), so TokenizerFactory::get rejects it with
Tokenizer 'japanese' is not allowed in this context and the kind cannot reach the
helper at all. true is the fail-closed answer the helper documents for exactly that
case, so a future tokenizer stays constrained until someone looks at it.

Verified in both directions by compiling the file against master's ITokenizer.h with a
generated config.h, using the real -Werror command from compile_commands.json:
with USE_MECAB 1 the unpatched file reproduces this error and nothing else, the patched
file compiles clean, and with USE_MECAB 0 it also compiles clean. The PR adds exactly
one switch, so there is no second site with the same omission.

2. Finish Workflow / Post Hooks: a consequence of 1, not a second defect.

new_tests_check.py reported all four per-arch Bugfix validation jobs as
DROPPED/SKIPPED. They never ran: Build (arm_tidy) failed at 11:09:33Z, which
cancelled the downstream chain, and Finish Workflow ran at 11:19:24Z against that
cancelled chain. Every other job on that commit is skipped. So this reports missing
validation, not failing validation, and it should clear now that the build compiles and
the bugfix-validation jobs can actually execute. If they run and still do not reproduce
the bug, that is a separate finding about the test and I will treat it as one.

Session id: cron:clickhouse-maint-slot-22:20260801-114800

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 94/100 (94.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 760e3cd

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
(none) 174 check-runs, 0 failures nothing to own

Config Workflow and Finish Workflow both completed successfully; no check queued or in progress.

Session id: cron:our-pr-ci-monitor:20260803-180000

@rschu1ze

Copy link
Copy Markdown
Member

@groeneai Please first post a minimal reproducible example for what you try to fix.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Minimal example, on master 604017b700591d49103f3f0a153373194cf86b2a:

CREATE TABLE t (s String, INDEX i s TYPE ngrambf_v1(3, 512, 2, 0) GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 1;

INSERT INTO t VALUES ('V0'), ('X');

SELECT count() FROM t WHERE s = toFixedString('V0', 3);
-- 0, wrong

SELECT count() FROM t WHERE s = toFixedString('V0', 3)
SETTINGS ignore_data_skipping_indices = 'i';
-- 1, correct

EXPLAIN indexes = 1 on the first query prints Granules: 0/2, so the granule holding the row is pruned. s = 'V0' returns 1, so only the FixedString spelling is affected.

Cause: index analysis tokenizes the constant's raw bytes, which still carry the FixedString(3) NUL padding, while equals compares 'V0' because the cast to String strips that padding. The probe filter is built from n-grams the granule never inserted.

The same cause reaches the other predicates listed in the description; hasAny(v, [toFixedString('V0', 3)]) over an Array(String) column with the same index reproduces identically.

@rschu1ze rschu1ze self-assigned this Aug 10, 2026
@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f0ceaf2f0 with master f3ecfbbe8 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

25 object files changed (+150.20 KiB total), 2 added.

Object file Master PR Δ
contrib/libhdfs3-cmake/CMakeFiles/_hdfs3.dir/__/libhdfs3/src/client/SlowNodeTracker.cpp.o new 97.27 KiB +97.27 KiB
contrib/libhdfs3-cmake/CMakeFiles/_hdfs3.dir/__/libhdfs3/src/client/SlowMetrics.cpp.o new 18.70 KiB +18.70 KiB

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

23 translation units recompiled, 137 s compile time in total, 23 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +7.7 s (+6%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d527b3c

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
Fast test (arm_darwin) / 01599_multiline_input_and_singleline_comments Timing flake in that test's sleep-based client synchronization, not PR-caused. It fired on 9 distinct PRs on Fast test (arm_darwin) alone in the 11 hours before this run, on no other platform, and this tree touches only the ngrambf_v1 and text index tokenizer path. #117053 (ours, open)

#117053 replaces the sleep in that test with synchronization on the client prompt, which is the step that loses the race on the slower arm_darwin runner.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112868&sha=d527b3cb258f2b6383298f4ab8eedf6adebcffdb&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29

171 check-runs, 0 incomplete, 1 failing.

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

@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Dear @rschu1ze, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@rschu1ze

Copy link
Copy Markdown
Member

@Ergus If you have some time - like to check this one (low prio though).

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

I think that these changes are superseded by #117314. Rebase onto current master and re-scope to the residual.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebasing and re-scoping as asked. Before deciding what is left I ran this branch's own fixture against today's master (bdd39260f887d, which carries #117314): 23 of its 113 cells differ, so the overlap is real but partial. Every row below is measured against an unindexed Log table holding the same rows, reported as oracle/indexed.

Still wrong on master, i.e. the matching granule is pruned:

predicate column oracle/indexed
has(v, toFixedString('VALUE0', 10)) Array(FixedString(8)) 1/0
mapContainsKey(m, toFixedString('VALUE0', 10)), mapContains, has(mapKeys(m), ...) Map(FixedString(8), String) 1/0
mapContainsValue(m, toFixedString('VALUE0', 10)) Map(String, FixedString(8)) 1/0
s = 'VALUE0\0\0\0\0', also spelled NOT (s != ...) FixedString(8) 1/0
s = toFixedString(concat('VALUE', unhex('C2')), 8), stored 'VALUE' || C2 00 String, LowCardinality(String), FixedString(8), sparse_grams 1/0

Three causes: functionIgnoresFixedStringPadding does not cover the membership arms; the strip is keyed on the constant's type, so a String constant with a genuine NUL tail is missed; and stripping is not token preserving when the trimmed value ends inside a declared UTF-8 sequence, because the n-gram tokenizer clamps its last gram to the buffer end and the probe emits 5545C2 where the granule holds 5545C200.

Answers correct but pruning lost, since a stripped probe is only a prefix of a fixed width value: ip = toFixedString(reinterpretAsFixedString(toIPv6('2001:db8::')), 16) on an IPv6 column reads 64/64 where it read 1/64, and on a fixture where every filler shares the trimmed probe's grams, hasAny, hasAll and equals read all 64 granules. In the other direction master is better in one cell and I keep its behaviour: s = toFixedString('VALUE0LONGER', 12) on FixedString(8) prunes 0/64 there (the answer is 0), while this branch declined the index.

On your four points:

  1. Mirror direction: correct, and it reaches past the membership arms. On master, with s FixedString(8) holding 'VALUE' || C2 00 and the constant concat('VALUE', unhex('C2')) as a plain String: has 1/0, hasAny 1/0, hasAll 1/0, mapContainsKey 1/0. This branch does nothing in that direction either (its membership guard wants both sides FixedString, its hasAny guard wants the constant array's nested type FixedString), so that measurement transfers to it unchanged. The rebase keys the normalisation on the index column's domain rather than on the constant's type.
  2. notEquals: agreed, and it is observable. A bare s != c never prunes (64/64), but NOT (s != c) prunes 1/64, so the atom's probe is used. I follow master's function list instead of leaving notEquals out.
  3. KeyValuePairs: confirmed, it is in the enum unguarded, so that switch does not build on master. It gets its own arm.
  4. Test prefix: confirmed, 04665 carries 18 tests on master now. I renumber above master's current maximum and cut the fixture down to the residual cases.

`stripFixedStringPaddingForTerms` trims the NUL tail of a `FixedString` constant
for `equals`, `notEquals`, `hasAny` and `hasAll`, which leaves three cases where
a matching granule is still pruned. Measured on master 398661c against an
unindexed `Log` twin holding the same rows:

- the membership arms never see the trim, so `has(v, toFixedString('VALUE0', 10))`
  over `Array(FixedString(8))`, and `mapContainsKey`, `mapContains`,
  `has(mapKeys(m), ...)` and `mapContainsValue` over a `FixedString` map key or
  value, all return 0 where the answer is 1;
- the trim is keyed on the constant's type, so `s = 'VALUE0\0\0\0\0'` over a
  `FixedString(8)` column, where the `String` constant carries the tail itself,
  returns 0;
- trimming is not token preserving when the trimmed value ends inside a declared
  UTF-8 sequence: the gram tokenizers walk by `UTF8::seqLength` and clamp the
  last gram to the buffer end, so a granule holding `5545C200` is probed with
  `5545C2` and dropped. This one also reaches `String`,
  `LowCardinality(String)` and `sparse_grams` columns, and the `text` index,
  whose own `canStripFixedStringPadding` does not look at the trimmed value.

Instead of trimming, re-encode the constant into the bytes the index stores: trim
the NUL tail, then pad back to the width of the index column's domain
(`FixedString(N)`, or 16 for `IPv6`); where the domain has no width, decline the
index if the trimmed constant ends mid sequence. Keying it on the column rather
than on the constant covers the `String` constant direction too. Exact pruning
comes back with it: an `IPv6` equality reads 1 granule of 64 instead of all 64.

The suffix independence of a tokenizer is now asked of `ITokenizer`, which answers
false for the tokenizers whose tokens can span the end of the value: with the
`array` and `splitByString` tokenizers a `text` index trimmed the constant and
then searched for its own single token, which a stored `String` carrying NUL bytes
does not hold, so `s = toFixedString('VALUE0', 8)` returned 0 of 1 rows there too.
Both condition classes now decline on the same ground, and a constant with nothing
to trim keeps reading through its index.

An `IPv6` index carried a fourth case of the same shape, which master has too:
`ip = '2001:db8::'` was tokenized as the characters of the literal while the
granule holds the 16 parsed bytes, so the matching granule was pruned and the
query returned 0 instead of 1. A textual constant is now parsed into those bytes,
which also makes it prune 1 granule of 64, and a constant that does not parse
declines the index.

A constant wider than the domain keeps its current probe, since it equals no
stored value and its own tokens prune every granule. Where the domain has no
width, only the predicates comparing through the `String` supertype re-encode the
constant: a membership predicate compares it byte for byte there, so its padded
bytes are already the exact probe and trimming them would only read more granules. `has(<constant array>,
<indexed scalar>)` does not ignore the padding, so that probe is unchanged, and a
constant redirected through `mapKeys` is a map key, which is stored as written.

Related: ClickHouse#117021
@groeneai
groeneai force-pushed the fix-text-index-padded-string-constant branch from d527b3c to 1a9a09f Compare September 17, 2026 15:10
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased and re-scoped: 1a9a09f, one commit on 398661cdf4e9b, +425/-18 across 6 files (the previous shape was +733/-5).

Your four points:

  1. Mirror direction: correct, and covered. On master with s FixedString(8) holding 'VALUE' || C2 00 and the plain String constant concat('VALUE', unhex('C2')), oracle/indexed was 1/0 for has, hasAny, hasAll, mapContainsKey and equals. The normalisation is now keyed on the index column's domain instead of the constant's type, and every membership arm goes through it.
  2. notEquals: the two arms are merged, so they share one atom and cannot disagree again. It is worth the line: a bare s != c never prunes (64/64), while NOT (s != c) prunes 1/64, so that probe is used.
  3. KeyValuePairs: the classification moved next to the enum, as tokensSurviveTrailingNuls in ITokenizer, which the text condition now shares. The switch there is exhaustive.
  4. Test prefix: renumbered to 05227 (master reached 05226 today). The fixture is down from 481 lines and 113 cells to 220 and 60.

Two calls I made rather than asking:

  • The text index runs the same trimming step behind its own guard, and array and splitByString reach it. s = toFixedString('VALUE0', 8) over text(tokenizer = array) on a String column storing 'VALUE0' || 00 00 returns 0 of 1 rows on master; that is now declined rather than trimmed, while a constant with nothing to trim keeps using the index.
  • An asciiCJK index is declined in the same narrow case instead of trimmed. Sound but conservative; I can special-case it if you would rather keep the pruning.

Four cases of the same shape are measured and deliberately not in this PR, each equally wrong on master today: prepared-set elements (s IN (SELECT toFixedString(concat('VALUE', unhex('C2')), 8)) gives 1/0 on both index families), a FixedString-domain text index with a suffix-dependent tokenizer, a configured text preprocessor, and an IPv6 map key reached through the optimize_functions_to_subcolumns rewrite (1/0 with the rewrite on, correct with it off). They live in different code paths and each needs its own oracle. I will send them separately unless you want them here.

Validation: 60 of 60 cells green, 36 of them red on master; 20 consecutive runs of the test under randomised settings; the 265 stateless tests that use these index types pass, except four that fail identically on a master binary in this environment (missing test.hits, no ZooKeeper, two parallel-load timeouts).

groeneai and others added 5 commits October 7, 2026 13:47
`tryPrepareSetBloomFilter` stripped a `FixedString` element without checking
that the trimmed value still tokenizes to a subset of the stored value, so
`s IN (SELECT toFixedString(concat('VALUE', unhex('C2')), 8))` pruned the
granule holding `'VALUE' || unhex('C200')` on `ngrambf_v1` (String and
`FixedString(8)` columns, 1 vs 0 rows on master). The set loop now goes through
`normalizeConstantForIndexDomain` with `equals` semantics, which subsumes both
of its branches (domain conversion and padding strip), and the helper takes
whether the comparison drops the padding instead of a function name.

The `text` index `IN` path already shares `tryNormalizeNeedlePadding` with the
direct path, so both index families now apply one rule to set elements.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `IN` rows compared answers only, which a silently declined index also
satisfies. Add the plan side: a `FixedString(8)` column prunes to exactly the
matching granule, and the widthless `ngrambf_v1` and `text` cases decline the
index. All three print 0 on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`hasAny` and `hasAll` cast only the constant to `String`, so a matching stored
element equals the trimmed constant byte for byte and tokenizes the same. The
UTF-8 tail decline is needed only where the stored value loses its zero bytes
as well (`equals`, `notEquals`, `IN`), so the helper now takes the comparison's
padding semantics instead of one flag, as the `text` index already models them.
Declining there lost the index for `hasAny(v, [toFixedString(concat('VALUE',
unhex('C2')), 8)])` over `Array(String)`, which master prunes to 1 of 64
granules; the new row flips to 0 with the old decline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`String = FixedString` compares zero padded, so a stored `'VALUE' ||
unhex('C200')` equals `toFixedString(concat('VALUE', unhex('C2')), 6)` even
though the constant has no padding to trim. The `ngrambf_v1` decline already
covers it (1 vs 0 rows on master); add the row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai requested a review from Ergus October 7, 2026 15:18
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master and re-scoped again. #118972 and master's convertConstantToIndexDomain now cover this PR's IPv6 and typed map key parts, so those are gone, and the de-duplication is moot (the text index no longer has its own copy). Against master 6c2c9c1e the fixture still differs in 35 of 67 cells:

  • the membership arms (has, mapContainsKey, mapContains, mapContainsValue) with a constant wider than a FixedString(N) column, and a String constant carrying a NUL tail: 1/0;
  • a constant or IN element that ends inside a UTF-8 sequence, on ngrambf_v1, sparse_grams, and a text index with ngrams or sparseGrams: 1/0.

normalizeConstantForIndexDomain now wraps master's converter and also serves the ngrambf_v1 prepared-set path (the IN fold-in from my previous comment). The text index's tokenizerSplitsAtZeroByte is replaced by the per-value tokensSurviveTrailingNuls; asciiCJK and icu keep master's answer, since the first drops a sequence cut by the buffer end and the second emits word tokens only. The test moved to 05332_.

One case is left out on purpose. String = FixedString compares zero padded, so a full-width needle matches a stored value that carries NULs, and a text index then prunes it: s = toFixedString('VALUE0', 6) with the array tokenizer against concat('VALUE0', unhex('00')), or ngrams with a UTF-8 tail, is 1/0 on master. Declining there means dropping the stripped_size != needle.size() gate in tryNormalizeNeedlePadding, which flips the "a needle that carries no padding still prunes" rows of 05223_text_index_fixed_string_padded_needle. That looks like a deliberate choice of #118972, so I did not change it here. Should I?

The PR workflow run 37642194989 on 434b2fe was dropped by the
GitHub Actions outage of 2026-10-07 15:15-15:35Z (every build abandoned,
dependent jobs failed on missing S3 artifacts) and was not retried.
No content change.

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

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1d305c0

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
Code Review infra, not from this PR: GitHub abandoned the job (Job did not finish, GitHub reported [abandoned]) and it is missing from the run's job list, so it never ran. The automatic infrastructure retry skips a failed run with no listed failed job, so nothing re-ran it #124479 (mine, open): retries a PR run whose failing jobs GitHub never ran
Mergeable Check, PR rollups, red only because of the row above (Failed: 0, Dropped: 1) #124479 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

All 148 check runs completed, Finish Workflow is green, and CIDB has no FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261007-230450

@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Dear @Ergus, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

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

Optional follow-up, not needed here: splitByString(['\0']) and a preprocessor that keeps NUL as a separator could count as surviving, which would recover pruning there. Master already declines those for a padded needle, so the change only extends that behavior to unpadded needles.

@Ergus Ergus self-assigned this Oct 21, 2026
`String = FixedString` compares zero padded, so a stored value can carry
trailing zero bytes that a full-width constant lacks, for example the
stored `VALUE C2 00` equals `toFixedString(concat('VALUE', unhex('C2')), 6)`.
`tryNormalizeNeedlePadding` declined such a needle only when it had padding
to trim, so a `text` index with `ngrams`/`sparseGrams` (when the needle ends
inside a UTF-8 sequence), `array`, `splitByString` or a preprocessor still
looked up the bare needle and could prune the only matching granule. This
matches the bloom-filter side of this PR, which already declines that case.

05223's "a needle that carries no padding" rows now expect `INDEX_NOT_USED`
for `array`, both `splitByString` variants and the preprocessor variant;
the `splitByNonAlpha` rows keep pruning. 05332 gains the full-width
`text(tokenizer = ngrams(3))` oracle row with its `Log` twin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
break;
/// The rest either emit the whole buffer as one token or take their separators from a configured pattern,
/// which a suffix can complete, and `KeyValuePairs` tokenizes no string at all.
case ITokenizer::Type::SplitByString:

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.

tokensSurviveTrailingNuls is keyed only on ITokenizer::Type, so every splitByString tokenizer is treated as suffix-sensitive. That loses a safe case: with splitByString(['\0']), world and world\0\0... still tokenize to the same single term world, so the old exact pruning was correct. The updated 05223 expectation flips that case to INDEX_NOT_USED, which means this change regresses index usage for zero-byte separators just because the helper cannot see the tokenizer's actual separators. Since the call sites already have the tokenizer instance, this needs configuration-aware logic rather than a blanket Type::SplitByString => false.

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.

Not changed here: the reviewer ruled this refinement an optional follow-up in #112868 (review), and its cost is lost pruning for a NUL separator, never wrong rows.

@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Dear @Ergus, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

groeneai and others added 2 commits November 24, 2026 13:57
`find_last_not_of('\0') + 1` reaches 0 for an all-NUL constant only by
wrapping `npos`, which the `unsigned-integer-overflow` check master now
enables reports as an error. `trimRight` from `Common/StringUtils.h` is
the shared helper master moved the sibling trims of this file to.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`tryPrepareSetBloomFilter` now normalizes each set element into its own
`String`, but still tokenized it with `forEachTokenToBloomFilter`. For
`tokenbf_v1` that reaches `forEachTokenSplitByBytes`, which reads whole
16-byte blocks and relies on the 15 bytes of right padding a column buffer
has. A `String` has none: a 17- to 22-byte element lives in the libc++
short-string buffer, so `s IN (SELECT repeat('a', 20))` read past the end
of the object (ASan: stack-buffer-overflow, READ of size 16).

Use `ITokenizer::stringToBloomFilter`, as the other constant probes in this
file do; it emits the same tokens and never reads past `length`.
Add a `tokenbf_v1` prepared-set row with a 20-byte element to 05332.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. and removed comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... labels Nov 24, 2026
Master now has 29 other tests with the 05332 prefix. No test on master
and no open pull request uses 05866. The test content is unchanged.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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