Skip to content

Read a text index's substreams lazily and without their marks - #120481

Closed
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai-lazy-skip-index-substream-open
Closed

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai-lazy-skip-index-substream-open

Conversation

@groeneai

@groeneai groeneai commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120409
Related: #112588

Changelog category (leave one):

  • Performance Improvement

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

A text index substream's data file is now opened only when something reads it, and its marks file is not read at all. MergeTreeIndexReader prepared every substream of every analysed part up front and read one marks file per substream, which a text index never consults: it is written for the whole part and addresses its own data by offsets kept in its header. A hasToken search that answers from the index caches now touches neither. Other skip index types keep their marks loader and prefetch unchanged.

Description

MergeTreeIndexReader::initStreamIfNeeded calls adjustRightMark() and seekToStart() on every substream as it is created. Both start with init(), which opens the data file and, through MergeTreeReaderStreamSingleColumn::estimateMarkRangeBytes, calls loadMarks(). So each substream cost a file open plus a marks file read even when the granule read nothing from it, and a text index granule frequently reads none of its three: the header comes from TextIndexHeaderCache, and analyzeDictionaryForTokens returns early once fillTokensFromCache has resolved every needle.

Those marks are never useful for a text index. Granularity is forced to DEFAULT_TEXT_INDEX_GRANULARITY for type text, so there is one index mark per part and getLastMark(all_mark_ranges) == marks_count; getRightOffset then returns file_size after loading the marks, and the only mark value consulted is mark 0, to size the read buffer. MergeTreeReaderStreamSingleColumnWholePart returns the same {file_size, file_size} with no IO, which is how ReadFromTextIndexCount and MergeTreeReaderTextIndex already read these substreams, via makeTextIndexInputStream.

Text index substreams therefore use that stream with no marks loader, and their positioning is left to the first read of each one. Every other skip index keeps its marks loader, its startAsyncLoad() and the eager positioning, so nothing changes for them: their granules read through the base deserializeBinaryWithMultipleStreams, which performs no seek of its own and does need the marks.

readPostingsBlock also read the buffer before consulting the postings cache, so a cache-hit execution opened the postings file too.

TextIndexReadGranulesMicroseconds rises even where the query gets faster, because init() now runs inside deserializeBinaryWithMultipleStreams, which that counter wraps.

Measurements

Debug build, 30 Compact parts x 8 rows, max_threads = 1, load_marks_asynchronously = 1, text index caches warm, both mark caches dropped before every measured query (so every marks file needed is read), median of 3.

shape FileOpen LoadedMarksFiles BackgroundLoadingMarksTasks WaitMarksLoadMicroseconds
hasToken matching 5 of 240 rows 211 -> 31 120 -> 30 150 -> 44 37845 -> 0
needle in every part 240 -> 60 120 -> 30 150 -> 60 37341 -> 6669
minmax/set/tokenbf_v1, point lookup 6 -> 6 3 -> 3 3 -> 3 939 -> 884
minmax/set/tokenbf_v1, range 42 -> 42 18 -> 18 18 -> 18 4883 -> 5072

The removed opens and reads are exactly 6 per part: the 3 substream data files and their 3 marks files. The 30 marks files that remain are the main reader's own. The last two rows are the regression control for the other index types: every counter is identical, as is SelectedParts/SelectedMarks/SelectedRanges on all four shapes. Answers are identical on both arms. LoadingMarksTasksCanceled is 16 on the first shape against 0 on master, all of them the main reader's own marks prefetches, which that query now finishes before they are needed.

Whole text_index stateless suite, same server config on both arms: master fails 4, this head fails 3, and the difference is the new test. The 3 common failures need a cluster, process_query_plan_packet and test.hits, which this server does not have. The minmax suite is 72 passed and the same 3 such failures on both arms.

Reported, measured and first patched by @ snelheidai in #120409; the scope is theirs, the code shape mine. #112588 is the same waste for the main reader's data marks and stays open.


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

groeneai and others added 3 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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Sep 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Self-review record: 2 rounds, 0 blockers, 0 majors (no reviewer action needed)

Two review rounds against a second model. Round 1 bounced back to implementation, round 2 came out
clean. The src/ change drew no finding in any pass; every item below is about the tests.

Round 2 (clean): 3 agreed, all nits; 0 disagreed; 1 dropped

finding disposition
💡 The comment above the test's settings block says "the two queries below always read their postings". Only the in-range query does: the selective token has cardinality 1, so its postings are embedded in the dictionary. Agreed on the facts, nit. The setting it over-justifies is correct and independently needed for the in-range control's margin. Left as written.
💡 The performance test pins force_data_skipping_indices but not query_plan_direct_read_from_text_index, while its sibling pins both. Nit, no action: performance tests are not setting-randomized and the default is true, so this would only harden against a future default flip.
💡 The new assertion is a one-sided bound with no positive index-usage control of its own. Nit, no action: the same-run in-range control already fails if the fixture stops reaching the index, and TextIndexReadPostings = 0 would not close it either, since a bypass also yields 0.
⚠️ My own round-2 write-up describes the direct_read probe inconsistently, and the probe kept no output log. Dropped: nothing rests on it. tests/clickhouse-test:1893 randomizes that setting at ~5%, matching the 4 draws in 50 runs; master measures 60-or-120 on the same query and so loses in both regimes.

Round 1 (bounced): 5 agreed, 4 disagreed, 2 dropped

finding verdict
The readPostingsBlock hunk had no oracle: use_text_index_postings_cache defaults to false, making the postings cache per-query and always cold; and the selective token's cardinality 1 is below MAX_CARDINALITY_FOR_EMBEDDED_POSTINGS = 6, so its postings stream is never read. ❌ Agreed, raised independently by both passes. Fixed with a third query on the in-range token against a warmed global cache.
The performance test did not force the index, so a lost target path would surface as timings rather than a failure. ❌ Agreed. force_data_skipping_indices added, matching the sibling text_index_lazy_apply.xml.
The in-range control's ~2x margin came from an unpinned default. ❌ Agreed. use_text_index_postings_cache now pinned.
The selective bound < PARTS tolerated 29 spurious opens against a measured value of 1. ⚠️ Agreed in substance; tightened to < PARTS / 3. The prescribed "exact isolated delta" was refused as a flake risk under CI randomization.
Fixed query ids would emit duplicate rows on a re-run. ⚠️ Does not stand: tests/clickhouse-test:2445-2466 gives every testcase a fresh database unless --database is passed, no CI job passes it, and --test-runs N is N separate testcases. The prescribed LIMIT 1 BY query_id appears in 0 of the 30,566 files in 0_stateless.
The prefetch-removal half should be oracled too (mine). ⚠️ Withdrawn: no deterministic counter exists. LoadingMarksTasksCanceled races the pool thread and reads 37-316 on the shipping tree itself, so an == 0 assertion would flake. That half is proven by mark-load arithmetic and guarded end-to-end by the performance test.
The 50-run sweep may not have been randomized, since the log carries no marker (mine). ⚠️ Withdrawn on better evidence: query_log shows min_bytes_to_use_mmap_io taking 19 distinct values, the smallest being exactly the clamp floor. Absence of a log line is not evidence.
Stray .stdout/.stderr files (mine). ⚠️ Harness artifacts, matched by .gitignore:35, absent from git ls-files and from the diff.
💡 A missing or corrupt index substream file is now reported at first read rather than at reader construction, so a granule answered entirely from caches never reports it. No wrong results are possible: parts are immutable, and a cached negative answer was learned from a successful read of that same part. The comment at the call site was corrected to describe the new timing.

@clickhouse-gh clickhouse-gh Bot closed this Sep 16, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e0674f]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 3/6) FAIL Performance dashboard
array_first_last #3 FAIL dashboard
timeseries_to_grid_aggregation_functions #0 unstable query history
timeseries_to_grid_aggregation_functions #6 unstable query history
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
and_compare_chain_derived #2 FAIL dashboard

AI Review

Summary

This PR fixes the query-time waste in MergeTreeIndexReader by switching text-index substreams to a whole-part reader and by deferring postings-buffer initialization until the postings cache actually misses. That part looks coherent, but the change still leaves the supported prewarm_mark_cache lifecycle treating text-index substreams like ordinary skip indexes, so the PR’s “text-index marks are never read” contract is still incomplete.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Read a text index's substreams lazily and without their marks #120481#discussion_r4084472324] [src/Storages/MergeTree/IMergeTreeDataPart.cpp:981, src/Storages/MergeTree/MergeTreeData.cpp:4032, src/Storages/MergeTree/MergeTreeDataWriter.cpp:469] The query-time reader no longer needs text-index substream marks, but the supported prewarm_mark_cache paths still do. MergeTreeData::prewarmCaches still calls loadIndexMarksToCache, which eagerly reads every text-index substream mark file on attach, fetch, and SYSTEM PREWARM MARK CACHE, and MergeTreeTemporaryPart::prewarmCaches still injects the writer’s text-index marks into index_mark_cache on insert/merge. After this patch no text-index read path consumes those marks, so warmup still pays useless I/O and cache space, contradicting both the new invariant in MergeTreeIndexReader.cpp and the changelog text.
    Suggested fix: skip text indexes in the index-mark prewarm/population paths as well, then replace the current coverage that relies on those marks with a detector that exercises the remaining writer invariant directly.
Final Verdict

Changes requested. The reader-side optimization itself looks fine, but the prewarm_mark_cache lifecycle still loads or populates dead text-index marks, so the behavior promised by the PR is not yet implemented end to end.

LLVM Coverage Report

Measured on commit 7e0674f.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 66/66 (100.00%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 9bccc6d6-8c8d-45b4-b26d-43fea71f8d31
  • MIRAI run: b8af7bc9-fe28-4ae6-a7cd-b9b9c9bf4279
  • PR check IDs:
    • clickbench_1579826_1790212295
    • clickbench_1579832_1790212295
    • clickbench_1579838_1790212295
    • tpch_adapted_1_official_1579844_1790212295
    • tpch_adapted_1_official_1579860_1790212295
    • tpch_adapted_1_official_1579896_1790212296

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 291017a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan) / Logical error: GroupingAggregatedTransform pushed bucket A twice (STID 3994-4c1d) LOGICAL_ERROR in memory-efficient two-level aggregation, unrelated to a skip-index substream change: 84 legs over 65 pull requests and 9 distinct master commits in 30 days, so not caused by this diff #119814 (external, open)
Stress test (arm_tsan) / Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected 2, found 1 (STID 2270-3184) LOGICAL_ERROR on an AggregateFunction(countResample(10, 5, 1), UInt64, UInt64) state whose serialized form is zero bytes, so the source emits a chunk with one column where the header has two. Reaches master and 11 unrelated pull requests in 30 days #119728 (mine, open)
Build profile diff infra: the readiness probe reported No connection to LogCluster on every retry, so query() raised RuntimeError: CI logs cluster query failed before any comparison ran (ci/jobs/build_profile_diff_job.py:234). Nothing about this commit was measured #120121 (mine, open)
Mergeable Check rollup: red only because of the rows above, no independent failure #119814, #119728, #120121
PR rollup: red only because of the rows above, no independent failure #119814, #119728, #120121

Finish Workflow and CH Inc sync are green on this head.

Session id: cron:our-pr-ci-monitor:20260917-053047

@groeneai

Copy link
Copy Markdown
Collaborator Author

The description argues the object-storage case from counters, source and precedent rather than measuring it. It is measured now, on this head.

MinIO in its own network namespace, netem 20 ms RTT on that link only, 400 Compact parts x 2000 rows on an s3 disk, max_threads = 1, both mark caches dropped before every measured query, medians of 3, a second master server as the A/A null (<= 1.9%), and a no-text-predicate control that stays flat to 0.3%.

shape, text index tokens master this PR delta
hasToken matching 5 of 800,000, warm 26412 ms 3448 ms -86.9%
needle in every part, warm 58843 ms 38420 ms -34.7%
hasToken matching 5 of 800,000, cold 43610 ms 34773 ms -20.3%
needle in every part, cold 76060 ms 73701 ms -3.1%

No shape issues more S3GetObject calls or loads more mark files than master, and both arms match the use_skip_indexes = 0 oracle. The prefetch this PR removes was not hiding round trips: on master the 1200 index marks files cost 21.7 ms each at a 20 ms RTT, with 99.2% of the selective query spent in WaitMarksLoadMicroseconds, because init() reaches future.get() on the same thread that queued the load. Absolute times are 400 parts of cold marks serialised at one thread over a 20 ms link, so read the ratios. Single node, injected rather than real latency.

Method, counters and the rows this replicates from the reporter's own object-storage run: #120409 (comment)

Comment on lines -26 to -43
auto context = data_part_info->getContext();
auto * load_marks_threadpool = settings.load_marks_asynchronously ? &context->getLoadMarksThreadpool() : nullptr;

const auto & index_granularity_info = data_part_info->getIndexGranularityInfo();
auto marks_loader = std::make_shared<MergeTreeMarksLoader>(
data_part_info,
mark_cache,
index_granularity_info.getMarksFilePath(stream_name),
marks_count,
index_granularity_info,
settings.save_marks_in_cache,
settings.read_settings,
load_marks_threadpool,
/*load_marks_threadpool=*/ nullptr,
/*num_columns_in_mark=*/ 1,
settings.use_streaming_marks_compression);

marks_loader->startAsyncLoad();

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.

It may introduce a regression in the regular skip indexes.

Marks are not needed for the text index at all. Maybe we can handle a case for streams of text index and create MergeTreeReaderStreamSingleColumnWholePart for them like in makeTextIndexInputStreamImpl?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, and I will narrow it that way: text index substreams get a MergeTreeReaderStreamSingleColumnWholePart with no marks loader, while every other skip index keeps its marks loader, startAsyncLoad() and the eager positioning exactly as on master, so regular skip indexes are not touched by this PR at all.

For the text index it is also strictly better than deferring. Granularity is forced to DEFAULT_TEXT_INDEX_GRANULARITY for type text (getSecondaryIndexGranularity), so getMarksCountForSkipIndex returns one mark per part and getLastMark(all_mark_ranges) == marks_count. MergeTreeReaderStreamSingleColumn then reads the marks file and returns file_size from getRightOffset regardless, and consults mark 0 only to size the read buffer, which the whole part stream gives as {file_size, file_size} with no IO. So that marks read is waste even when the substream is read, and deferring alone does not remove it.

The other three text index read paths already do this: ReadFromTextIndexCount runs the same deserializeBinaryWithMultipleStreams over makeTextIndexInputStream streams, and MergeTreeReaderTextIndex uses them for postings and positions. MergeTreeIndexReader is the only one left.

One detail for whoever reads the next diff: the whole part stream asserts a single range covering the part, and for a text index index_ranges holds {0, 1} once per selected data range, so the stream is given MarkRanges{{0, marks_count}} instead of the index reader's own ranges.

I will push that and post the counters here.

Comment on lines -124 to -125
stream->adjustRightMark(last_mark);
stream->seekToStart();

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.

Why do we need this? Do adjustRightMark or seekToStart really triggers a GET request from the object storage?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Not for the index data file. prepareRead builds the buffer without reading it and the seek only moves the position: on an s3 disk with 20 ms RTT injected on the S3 port, master issues 1601 S3GetObject for 1600 LoadedMarksFiles, so the 1200 index substream files it opens and positions cost no request at all.

The marks are the cost. adjustRightMark begins with init(), init() calls estimateMarkRangeBytes, and MergeTreeReaderStreamSingleColumn::estimateMarkRangeBytes calls loadMarks() unconditionally: one marks file per substream per part whenever it is not already in the mark cache. Same rig, selective shape: LoadedMarksFiles 1600 -> 400, S3GetObject 1601 -> 401, and master spends 26.0 s of a 26.2 s query inside WaitMarksLoadMicroseconds for 1200 index marks files, 21.7 ms each at a 20 ms RTT, i.e. a serialized round trip per file even with load_marks_asynchronously = 1. On a local disk the cost is the open(): FileOpen 1201 -> 1.

Once the text index streams stop loading marks (your other comment), the premise of your question holds: the eager positioning then costs only the local open and the buffer, not a request. I keep it deferred for that reason alone, 1200 opens per query on the 400 part shape, and it is no longer a remote storage argument.

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.
@groeneai groeneai changed the title Open a skip index's substream files only when they are read Read a text index's substreams lazily and without their marks Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Narrowed as you suggested, in d21a74d: text index substreams are read with MergeTreeReaderStreamSingleColumnWholePart and no marks loader, and every other skip index keeps its marks loader, its startAsyncLoad() and the eager positioning exactly as on master, so the optional-right-mark plumbing in MergeTreeReaderStream is gone with it. Title, changelog and description are rewritten around that. Master is merged in as well; the branch had conflicted with the interruptible_marks_read signature.

Debug A/B against the merge base, 30 Compact parts x 8 rows, max_threads = 1, load_marks_asynchronously = 1, text index caches warm, both mark caches dropped before every measured query, median of 3:

shape FileOpen LoadedMarksFiles BackgroundLoadingMarksTasks WaitMarksLoadMicroseconds
hasToken matching 5 of 240 rows 211 -> 31 120 -> 30 150 -> 44 37845 -> 0
needle in every part 240 -> 60 120 -> 30 150 -> 60 37341 -> 6669
minmax/set/tokenbf_v1, point lookup 6 -> 6 3 -> 3 3 -> 3 939 -> 884
minmax/set/tokenbf_v1, range 42 -> 42 18 -> 18 18 -> 18 4883 -> 5072

The last two rows are the regression question answered directly: every counter identical, and so are SelectedParts, SelectedMarks and SelectedRanges on all four shapes. What disappears on the text shapes is 6 opens per part, the 3 substream data files plus their 3 marks files; the 30 marks files left are the main reader's own.

The whole text_index stateless suite and the minmax suite return the same pass set on both arms, with one difference: the new test fails on the merge base and passes here.

}

/// A text index is written for the whole part and addresses its own data by offsets kept in its
/// header, so its marks are never read. The other text index readers use makeTextIndexInputStream.

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.

The query-time MergeTreeIndexReader path is now marks-free for text indexes, but the supported prewarm_mark_cache lifecycle still is not. MergeTreeData::prewarmCaches calls IMergeTreeDataPart::loadIndexMarksToCache, and that function still iterates every secondary-index substream and eagerly loads its marks on insert, fetch, and attach. So tables with prewarm_mark_cache = 1 keep paying the useless .dct.idx / .pst.idx mark I/O and filling index_mark_cache with entries that no text-index read path uses after this change. If the new invariant is that text-index substream marks are dead, this needs the same special-case there too.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Mechanism confirmed, with one correction, and not changed in this PR.

Measured on this branch (build f0ea457a, a comments-only delta from the published head) against its merge base bf8170e7: 5 Compact parts, one text index, prewarm_mark_cache = 1, LoadedMarksFiles from system.query_log.

  • SYSTEM PREWARM MARK CACHE: 15 index mark files, identical on both arms (3 per part, the regular substream plus .dct and .pst, a fourth with params.positions). This branch does not touch that path.
  • The same text search with the index mark cache warm, then again with only SYSTEM DROP INDEX MARK CACHE in between: base 15, this branch 0. Those entries were consumed before this change and by nothing after it. A minmax table beside it reads 5 on both arms in the dropped run, so the counter is not blind.
  • The correction: an INSERT with prewarm_mark_cache = 1 reads 0 mark files on both arms. Insert and merge pass the writer's in-memory marks to addMarksToCache (MergeTreeDataWriter.cpp:481); the file-reading loadIndexMarksToCache is reached only from startup/attach (StorageMergeTree.cpp:238, StorageReplicatedMergeTree.cpp:595), from fetch (StorageReplicatedMergeTree.cpp:5827) and from SYSTEM PREWARM MARK CACHE. So the wasted I/O is on attach, fetch and the explicit statement, while insert and merge only add entries that nothing reads.

Not doing it here, for two reasons. This PR was narrowed to the text index read path earlier today at a reviewer's request. And the skip would silently retire existing coverage: 04326_text_index_empty_part_marks_prewarm (commit d1b06894d) guards a writer invariant for an empty merged part, and in its own fixture the attach prewarm reads 4 index mark files while its SELECT reads 0, on both arms, so that prewarm read is the whole detector. Skipping text indexes in loadIndexMarksToCache would make it pass whether or not the writer regresses. The prewarm side therefore wants its own PR, with a replacement detector and removeIndexMarksFromCache made symmetric, and that is how I am carrying it.

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 7e0674f9 for the one red check on the previous head, which is PR-caused: Stateless tests (arm_binary, sequential) / 04741_cancel_skip_index_marks_remote_read, a test of mine.

Its first two arms assert that a skip index marks read from object storage is interruptible, and they used a text index as the carrier. After the narrowing a text index reads no marks, so there was nothing left to interrupt and both arms reported the marks read never reached the interruption point. Reproduced locally byte for byte against the pushed head.

The arms now carry a tokenbf_v1 index on the same column with the same hasToken query, so they exercise the marks read of makeIndexReaderStream, which this PR leaves as master has it. Interruptible gather-buffer fills of one cold query, counted with SYSTEM WAIT FAILPOINT and SYSTEM NOTIFY FAILPOINT on remote_fs_gather_pause_in_read (that failpoint sits inside the 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, 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.

Both directions with settings randomization live: 10/10 OK on this head, OK on the merge base, and a build with only query_status->throwIfKilled() removed reddens the first arm with its own distinct message. One tokenbf_v1 marks file is 475 bytes at index_granularity 512, which a single 500 byte fill covers, so the arm would have passed without testing cancellation: index_granularity 64 and filesystem_cache_prefer_bigger_buffer_size 0 keep the second interruptible fill its discriminator needs, and that premise is now asserted on the fixture rather than left to those settings.

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7e0674f9a with master a9f15582e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 455029b82; 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

13 translation units recompiled, 49 s compile time in total, 13 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 +3.7 s (+8%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7e0674f

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (amd_release, master_head, 3/6) / array_first_last #3 false red of the dashboard gate. 3 too long, 1 slower, 2 unstable; 1 confirmed regression(s) on the performance dashboard, +16.2% on an 8.6 ms query. This PR cannot reach that query: its only source changes are MergeTreeIndexReader.cpp and MergeTreeIndexText.cpp, and the fixture's three tables are ENGINE = Memory with no skip index declared, so no index reader is ever constructed for them #121847 (merged 2026-09-23 23:29Z), measured absent from the tree this job actually built (45b9155b3fe2), plus ClickHouse/performance-comparison#5 for the dashboard's confidence scoring, which its author names as where noisy queries are handled
Performance Comparison (arm_release, master_head, 6/6) / and_compare_chain_derived #2 same class, and here the shard's own report does not agree: 3 too long, 1 unstable; 1 confirmed regression(s) on the performance dashboard, with no slower query, so the dashboard verdict was the only red-maker. That query measures slower on 112 and unstable on 96 distinct pull requests over 30 days, master included #121847 (merged 2026-09-23 23:29Z), measured absent from the same tree, plus ClickHouse/performance-comparison#5 for the dashboard side
Mergeable Check, PR rollup: red only because of the two rows above, no independent failure #121847, ClickHouse/performance-comparison#5

All 176 checks completed (158 pass, 14 not selected), Finish Workflow and CH Inc sync green, the
last one at 06:50:24Z. CIDB carries no FAIL or ERROR row on this head.

Master merge deliberately not pushed now. #121847 is genuinely absent from the tree these jobs built (45b9155b3fe2, 0 hits for a symbol it introduces, against 0 pre-fix and 4 at the fix and 4 on live master), but neither mechanism it fixes fired here.
Both job logs show historical-thresholds.tsv present and consumed with no threshold-fetch warning,
and the shards ran 05:09 to 06:02 UTC, so its local-time date rollover cannot apply either. The half
that reddened them is the dashboard's scoring, which is fixed service side, so picking up #121847
would restart about five hours of CI without reliably clearing either row.

Session id: cron:our-pr-ci-monitor:20260924-070110

CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Sep 25, 2026
…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]>
@CurtizJ

CurtizJ commented Sep 25, 2026

Copy link
Copy Markdown
Member

I'll include changes from this PR into #121040.

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 comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

2 participants