Skip to content

Speed up intersection of text index posting lists in lazy apply mode - #123873

Merged
CurtizJ merged 10 commits into
ClickHouse:masterfrom
CurtizJ:text-index-lazy-intersection-optimizations
Oct 6, 2026
Merged

CurtizJ merged 10 commits into
ClickHouse:masterfrom
CurtizJ:text-index-lazy-intersection-optimizations

Conversation

@CurtizJ

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

Improved performance of intersection of text index posting lists.


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

Version info

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

CurtizJ and others added 2 commits October 4, 2026 13:33
- Brute-force intersection: a packed block (or segment) of the next posting list is skipped when no counter
  in its rows equals the number of posting lists applied so far, i.e. when no row there is in all of them.
  Before, it was skipped only when its rows were all zero, so rows of earlier lists that had already failed
  kept the blocks of the following lists from being skipped.
- Leapfrog intersection: a single loop led by the sparsest cursor replaces `intersectTwo`, `intersectThree`,
  `intersectFour`, `intersectLeapfrogLinear` and `intersectLeapfrogHeap`. The other cursors are advanced to
  the lead's doc id in ascending cardinality, and the first one that overshoots moves the lead, so a denser
  cursor only advances to the doc ids that all the sparser ones contain. The loop is unrolled for up to
  8 cursors.
- A packed block of consecutive row ids is padded as a whole instead of being decoded
  (new ProfileEvent `TextIndexLazyBlocksSkippedDense`).
- The resolved-region checks are skipped for an already loaded segment or decoded block, and use `memchr`
  instead of the hand-written AVX2 `hasNoZeros`.

Local measurements (50M rows, one part, `max_threads = 1`, interleaved A/B against the same master):
leapfrog over 3+ skewed posting lists -30..-63%, brute force over 3 lists with clustered rows -20..-34%,
tokens with long runs of consecutive rows -17..-69%, other shapes within noise. The perf test
`text_index_lazy_wide_granule` shows -42..-48% for the 4-token leapfrog queries and no slowdowns.

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 [b2bc31e]

Summary: ✅


AI Review

Summary

This PR speeds up lazy text-index intersections by tightening the brute-force skip condition for AND, adding dense-block padding, and simplifying leapfrog cursor advancement into a single loop. After reviewing the current head code, the existing review-thread discussion, the affected call sites, and the updated tests, I do not see an unresolved correctness or contract violation in the current version; the coverage added here and the all-green CI, including performance comparison jobs, are consistent with the stated Performance Improvement goal.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit b2bc31e.

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

Changed lines: Changed C/C++ lines covered: 139/142 (97.89%) · 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 16:11
@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
CurtizJ and others added 3 commits October 5, 2026 13:17
A loaded dense segment skipped the segment-level `canSkipRegion` check and was
padded even when its region was already resolved.
ClickHouse#123873 (comment)

- Run the segment-level and block-level `canSkipRegion` checks for loaded
  segments and decoded blocks too.
- Move the dense block shortcut before the block-level check: padding at most
  a block of rows is cheaper than the check.
- Replace `finalizeCounters` (AVX2 intrinsics with one vector per iteration,
  chosen by the runtime dispatch even on the default `x86-64-v3` build) with a
  plain loop inlined into `intersectBruteForce`, which the compiler vectorizes
  and unrolls.
- In `advance` past the last doc_id of an embedded list, move `index` to its end.
- `04257_text_index_lazy_profile_events`: the covered block of Q4 is dense and is
  now padded by the dense shortcut, so Q4 uses a token with a non-dense block.

In a standalone microbenchmark of the linear path, the dense block shortcut
first is −41..−44% for an AND with dense runs, and the plain finalize loop is
−22..−48% on the kernel and −0.5..−10% per brute-force window.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A segment that reaches the clip computation always overlaps the window: the preceding
`continue` / `break` filters, the `begin <= end` validation of ranges on read, and the
non-empty windows passed by the callers guarantee it. Replace the checks with `chassert`
and compute the clipped offset and count once for segments and blocks.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Both scans searched the decoded values for the window, moved `index` past it and padded
the matched rows with the same code. Move it to `linearDecoded`, which returns the range
of rows written.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Clang emitted `linearDecoded` out of line, adding a call per decoded block to `linearSegments`.
In a microbenchmark of the lazy linear path this cost +0.7..+0.9% on average and up to +6%
for a union of a list of dense runs with a uniform list. With `ALWAYS_INLINE` the timings are
within the noise of the code before the refactoring.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@CurtizJ CurtizJ assigned CurtizJ and unassigned CurtizJ Oct 5, 2026
@CurtizJ
CurtizJ marked this pull request as ready for review October 5, 2026 15:52
CurtizJ and others added 3 commits October 5, 2026 17:38
…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]>
`std::ranges::copy` took the length from the vector at runtime, so every
fixed-size specialization called `memcpy` with a runtime size. With
`num_cursors` as the count the copy is inlined.

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

@CurtizJ CurtizJ left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few optimizations in this PR

/// to its doc_id. So a denser cursor only advances to the doc_ids that all the sparser cursors contain.
/// `num_cursors` is the number of cursors when it is fixed at compile time, which unrolls the loops over them, or 0.
template <size_t num_cursors>
bool intersectLeapfrogImpl(UInt8 * out, const std::vector<PostingListCursor *> & cursor_ptrs, size_t row_offset, size_t effective_end)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. More optimal and simpler leapfrog.

Comment on lines +713 to +719
if (static_cast<size_t>(block_last) - block_first + 1 == block_size)
{
++stats.blocks_skipped_dense;
padDenseRange<op>(data + block_clip_offset, block_clip_count);
window.extend(block_clip_begin, block_clip_end);
continue;
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Fill contiguous blocks without decoding.

Comment on lines +596 to +597
const int value = op == PadOp::Or ? 0 : num_applied;
return memchr(data, value, count) == nullptr;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Skip regions for AND not only if the region is full 0, but also if the region doesn't have rows that can reach count == n.

…ear scan

For `PadOp::And`, a dense block whose rows have no counter equal to
`num_applied` was padded and added to the returned window, so
`intersectBruteForce` neither stopped early on an empty intersection nor
narrowed the window for the next cursor. The block-level `canSkipRegion`
check now runs before the dense block shortcut again.
ClickHouse#123873 (comment)

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

clickhouse-gh Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only changes the lazy text-index posting-list code: it merges the leapfrog intersection variants into one loop, makes the AND-side skips exact, adds a dense-block shortcut and drops the hand-written AVX2 helpers. ClickBench and TPC-H queries don't use text indexes, so none of them run this code. The three flagged ClickBench queries (Q16 +15.9%, Q32 +10.1%, Q33 +5.6%) are all aggregation-heavy and stay not_sure. Q16 and Q33 are within master's normal range for those queries, and on Q32 the two tests disagree. Two of the PR's runs also shared a host, which likely explains the small, uniform rise in CPU time, so nothing here needs action from the author.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 529 613 +15.9% <0.0001 aggregation: This is a high-cardinality GROUP BY over a table with no text index, so it never runs the changed posting-list cursor code. The +15.9% sits inside master's normal range for this query, and the query has a noisy history.
⚠️ 32 not_sure 714 786 +10.1% 0.0001 aggregation: The +10.1% is borderline: the two tests disagree and the measurements were very noisy. This aggregation query does not touch the text-index intersection code the PR changes.
⚠️ 33 not_sure 1132 1195 +5.6% <0.0001 aggregation: The +5.6% falls within master's normal range for this query. It is a plain GROUP BY scan with no text-index lookups, so the leapfrog and brute-force changes cannot reach it.

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: 6e5589a2-c19a-45d4-90a1-3ef9588a0319
  • MIRAI run: 56497fd6-4bc6-43d5-b49f-5a0fbd8fedb9
  • PR check IDs:
    • clickbench_3427667_1791234574
    • clickbench_3427673_1791234574
    • clickbench_3427679_1791234575
    • tpch_adapted_1_official_3427690_1791234574
    • tpch_adapted_1_official_3427699_1791234575
    • tpch_adapted_1_official_3427737_1791234574

@CurtizJ CurtizJ self-assigned this Oct 6, 2026
@CurtizJ
CurtizJ added this pull request to the merge queue Oct 6, 2026
@CurtizJ

CurtizJ commented Oct 6, 2026

Copy link
Copy Markdown
Member Author

Perf tests:
Screenshot 2026-10-06 at 14 09 33

Merged via the queue into ClickHouse:master with commit ce1cb99 Oct 6, 2026
149 checks passed
@CurtizJ
CurtizJ deleted the text-index-lazy-intersection-optimizations branch October 6, 2026 13:14
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 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