Skip to content

Add lazy posting list evaluation mode for text index - #100035

Merged
CurtizJ merged 93 commits into
ClickHouse:masterfrom
fastio:feature-lazy-apply-posting-list
May 24, 2026
Merged

CurtizJ merged 93 commits into
ClickHouse:masterfrom
fastio:feature-lazy-apply-posting-list

Conversation

@fastio

@fastio fastio commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

The text index (skip index) currently materializes all posting lists into
Roaring Bitmaps eagerly, which can be wasteful when only a small fraction of
the posting list is needed for intersection. This change introduces a lazy,
cursor-based evaluation path that decodes posting lists on demand at packed-block
granularity, avoiding full materialization.

Block index section in posting list codec. Each segment's payload in the .pst
stream now always includes an appended Index Section containing per-packed-block
last_row_id and relative_offset arrays, enabling O(log N) seek within segments
without decoding entire blocks. This is backward compatible — existing indices
without the index section are handled by reconstructing block metadata via payload
scanning.

PostingListCursor. A new cursor class provides lazy seek/next/linearOr/linearAnd
operations, decoding packed blocks on demand using BitpackingBlockCodec.
Embedded (small) postings are handled as a special case. Cursors are cached across
marks within the same part to avoid redundant construction.

Intersection algorithms. Two strategies are selected adaptively based on posting
list density:

  • Leapfrog (sparse, density < threshold): 2/3/4-way specializations plus N-way
    generics with min-heap for >8 cursors
  • Brute-force (dense, density ≥ threshold): counter-based linear scan with
    AVX2-accelerated hasAllZeros/hasNoZeros/finalizeCounters for cache-friendly
    access and fast zero-region / dense-segment skipping

Observability. 11 new profile events (TextIndexLazy*) for monitoring block
decoding, seek counts, algorithm selection, and skip optimizations.

This is a continuation of earlier unfinished work #95176

Changelog category (leave one):

  • Experimental Feature

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

Added lazy posting list apply mode for the text index. When enabled via
SET allow_experimental_text_index_lazy_apply = 1 and
SET text_index_posting_list_apply_mode = 'lazy', posting lists are decoded on demand
at packed-block granularity using a cursor-based approach instead of being fully
materialized into Roaring Bitmaps, reducing memory usage and CPU time for selective
text index queries.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

New settings:

  • allow_experimental_text_index_lazy_apply — experimental gate for lazy posting list mode (default false)
  • text_index_posting_list_apply_mode — controls whether posting lists are materialized eagerly ('materialize', default) or decoded lazily on demand ('lazy')
  • text_index_density_threshold — density threshold for selecting between leapfrog and brute-force intersection algorithms (default 0.5)

Note

High Risk
High risk because it changes the on-disk text index header/postings encoding (adds codec metadata + per-segment block index) and introduces a new lazy evaluation path in MergeTreeReaderTextIndex, which can affect query correctness/performance and compatibility with existing parts.

Overview
Adds an experimental lazy, cursor-based posting list evaluation mode for text skip indexes, selectable via new settings allow_experimental_text_index_lazy_apply, text_index_posting_list_apply_mode (materialize/lazy), and text_index_density_threshold.

Updates text index serialization to write/read a new header (TextIndexHeader) that includes the index version and posting-list codec type, and extends compressed posting list encoding to append a per-segment packed-block Index Section (HasBlockIndex) used for O(log N) block seeks.

Introduces PostingListCursor plus lazy union/intersection routines (density-based leapfrog vs brute-force), wires them into MergeTreeReaderTextIndex with per-(virtual column, token) cursor caching and new TextIndexLazy* profile events, and adjusts codec creation/compat handling and stream initialization accordingly.

Reviewed by Cursor Bugbot for commit b77fdc1. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.118

Implement cursor-based on-demand decoding of posting lists for skip
index text index, avoiding eager materialization into Roaring Bitmaps.

V2 format appends an Index Section after each segment's payload in
the .pst stream, containing per-packed-block `last_row_id` and
`relative_offset` arrays for O(log N) seek within segments.

New `PostingListCursor` class provides lazy seek/next/linearOr/linearAnd
operations, decoding packed blocks on demand via `BitpackingBlockCodec`.

Intersection algorithms:
- Leapfrog (sparse): 2/3/4-way specializations + N-way generics
- Brute-force (dense): bitmap counting for cache-friendly access
- Automatic selection based on `text_index_density_threshold`

New settings:
- `text_index_posting_list_apply_mode` ("materialize"/"lazy")
- `text_index_density_threshold` (default 0.5)

Backward compatible: V1 parts use existing materialize path;
lazy mode requires V2 format and opt-in via setting.

Reference: amosbird#4
@fastio
fastio marked this pull request as draft March 19, 2026 13:08
@fastio fastio changed the title Add lazy posting list evaluation mode for text index [WIP]: Add lazy posting list evaluation mode for text index Mar 19, 2026
@CurtizJ CurtizJ added the can be tested Allows running workflows for external contributors label Mar 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b77fdc1]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, flaky check) FAIL
clickhouse-test FAIL cidb IGNORED
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR introduces an experimental lazy, cursor-based posting-list apply mode for text index queries, adds codec/version metadata in the text index header, and wires adaptive intersection (leapfrog vs brute-force) with broad test coverage. I reviewed the current PR diff and all prior PR discussion threads, including thread replies; in the current HEAD state I did not find unresolved correctness/safety regressions that require additional inline comments.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 19, 2026
@Ergus Ergus self-assigned this Mar 24, 2026
fastio added 2 commits March 25, 2026 14:45
- Fix density overflow: use double for span computation
- Validate codec_type in prepareSegment
- Add payload_offset bounds check in decodeBlock
Comment thread src/Core/Settings.cpp Resolved
…gate

- Use `getDeserializedFormat` substreams in read path for correct file extensions
- Add `allow_experimental_text_index_lazy_apply` setting to gate lazy mode
@fastio

fastio commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @Ergus, The current design requires users to explicitly opt in to V2 via version=2 in the text index definition, unlike MinMax which transparently writes the latest version and only maintains backward compatibility on reads — is this explicit version parameter the right approach here?

e.g.

INDEX idx col TYPE text(tokenizer = 'splitByNonAlpha', version = 2)

@Ergus

Ergus commented Mar 27, 2026

Copy link
Copy Markdown
Member

Hi @Ergus, The current design requires users to explicitly opt in to V2 via version=2 in the text index definition, unlike MinMax which transparently writes the latest version and only maintains backward compatibility on reads — is this explicit version parameter the right approach here?

e.g.

INDEX idx col TYPE text(tokenizer = 'splitByNonAlpha', version = 2)

Hi @fastio

We are on version 3 by default now. Which is the latest. So any new development is intended to be for v3. The version argument is not needed.

@fastio

fastio commented Mar 27, 2026

Copy link
Copy Markdown
Contributor Author

Hi @Ergus, The current design requires users to explicitly opt in to V2 via version=2 in the text index definition, unlike MinMax which transparently writes the latest version and only maintains backward compatibility on reads — is this explicit version parameter the right approach here?
e.g.

INDEX idx col TYPE text(tokenizer = 'splitByNonAlpha', version = 2)

Hi @fastio

We are on version 3 by default now. Which is the latest. So any new development is intended to be for v3. The version argument is not needed.

Thanks for the feedback — let me take another look at the latest code.

fastio added 2 commits March 30, 2026 15:29
The block index section is now always written when using compressed
posting lists, removing the version-gated conditional. This simplifies
the codec interface by eliminating the `version` parameter from
`encode` and `serialize` methods throughout the pipeline.

Tests updated to remove `version` references and consolidate v1/v2
table variants into a single table.
Add multiple performance optimizations to `linearAnd` and supporting code:

- Dense segment/embedded shortcut: skip per-row binary search when every
  row in the range has a posting, increment the clipped region directly.
- All-zeros skip at segment and block level: when the output region is
  already all-zeros, no increment can contribute to a match, so skip
  the entire segment or block without decoding.
- AVX2-accelerated `hasAllZeros` for fast zero-region detection.
- AVX2-accelerated `finalizeCounters` for the brute-force intersection
  final pass (count == n → 1, else → 0).
- Binary search in `seek` across segments instead of linear scan.
- Simplify embedded posting list decoding (eliminate intermediate buffer).
- Cache lazy cursors across marks within the same part in
  `MergeTreeReaderTextIndex` to avoid redundant cursor construction.

New profile events: `TextIndexLazyAndSegmentsSkippedZero`,
`TextIndexLazyAndBlocksSkippedZero`, `TextIndexLazyAndSegmentsSkippedDense`.
@CurtizJ

CurtizJ commented May 23, 2026

Copy link
Copy Markdown
Member

@fastio

I've recently made a few minor changes and addressed AI review comments. I've also tested new algorithms on a large dataset in S3, and performance looks great. I'll merge the PR as soon as CI passes.

Once again, thank you for your contribution!

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 6109354. Configure here.

@fastio

fastio commented May 24, 2026

Copy link
Copy Markdown
Contributor Author

I've recently made a few minor changes and addressed AI review comments. I've also tested new algorithms on a large dataset in S3, and performance looks great. I'll merge the PR as soon as CI passes.

Once again, thank you for your contribution!

@CurtizJ, Awesome, glad the perf looks good on the S3 dataset. Thanks for the thorough review and follow-ups!

@clickhouse-gh

clickhouse-gh Bot commented May 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 96.72% (2743/2836) | lost baseline coverage: 2 line(s) · Uncovered code

Full report · Diff report

@CurtizJ
CurtizJ added this pull request to the merge queue May 24, 2026
Merged via the queue into ClickHouse:master with commit 83c2b12 May 24, 2026
164 of 167 checks passed
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 24, 2026
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…osting-list

Add lazy posting list evaluation mode for text index
return true;

#if USE_MULTITARGET_CODE
if (isArchSupported(TargetArch::x86_64_v3))

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.

Do we really need AVX2 for this? Also, AVX2 is on by default so we don't need to use multi target code for it, just a __AVX2__ guard

@CurtizJ CurtizJ Oct 5, 2026 •

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'll remove the hand-written AVX2 code here in #123873. The code by complier is faster.

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 pr-experimental Experimental Feature 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.

6 participants