Skip to content

Simplify and optimize building of text indexes [2] - #106735

Closed
CurtizJ wants to merge 6 commits into
ClickHouse:masterfrom
CurtizJ:text-index-streaming-accumulators
Closed

CurtizJ wants to merge 6 commits into
ClickHouse:masterfrom
CurtizJ:text-index-streaming-accumulators

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Jun 8, 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).

CurtizJ and others added 3 commits June 8, 2026 14:44
Unify and speed up posting-list construction in the text index. Previously
compressed posting lists were serialized via `PostingListCodecBitpacking`
while uncompressed ones were written by ad-hoc code in
`TextIndexSerialization::serializePostings`, and the `bitpacking` codec built
a full Roaring bitmap during the build only to convert it to a `UInt32` array
and re-encode it at serialization time.

Now every posting list is encoded directly into its codec's on-disk form
during the build via a new streaming `IPostingListAccumulator`:
`createAccumulator` replaces `IPostingListCodec::encode`; the `none` codec adds
row ids to segmented Roaring bitmaps, and the `bitpacking` codec streams
bit-packed 128-row blocks (see `PostingListCodecBitpackingImpl`), both creating
new segments of `posting_list_block_size` row ids and flushing on `finalize`.

`PostingListBuilder` keeps the first `MAX_CARDINALITY_FOR_RAW_POSTINGS` row ids
inline (raw and embedded tokens never touch a codec) and promotes to an
accumulator on overflow. To keep the per-row hot path as cheap as the previous
inline representation, the accumulators are `final` and dispatched on the codec
type once per document (`dispatchByPostingCodec` plus a templated
`PostingListBuilder::add`), the roaring `BulkContext` is kept in the builder
(cache-warm next to the token's hash-map entry) and passed into `insert`, and
the accumulator holder is a `std::vector` (pointee stability comes from the
`unique_ptr`).

The on-disk format is unchanged and `bitpacking` output is byte-identical. The
only behavioral change is that the `none` codec now splits posting lists into
segments by `posting_list_block_size` row count, like `bitpacking`, instead of
by Roaring container, so the number of posting-list blocks for a dense token
can change (reflected in the updated test reference).

Building text indexes is faster: `bitpacking` is ~9% faster for small inputs and
~27% faster for large vocabularies and is now the faster codec to build; `none`
is ~28% faster for large vocabularies.

Related: ClickHouse#105850

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Follow-up to the streaming posting-list accumulators that cuts peak build
memory and removes per-token state that does not need to be stored:

- Pass the segment size (`posting_list_block_size`) into `insert` instead of
  storing it in every accumulator (`PostingListAccumulatorNone` and
  `PostingListCodecBitpackingImpl`). It is a per-index constant, so keeping a
  copy per token only wasted space.
- Make the portable-Roaring serialization buffer in
  `PostingListAccumulatorNone::finalize` a local instead of a member. As a
  member it stayed alive for every accumulator until the whole granule was
  serialized, holding one buffer per token simultaneously.
- Union the builder's accumulator pointer with the (dead after promotion)
  inline `small` array in `PostingListBuilder`, discriminated by a `promoted`
  flag, so the builder that lives by value in the hash map stays small.
- Move the roaring `BulkContext` into `PostingListAccumulatorNone` so `insert`
  takes no context argument and the generic builder carries no codec-specific
  field (`bitpacking` no longer takes an ignored context parameter either).

Peak build memory over the previous Roaring-based implementation drops from
about +23% to +12% at medium token counts and from +14% to +9% at large
vocabularies; the smaller per-token objects also speed up the build.

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

clickhouse-gh Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3c33b60]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential) FAIL
Server died FAIL cidb
03716_mutations_parts_postpone_reasons_rmt UNKNOWN cidb
03714_queries_escaping_3 UNKNOWN cidb
Segmentation fault (STID: 3502-2704) FAIL cidb
Stateless tests (arm_asan_ubsan, azure, parallel) FAIL
Server died FAIL cidb
01276_random_string UNKNOWN cidb
04033_tpc_ds_q64 UNKNOWN cidb
Logical error: Expected 3 to 10 arguments in table function azureBlobStorage, got 1` (STID: None) FAIL cidb
OOM in dmesg FAIL cidb

AI Review

Summary

This PR replaces text-index posting-list construction with streaming codec accumulators for none and bitpacking, and updates merge-time reserialization plus the build benchmark. I’m requesting changes because the current code still violates the accepted posting_list_block_size contract for bitpacking at size 1, and several newly introduced accumulator containers are omitted from writable-granule memory accounting.

Missing context / blind spots
  • ⚠️ I could not run .claude/tools/fetch_perf_report.py because no clickhouse binary is available in PATH or the usual build* directories. The PR CI report fetched successfully and showed no failed checks, but I could not locally inspect the machine-readable performance comparison.
Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeIndexTextPostingListCodec.h:124] textIndexValidator accepts posting_list_block_size = 1, but PostingListCodecBitpackingImpl::insert returns immediately after startSegment for the first row and skips the segment-boundary check. After that, row_ids_in_current_segment becomes 2, 3, ... and never equals 1, so the whole posting list is serialized as one segment instead of honoring the configured one-row segments. Run the same flush check after starting the first segment, or reject sizes below the supported minimum explicitly.
  • [src/Storages/MergeTree/MergeTreeIndexTextPostingListCodec.h:172] PostingListCodecBitpackingImpl::memoryUsageBytes counts the outer segment_block_metas storage, but each SegmentBlockMetas::metas can allocate out-of-line once a segment has more than one packed block. Large bitpacking posting lists can therefore hide the per-block PackedBlockMeta heap from granule accounting. Include the out-of-line storage for every metas vector whose capacity exceeds the inline element.
  • [src/Storages/MergeTree/MergeTreeIndexTextPostingListCodec.cpp:246] PostingListAccumulatorNone::memoryUsageBytes sums the Roaring payloads but omits the heap owned by the segments vector itself. With a small posting_list_block_size, sealSegment can push one PostingList object per row, so memory accounting misses segments.capacity() * sizeof(PostingList). Add that vector storage to the returned size.
  • [src/Storages/MergeTree/MergeTreeIndexText.cpp:1225] MergeTreeIndexGranuleTextWritable::memoryUsageBytes now sums each accumulator payload, but it still omits the heap owned by the accumulators holder. Since the PR replaced posting_lists with one unique_ptr per promoted token, large vocabularies can hide accumulators.capacity() * sizeof(std::unique_ptr<IPostingListAccumulator>) bytes. Add the holder storage alongside accumulators_size.
Tests
  • ⚠️ Please add the smallest focused regression test for posting_list_codec = 'bitpacking' with posting_list_block_size = 1, either proving that each row becomes its own segment or proving that this configuration is rejected.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix or reject the posting_list_block_size = 1 bitpacking path, include the omitted accumulator heap storage in memory accounting, and add the focused segment-size regression coverage.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 8, 2026
}

void PostingListCodecBitpackingImpl::insert(uint32_t row_id)
void PostingListCodecBitpackingImpl::insert(uint32_t row_id, size_t max_rowids_in_segment)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

posting_list_block_size = 1 is still accepted by textIndexValidator, but this path now returns before applying the segment-boundary check to the first row. With bitpacking, the first insert leaves row_ids_in_current_segment == 1; every later insert increments it to 2, 3, ... so row_ids_in_current_segment == max_rowids_in_segment never fires and the whole posting list is serialized as one segment instead of one row per segment. Please run the same flush logic for the first row as for the later rows, or reject sizes below the minimum segment size explicitly.

return compressed_data.capacity()
+ current_segment.capacity() * sizeof(uint32_t)
+ segment_descriptors.capacity() * sizeof(SegmentDescriptor)
+ segment_block_metas.capacity() * sizeof(SegmentBlockMetas);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

memoryUsageBytes is meant to account for the heap held by the accumulator, but this only counts the outer segment_block_metas array. Each SegmentBlockMetas::metas owns a separate vector and encodeBlock pushes one PackedBlockMeta per packed block, so large bitpacking posting lists can hide roughly block_count * sizeof(PackedBlockMeta) bytes from the granule memory accounting. Please include the inner metas.capacity() * sizeof(PackedBlockMeta) totals here as well.

@clickhouse-gh

clickhouse-gh Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This change is confined to full-text (text) index posting-list construction and serialization in the MergeTree index writer. ClickBench Q18 is a GROUP BY aggregation that does not use any text index, so the query-execution path it exercises is untouched by this PR. The flagged -5.01% improvement (median 1437ms to 1365ms) is therefore not attributable to the change, and Q18's history is intrinsically noisy, so we read this delta as normal run-to-run variance and downgrade it to not-sure rather than crediting it as a real speedup.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 18 not_sure 1437 1365 -5.0% 0.0001 PR only changes text-index posting-list build; Q18 (GROUP BY) never touches it. Noisy history, -5% is variance.

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: 18e05295-2ae6-47e4-b306-43ff18199bc7
  • MIRAI run: ab06553e-dd70-420a-8d35-a8cc4ae83e00
  • PR check IDs:
    • clickbench_229259_1781147433
    • clickbench_229273_1781147433
    • clickbench_229279_1781147433
    • tpch_adapted_1_official_229285_1781147433
    • tpch_adapted_1_official_229299_1781147433
    • tpch_adapted_1_official_229708_1781147457

CurtizJ and others added 2 commits June 9, 2026 13:34
When building a text index with `posting_list_codec = 'none'`, each promoted
token's row ids are streamed into a Roaring bitmap via `roaring_bitmap_add_bulk`,
whose fast path loads the cached container from a `roaring::BulkContext`. The
context lived inside the heap-allocated `PostingListAccumulatorNone`, reached only
through the builder's `accumulator` pointer, so the per-row `context->container`
load missed cache for every token whose accumulator had been evicted by the many
other per-token accumulators touched in between.

Move the `BulkContext` back into `PostingListBuilder`, paired with the accumulator
pointer in a `PromotedState` that is unioned with the now-dead inline buffer. It
then shares the cache line of the token's hash-map entry, which the per-row lookup
already warms, so the hot `context->container` load hits. The builder stays 56
bytes and trivially relocatable (`BulkContext` holds only a POD). `insert` now
takes the context by reference; `PostingListAccumulatorBitpacking` ignores it.

Isolated A/B (both RelWithDebInfo, interleaved, merges stopped, TRUNCATE per
measure): the `none` build for 5000 distinct tokens is ~8.5% faster; other sizes
and `bitpacking` are within noise.

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

Each posting list accumulator now defines a trivially destructible
InsertState struct holding the state its insert reads and writes on
every row: for the none codec the Roaring bulk-insert context and the
segment row counter, for bitpacking nothing. PostingListBuilder stores
it as opaque bytes in the promoted-state union (overlapping the dead
inline buffer, so the builder stays 56 bytes) and recovers the concrete
type in the templated add, so the builder no longer names any Roaring
type and bitpacking no longer takes an ignored context argument.

Moving the segment counter out of the heap accumulator also removes the
last per-row access to a cold cache line: the per-row path now touches
only the line warmed by the token hash-map lookup plus the Roaring
container itself, matching the access pattern of the pre-refactoring
code. Index files are byte-identical on both the insert and merge
paths; the `add` self-time profile is back at parity with master, and
inserts of real-world text become 5-9% faster for the none codec.

ClickHouse#106735

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

size_t PostingListAccumulatorNone::memoryUsageBytes() const
{
size_t result = current_segment.getSizeInBytes();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

memoryUsageBytes also needs to count the heap owned by the segments vector itself. Each sealSegment pushes a PostingList object into that vector; with a small allowed posting_list_block_size this can be one object per row, while the current accounting only adds each bitmap payload via getSizeInBytes. Please include segments.capacity() * sizeof(PostingList) so granule memory accounting sees the vector storage as well.

A CPU profile of the text index build with the bitpacking codec showed
that per-row bookkeeping dominates while the SIMD packing kernels are
only a few percent: the out-of-line call to insert of
PostingListCodecBitpackingImpl alone took 26% of the INSERT.

- Define insert inline in the header (including the accumulator shim)
  so the whole per-row chain folds into the templated
  PostingListBuilder::add; the segment-start branch is split into a
  cold out-of-line startSegment.
- Reorder the impl fields so everything insert touches per row
  (previous row id, both counters, the block buffer header) shares the
  first cache line of the object.
- Reserve the block buffer to BLOCK_SIZE once per accumulator.
- Grow compressed_data geometrically: the old policy reserved only the
  shortfall, reallocating and copying the whole buffer every couple of
  blocks, which made the build quadratic in the posting list size.
- Store segment descriptors and block metadata in absl::InlinedVector
  with one inline element: with the default posting_list_block_size
  almost every token has a single segment, and tokens with up to 128
  rows have a single packed block, so the common case needs no heap
  allocations and back() reads the accumulator object itself.

Index files are byte-identical on both the insert and merge paths.
Build time: -7.7% on the 5000-token synthetic workload, -5.1% on a
fineweb sample (single-threaded CPU samples -15.1% and -4.6%).

ClickHouse#106735

Co-Authored-By: Claude Fable 5 <[email protected]>
+ tokens_and_postings.capacity() * sizeof(SortedTokensAndPostings::value_type)
+ tokens_map.getBufferSizeInBytes()
+ posting_lists_size
+ accumulators_size

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

memoryUsageBytes now sums each accumulator payload, but it still omits the heap owned by the accumulators holder itself. This PR replaced posting_lists with one unique_ptr per promoted token, so large vocabularies can hide accumulators.capacity() * sizeof(std::unique_ptr<IPostingListAccumulator>) bytes from the writable granule accounting. Please add the holder storage alongside accumulators_size.

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 225/248 (90.73%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@CurtizJ

CurtizJ commented Jun 12, 2026

Copy link
Copy Markdown
Member Author

Continued in #107367.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant