Repository navigation
Let a text index reader serve incomplete granules - #120517
Conversation
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.
|
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 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.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260917-055700 |
|
Workflow [PR], commit [fb760e0] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict
LLVM Coverage ReportMeasured on commit fb760e0.
Changed lines: Changed C/C++ lines covered: 37/44 (84.09%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (1 of 43)
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
|
CI finish ledger - c1747bcEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260917-113202 |
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units9 translation units recompiled, 37 s compile time in total, 9 of them have a recent master baseline. |
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]>
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]>
…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]>
Related: #120456
Changelog category (leave one):
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 hardfalse, andcreateReadersChainANDs it over the main reader and every prewhere reader, where it gates zero-tail trimming inReadResult::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. Thefalsewas load-bearing:readRowsadvancedfrom_markunconditionally, so it assumed each call starts at a mark boundary.This makes the reader mark-boundary-safe, then delegates the flag:
from_markonly when it is finished, so a mid-mark continuation resolves against the right mark's postings;from_mark - 1once advancement is conditional;true, which keeps Compact parts correct (their reader isfinal { 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_sizedown to 1, lightweightDELETE/UPDATE,FINAL,ORandNOT, 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, withRowsReadByMainReaderin brackets.SelectedMarksis 64 of 128 on both sides: granule exclusion already worked, so this is intra-granule waste only and the saving is additive to it.ts, payload WHERE hasTokenargMax(payload, ts) WHERE hasToken+ AND payload LIKE '%ffff%'message LIKE '%needle%'ts, payload, match at a random offsetcount()tsonlyts, messageORDER BY ts DESC LIMIT 10... OR payload LIKE ...NOT hasTokenoptimize_move_to_prewhere = 0Workflow [PR]
Sync PR [sync-upstream/pr/120517]
Version info
26.10.1.1209-master(included in26.10and later)