Skip to content

Let a text index reader serve incomplete granules - #120517

Merged
CurtizJ merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai-text-index-incomplete-granules
Oct 1, 2026
Merged

CurtizJ merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai-text-index-incomplete-granules

Conversation

@groeneai

@groeneai groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120456

Changelog category (leave one):

  • Performance Improvement

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

A query that searches a text index and also selects a column no index covers no longer reads that column for every row of every granule the index selected. On a 1M-row table with a 1055-byte payload and 64 matching rows, SELECT ts, payload FROM t WHERE hasToken(message, 'needle') now reads 578 KiB instead of 532 MiB.

Description

Reported by @ snelheidai in #120456 with a candidate patch.

MergeTreeReaderTextIndex::canReadIncompleteGranules() returned a hard false, and createReadersChain ANDs it over the main reader and every prewhere reader, where it gates zero-tail trimming in ReadResult::countZeroTails. So once a text index is read on the data path a granule can only be dropped whole, never truncated, and its 8191 non-matching rows are still materialized. The false was load-bearing: readRows advanced from_mark unconditionally, so it assumed each call starts at a mark boundary.

This makes the reader mark-boundary-safe, then delegates the flag:

  • clamp each read to the current mark's last row and advance from_mark only when it is finished, so a mid-mark continuation resolves against the right mark's postings;
  • clean up posting blocks against the last mark actually processed, which is no longer from_mark - 1 once advancement is conditional;
  • delegate rather than return true, which keeps Compact parts correct (their reader is final { return false; }, so this is a no-op there).

Not included: the reported planner half, typing the index read step as a Filter. Alone it is byte-identical to master on all 14 shapes measured, since the filter it creates has nothing to trim by until this reader change lands; on top of this it adds one shape, optimize_move_to_prewhere = 0. Whether that path should carry a new planner heuristic is yours to decide.

Validation: 1451 answers across table shapes, predicates, granularities, max_block_size down to 1, lightweight DELETE/UPDATE, FINAL, OR and NOT, all byte-identical to master. The new test fails on master and passes here, 50/50 randomized runs.

Peak query memory rises 5.9% on the shape that gains least, a match at an arbitrary offset in its granule (71.20 to 75.42 MiB at max_threads = 4), and falls over 99% on a concentrated match.

Per-shape numbers (1M rows, 1055-byte payload, 64 matches, max_threads=1, median of 5)

read_bytes, with RowsReadByMainReader in brackets. SelectedMarks is 64 of 128 on both sides: granule exclusion already worked, so this is intra-granule waste only and the saving is additive to it.

query master this PR
ts, payload WHERE hasToken 532.00 MiB [524288] 578.31 KiB [64]
argMax(payload, ts) WHERE hasToken 532.00 MiB [524288] 578.31 KiB [64]
+ AND payload LIKE '%ffff%' 530.00 MiB [0] 578.06 KiB [0]
message LIKE '%needle%' 532.00 MiB [524288] 578.31 KiB [64]
ts, payload, match at a random offset 532.00 MiB [524288] 340.25 MiB [335159]
common token, 747 rows 1.04 GiB [1048576] 1.00 GiB [1012188]
count() 16 B [0] 16 B [0]
ts only 2.50 MiB [524288] 512.25 KiB [64]
ts, message 42.17 MiB [524288] 517.65 KiB [64]
ORDER BY ts DESC LIMIT 10 1.13 MiB [90122] 98.45 KiB [21]
... OR payload LIKE ... 1.04 GiB [524288] 1.04 GiB [64]
NOT hasToken 1.04 GiB [1048576] 1.04 GiB [1048576]
optimize_move_to_prewhere = 0 532.00 MiB [524288] 532.00 MiB [524288]

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

Version info

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

groeneai and others added 2 commits September 17, 2026 05:49
MergeTreeReaderTextIndex::canReadIncompleteGranules() returned a hard false, and
MergeTreeReadTask::createReadersChain takes the AND of that flag over the main reader and every
prewhere reader before handing the single result to all of them, where it gates zero-tail trimming
in ReadResult::countZeroTails and countZeroTailsFromSparse. So as soon as a text index is read on
the data path, a granule can only be dropped whole and never truncated: the filter a text predicate
produces has 8191 trailing zeros per match, yet the main reader still materializes all 8192 rows.
On the reporter's fixture (1,048,576 rows, 1055-byte payload, 64 matching rows) SELECT ts, payload
WHERE hasToken(message, 'needle') reads 532.00 MiB instead of 578.31 KiB, and RowsReadByMainReader
is 524288 instead of 64. Enabling the index costs 8192x more wide-column rows than not using it: on
the four-granule table of the new test, master reads 16384 rows of the wide column with
query_plan_direct_read_from_text_index = 1 and 2 rows with it set to 0.

The false was not gratuitous. readRows advanced from_mark unconditionally, so it assumed every call
starts at a mark boundary, which the flag guaranteed. Returning true without the rest of this
change makes the virtual column come back the wrong length: measured on a mutation arm, the server
aborts in ReadResult::checkInternalConsistency with 'column->size() == num_rows'.

So the reader is made mark-boundary-safe first. Each iteration is clamped to the current mark's
last row and from_mark advances only once that mark is finished, so a read that continues inside a
mark still resolves against that mark's own postings. The posting-block cleanup at the tail of
readRows then has to change with it: it erases every block that does not intersect the range it is
handed, and from_mark - 1 named the last mark read only while advancement was unconditional. Once
advancement is conditional, an unfinished read leaves from_mark on the current mark M, so
from_mark - 1 names M-1 and the cleanup erases the blocks for M that the immediate continuation
needs. Keying it on the last mark actually processed is the same mark whenever the mark finished,
and the right one when it did not; on a mutation arm that keeps from_mark - 1, a mid-mark read
re-fetches 18 posting blocks it had just loaded, and none at a mark-aligned block size.

canReadIncompleteGranules() then delegates to the main reader rather than returning true, because
MergeTreeReaderCompact::canReadIncompleteGranules() is final { return false; }. Delegating keeps
the chain flag false on compact parts, where this optimization is a no-op.

The reporter also proposed typing the index read step as a Filter in the planner. Measured on its
own that half is byte-identical to master on all 14 shapes: the filter it creates has nothing to
trim by while the chain flag is false. On top of this change it adds exactly one shape,
optimize_move_to_prewhere = 0, where the text predicate stays in WHERE and never enters the chain.
Whether that path should carry a new planner heuristic is a maintainer's decision, so it is left
out here.

Correctness is unchanged: 1451 answers over 4 table shapes, 18 predicates, index_granularity 8 and
32, GRANULARITY 1 and 3, one- and two-part tables, max_block_size from 1 to 100000, parts smaller
than a single granule, lightweight DELETE and UPDATE with patch parts, two text indexes in one
query, FINAL, OR, NOT and _part_offset projections are byte-identical to master and all match a
use_skip_indexes = 0 oracle. Peak query memory falls by more than 99% when the match sits early in
its granule and rises 5.9% when it sits at an arbitrary offset (71.20 MiB to 75.42 MiB at
max_threads = 4), which is the one regression this trades for.

The new stateless test measures the fix with RowsReadByMainReader rather than bytes or elapsed time,
pins min_bytes_for_wide_part = 0 so the part cannot be Compact, and pins both prewhere settings,
since either one off keeps the text predicate out of the readers chain and would make the assertion
fail. It sums the ids it returns, so that a match moved to a neighbouring row of the same granule is
caught and not only a wrong row count, and it asserts that the plan carries the __text_index_* column
at all, so a future planner change cannot make it pass without reading the index. It also requires
TextIndexReaderTotalMicroseconds to be nonzero, the only witness in the tree that
MergeTreeReaderTextIndex served the step and not the plain reader a step falls back to when the index
is not materialized in a part. It is tagged no-parallel-replicas because with
parallel_replicas_local_plan = 0 the initiator reads no rows itself and the counter lands in the
replica's own query_log row, so the assertion reads 0 while the answers stay correct.

The performance case fills the wide column with hex that does not compress. With a single repeated
byte the shape measures nothing: ReadCompressedBytes comes out identical on both sides, because the
rows that are read and discarded cost no decompression. With an incompressible payload the same
query reads 534 MB against 4.6 MB, and 466 ms against 64 ms on a debug build.

Related: ClickHouse#120456

Co-Authored-By: Claude Opus 5 <[email protected]>
Keep the addressing invariants, drop the narration of the change: the per-mark
postings note loses the sentence about a previous read stopping mid-mark, the
conditional mark advance loses its restatement of that note, the cleanup note
loses the back-reference to last_processed_mark, and the header note loses the
clause that repeats the returned expression.
@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 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

On the timing I said I would re-measure before publishing (#120456): the one wall-clock pair in the commit message ("466 ms against 64 ms") is a debug-build measurement, and I am not publishing a local optimized number, because a wall-clock figure from my build host would be noise. The measurement of record for the shipped case is this PR's own Performance Comparison run of tests/performance/text_index_wide_column_read.xml; the byte, row and mark counters in the description are build-independent.

Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 full pass + 3 delta rechecks; 4 findings), plus 4 rounds of cold review of the resulting code by a reviewer that does not edit it. The last two passes returned 0 findings, and the two source files have been byte-identical for the last three rounds. The branch is a single commit amended across rounds, so every fix below is in the published head.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test could pass without the text index reader being constructed, because use_skip_indexes_on_data_read is randomized and unpinned AGREE, fixed The test now asserts that the plan carries a __text_index_* column and that TextIndexReaderTotalMicroseconds is nonzero for the logged query; that event has exactly one increment site in the tree. Randomization is per run, so the 50 passing randomized runs exercise both values.
2 ⚠️ The EXPLAIN assertion proves only that the optimizer synthesized the virtual column, not that the index reader served the step (raised in two rounds) AGREE, fixed Same runtime witness as row 1, so a per-part fallback to a plain reader can no longer satisfy the row count silently.
3 ⚠️ The commit message published a wall-clock pair with no build class AGREE, fixed Message-only amend: the sentence now leads with the two build-independent byte counters and names the build. See the line above this block.
4 💡 The perf fixture comment said 61 matching rows; the fixture generates 62 AGREE, fixed Both token counts recomputed from the fixture.
5 💡 The Compact-part comment claimed the assertions would pass vacuously there, when they would fail AGREE, fixed It now states that the fixture pins Wide parts because a Compact reader keeps complete granules.
6 💡 The witness comment named the second column; the witness is the third AGREE, fixed One word.
7 💡 The witness is a truncating microsecond timer, so it could read 0 on a faster build DISAGREE Measured rather than argued: 30 repetitions per shape give a minimum of 9 microseconds and no zero runs, and truncation predicts fewer microseconds from more and smaller calls while the probe measures the opposite (max_block_size 8192 gives 10 microseconds, 3000 gives 12, 100 gives 172, 1 gives 38). Every count-based alternative is cache-fed and reads 0 on a warm server.
8 💡 No oracle guards the posting-block cleanup being keyed on the last mark processed instead of from_mark - 1 DISAGREE Its only observable effect is refetching blocks already loaded (18 of them on a mutation arm that keeps from_mark - 1), and the natural counter oracle is randomized over text_index_posting_list_block_size. Correctness of that path is covered by the 1451-answer comparison against master.
9 💡 The no-parallel-replicas tag reason does not cite the source of the behaviour it describes DISAGREE A tag reason should state the observed effect, not carry file citations that go stale; the observation behind it was measured at both values of parallel_replicas_local_plan.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260917-055700

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

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fb760e0]

Summary: ✅


AI Review

Summary

This PR makes MergeTreeReaderTextIndex safe to continue inside a mark, then propagates canReadIncompleteGranules from the wrapped reader so zero-tail trimming can finally drop non-matching row tails instead of forcing full-granule materialization. I reviewed the current diff, the surrounding MergeTreeRangeReader contract, and the existing PR discussion, and I did not find an unresolved correctness, compatibility, or performance-safety issue in the head revision.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit fb760e0.

Metric Baseline Current Δ
Lines 88.30% 88.20% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.60% -0.10%

Changed lines: Changed C/C++ lines covered: 37/44 (84.09%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 17, 2026
@groeneai
groeneai requested review from CurtizJ and Ergus September 17, 2026 06:36
@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 17, 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 35 queries analysed

This PR only changes MergeTreeReaderTextIndex, the reader for full-text index virtual columns. It lets that reader start or stop a read in the middle of a granule and keeps its row and mark positions in step. The rest of the diff is tests. The one flagged result, a -12.4% improvement on ClickBench Q31, is downgraded to not_sure: Q31 is a filtered GROUP BY on a table with no text index, so it never runs the changed reader, and its CPU time was unchanged (2816 vs 2834 ms). No query in clickbench or tpch_adapted_1_official uses a text index, so these benchmarks cannot show this PR's performance effect in either direction.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 31 not_sure 274 240 -12.4% <0.0001 aggregation: This PR only changes the full-text index reader, and the ClickBench hits table has no text index, so this GROUP BY scan never runs the changed code. CPU time is flat (2816 to 2834 ms), so the -12.4% wall-time drop is not backed by less work.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: e297104f-3dc6-4812-b1e0-73f39bdc846f
  • MIRAI run: aae81bea-b49d-48d0-9443-497ac2027a91
  • PR check IDs:
    • clickbench_2623850_1790820038
    • clickbench_2623856_1790820038
    • clickbench_2623867_1790820038
    • tpch_adapted_1_official_2623878_1790820038
    • tpch_adapted_1_official_2623913_1790820038
    • tpch_adapted_1_official_2623927_1790820038

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c1747bc

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
Build profile diff CI infra, not this diff: build_profile_diff_job.py:234 raises RuntimeError: CI logs cluster query failed from compare_symbols (:1405) when the binary_symbols read fails. Broad, not specific to this PR: 393 distinct PRs and 593 error rows over 7 days, 0 on master, spiking from 2026-09-15. #120121 (mine, open)
PR praktika rollup reflecting the row above, no independent failure #120121 (mine, open)

Mergeable Check and Finish Workflow both passed, so nothing on this head blocks mergeability.
161 of 177 checks passed and 14 were skipped: the full build matrix, all 7 AST fuzzer flavours,
all 4 BuzzHouse flavours, every Stateless, Integration, Stress, Upgrade and Unit test job.
No test-level failure was recorded anywhere on this head.

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

alexey-milovidov and others added 3 commits September 26, 2026 02:55
05233_text_index_lazy_brute_force_early_exit and
05234_text_index_lazy_brute_force_narrow_window expect
TextIndexLazyBruteForceEarlyExits to stay at zero for intersections whose
posting lists have rows in every mark. That holds only while every read
covers whole marks. A text index reader now serves incomplete granules on a
Wide part, so a max_block_size that is not a multiple of index_granularity
ends a read inside a mark: the rest of that mark becomes a separate window,
and a window with no rows of one of the posting lists exits early. The
results are unaffected, only the counter moves.

CI hit this on 05234 with min_bytes_for_wide_part = 0, where the default
max_block_size of 65409 already cuts a mark. 05233 fails the same way on a
Wide part with max_block_size 8193, 10923 or 16385. Pin max_block_size =
8192 in both tests, so that every read is one mark on any part type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eads

Now that `readRows` may stop inside a mark, `current_mark` can stay on a
partially read mark:

- Reset the forward-only lazy cursors on backward jumps by comparing rows
  (`from_row < current_row`) rather than marks, so re-reading a half-read mark
  from its start does not reuse cursors positioned past it.
- Throw `LOGICAL_ERROR` when the read position is outside the current mark
  instead of silently returning fewer rows, which would truncate the result.
- Keep `current_mark` the mark containing `current_row` in the early return
  for empty `res_columns`, instead of unconditionally incrementing it.
- Rename the flag member to `can_read_incomplete_granules` and remove the
  `text_index_wide_column_read` performance test.

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

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fb760e010 with master aa370dbfd (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 253f06071; 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

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

Job report

@CurtizJ
CurtizJ added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit 2f70ab6 Oct 1, 2026
149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
@alexey-milovidov alexey-milovidov mentioned this pull request Oct 5, 2026
1 task done
alexey-milovidov added a commit to amosbird/ClickHouse that referenced this pull request Oct 5, 2026
ClickHouse#120517 made
`MergeTreeReaderTextIndex::canReadIncompleteGranules` follow the main reader, and
`MergeTreeReaderTextProjectionIndex` inherited it. Its `readRows` still walks whole
marks, so a read starting inside a mark returned a wrong row count: wrong `count()`
in release builds and a `RangeReader read N rows, but M expected` exception in debug
builds (`03800_projection_text_index_hint_map`).

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93114&sha=13ac949ab297fe63913a1c38c29aba00996f342a&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 12, 2026
Since ClickHouse#120517 the text index reader serves incomplete granules, so with
a random `max_block_size` below 65536 (and prewhere off) one granule of
`tab_container` is read in several slices. Slices of one granule share
the cached intersection, which is correct, but it made the negative
control report a reuse in 4 of 20 randomized runs. Pin `max_block_size`
to the granule size so the control keeps checking that whole granules
of different containers never share an intersection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 12, 2026
…ainer

Since ClickHouse#120517 the reader serves incomplete granules, so the one-container
check on the read slice also let slices of granules spanning several
Roaring containers into the cached path. Check the whole granule instead,
which keeps those granules on the previous code as measured.

The test now also checks that a granule spanning two containers read in
1024-row slices and a single-token search never reuse an intersection;
reverting either check makes its line fail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants