Skip to content

Text index: choose leapfrog intersection algorithm only when it can skip blocks - #121038

Merged
CurtizJ merged 16 commits into
ClickHouse:masterfrom
CurtizJ:text-index-postings-cursor-algorithm
Sep 24, 2026
Merged

CurtizJ merged 16 commits into
ClickHouse:masterfrom
CurtizJ:text-index-postings-cursor-algorithm

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Optimized queries that search for several tokens at once with a text index, such as hasAllTokens. Improved the automatic choice of algorithm for intersecting posting lists, controlled by the new setting text_index_postings_intersection_algorithm.


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

Version info

  • Merged into: 26.10.1.613-master (included in 26.10 and later)

CurtizJ and others added 3 commits September 19, 2026 16:02
…ne the cursor fast paths

The lazy AND over bitpacked posting lists chose leapfrog whenever the minimum
density was below `text_index_lazy_intersection_density_threshold` (0.2). But
leapfrog only pays off when the sparsest list can skip whole packed blocks of
the densest one: a block of `BLOCK_SIZE` postings of a list with density d_max
spans about `BLOCK_SIZE / d_max` rows, and the sparsest list has about
`d_min * BLOCK_SIZE / d_max` postings in that span. Once that is at least one,
every block is decoded anyway and leapfrog only adds a search per posting.
For an AND over tokens of comparable moderate density (0.05-0.11), where the
result is nearly the smallest list, leapfrog took 2.5-3x the CPU of the
brute-force counting pass and lost to the roaring codec.

The selector now uses brute force when `d_min * BLOCK_SIZE >= d_max` as well.
The setting keeps its role as an absolute cap: `0` still forces brute force
and `1` still forces leapfrog, which the existing tests rely on.

`advance` and `next` get inline fast paths for the common case (the target or
the next value lies within the decoded block); block and segment transitions
go through the out-of-line `advanceSlow` and `nextSlow`. `gallopingLowerBound`
moves to the header for that. Forced leapfrog gets 14-15% cheaper.

With both changes, multi-token AND queries over a 1B-row table take 2.4-3x
less single-thread CPU with the bitpacking codec and are on par with or
faster than the roaring codec.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…lgorithm setting

`text_index_lazy_intersection_density_threshold` becomes obsolete and
`text_index_postings_cursor_intersection_algorithm` takes its place, with the
values `auto` (the default), `bruteforce` and `leapfrog`.

The threshold no longer selected anything. A posting list density is at most `1`,
so the block span rule (brute force when `min_density * BLOCK_SIZE >= max_density`)
already holds for every density at or above `1 / BLOCK_SIZE`, which is `0.0078`:
at the default threshold of `0.2` the comparison against it could never decide a
query, and only the two ends of the range still did anything - `0` forced brute
force and `1` forced leapfrog. The new setting says that directly: `auto` applies
the block span rule, `bruteforce` and `leapfrog` pin a path. Leapfrog is still
used regardless of the setting for 256 or more posting lists, which the
brute-force `UInt8` counters cannot represent.

The old name stays accepted and ignored, and so does the name it itself replaced,
`text_index_density_threshold`, which is why the obsolete entry is declared with
`ALIAS` rather than `MAKE_OBSOLETE`.

Tests that pinned a path through the threshold now name the algorithm instead.
`04652_system_documentation_settings_history` used the old setting as its example
of a rename that keeps the old name as an alias; `system.documentation` does not
list obsolete settings, so that case moves to `evaluation_time`, which has the
same shape.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… trim the setting description

The two old names, `text_index_lazy_intersection_density_threshold` and
`text_index_density_threshold`, are declared with `MAKE_OBSOLETE` like the rest
of the obsolete section instead of one `ALIAS` entry. Both stay accepted and
ignored. The obsolete name has no settings changes record, only the new setting
`text_index_postings_cursor_intersection_algorithm` does.

The description of the new setting drops the block span formula and the note on
the 256 posting lists limit of brute force. The comment of `advance` is shortened.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [52ceb02]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
Check Results FAIL IGNORED
Performance Comparison (amd_release, master_head, 2/6) FAIL Performance dashboard
array_first_last #7 FAIL dashboard IGNORED
timeseries_to_grid_aggregation_functions #0 unstable query history IGNORED
timeseries_to_grid_aggregation_functions #6 unstable query history IGNORED
timeseries_to_grid_aggregation_functions #15 unstable query history IGNORED
timeseries_to_grid_aggregation_functions #17 unstable query history IGNORED
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
Check Results FAIL IGNORED

AI Review

Summary

This PR changes lazy text-index AND planning: auto now chooses brute force whenever leapfrog cannot skip packed blocks, adds a forcing enum setting, and narrows brute-force scans to the rows already matched by earlier cursors. The implementation and new SQL/gtest coverage look mostly coherent, but I still see one compatibility break in the replaced threshold setting, one missing-proof problem for the claimed 3x win, and one still-untested 256-token contract edge.

PR Metadata
  • Changelog category: Performance Improvement matches the code.
  • Changelog entry: required and mostly specific, but it names a setting that does not exist. Replace text_index_postings_cursor_intersection_algorithm with text_index_postings_intersection_algorithm.
  • Exact replacement:
Queries that search multiple tokens at once with a text index, such as `hasAllTokens`, now use up to 3x less CPU because posting-list intersections choose the better algorithm automatically. The new setting `text_index_postings_intersection_algorithm` allows forcing `bruteforce` or `leapfrog`.
Findings

❌ Blockers

  • [src/Core/Settings.cpp:9705, src/Core/SettingsChangesHistory.cpp:57] [dismissed by author -- https://github.com/Text index: choose leapfrog intersection algorithm only when it can skip blocks #121038#discussion_r4053667867] Turning text_index_lazy_intersection_density_threshold and text_index_density_threshold into silent no-ops still breaks both explicit legacy configs and compatibility = '26.9'. The current code accepts old non-default values but ignores them, and the 26.10 history entry still says auto preserves the previous default behavior even though the new block-span rule now picks a different algorithm for cases like the new bmid/cmid test. Please either map legacy values onto the new enum / compatibility path or reject non-default obsolete values instead of silently accepting them.

⚠️ Majors

  • [tests/performance/text_index_lazy_wide_granule.xml:46-57] The PR is categorized as Performance Improvement and the changelog promises "up to 3x less CPU", but the public PR evidence is still missing: the only benchmark comment on the PR says there were no significant changes in the generic cloud suites, and there is still no focused before/after output for these text_index_lazy_wide queries. Please attach the local benchmark or perf-report output for the affected workload so reviewers can verify the claimed win.
  • [tests/queries/0_stateless/05232_text_index_lazy_intersection_block_span_rule.sql:60] [dismissed by author -- https://github.com/Text index: choose leapfrog intersection algorithm only when it can skip blocks #121038#discussion_r4082203376] The setting contract now explicitly documents the n >= 256 leapfrog exception, but the new coverage still never exercises 255 vs 256 tokens. That leaves the only path protecting the UInt8 brute-force counters from overflow without a regression test. Please add a focused query/gtest that proves 255 can still honor bruteforce while 256 is forced onto leapfrog.
Final Verdict

Request changes.

LLVM Coverage Report

Measured on commit 52ceb02.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 203/207 (98.07%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 19, 2026
@CurtizJ CurtizJ changed the title Text index postings cursor algorithm Text index: choose the lazy intersection algorithm by whether leapfrog can skip blocks Sep 19, 2026
@CurtizJ CurtizJ changed the title Text index: choose the lazy intersection algorithm by whether leapfrog can skip blocks Text index: choose lazy intersection algorithm by whether leapfrog can skip blocks Sep 19, 2026
Comment thread src/Core/Settings.cpp Resolved
@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 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 52ceb02b6 with master 455029b82 (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

71 object files changed (+34.97 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Core/SettingsEnums.cpp.o 2.14 MiB 2.16 MiB +23.41 KiB (+1.07%)

716 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

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse ProfileEvents::global_counters_storage 12.56 MiB 12.62 MiB +64.00 KiB (+0.50%)
programs/clickhouse-keeper ProfileEvents::global_counters_storage 12.56 MiB 12.62 MiB +64.00 KiB (+0.50%)

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 74cb8bba-3591-4f1e-be68-575d1cb2b19d
  • MIRAI run: 4091657a-f0e9-4eee-984b-cb5c3426a136
  • PR check IDs:
    • clickbench_1574244_1790209851
    • clickbench_1574258_1790209851
    • clickbench_1574487_1790210038
    • tpch_adapted_1_official_1574601_1790210099
    • tpch_adapted_1_official_1574743_1790210122
    • tpch_adapted_1_official_1574903_1790210186

@CurtizJ CurtizJ changed the title Text index: choose lazy intersection algorithm by whether leapfrog can skip blocks Text index: choose leapfrog intersection algorithm only when it can skip blocks Sep 19, 2026
CurtizJ and others added 12 commits September 19, 2026 20:25
`05232_text_index_lazy_intersection_block_span_rule` asserts which algorithm
the `auto` rule picks, but the same commit added
`text_index_postings_cursor_intersection_algorithm` to the settings
randomizer of `tests/clickhouse-test`. When the randomizer picked
`bruteforce` or `leapfrog`, the two `_default` queries ran the forced
algorithm and the profile event assertions flipped:

    -05232_rule_mid_pair_default	1	0
    +05232_rule_mid_pair_default	0	1

Set the algorithm to `auto` in the test instead of relying on the default
value. The two queries that force `bruteforce` and `leapfrog` already pin it
per query.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121038&sha=latest&name_0=PR
ClickHouse#121038

Co-Authored-By: Claude Opus 5 <[email protected]>
…rithm setting

The brute-force intersection counts matches in a `UInt8` per row, so an
intersection of 256 or more tokens takes leapfrog even when the setting
`text_index_postings_cursor_intersection_algorithm` forces `bruteforce`.
Say so in the description of the setting.

ClickHouse#121038 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
…st has no rows in the window

`linearOr` and `linearAnd` now return whether they wrote anything to the
output. Both scan functions return as soon as the lower bound for the
window lands past it: the block has a doc_id at or past `row_offset`, so
an empty range means that doc_id and everything after it are beyond the
window.

`intersectBruteForce` stops at the first cursor that wrote nothing, since
the intersection over the window is then empty: the output is left
zero-filled when it is the first cursor and cleared with `memset`
otherwise, and `finalizeCounters` is skipped. The new profile event
`TextIndexLazyBruteForceEarlyExits` counts the exits.

The cursors are sorted by ascending cardinality for the brute-force
intersection as well, not only for the leapfrog. The sparsest list is the
most likely to be empty in a window, and it leaves the largest all-zero
regions for the denser lists to skip. Before, the order came from a hash
map and was arbitrary.

Marks outside the row range of a token's posting-list segments never
reach the cursors, so the exit fires for marks inside a gap of a token's
range, where the straddling segment covers the marks but has no rows in
them. Single-threaded, the intersections with such a token get 26 % faster
on a 50M-row table; `text_index_lazy_wide_granule` is unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… posting list wrote

`linearOr` and `linearAnd` return a `PostingsCursorWindow`, the half-open
range of rows they wrote, instead of a flag. The cursors after the first
one scan only the window of the previous cursor, each narrowing it to the
rows it incremented itself: a row outside misses at least one posting
list and can never reach count == n. Packed blocks and segments outside
the window are skipped by a range comparison instead of a scan of their
all-zero output region, and `finalizeCounters` runs over the first
cursor's range instead of the whole mark.

The block search in `linearSegments` resumes from `current_block`, the
last decoded block, when that block still lies before the window, instead
of bisecting the whole segment on every call. `linearEmbedded` resumes
from `index` in the same way and leaves it at the first doc_id past the
window; before, it galloped from index 0 on every mark, which for a flat
array of a million postings costs about 40 cache-missing probes per mark.
`findRowRangeEnd` gallops as well. Both resume positions are checked
against the window first, so a call out of order only costs a search from
the start.

Zeroing the counters between the first cursor's range and the final
window with `memset` and comparing the window alone was measured against
the single compare pass: it wins only when the first range is large and
the window much narrower (8192 rows narrowed to 440: 50 vs 64 ns) and
loses on the common narrow ranges (440 rows: 7.5 vs 5.2 ns), so the
compare pass covers the first range.

Single-threaded on a 50M-row table: intersections with a token clustered
inside every mark get 13-27 % faster; queries whose sparsest list is a
single-segment flat array get 16-28 % faster (the resume in
`linearEmbedded`); `text_index_lazy_wide_granule` and the gap queries are
unchanged. The number of decoded packed blocks does not change: the
all-zero regions were already skipped, what goes away is the scans that
found them.

The new test `05234_text_index_lazy_brute_force_narrow_window` compares
the results with a plain column scan and checks through
`TextIndexLazyBlocksSkippedResolved` and
`TextIndexLazySegmentsSkippedResolved` that the blocks outside the window
are no longer examined.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The linear scans write their ranges in ascending order, so a new range
always starts past the current end of `PostingsCursorWindow`: `extend`
only sets `begin` on the first write and moves `end` afterwards. The
`std::min` on `begin` was redundant; both preconditions are asserted.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The flag was equivalent to `current_segment != nullptr` on every path that
read it. `prepareSegment` is never called for embedded cursors, so its early
return is replaced by `chassert(!is_embedded)`. Add `chassert(current_segment)`
in `next`, which relies on `advance` positioning a compressed cursor first.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
@CurtizJ

CurtizJ commented Sep 24, 2026

Copy link
Copy Markdown
Member Author

2 queries has sped up:
Screenshot 2026-09-24 at 11 53 25

@CurtizJ CurtizJ self-assigned this Sep 24, 2026
@CurtizJ
CurtizJ added this pull request to the merge queue Sep 24, 2026
Merged via the queue into ClickHouse:master with commit cf7023d Sep 24, 2026
172 of 176 checks passed
@CurtizJ
CurtizJ deleted the text-index-postings-cursor-algorithm branch September 24, 2026 14:45
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... pr-performance Pull request with some performance improvements 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.

3 participants