Skip to content

Text index: resolve the lazy cursors of a column once per part instead of per granule - #123786

Merged
CurtizJ merged 8 commits into
ClickHouse:masterfrom
CurtizJ:text-index-resolve-lazy-cursors-once
Oct 5, 2026
Merged

CurtizJ merged 8 commits into
ClickHouse:masterfrom
CurtizJ:text-index-resolve-lazy-cursors-once

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Oct 3, 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):

Reduced the per-granule CPU overhead of reading text index posting lists in the lazy apply mode.


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

Version info

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

CurtizJ and others added 3 commits October 3, 2026 22:34
…granule

`MergeTreeReaderTextIndex::readRows` fills the virtual columns granule by granule, and
`fillColumnLazy` redid work per granule that only depends on the part: the
`analyzer.getQueryBuilder` lookup, the per-token `hasReadPostings` and `try_emplace`
string-hash lookups, `shared_ptr` copies into a freshly allocated cursor vector and the
prebuilt-cursor handling. `lazyIntersectPostingLists` then copied the vector again, recomputed
the densities for the `Auto` algorithm decision and sorted by cardinality, and
`lazyUnionPostingLists` copied and stable-sorted by density, although densities and
cardinalities are properties of the posting lists and never change between granules. Each
intersection also incremented `TextIndexLazyBruteForceIntersections`,
`TextIndexLazyBruteForceEarlyExits` or `TextIndexLazyLeapfrogIntersections` per granule,
and every `ProfileEvents::increment` walks the thread, query and global counters.

Measured over 13.7M granules on aarch64: about 2.3 CPU-s of hash lookups and `shared_ptr`
reference counting and about 2 CPU-s of profile-event atomics.

Now the reader resolves each search column once per part into `ResolvedSearch`: the kind of
fill (all zeros, analyzer-folded postings clipped per granule, or cursors), the cursors as raw
pointers already ordered for the search mode, and the concrete intersection algorithm. It is
built on the first granule of the column and dropped in `resetCursors`, together with
`lazy_cursors` and `prebuilt_cursors`, which keep the ownership. The ordering rules and the
`Auto` decision moved into `sortCursorsForUnion`, `sortCursorsForIntersection` and
`chooseIntersectionAlgorithm`, and `lazyUnionPostingLists` / `lazyIntersectPostingLists` take
the ordered cursors by const reference and neither copy nor sort; passing `Auto` to the
intersection is now an exception. The internal leapfrog and brute-force helpers take raw
pointers instead of `shared_ptr` copies; their bodies are unchanged.

The three intersection profile events are accumulated in `LazyPostingsStats` and flushed with
one `ProfileEvents::increment` per event at the end of each `readRows` call, so the totals
per query are the same as before.

The unit tests keep their meaning through the `unionSorted` and `intersectSorted` helpers,
which order the cursors and resolve the algorithm per call the way the reader does per part.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…omments

`MergeTreeReaderTextIndex.h` holds a `LazyPostingsStats` member by value, so it needs the complete
type: include `MergeTreeIndexTextPostingListCursor.h` instead of forward-declaring `PostingListCursor`.

Shorten the comments added by the previous commit and simplify the exception message for an
unresolved intersection algorithm.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Move the counters of `PostingListCursor::EventsCounters` into `LazyPostingsStats` and add the
counters to the profile events in the destructor of `LazyPostingsStats` instead of
`LazyPostingsStats::flush` and `~PostingListCursor`. The cursor owns one instance for its own
counters; the reader owns one for the intersection counters, which is now flushed when the reader is
destroyed rather than at the end of each `readRows` call.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [26e5067]

Summary: ✅


AI Review

Summary

This PR refactors the lazy text-index read path so each virtual column resolves and orders its posting-list cursors once per part, and it replaces the per-granule direct fill of analyzer-folded postings with a shared flat-postings cursor. I did not find a concrete correctness regression in the current code, but I still cannot approve it as a Performance Improvement because the PR does not yet include focused evidence that this hot path is actually faster on a workload that exercises it.

Tests
  • ⚠️ Please add before/after timings or query-profile evidence for a lazy text-index query that goes through the multi-block cursor path in src/Storages/MergeTree/MergeTreeReaderTextIndex.cpp. The generic cloud benchmarks on this PR explicitly do not execute text-index queries, so they do not validate the claimed CPU reduction.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Add focused performance evidence for a lazy text-index workload that exercises this code path.

LLVM Coverage Report

Measured on commit 26e5067.

Metric Baseline Current Δ
Lines 88.30% 88.20% -0.10%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 202/205 (98.54%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 4, 2026
@CurtizJ
CurtizJ marked this pull request as draft October 4, 2026 00:06
@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 Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 26e50672a with master 915744a54 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 9303f58ce; 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

6 object files changed (+19.88 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexTextPostingListCursor.cpp.o 218.31 KiB 250.65 KiB +32.34 KiB (+14.81%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderTextIndex.cpp.o 468.82 KiB 452.39 KiB -16.43 KiB (-3.50%)

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

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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

No query shows a performance change that can be traced to this PR. The PR refactors how the text-index reader handles lazy posting lists: cursors are now sorted and the intersection algorithm is picked once per part instead of on every call, and profile counters are batched. That code only runs for queries filtered through a text index, and neither clickbench nor tpch_adapted_1_official exercises it. The only flagged query is clickbench Q28 (+5.1%), which stays not_sure: the two tests disagreed, the measurements were noisy, CPU time barely moved (14945 ms vs 15010 ms), and the query never reaches the changed code.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1017 1069 +5.1% 0.0355 This PR only changes how the text-index reader handles lazy posting lists. ClickBench tables have no text index, so Q28 never runs that code, and its CPU time is nearly unchanged.

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

🟢 No significant changes

Debug info
  • StressHouse run: e3d46308-6a9f-44d4-9488-518b25ac2be3
  • MIRAI run: 888a2043-d6c0-4add-a34b-19deb16a4880
  • PR check IDs:
    • clickbench_3353843_1791203810
    • clickbench_3353849_1791203810
    • clickbench_3353871_1791203810
    • tpch_adapted_1_official_3353885_1791203810
    • tpch_adapted_1_official_3353900_1791203810
    • tpch_adapted_1_official_3353914_1791203810

CurtizJ and others added 2 commits October 4, 2026 16:35
`resolveSearch` runs once per column between resets of `resolved_searches`,
so the per-token map of lazy cursors and the per-column prebuilt cursors
never served a cached cursor. They only owned the cursors, so replace both
with a single `std::vector<PostingListCursorPtr>` that `ResolvedSearch`
points into.

Also restructure `lazyIntersectPostingLists` into one `if`/`else` chain and
shorten comments.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…e-lazy-cursors-once

Conflicts in `MergeTreeIndexTextPostingListCursor` with
ClickHouse#123294: keep the raw-pointer
cursors with `LazyPostingsStats` and make the lazy union and intersection
return whether any row of the window may be set.

`ReadFromTextIndexCount` now sorts its cursors and chooses the intersection
algorithm once per part, as `MergeTreeReaderTextIndex` does.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
CurtizJ and others added 3 commits October 5, 2026 09:11
`tokens_to_read` cached `isTokenNeeded(token) && !hasReadPostings(token)`
for every token of the analyzer, which is constant once the analysis is
done. Its only consumer, `buildPostingsForQuery`, iterates the query's
tokens, all of which are in `getAllTokenInfos`, so check the analyzer in
place instead. This also drops `string_view`s into the analyzer that
outlived a granule swap in `setPrecomputedGranule`.

`resolveSearch` now skips the tokens the analysis no longer needs, the
same way, instead of opening cursors for them.

Also explain when `Auto` picks the leapfrog intersection, rename
`any_set` to `may_be_true` in `lazyUnionPostingLists`, initialize
`resolved_searches` in the constructor's initializer list, and assert
that the search query of a resolved column is set.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…at cursor

A lazy column whose postings were all folded by the analysis was filled by
intersecting `query_builder.postings` with the granule's range and expanding
the result, which allocates a bitmap per granule. Use the cursor over
`getFlatPostings` instead, as the columns that also have lazy cursors already
do: the array is built once per part and shared by the readers of the
granule, and each granule then costs a galloping search plus the scatter.

In a microbenchmark (8192-row granules, the one-time flattening included)
this is 3-4x faster on sparse postings and on par for 50-95% dense bitsets,
but 2.5-3.5x slower for runs and contiguous postings, where flattening
dominates. The flat array takes 4 bytes per posting, bounded by
`text_index_posting_list_block_size` per folded token.

`ResolvedSearch::Kind` is removed with `DirectPostings`: a search without
cursors matches no rows. `range_posting` becomes a local of
`buildPostingsForMark`, and `requireRowOffsetRepresentable` becomes local
to the cursor.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@CurtizJ
CurtizJ force-pushed the text-index-resolve-lazy-cursors-once branch from b98da6c to 26e5067 Compare October 5, 2026 10:17
@CurtizJ
CurtizJ marked this pull request as ready for review October 5, 2026 10:49
@CurtizJ CurtizJ self-assigned this Oct 5, 2026
@CurtizJ

CurtizJ commented Oct 5, 2026

Copy link
Copy Markdown
Member Author

There is a small performance improvement in the perf tests (maybe just flaky). It should be more noticeable on very large tables (100B+ rows).

Screenshot 2026-10-05 at 17 51 35

@CurtizJ
CurtizJ added this pull request to the merge queue Oct 5, 2026
Merged via the queue into ClickHouse:master with commit 76ec7cc Oct 5, 2026
149 checks passed
@CurtizJ
CurtizJ deleted the text-index-resolve-lazy-cursors-once branch October 5, 2026 16:28
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 5, 2026
CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Oct 5, 2026
…ntersection-optimizations

Resolve conflicts with ClickHouse#123786 in
`MergeTreeIndexTextPostingListCursor`: move the new `blocks_skipped_dense` counter
into `LazyPostingsStats`, switch `intersectLeapfrogImpl` to raw cursor pointers,
and move the lead-first cursor positioning into the `Leapfrog` branch of
`lazyIntersectPostingLists` (cursors are now sorted by the caller).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Oct 9, 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.

2 participants