Skip to content

Simplify and optimize building of posting lists in text index [4] - #113856

Merged
CurtizJ merged 48 commits into
ClickHouse:masterfrom
CurtizJ:text-index-build-4
Sep 22, 2026
Merged

CurtizJ merged 48 commits into
ClickHouse:masterfrom
CurtizJ:text-index-build-4

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Aug 7, 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 building text indexes during inserts (especially for indexes with bitpacking codec).

Depends on #113843.


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

Version info

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

CurtizJ added 2 commits August 7, 2026 18:51
Port the encoder-based posting list build from
ClickHouse#107367 onto the pluggable
per-block codec framework:

- `IPostingListEncoder` accumulates row ids of one token encoded into the
  codec's in-memory form and serializes all segments on `finalize`. Both
  codecs implement it: `bitpacking` via `SegmentedPostingListCodecImpl`
  (works for any per-block payload codec) and `none` via per-segment
  Roaring bitmaps, so large posting lists are no longer materialized as a
  single Roaring bitmap during the build.
- `PostingListBuilder` becomes a variant of an inline array (up to 11 row
  ids, no heap) and a heap state, whose raw values are flushed to the
  encoder every `append_granularity` row ids. The encoder is created
  lazily on the first flush, so raw and embedded posting lists never
  allocate one.
- Positions for phrase search are now built by `PostingListBuilder` itself
  (in its heap state) instead of a separate token map, and add no overhead
  when disabled. The heap state is the extension point for future optional
  per-token payloads (per-row term frequencies and document length norms
  for BM25 scoring).
- The `none` codec now splits posting lists into exact
  `posting_list_block_size` segments (previously it split by Roaring
  containers), which changes the number of posting blocks in the test
  reference.
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [314e079]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_msan) FAIL
Logical error: Chunk should have AggregatedChunkInfo in TotalsHavingTransform. (STID: 3546-3720) FAIL cidb IGNORED
Performance Comparison (amd_release, master_head, 5/6) FAIL Performance dashboard
order_by_read_in_order #1 FAIL dashboard IGNORED
number_formatting_formats #2 unstable query history IGNORED
number_formatting_formats #4 unstable query history IGNORED
number_formatting_formats #8 unstable query history IGNORED
tpch #1 unstable query history IGNORED

AI Review

Summary

This PR substantially rewrites text-index posting-list building and merge-time encoding, and most of the new corruption checks look sound. I would still block it: the merge path keeps one release-build validation hole for decoded row ids, so corrupted posting-list data can still reach offset remapping or be forwarded as invalid merged postings.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeIndexText.cpp:290, src/Storages/MergeTree/TextIndexUtils.cpp:506, src/Storages/MergeTree/TextIndexUtils.cpp:589] [dismissed by author -- https://github.com/Simplify and optimize building of posting lists in text index [4] #113856#discussion_r4066199481] Release builds still trust the interior row ids of each decoded segment. checkSegmentRowRange accepts a segment as long as its first and last row ids match the recorded range, checkRowIdsInPart only bounds row_ids.back(), and advancePostingsCursor keeps the sortedness check as a chassert only. A corrupted segment such as [0, part_rows + 1, 5] with metadata range [0, 5] still reaches adjustPartOffset with the out-of-range middle element, and a solo-source or solo-window run can also forward unsorted or duplicate interior values in release builds. Suggested fix: validate decoded row ids once per materialized segment before remapping or forwarding them, enforcing both row_ids[i] < part_rows and strict monotonic increase.
Final Verdict

Changes requested. The merge-time rewrite still relies on debug-only assertions for one of its core on-disk invariants, so corrupted posting lists can still trigger out-of-bounds remap lookups or produce invalid merged output in release builds.

LLVM Coverage Report

Measured on commit 314e079.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 750/824 (91.02%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there.

This PR rewrites the text-index posting-list encoder and serialization path (MergeTreeIndexText, IPostingListCodec, bitpacking codec) — a write/build path that ClickBench queries do not exercise. The only flagged query, ClickBench Q5, shows a -12.9% median drop but essentially unchanged CPU time (2938.8 vs 2889.7 ms), and the changed code cannot plausibly touch its execution path, so this reads as normal run-to-run variance rather than a real speedup. Downgraded to not_sure accordingly; no evidence of any regression from this change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 5 not_sure 256 223 -12.9% <0.0001 This PR only reworks text-index posting-list build/serialization; ClickBench Q5 runs no text index, so the -12.9% improvement is run-to-run variance, not a PR effect. CPU time is essentially flat (2938.8 vs 2889.7 ms).

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: c305977c-5b45-49c4-9d5c-3a65ef6f3a83
  • MIRAI run: 23245ea1-8c9e-40ba-912f-51ffcf88699f
  • PR check IDs:
    • clickbench_1257421_1790034627
    • clickbench_1257423_1790034627
    • clickbench_1257425_1790034627
    • tpch_adapted_1_official_1257427_1790034627
    • tpch_adapted_1_official_1257478_1790034627
    • tpch_adapted_1_official_1257492_1790034627

Conflicts came from both branches touching the same posting list codec code:

* `SegmentedPostingListCodecImpl` is renamed to `SegmentedPostingListCodec`
  (from `postings-codec-refactoring`), while keeping the new batch `append` API
  and the `IPostingListEncoder` accumulators from `text-index-build-4`. The
  segment size is no longer a constructor argument: it is passed to `append`
  and normalized in `PostingListCodecBitpacking::getSegmentSize`.

* In `BitpackingPostingListBlockCodec::encodeBlock`, the manual reservation of
  the output buffer is dropped, because `std::string::resize` already grows the
  buffer geometrically. Both branches were fixing the same pathological
  `reserve` that reallocated on almost every block.

* Comment simplifications from `postings-codec-refactoring` are kept.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 314e0795d with master 543631e63 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of b56918545; 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

11 object files changed (+103.80 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/TextIndexUtils.cpp.o 408.12 KiB 464.43 KiB +56.31 KiB (+13.80%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexTextPostingListCodec.cpp.o 79.80 KiB 111.59 KiB +31.79 KiB (+39.84%)

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

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

Job report

CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Aug 11, 2026
`PostingsSerialization::deserialize` decoded posting lists marked
`IsCompressed` with the configured codec, but handled the uncompressed
roaring format inline, so `PostingListCodecNone::decode` was an unused
no-op. Implement it, and route everything except raw postings through
the codec, in both the posting list and the row ids overloads.

The codec is now selected by the posting list header instead of the
codec configured for the part, so `resolveCompressedCodec` is replaced
by `resolveCodec`. An uncompressed posting list is always a serialized
roaring bitmap, and picking the codec by the header keeps that
independent of the lazy `Bitpacking` resolution done for pre-`WithCodec`
parts.

Adapted from ClickHouse#113856

Co-Authored-By: Claude Opus 5 <[email protected]>
CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Aug 11, 2026
`PostingsSerialization::deserialize` decoded posting lists marked
`IsCompressed` with the configured codec, but handled the uncompressed
roaring format inline, so `PostingListCodecNone::decode` was an unused
no-op. Implement it, and route everything except raw postings through
the codec.

The codec is now selected by the posting list header instead of the
codec configured for the part, so the resolution is extracted into
`resolveCodec`. An uncompressed posting list is always a serialized
roaring bitmap, and picking the codec by the header keeps that
independent of the lazy `Bitpacking` resolution done for pre-`WithCodec`
parts.

Adapted from ClickHouse#113856

Co-Authored-By: Claude Opus 5 <[email protected]>
CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Aug 11, 2026
`PostingsSerialization::deserialize` decoded posting lists marked
`IsCompressed` with the configured codec, but handled the uncompressed
roaring format inline, so `PostingListCodecNone::decode` was an unused
no-op. Implement it, and route everything except raw postings through
the codec.

The codec is now selected by the posting list header instead of the
codec configured for the part, so the resolution is extracted into
`resolveCodec`. An uncompressed posting list is always a serialized
roaring bitmap, and picking the codec by the header keeps that
independent of the lazy `Bitpacking` resolution done for pre-`WithCodec`
parts.

Adapted from ClickHouse#113856

Co-Authored-By: Claude Opus 5 <[email protected]>
Resolved conflicts with `Minor refactoring of posting lists deserialization`
(ClickHouse#114317) in the text index
posting list codecs:

- `IPostingListCodec::decode` keeps the new `PaddedPODArray<char> & buffer`
  scratch parameter from master, threaded through `SegmentedPostingListCodec`,
  `PostingListCodecBitpacking` and `PostingListCodecNone`, while keeping
  `createEncoder` from this branch. `IPostingListCodec::encode` and
  `encodePostingsInBlocks` stay removed - encoding goes through
  `IPostingListEncoder`.
- `PostingsSerialization::deserialize` uses `resolveCodec` from master, so an
  uncompressed posting list is always decoded by `PostingListCodecNone` instead
  of the configured codec, and contradictory `RawPostings` / `IsCompressed`
  header flags are rejected.
- `PostingListCodecNone::decode` now reuses the shared `readContiguousBytes`
  helper and the caller-owned scratch buffer instead of a local `std::vector`.
- Kept both `TextIndexSerialization::serializeRawPostings` (this branch) and
  `TextIndexSerialization::checkTokenSize` (master).

Co-Authored-By: Claude Opus 5 <[email protected]>
@ahmadov ahmadov self-assigned this Aug 24, 2026
# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexText.cpp
#	src/Storages/MergeTree/MergeTreeIndexText.h
#	src/Storages/MergeTree/MergeTreeIndexTextPostingListCodec.cpp
#	src/Storages/MergeTree/TextIndexUtils.cpp
@CurtizJ

CurtizJ commented Aug 25, 2026

Copy link
Copy Markdown
Member Author

Merges of text index have slowed down. I'm implementing a proper solution for merges using encoders.

# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexText.cpp
#	src/Storages/MergeTree/MergeTreeIndexText.h
Port the build-path refactoring from the BM25 branch (the parts not
related to scoring):

- Introduce `PostingListBuildContext` (codec, segment size, positions
  flag), built once per batch by
  `MergeTreeIndexTextGranuleBuilder::buildContext` and passed down to
  `addDocument`/`addToken` and to the serialization of posting lists.
- Unify `PostingListBuilder::add` and the constructor for indexes with
  and without positions.
- Rework `PostingListBuilder::Large::flush`: it now flushes all buffered
  row ids unconditionally and the callers control the flush size. `add`
  flushes a full block before appending a new row id, so `values` is
  never empty between adds and `Large::last_value` is not needed
  anymore.
- Pass `TextIndexHeader` to `TextIndexSerialization::serializeHeader`
  instead of separate arguments.

Ported from ClickHouse/clickhouse-private#70235
(on top of ClickHouse#113856).

Co-Authored-By: Claude Fable 5 <[email protected]>
Rewrite the posting-list handling in `MergeTextIndexesTask`. Postings of
the current token are no longer decoded eagerly into a union of roaring
bitmaps with a full array materialization. Instead the merge queue only
collects a `TokenSource` (source number and `TokenPostingsInfo`) per
source, and postings are decoded lazily when the token is flushed:

- The merged cardinality is known upfront because sources own disjoint
  row sets, so the serialization format is chosen before decoding a
  single posting.
- Posting lists of up to `MAX_CARDINALITY_FOR_RAW_POSTINGS` row ids are
  merged into a buffer and written as raw or embedded postings.
- Larger posting lists are fed into `IPostingListEncoder` through a
  k-way merge over cursors that decode and remap one segment of one
  source at a time. Row ids of the winning cursor below the
  second-smallest cursor head are emitted in bulk without heap
  operations.
- A duplicate row id across sources and a mismatch between the encoded
  and the expected cardinality throw an `INCORRECT_DATA` exception.
- `TextIndexSerialization::serializePostings` is replaced by
  `MergeTextIndexesTask::serializeSmallPostings` and
  `MergeTextIndexesTask::encodePostings`.
- `TextIndexPositionCodec::decode` reads into a memory-tracked
  `PaddedPODArray` on the merge path.

Co-Authored-By: Claude Fable 5 <[email protected]>
@CurtizJ
CurtizJ marked this pull request as draft August 25, 2026 17:19
Rework the k-way merge of posting lists in `MergeTextIndexesTask`:

- Fix an out-of-bounds access: `postings_merge_cursors` was never sized,
  so the first flush of a posting list aborted the server with a libc++
  hardening assertion in the release build.
- Replace the hand-rolled binary heap over cursors with
  `SortingQueueBatch<SpecializedSingleColumnSortCursor<ColumnUInt32>>`,
  the same machinery the dictionary merge above it uses. Each cursor
  decodes into its own `ColumnUInt32` and its `SortCursorImpl` is built
  once in the task constructor, so a segment refill only rewinds the
  cursor instead of paying `SortCursorImpl::reset` per token and source.
- A token that lives in a single source (the most common case) is
  drained directly into the sink without touching the queue.
- A granularity-aligned chunk arriving on an empty staging buffer is
  passed to the encoder directly, skipping a copy for whole segments.
- A duplicate row id across sources throws `INCORRECT_DATA`: sources
  must own disjoint row sets, and the queue would otherwise silently
  order equal values by cursor number.

An alternative tier that unioned overlapping sources into a roaring
bitmap was measured and dropped: on 50M rows of real server logs
(`message` column, 6-part merges, both time-disjoint and fully
interleaved part layouts) the queue merge is the fastest variant on
both layouts, while the bitmap union only wins on the synthetic
uniform-random interleave of `text_index_merge.xml`, where the
`*_intersecting_*` queries are expected to regress.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread tests/performance/text_index_build.xml Resolved
CurtizJ and others added 2 commits September 11, 2026 15:45
…them

`PostingListCodecNone::decode` grew the decode buffer to the VarUInt size
prefix read from disk before checking anything. The allocator rejects only
sizes of 2^63 and above, and with `LOGICAL_ERROR`, which aborts debug and
sanitizer builds. Smaller corrupted sizes failed with `MEMORY_LIMIT_EXCEEDED`
or `CANNOT_READ_ALL_DATA` after the allocation.

Reject the size up front with `CORRUPTED_DATA` when it exceeds the upper
bound of a portable Roaring bitmap with `max_cardinality` row ids, so the
bounded-decode contract of `IPostingListCodec::decode` holds for the `none`
codec as it does for `bitpacking`.

ClickHouse#113856 (comment)

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

@ahmadov ahmadov left a comment

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.

in general, LGTM 👍

Comment thread src/Storages/MergeTree/TextIndexUtils.h Resolved
CurtizJ and others added 5 commits September 20, 2026 00:08
Resolves conflicts with the `pfor` posting list codec from
ClickHouse#118123:

- `SegmentedPostingListCodecBase` keeps master's class hierarchy and takes over
  `getSegmentSize`, `createEncoder` and the `decode` overloads bounded by the
  token metadata; `createEncoder` uses the codec's own type, so `pfor` indexes
  are built with a PFor encoder
- `addDocumentsFromMap` from master takes the `PostingListBuildContext`
- the memory accounting of posting list encoders is removed together with the
  granule memory accounting removed in
  ClickHouse#119927

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Remove the global `BLOCK_SIZE` from `BitpackingBlockCodec.h`. Each
`BitpackingBlockCodecImpl` specialization now owns the block size of the
bit-packing layout, and `IPostingListBlockCodec::BLOCK_SIZE` owns the
number of row ids in one block of a segmented posting list, with a static
assertion that the latter is a multiple of the former.

Add `IPostingListCodec::getBlockSize`, overridden by
`SegmentedPostingListCodecBase`, and round the segment size to it in
`getSegmentSize`.

Resolves ClickHouse#113856 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…f every `append`

The segment size cannot change between `append` calls of one encoder, so it is
fixed when the encoder is created. `IPostingListEncoder::append` takes only the
row ids, and the codec rounds the requested size itself, which makes
`getSegmentSize` and `getBlockSize` unnecessary in `IPostingListCodec`.

Addresses ClickHouse#113856 (comment)

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

The lazy cursor only checked that the segment cardinality fits into the
row range stored in the dictionary. A corrupted segment whose header or
Index Section disagreed with that range was still accepted: `advance` and
the skip heuristics position by the range and by `block_last_row_ids`,
while `decodeBlock` uses the header `first_row_id` and the previous block's
last row id as delta bases, so such a segment could silently drop rows or
return rows outside the token range.

Now `buildPostingSegment` requires the header to start at the first row id
of the range, the block index to end at its last row id and to stay after
the segment start, and `decodeBlock` requires every decoded block to end at
the row id its Index Section entry claims. Otherwise the segment is
rejected with a `CORRUPTED_DATA` exception, matching `checkSegmentRowRange`
on the eager path.

ClickHouse#113856 (comment)

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

CurtizJ commented Sep 22, 2026

Copy link
Copy Markdown
Member Author

Fix for fuzzer failure: #121522.

Merged via the queue into ClickHouse:master with commit 889b021 Sep 22, 2026
174 of 177 checks passed
@CurtizJ
CurtizJ deleted the text-index-build-4 branch September 22, 2026 12:03
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 22, 2026
CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Sep 22, 2026
Resolve the conflicts with the merged text-index-build-4 (ClickHouse#113856) and the
later text index changes on master: keep the `max_cardinality` bound of the
segment decoding, `createEncoder(segment_size)`, the `PFor` block codec and
the `PODArray` output, and layer the BM25 term frequencies (`tf_minus_one`,
`decodeWithTermFrequencies`) on top of them. Add the `.dl` substream to
`getPotentialSubstreams`, implement `encodeZeros` and `skipBlock` for the
`PFor` block codec, and resolve the text index streams from the part's
checksums in `BM25State`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
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.

4 participants