Skip to content

Text index: intersect posting lists once per 65536 rows instead of once per granule in materialize mode - #122597

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai-text-index-intersect-per-container
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai-text-index-intersect-per-container

Conversation

@groeneai

@groeneai groeneai commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122557

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Text index searches for several tokens (hasAllTokens, hasAll) with frequent tokens are faster when posting lists are applied in materialize mode, which is always the case for the default none posting list codec: the intersection of the posting lists is built once per 65536 rows instead of once per granule.

Description

In materialize mode the text index reader clipped the folded postings and every block of each frequent token (its posting list spans several blocks) to each granule and intersected them per granule, although eight default granules share one 65536-row Roaring container. Analysis and patch by @ snelheidai.

For a granule inside one container, an All search now keeps per column the intersection of the folded postings with each frequent token's blocks in turn, restricted to that container, and reuses it while the next granules lie in it and use the same blocks (compared by identity); each granule then does one clip and the existing flatten. Granules spanning several containers (nothing to reuse), hasAnyTokens, single-token searches and lazy mode keep the previous code. Blocks are read as before, so results and TextIndexReadPostings are unchanged. A kept intersection is at most one container (8 KiB) per token.

A new test compares multi-block searches with evaluation without the index (granules inside one container, spanning several or crossing a boundary; reverse reads; several parts) and checks the new profile event TextIndexPostingsIntersectionsReused; removing either cache key, the final clip, the All or one-container check, or the reuse fails it. A sweep of 1220 predicate and setting combinations over three codecs matched master; a performance test is added.

Against an A/A control on release builds, the text index read takes 26-71% less time at one thread (9-50% at four) and index-bound count queries run up to 3 times faster; unchanged paths stay within the noise (instructions within 2%). Peak memory grows by at most 1.5 MiB.

I did not take the posted patch as is: it also replaced the flatten and the hasAnyTokens and single-list fills, was 54% slower on 1M-row granules on x86 and used up to 64 MB more memory per query.

Measurements

x86 release builds without ThinLTO, 10M-row single-part tables, postings cache off; crossover effect FIX/BASE over 20 paired rounds; "within" = inside the A/A noise.

query wall, 1 / 4 threads index read, 1 / 4 threads
count(), hasAllTokens(s, ['w1', 'w10']) -32% / -11% -54% / -45%
count(), hasAllTokens(s, ['w1', 'w2', 'w3']) -45% / -19% -60% / -50%
count(), hasAll(tags, ['t1', 't2']) -19% / -5% -34% / -27%
sum(id), hasAllTokens(s, ['w1', 'w2']) -2.5% / within -37% / -30%
64 correlated tokens, 4M rows -68% / -40% -71% / -46%
64 sparse tokens, 65536-posting blocks -38% / -20% -41% / -25%
5 isolated granules within within; +0.06-0.09 ms (+12-17%) for 64 sparse tokens with the postings cache on
hasAnyTokens, hasToken, LIKE, pfor, count from the index, 1M-row granules within within; instructions within 2%

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

groeneai and others added 4 commits September 27, 2026 22:57
In materialize mode (always for the default `none` posting list codec and for
`LIKE`), `MergeTreeReaderTextIndex` builds the rows of every granule
separately: it clips the analyzer's folded postings and every block of every
large token to the granule's range, intersects the clipped lists and flattens
the result. For an `All` query over frequent tokens each clip copies and
recounts the 65536-row Roaring container that eight consecutive 8192-row
granules share, and every intersection is redone per granule.

An `All` query with at least two posting lists and a large token now keeps,
per virtual column, the intersection of the folded postings with the blocks of
the first, second, ... large token, restricted to the Roaring container that
holds the granule. A kept step is reused while the granule lies in the same
container and its token has the same blocks (compared by identity), so it is
rebuilt once per container and once per block boundary instead of once per
granule; each granule then does one clip and the existing flatten. Blocks are
read with the same arguments and the same early exits as before, so results
and `TextIndexReadPostings` are unchanged.

Only granules whose rows lie in one container take this path. A granule that
spans several containers (`index_granularity` above 65536, or an adaptive
granule crossing a container boundary) has nothing to reuse, because its clips
and intersections are already one per container, so it keeps the previous
code, as do `Any`, single-list and lazy-mode reads.

Based on the analysis and patch by @snelheidai, ClickHouse#122557.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Results of multi-token searches read from a text index must match evaluation
without the index when posting lists span several posting list blocks,
granules, Roaring containers and parts, including partial-granule and reverse
reads, and granules of several sizes: inside one container, spanning several
containers, and crossing a container boundary.

The performance test measures multi-token `hasAllTokens` searches over
frequent tokens on the default `none` posting list codec.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The new `TextIndexPostingsIntersectionsReused` counts granules that reuse the
intersection kept for the previous granules of the same 65536 rows. Test 05275
asserts it is positive for a scan of 1024-row granules and zero for 65536-row
granules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the comment on the one-caller helper intersectWithBlocks and shorten the comments on the cache invalidation in setIndexGranule and on intersectPostingsInContainer to one line each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Sep 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding, none on the re-review after the fix) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The tests do not show that the kept intersections are reused, so a disabled reuse would still pass (05275) AGREE, fixed @ 3c0d6fd new profile event TextIndexPostingsIntersectionsReused; 05275 asserts it is positive for 1024-row granules and zero for 65536-row granules, red on master and with the reuse disabled
2 💡 The container width is written as literals (>> 16, 0xFFFF) noted, not changed cosmetic: the three uses are the dispatch and the one function it calls
3 💡 The description did not say why granules spanning several containers keep the previous code AGREE, fixed in the description nothing to reuse there
4 💡 A granule that is the only one read in its container rebuilds the intersection for the whole container noted, not changed wall within the noise; index read +0.06-0.09 ms on the 64 sparse tokens arm with the postings cache on, listed in the description

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260928-014000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Performance change: a paired crossover of release builds (FIX and master on two servers, swapped, 20 and 40 rounds) against an A/A control, plus per-query instruction counts (64 correlated tokens: 0.14x of master's instructions; ['w1', 'w10'] count: 0.51x).
b Root cause explained? For an All search in materialize mode the reader clipped every posting list block to each granule and intersected again per granule, although the inputs change only once per 65536-row container or block boundary.
c Fix matches root cause? The intersection is kept per column, keyed on the container and on the identity of the blocks, and entered only for granules inside one container; granules spanning several containers keep the previous code.
d Test intent preserved / new tests added? New stateless test comparing multi-block searches with evaluation without the index (granules inside one container, spanning several, crossing a boundary; reverse reads; several parts) and checking the new profile event TextIndexPostingsIntersectionsReused through system.query_log: positive for 1024-row granules, zero for 65536-row granules; new performance test.
e Both directions demonstrated? Changed queries faster than master beyond the A/A noise, unchanged ones within it (instruction counts within 2% of master); the test fails when either cache key, the final clip, the All check or the one-container check is removed; its profile event check fails on master and with the reuse disabled (0 for 1024-row granules) or counted without reuse (1 for 65536-row granules); the result lines match master, and the whole test passes on the fix.
f Fix is general across code paths? hasAnyTokens, single-token, lazy-mode and count-from-index paths are unchanged and measured as controls; lazy mode reads through cursors and has no per-granule clipping to reuse.
g Fix generalizes across inputs (params/datatypes/wrappers)? Sweep of 1220 predicate and setting combinations: none/pfor/bitpacking, String and Array(String), granularities 1024 to 1000000, 1/3/4/7 threads, reverse reads, FINAL, PREWHERE, LIKE, NOT, OR, 200 parts, dense and sparse posting lists: 0 mismatches.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, no format change; results and TextIndexReadPostings are unchanged.
i Invariants and contracts preserved? A reused step equals the previous per-granule result on the granule's range (same blocks, same container, earlier steps intact); the final clip keeps rows inside the granule as fillColumn requires; blocks are read and exits taken as before; memory per column is at most one container per frequent token.

Session id: cron:clickhouse-impl-slot-4:20260927-225300

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [65d5208]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Received signal 6 (internal) (STID: 2360-3d86) FAIL cidb
Build profile diff ERROR

AI Review

Summary

This PR reuses All posting-list intersections within a 65536-row container in MergeTreeReaderTextIndex, reducing repeated work for multi-token searches in materialize mode. No actionable findings remain at 65d5208dce77cde28e3eb6e08b2cf00783559ec0; the previous benchmark-setting finding is addressed.

Missing context / blind spots
  • ⚠️ CI for the current head is still running. No local compiled ClickHouse executable is available, so runtime validation relies on the supplied measurements and regression-test evidence until current-head CI completes.
Final Verdict

Status: ✅ Approve, subject to normal CI completion. No review changes required.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 28, 2026
@groeneai
groeneai requested review from CurtizJ and ahmadov September 28, 2026 02:16
@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 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 65d5208dce77cde28e3eb6e08b2cf00783559ec0 with master failed: LogClusterNotReady: the endpoint never became ready.

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR changes only the text index direct-read path. Consecutive granules in the same 65536-row range can now reuse a cached intersection of posting lists for multi-token hasAllTokens searches. It also adds a new profile event and new tests. None of the four flagged improvements (clickbench Q33 -13.8%, Q34 -13.1%, tpch_adapted_1_official Q1 -18.5%, Q7 -22.2%) reads a text index, and all four have noisy history, so all are downgraded to not sure as run-to-run variance. The ClickBench medians are inside master's recent range, and the TPC-H deltas are only 12 to 18 ms. The change's real effect should be measured with the new text_index_materialize_intersection performance test, not with these benchmarks.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1134 977 -13.8% <0.0001 aggregation: This is a large GROUP BY over the hits table with no text index, so the changed posting-list intersection code never runs. The 977 ms median sits inside master's recent range, and this query's history is noisy.
⚠️ 34 not_sure 1140 990 -13.1% <0.0001 aggregation: This query is aggregation-heavy and never reads a text index, so the change cannot affect it. The -13.1% shift stays inside master's recent range on a noisy query.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 53 -18.5% <0.0001 aggregation: TPC-H Q1 is a scan plus aggregation over lineitem and touches no text index. The -18.5% change is only 12 ms on a noisy query with very spread-out timings.
⚠️ 7 not_sure 81 63 -22.2% <0.0001 join_operator: TPC-H Q7 is a multi-table join with no text index, so the changed text index read path does not run. The -22.2% change is an 18 ms shift on a noisy query.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: a110e38b-16a0-4e74-8894-58d9e576d141
  • MIRAI run: 70e17d53-2a09-4480-9b4b-d0beedddd79b
  • PR check IDs:
    • clickbench_1101805_1791829633
    • clickbench_1101818_1791829633
    • clickbench_1101824_1791829633
    • tpch_adapted_1_official_1101835_1791829633
    • tpch_adapted_1_official_1101861_1791829633
    • tpch_adapted_1_official_1101875_1791829633

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e334abb

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
Performance Comparison (arm_release, master_head, 3/6) / optimize_time_filter_with_preimage #4 dashboard confirmed_regression, client_time 0.531 -> 0.675 s (+27.0%), which the shard's own report calls only unstable. #4 is the DateTime month baseline arm: it sets optimize_time_filter_with_preimage = 0 and counts rows of a MergeTree table that has only minmax indexes, so no text index is read. In the last 7 days the same query was reported slower on 29 other pull requests and unstable on 6, true master included #122156 (mine, open): it deletes this arm together with the other two = 0 baselines
Performance Comparison (arm_release, master_head, 5/6) / json_to_string #1 dashboard confirmed_regression, client_time 1.377 -> 2.011 s (+46.1%), also slower in the shard's own report. The query is SELECT sum(length(toString(payload))) FROM json_to_string_shared_data, a MergeTree table without a text index, so it never reaches the text index reader this PR changes. On arm this query has a slow mode drawn per server process: the same row was slower on 40 other pull requests and one master run in the last 7 days a fix task is created (its fix direction awaits the performance harness owner's decision; fixing-PR link to follow on this PR)
Mergeable Check, PR rollups, red only because of the two shards above #122156 (mine, open), and the fix task of the json_to_string #1 row

146 of 146 check runs completed (130 passed, 14 not selected, 2 red: the two shards above), Finish Workflow is green and CH Inc sync passed. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260928-073120

@groeneai

groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the json_to_string #1 arm_release perf red: #125278 (closed unmerged: the release binaries stay PIE). A fix task is moved to pending; the fixing-PR link will follow here.

groeneai and others added 3 commits October 12, 2026 12:16
…-intersect-per-container

Master replaced `large_postings_streams` with in-place analyzer checks
(`isTokenNeeded` / `hasReadPostings`, 67bc365), so the per-container
intersection path now skips tokens with the same predicate as
`buildPostingsForQuery` and takes the analyzer as a parameter. The
constructor keeps only the `intersection_steps` resize; master dropped the
other cursor resizes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#120517 the text index reader serves incomplete granules, so with
a random `max_block_size` below 65536 (and prewhere off) one granule of
`tab_container` is read in several slices. Slices of one granule share
the cached intersection, which is correct, but it made the negative
control report a reuse in 4 of 20 randomized runs. Pin `max_block_size`
to the granule size so the control keeps checking that whole granules
of different containers never share an intersection.

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

Since ClickHouse#120517 the reader serves incomplete granules, so the one-container
check on the read slice also let slices of granules spanning several
Roaring containers into the cached path. Check the whole granule instead,
which keeps those granules on the previous code as measured.

The test now also checks that a granule spanning two containers read in
1024-row slices and a single-token search never reuse an intersection;
reverting either check makes its line fail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test measures the direct-read reuse path, so it should not depend on
the default of query_plan_direct_read_from_text_index. Forcing idx makes
it fail loudly if the planner stops using the index, as text_index.xml
does.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7390ee9

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
Integration tests (arm_binary, 1/4) / test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested not from this PR (it only changes the text index reader, adds a profile event and its tests): the Spark 4.0 runner image of #117198 broke this test on master. The tested tree predates the revert #125455 (external, merged)
Integration tests (arm_binary, 1/4) / test_storage_delta/test_writes_interop.py::test_write_to_table_with_unsupported_writer_feature_is_rejected same cause as the row above #125455 (external, merged)
Mergeable Check, PR praktika rollups of the rows above #125455 (external, merged)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261013-030009

@groeneai

groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the json_to_string #1 arm_release perf red: #125949 Correction: #125949 is not shown to fix this red. Since PIE this query has more reds (PR side at least 15% slower in 0.1% of PR runs from Jul 1 to Sep 9, 1.3% since Sep 15), and within one build its slow runs follow the load address, which #125949 makes the same at every start, but I have not shown that this red is one of them. Per-query numbers: #125949 (comment)

…-intersect-per-container

Master builds `range_posting` lazily in `buildPostingsForMark` and skips
columns answered by the analyzer's folded postings (ClickHouse#122896); the
per-container path only runs when postings must still be read, so it is
disjoint from the folded one. `setIndexGranule` keeps only the reset of
`intersection_steps`: master moved the per-granule phrase results into
`phrase_streams` (ClickHouse#118885) and dropped `blocked_positions_scratch`.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 65d5208

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Received signal 6 (internal) (STID: 2360-3d86) trunk bug, not from this PR (it changes only the text index reader): the embedded client (web terminal / SSH) calls LocalConnection::sendCancel from processInsertQuery when no query state is left, and libc++ hardening aborts on the empty std::optional. The same abort hit master twice today #127364 (mine, open)
Build profile diff infra, not from this PR: the CI logs cluster rejected every readiness probe (No connection to LogCluster), so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 196 of 200 runs since 2026-10-26 22:00 UTC are red, on 167 PRs #126200 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #127364 and #126200 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-153012

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-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

1 participant