Skip to content

Text index: size the read buffers of the posting lists according to expected read size - #121040

Merged
CurtizJ merged 26 commits into
ClickHouse:masterfrom
CurtizJ:text-index-cursor-postings-buffer-size
Oct 4, 2026
Merged

CurtizJ merged 26 commits into
ClickHouse:masterfrom
CurtizJ:text-index-cursor-postings-buffer-size

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

Closes #120409.

Changelog category (leave one):

  • Performance Improvement

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

Queries that use a text index read large posting lists faster and with fewer disk operations. The improvement is most noticeable for searches for frequent tokens in big tables.


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

Version info

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

groeneai and others added 8 commits September 16, 2026 16:25
MergeTreeIndexReader::initStreamIfNeeded built one MergeTreeReaderStream per skip
index substream and immediately positioned every one of them with
adjustRightMark() + seekToStart(). Both of those begin with
MergeTreeReaderStream::init(), and init() is the only place that opens the
substream's data file and allocates its read buffer; it is otherwise lazy, guarded
by `initialized` and reached from getDataBuffer(), seekToMark() and
seekToMarkAndColumn(). So the eager positioning was the sole reason a substream
file was opened at all.

A text index granule frequently reads none of its three substreams:
MergeTreeIndexGranuleText::deserializeBinaryWithMultipleStreams takes the header
from TextIndexHeaderCache and analyzeDictionaryForTokens returns early once
fillTokensFromCache has resolved every needle, which is the steady state for a
repeated or shared search term.

The stream now takes an optional initial right mark at construction and applies
adjustRightMark() + seekToStart() at the end of init(), after `initialized` is
set so the nested init() calls are no-ops. The position at first read is
therefore identical to what master produced eagerly: nothing between
construction and first use can move a stream; a caller's own seekToMark() runs
after the deferred block and wins, as it did on master; and adjustRightMark()
only ever widens, while getLastMark(all_mark_ranges) is the maximum, so the final
read bound does not depend on the order. This matters because the base
IMergeTreeIndexGranule::deserializeBinaryWithMultipleStreams, used by minmax,
set, bloom_filter, ngrambf_v1 and vector_similarity, performs no seek at all and
relies entirely on the caller having positioned the stream.

initStreamIfNeeded was the only construct-all-and-position-all site in the tree.
MergeTreeReaderWide::getStream, MergeTreeReaderCompactSingleBuffer::readRows and
the text index direct-read path already position at point of use, so this aligns
an outlier rather than adding machinery. Same class of change as 56f22cc
("Don't load marks and don't prefetch data of streams with an empty data file")
and 8aed5a9, both in this file.

The reported patch also skipped marks_loader->startAsyncLoad() for these
substreams. That half is not taken here. MergeTreeMarksLoader::loadMarksAsync
short-circuits on a mark cache hit without queueing anything, so in a warm
fixture the saving is mark cache lookups; on master startAsyncLoad() is followed
microseconds later by a blocking wait on the same future, so deferring the
positioning is what first gives the prefetch a real window (with a cold mark
cache this change raises LoadingMarksTasksCanceled from 30 to 273); and
load_marks_asynchronously defaults to true because synchronous mark loading costs
one network round trip per stream on remote disks, which a local MinIO cannot
measure honestly.

Measured on 400 Compact parts x 2000 rows with a text index, hasToken matching 5
of 800,000 rows, max_threads = 1: FileOpen 1201 -> 1 on the selective shape and
1600 -> 800 when nothing is pruned, with SelectedParts, SelectedMarks,
SelectedRanges, TextIndexHeaderCacheHits and TextIndexTokensCacheNegativeHits
identical in both builds. A 418-row correctness matrix over text, minmax, set,
bloom_filter, ngrambf_v1 and vector_similarity indexes, on-read and
planning-time analysis, one and four threads, bulk filtering on and off, plus
patch parts, is byte-identical between the two builds and agrees with the
use_skip_indexes = 0 oracle throughout.

Reported and first patched by @snelheidai in ClickHouse#120409.

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit deferred the positioning of a skip index substream's stream
to its first read, so that a granule answering from a cache no longer opens the
file. It left marks_loader->startAsyncLoad() in makeIndexReaderStream. This
removes it, along with the load marks threadpool plumbing it was the only user
of, and passes /*load_marks_threadpool=*/ nullptr instead.

The two belong together. On master startAsyncLoad() is followed, about ten
statements later in the same thread, by adjustRightMark() -> init() ->
estimateMarkRangeBytes() -> loadMarks() -> future.get(), so master queues a task
on the load marks pool and immediately blocks on it: the prefetch buys master no
overlap on any disk, but it does get consumed, which is how master's mark cache
fills in one query. Deferring the positioning without also removing the prefetch
takes that consumer away. ~MergeTreeMarksLoader then sets is_canceled and blocks
in future.wait(), the task throws ASYNC_LOAD_CANCELED before loading anything,
the marks never reach the cache, and the next query queues the same substreams
again. With a cold index mark cache that is a permanent queue-block-cancel loop:
about 280 to 400 canceled tasks per query, MarkCacheHits stalling below the
number of lookups, and a median of 85 ms and 127 ms in two runs of twenty
back-to-back selective queries where master is at 32 ms. Removing the prefetch
turns "queue on a pool thread and block" into "read inline": the same single
round trip per stream that is actually read, and none for a stream that is not.

Skipping the marks prefetch of a stream that will not be read is the established
direction here rather than a new risk. 56f22cc made startAsyncLoad()
conditional in MergeTreeReaderWide::addStream for a stream whose data file is
empty, because on object storage every marks file is a network round trip, and
8aed5a9 followed it. IMergeTreeDataPart::loadIndexMarksToCache, the other
place that loads skip index substream marks, already builds its loaders with no
threadpool, so this makes the two index mark paths agree. The rationale recorded
for defaulting load_marks_asynchronously to true names columns with many
substreams, which is the main reader: its constructor queues every column before
any read and does have overlap to lose. The setting keeps that meaning
everywhere else; it only becomes inert for index substreams. Measured on a cold
index mark cache, this change loads no more mark files than master on any shape,
and fewer on two: 400 against 1600 on the selective shape and 800 against 1600
when nothing is pruned, with LoadingMarksTasksCanceled back to zero in the
steady state.

MergeTreeIndexGranuleText::readPostingsBlock also called stream.getDataBuffer()
before consulting the postings cache, so a cache hit still opened the postings
file and loaded its marks. Reading the buffer inside the load_postings lambda
instead matches loadHeader directly above it and PostingListCursor::readSegment,
both of which already consult their cache first. With
use_text_index_postings_cache = 1 and text_index_posting_list_apply_mode =
'materialize', a second execution over 400 parts opens 400 files instead of 800
and performs 800 mark cache lookups instead of 1200, returning the same result,
so no index substream is opened at all once the postings are cached.

Measured on 400 Compact parts x 2000 rows with a text index, hasToken matching 5
of 800,000 rows, max_threads = 1, twenty back-to-back queries after dropping
both mark caches, optimized build:

    shape                  master        this change
    selective, 399/400 parts pruned
      FileOpen             1201          1
      median of last 10    32 ms         25 ms
      first query          490 ms        83 ms
    needle in every part
      FileOpen             1600          800
      median of last 10    50 ms         46 ms
    no text index predicate (control)
      FileOpen             400           400
      median of last 10    29 ms         31 ms

The control shape is identical code in both builds and moves by up to 20 percent
between runs, which is the band the nothing-pruned shape should be read against.
SelectedParts, SelectedMarks, SelectedRanges, TextIndexHeaderCacheHits and
TextIndexTokensCacheNegativeHits are unchanged, so no pruning decision moves.
TextIndexReadGranulesMicroseconds rises even where the query gets faster,
because init() now runs inside deserializeBinaryWithMultipleStreams, which that
counter wraps.

This supersedes the final paragraph of the previous commit, which argued for
keeping the prefetch. Its first ground, that the saving is only mark cache
lookups, does not survive an optimized build; its second, that deferring the
positioning gives the prefetch a real window, has the mechanism backwards, since
deferring removes the only consumer; and its third, the remote disk round trip,
points the other way once 56f22cc is taken into account.

Reported and first patched by @snelheidai in ClickHouse#120409.

Co-Authored-By: Claude Opus 5 <[email protected]>
The test that came with the previous two commits asserted the substream opens of
the deferred positioning, but nothing covered the readPostingsBlock change, and
two independent facts hid it. use_text_index_postings_cache defaults to false, so
MergeTreeIndexConditionText builds a fresh per-condition TextIndexPostingsCache
and every lookup misses, which means the load_postings lambda always runs. And
the selective token occurs in one row, so its cardinality of 1 is at or below
MAX_CARDINALITY_FOR_EMBEDDED_POSTINGS and its postings are embedded in the
dictionary, so that query never reads the postings stream at all. Hoisting
stream.getDataBuffer() back out of the lambda, which is the obvious way to undo
the change, left the whole suite green.

The third measured query uses the in-range token instead, whose cardinality of 8
is above that limit, with use_text_index_postings_cache = 1 so that the global
cache carries the block from an unmeasured warm-up into the measured execution.
It asserts FileOpen below one and a half opens per part: with the buffer inside
the lambda a cache hit opens no index substream and the count is the Compact
data.bin of each part, without it there is one wasted postings open per part.
Measured 30 against 60 at 30 parts, the same ratio as the 400 against 800 of the
optimized-build measurement, with TextIndexReadPostings at 0 on both sides. The
bound sits half way between the two, since the global cache is shared with
concurrently running tests and an exact count would flake.

That query also pins query_plan_direct_read_from_text_index. When the randomizer
draws 0, hasToken is evaluated on the column instead of being answered from the
index, each Compact part's data.bin is opened a second time, and the count lands
on the bound; four of fifty randomized runs draw it. The substream saving itself
is unaffected either way, 30 with the change and 60 without it under both values,
so this pins away a data read rather than the property under test.

The selective bound goes from one open per part to a third of that, ten times the
value observed across fifty randomized runs, so it now forecloses a regression
that opens a substream for even a third of the parts.

The performance test gains force_data_skipping_indices, as its sibling
text_index_lazy_apply.xml already carries in the same position. Both of its
queries stay valid and return the same sums if index analysis is declined, so
without it a silent loss of the target path would be reported as timings rather
than as a failure. The whole settings block, which perf.py applies to every
statement, was run over the create, both fills, both queries and the drop, and
none of them raises INDEX_NOT_USED or an unknown setting; after dropping the
index the query is refused with INDEX_NOT_USED as intended.

The comment on an unresolvable substream name said the missing file surfaces when
the file is opened, which on master meant at reader construction. It now happens
at first read, and a granule that answers entirely from its caches never reports
it at all.

Reported and first patched by @snelheidai in ClickHouse#120409.

Co-Authored-By: Claude Opus 5 <[email protected]>
`makeCursorPostingsInputStream` opens the postings stream that a cursor reads a
token through with a buffer sized to the token's largest segment instead of the
16 KiB that suits the dictionary lookups. The cursor reads a segment whole
(header, payload, block index), so with the small buffer a segment of several
hundred KiB cost a read syscall per 16 KiB. Segment sizes follow from the
consecutive offsets recorded in the dictionary entry; the last segment ends
where the next token's postings start, which the entry does not record, so a
single-segment list is estimated from its cardinality and row span (an
underestimate only costs a second read). The size is clamped between the
dictionary read buffer size and the query's regular read buffer size, so a
cursor stream never uses more than a column stream. Used by the per-token
streams of `MergeTreeReaderTextIndex`.

On a 100M-row table with the bitpacking codec, a four-token AND query takes
about 5x fewer read syscalls (201 instead of 1064).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`makeCursorPostingsInputStream` becomes `makePostingsInputStream` and takes the
number of bytes a reader consumes from one seek position instead of a token: the
buffer is clamped between the 16 KiB of `MergeTreeIndexReader::patchSettings` and
the regular read buffer size of the query, as before. Every reader of posting
lists now opens its stream through it:

- The per-token cursor streams of `MergeTreeReaderTextIndex` pass the estimated
  largest segment of the token, as before. The shared `small_postings_stream`
  that served the cursors and phrase tokens without a dedicated stream is gone;
  those tokens get their own sized stream on demand (`getPostingsStream`), kept
  in `other_postings_streams` so that the tokens the analysis left to read stay
  distinguishable by `large_postings_streams`.

- `MergeTreeIndexGranuleText::analyzePostings` reads single-segment lists whole
  and opens the stream itself, once the tokens are known, sized to the largest of
  them. `MergeTreeIndexDeserializationState` carries the reader settings for that,
  and `deserializeBinaryWithMultipleStreams` no longer requires a postings stream:
  `MergeTreeReaderTextIndex` and `ReadFromTextIndexCount` stop opening one before
  the analysis. `MergeTreeIndexReader` still opens one with the other substreams
  of the index format, which the text index leaves unused.

- `ReadFromTextIndexCount` reads the multi-segment lists left after the analysis
  through a stream sized to the largest segment among them.

- The merge of text indexes reads the postings of a source part in order, list
  after list, so its stream takes the regular read buffer size instead of the
  16 KiB meant for dictionary lookups.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The test pins the results of every path that reads posting lists through
`makePostingsInputStream` - the lazy cursors, the analysis of single-segment
lists, the count computed from the index and the merge of two parts - on
multi-segment and single-segment lists, with materialize mode as the control.
Its last query reads a single-segment posting list of about 300 KiB through a
lazy cursor and asserts that the query takes fewer than 8 read syscalls in
total, where the 16 KiB buffer took about 20 for the list alone.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…und from measurements

The test moves to 05233, past the numbers taken by tests in flight on other
branches. The lazy read of the 246 KB posting list takes 8 read syscalls with
this change and 23 without it: besides the list, the query reads the index
header, a dictionary block, the marks and the primary key, six reads in all,
and the list itself takes two reads through a buffer capped at the regular
local read buffer size of 128 KiB against fifteen through a 16 KiB one. The
bound is 12, below the old count with margin on both sides.

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

`MergeTreeIndexReader` opened a stream for every substream of the index format
and seeked each to its start, which loads the marks and opens the data file.
The text index granule reads its postings through a stream that
`MergeTreeIndexGranuleText::analyzePostings` opens itself once it knows the
posting lists it needs, and the positions only through the streams of
`MergeTreeReaderTextIndex`, so the two streams the generic reader opened for
them went unused, at the cost of an asynchronous marks load and a file open
per part. `MergeTreeIndexSubstream::isOpenedByIndexReader` names the substreams
the generic reader opens: the index itself and the dictionary.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@CurtizJ CurtizJ changed the title Text index cursor postings buffer size Text index: size the read buffers of the posting lists by what they read Sep 19, 2026
@CurtizJ CurtizJ changed the title Text index: size the read buffers of the posting lists by what they read Text index: size the read buffers of the posting lists according to expected read size Sep 19, 2026
@CurtizJ
CurtizJ marked this pull request as draft September 19, 2026 15:25
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b8d00cc]

Summary: ❌

job_name test_name status info comment
Build (amd_fuzzers) FAIL
Build ClickHouse FAIL cidb IGNORED
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) FAIL
05237_with_expression_alias_scope_descendant FAIL cidb IGNORED
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05257_sql_security_view_sealed FAIL cidb IGNORED
05213_timeseries_metric_families_target FAIL cidb IGNORED
03008_optimize_equal_ranges FAIL cidb IGNORED
04316_reader_executor_basic FAIL cidb IGNORED
02884_create_view_with_sql_security_option NOT_FAILED cidb IGNORED
01283_max_threads_simple_query_optimization NOT_FAILED cidb IGNORED

AI Review

Summary

This PR moves text-index dictionary/postings stream opening into the text-index reader/granule so unused substreams stay unopened, skips marks for single-mark skip-index streams, and sizes text-index posting-list buffers from the expected segment size instead of a fixed small buffer. I reviewed the current net diff together with the resolved inline threads and do not see any remaining correctness, resource-lifetime, or concurrency issues in the landed code; the targeted stateless coverage around lazy opens and reduced read syscall counts is enough to support the claimed local-file improvement.

Final Verdict
  • Status: ✅ Approve
  • No additional changes requested from code review.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 19, 2026
@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 Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b8d00ccbb with master 501d978d7 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Compile time of recompiled translation units

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

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

Job report

CurtizJ and others added 8 commits September 19, 2026 21:49
`05233_text_index_postings_stream_buffer` ended with a bound on
`ReadBufferFromFileDescriptorRead` for a lazy read of a large posting list. On
object storage the posting list is not read through a file descriptor at all,
so the counter measures unrelated local reads of the disk metadata: in
`Stateless tests (amd_llvm_coverage, s3 storage, DBReplicated, parallel, 1/3)`
the query made 16 such reads of 720 bytes in total and the bound of 12 failed,
reproducibly.

Split that last section into `05234_text_index_postings_stream_buffer_reads`
tagged `no-object-storage`, so the results of the read paths keep being checked
on every storage while the read count is pinned where it is meaningful. The new
test also pins `max_read_buffer_size_local_fs`, the cap the expected count is
derived from.

Measured locally on the table of the test: 23 reads with a 16 KiB postings
buffer, 8 with one sized to the segment.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121040&sha=1b20ab54827168e2a14bce6c74118497d3969e61&name_0=PR
Related: ClickHouse#121040

Co-Authored-By: Claude Opus 5 <[email protected]>
…ostings-buffer-size

Adapt to master: `makePostingsInputStream` takes the part info and resolves the
stream name and size from the checksums, like `makeTextIndexInputStream` now does
(a `DataPartStoragePtr` overload remains for the index merge), and the block
size comes from `IPostingListBlockCodec::BLOCK_SIZE`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A text index is written for the whole part and addresses its own data by
offsets kept in its header: the header is deserialized from the start of the
file, and dictionary and postings blocks are seeked to by offset. Its marks are
therefore never consulted. MergeTreeReaderStreamSingleColumn read them anyway,
because init() calls estimateMarkRangeBytes(), which calls loadMarks()
unconditionally, and getRightOffset(marks_count) then returns file_size
regardless. Granularity is forced to DEFAULT_TEXT_INDEX_GRANULARITY for type
text, so marks_count is 1 and the only mark value consulted is mark 0, used to
size the read buffer; MergeTreeReaderStreamSingleColumnWholePart returns the
same {file_size, file_size} with no IO. The other text index readers already
read these substreams that way, via makeTextIndexInputStream.

Every other skip index keeps its marks loader, its startAsyncLoad() and the
eager positioning exactly as before, so nothing about them changes: a regular
granule reads its substream through
IMergeTreeIndexGranule::deserializeBinaryWithMultipleStreams, which performs no
seek of its own and does need the marks.

Positioning the text index streams is left to the first read of each one, which
is what keeps the file of a substream that the granule never reads from being
opened at all: the header comes from TextIndexHeaderCache, and
analyzeDictionaryForTokens returns early once fillTokensFromCache has resolved
every needle.

The whole part stream requires one mark range covering the part, and the index
reader's own ranges repeat the single text index mark once per selected data
range, so the stream is given MarkRanges{{0, marks_count}}.
Resolves the makeIndexReaderStream signature conflict: the regular skip index
path keeps master's interruptible_marks_read argument, and readPostingsBlock
keeps master's deserializeToBitmap arguments with the buffer fetched inside the
postings cache miss.
The missing-stream comment claimed the original error behaviour is preserved,
which a text index substream that is opened on its first read no longer does
when the granule answers from its caches. The test's comment said both of its
first two queries read their postings, but the selective token has cardinality
1, so its postings are embedded in the dictionary block.
…arks

This branch stops a text index's substreams from loading their marks, so the two
arms of 04741_cancel_skip_index_marks_remote_read that assert a skip-index marks
read is interruptible had no marks read left to interrupt: both printed "the marks
read never reached the interruption point" in Stateless tests (arm_binary,
sequential), reproduced here byte for byte against this head.

The subject of those arms is the marks read of makeIndexReaderStream, which this
branch leaves byte-identical to master, so they now carry a tokenbf_v1 index on the
same column with the same hasToken query. Counting the interruptible gather-buffer
fills of one cold query over an s3_cache table with SYSTEM WAIT FAILPOINT and
SYSTEM NOTIFY FAILPOINT on remote_fs_gather_pause_in_read, which sits inside the
interruptible_reads opt-in so a fill can only pause when the marks reader asked for
it:

  carrier                            merge base   this head
  text index, as the arms had it     6            0
  tokenbf_v1 index, as they have it  8            8

That a text index reads no marks in either of its read paths is what
05218_text_index_substreams_opened_lazily asserts. query_plan_direct_read_from_text_index
no longer needs pinning off in these arms, since neither reads a text index.

Two fixture facts change with the carrier. A text index writes three substreams, so
its three marks files gave the first arm the second interruptible fill its
discriminator needs, while one tokenbf_v1 index writes a single marks file of 475
bytes at index_granularity 512: one fill, after which a read that ignored
cancellation would have finished rather than paused again, and the arm would have
passed for the wrong reason. index_granularity 64 makes that file 3119 bytes, and
filesystem_cache_prefer_bigger_buffer_size 0 stops the filesystem cache growing the
500 byte buffer up to prefetch_buffer_size and serving the whole file in one fill.
The premise is now asserted on the fixture instead of inferred from those two
settings, in the style of the arm's other preconditions.

Both directions, with settings randomization live (13 distinct max_block_size, 6
session_timezone, 4 max_threads over 745 queries): 10/10 OK on this head, OK on the
merge base, and a build with only query_status->throwIfKilled() removed from
ReadBufferFromRemoteFSGather::readImpl reddens the first arm with "the read paused
again after cancellation". index_granularity 512 reddens the new premise assertion
with its 475 byte measurement.

Co-Authored-By: Claude Opus 5 <[email protected]>
…to text-index-cursor-postings-buffer-size

Both PRs change how text index substreams are opened, so they are merged together:
the postings stream is already opened by `analyzePostings` with a buffer sized to the
expected read, and the remaining index and dictionary streams are now opened only on
their first read and without marks.

Related: ClickHouse#120481
Related: ClickHouse#121040

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`MergeTreeIndexReader` now opens only the `Regular` substreams. The text index
opens its dictionary stream itself during the analysis, like the postings stream,
which prepares for prefetching dictionary blocks through several stream copies.
`isOpenedByIndexReader` is removed, and `MergeTreeReaderTextIndex` and
`ReadFromTextIndexCount` no longer pass a dictionary stream.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
CurtizJ and others added 5 commits October 1, 2026 01:37
Rename `estimateLargestPostingListSegmentBytes` to `estimatePostingListBufferSize`
and never return less than 16 KiB, the default buffer size for postings.
Estimate a single-segment list as twice the bit width of its average gap
per posting instead of a formula with block overheads and clamps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`large_postings_streams` held both the streams of the tokens the analysis
left to read and served as the set of those tokens for
`buildPostingsForQuery`, so the streams of the other tokens (phrase tokens
whose lists the analysis folded already, cursors of tokens it no longer
needs) needed a second map, `other_postings_streams`.

Split the two jobs instead: `postings_streams` keeps every stream, opened on
first use by `getPostingsStream`, and `tokens_to_read` is the set of tokens
the analysis left to read, filled by `initializeTokensToRead`.

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

- `MergeTreeIndexReader` opens only the regular substream of an index. Any
  index with a single mark (a text index, built for the whole part, or a
  vector similarity index with a large granularity) is read to the end of its
  file through `MergeTreeReaderStreamSingleColumnWholePart` without loading
  its marks, instead of a separate text index path.
  `MergeTreeReaderStreamSingleColumnWholePart::seekToMark` accepts mark 0.
- `makePostingsInputStream` takes `expected_buffer_size`, the largest
  contiguous read after a seek.
- `MergeTreeIndexGranuleText::analyzePostings` computes the buffer size of
  the postings stream while collecting the tokens to read.
- Shorter comments.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Remove `MergeTreeIndexReader::patchSettings` and `makePostingsInputStream`.
`makeTextIndexInputStream` takes the substream and an explicit
`expected_buffer_size`, and derives the reader settings itself: `is_compressed`
from the substream type, and for the dictionary and postings a read buffer of
`expected_buffer_size`, but at least 16 KiB and at most the regular read
buffer size. `MergeTreeIndexReader` opens only the regular substream, so it
uses its settings as they are.

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

`expected_buffer_size` is now `std::optional<size_t>`: when it is not set, the stream
takes the regular read buffer size instead of being clamped. The merge reads the
dictionary and the postings of a source part sequentially, so it no longer lowers
the buffer size of the dictionary stream. Streams without an estimate (the sparse
index and the positions) pass `std::nullopt` instead of `0` or `DBMS_DEFAULT_BUFFER_SIZE`.

Also inline `MergeTreeReaderTextIndex::makeTextIndexStream` into its only caller.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@CurtizJ
CurtizJ marked this pull request as ready for review October 2, 2026 16:37
CurtizJ and others added 2 commits October 2, 2026 16:50
…eams

A skip index with a single mark is now read to the end of its file without
loading its marks (5f85b71), so the query creates one mmap read buffer less.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121040&sha=3b4f668dd853351e797afc27438dfe27e801c2b4&name_0=PR&name_1=Fast%20test
PR: ClickHouse#121040

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`readAllPostingsForToken` reads the whole posting list once, so it no longer
caches a stream in `postings_streams`. It reuses the token's existing stream
if there is one, otherwise opens a stream scoped to the call.

Related: ClickHouse#121040 (comment)

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

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes only how skip indexes and text indexes are read. Dictionary and postings streams now open on demand with sized buffers, and single-mark indexes skip loading their marks. The deterministic checks flagged no query. The only row reviewed was clickbench Q33 (-5.9%), which was left as no_change because the shift sits inside master's current range of run-to-run variation. That result is consistent with the diff: Q33 is an aggregation that reads no skip or text index, and its CPU time is unchanged. Neither benchmark exercises the text-index paths, so this run gives no evidence of a performance effect in either direction.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 66c6bb1d-2b5b-4132-b3d8-7f4cef5fe2e5
  • MIRAI run: f8784b1f-49e8-4177-b96b-caa957ed67ea
  • PR check IDs:
    • clickbench_3084787_1791048839
    • clickbench_3084793_1791048839
    • clickbench_3084804_1791048839
    • tpch_adapted_1_official_3084829_1791048839
    • tpch_adapted_1_official_3084843_1791048839
    • tpch_adapted_1_official_3084857_1791048839

@CurtizJ

CurtizJ commented Oct 3, 2026

Copy link
Copy Markdown
Member Author

Perf tests:
Screenshot 2026-10-03 at 17 30 30

I'll remove the test text_index_lazy_substreams.xml since there is a similar perf test with many parts already (text_index_count_stream_resolution.xml).

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

4 participants