Skip to content

Add a maintained ReadPlan to the experimental ReaderExecutor - #115816

Merged
CheSema merged 48 commits into
masterfrom
reader-executor-read-plan
Sep 24, 2026
Merged

CheSema merged 48 commits into
masterfrom
reader-executor-read-plan

Conversation

@CheSema

@CheSema CheSema commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Introduces a maintained ReadPlan to the experimental ReaderExecutor (gated by use_reader_executor, default off). It resolves the residency of a look-ahead span once and holds the pinned hit-readers and miss-writers across serves, instead of re-resolving the cache chain on every read window. The plan grows right (extend) and retires the consumed prefix left (retireBefore) as the cursor advances.

  • Drives the resolve. extend asks every cache layer itself (fastest-first), matched to held tiers by CacheTier - "all layers asked" is the plan's invariant.
  • Owns the read geometry. runAt(offset) returns a std::variant: ServeFromReader, ServeFromWriter, ServeFromMemory, Fetch, or std::monostate. A Fetch extent is coalesced right to the nearest resident byte (capped at the window), extended left to each covering segment's write frontier, and widened to cover any whole-segment cell it enters (all-or-nothing fill).
  • fetchFillServe reads that extent once, fills the tiers, serves one block, and parks the bytes no tier accepted (bypass / detached / rejected write) in the plan's memory hold - served first, freed as the cursor passes, never re-read.
  • Writer-less misses (no cache / read-only / detached) are read from source, not populated; their residency is a snapshot of the held span.

Builds on the cache-provider API simplification in #116092 (merge first). Look-ahead is reader_executor_plan_look_ahead (default 16 MiB, at least reader_executor_block_size).

Schema and walkthrough: #115816 (comment)

Related: #116092
Related: #103706

Changelog category (leave one):

  • Experimental Feature

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

The experimental ReaderExecutor resolves cache residency once into a maintained read plan (configurable via reader_executor_plan_look_ahead) instead of re-resolving on every read window.


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

Version info

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

Add ReadPlan: resolve the cache residency of a look-ahead span once, hold the
pinned hit-readers and miss-writers, and answer per-offset which tier serves an
offset - coalescing consecutive misses (across cells and tiers) into one fetch
run - via runAt/writersFor, growing the span on the right and retiring the
consumed prefix on the left as the cursor advances. Adds IntervalSet::ranges
for the committed-range query. Unit-tested in gtest_read_plan; not yet wired
into the executor.
Replace the per-window cache resolve in readThroughCaches with the maintained
ReadPlan: ensureResolved resolves the look-ahead span once (Options
plan_look_ahead, default 16 MiB) into the held plan; readThroughCaches serves
one block per window from the tier runAt reports (hit reader, committed
writer, or a coalesced miss); fetchAndServe reads a miss run in one capped
source request and populates every populating tier. The plan grows right and
retires the consumed prefix as the cursor advances. Serve semantics are
unchanged - the existing executor tests pass; only the resolve is now held
across windows instead of repeated per window.
Expose the ReaderExecutor look-ahead as an experimental setting (default
16 MiB), validated to be at least 4 KiB like the other reader_executor_*
sizes, mapped through ReadSettings into the executor Options. Add the
settings-history entry.
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [629784f]

Summary: ❌

job_name test_name status info comment
Stress test (arm_msan) FAIL
MemorySanitizer: use-of-uninitialized-value (STID: 0250-1463) FAIL cidb
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
json_to_string #0 FAIL dashboard

AI Review

Summary

This PR adds a maintained ReadPlan to the experimental ReaderExecutor, so cache residency is resolved once and then reused across windows, with a new reader_executor_plan_look_ahead setting controlling how far ahead the plan is held. The plan machinery and test coverage are much stronger now, but two review concerns remain: bounded reads still resolve and pin well past read_until, and the new cache-get metric / modeled-cost KPI still undercount page-cache probes, so I do not think this is ready to merge as-is.

Findings

⚠️ Majors

  • [src/IO/ReaderExecutor.cpp:420-429] [dismissed by author -- https://github.com/Add a maintained ReadPlan to the experimental ReaderExecutor #115816#discussion_r4064579446] ensureResolved still uses pos + look_ahead for both dropAfter and the refill target even when the current read_until bound is much smaller. That means a bounded PipelineReadBuffer::setReadUntilPosition call can still create and hold page-cache pins / filesystem-cache segments for bytes the caller is not allowed to return. This is externally visible shared-cache pressure, not just an internal optimization choice, and it persists until the next read or destruction because setReadUntil itself does not trim the held plan. Suggested fix: clamp the resolved span to the current physical bound (or otherwise trim the held plan immediately when the bound shrinks) before resolving ahead, and handle any future “fetch past the bound for cache fill” work as a separate follow-up.
  • [src/IO/ReaderExecutor.cpp:443] ReaderExecutorCacheGetRequests increments once per provider per extend, but PageCacheProvider::resolve probes one block at a time and does one cache->get per block. With the default 1 MiB page blocks and 16 MiB look-ahead, one extend can do 16 page-cache gets while the counter rises by 1, so ReaderExecutorModeledCostMicroseconds becomes systematically optimistic on page-cache-heavy reads. Suggested fix: move CacheGetRequests accounting into the providers, or make resolve report the number of underlying probes so the executor can charge the actual count.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Measured on commit 629784f.

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: 261/275 (94.91%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Aug 21, 2026
Grow the plan only once less than half the look-ahead remains ahead of the
cursor, then resolve up to the full length - replacing the per-window top-up
with fewer, larger resolves.
Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/ReadPlan.cpp Resolved
When the head block is uncommitted and a concurrent downloader owns it on every
populating tier, fetchAndServe now waits for that download (CacheWriter::waitAndRead)
and serves the block from cache instead of re-reading the same bytes from source;
on a wait timeout it falls back to a source read of just the head block. The
decision is head-based, so a role held on a later block of a coalesced miss run
does not force a re-read of a concurrently-downloaded head. Adds gtests for both
the wait-served and the timeout-fallback paths.
Drop the head_is_ours tracking: with one coordinating cache tier in practice,
wait whenever a concurrent downloader leads the head block. Still a single
iteration - wait once, then serve from cache or fall back to one source read
of the head block; no waiting/reclaiming loop.
When the wait for a concurrent downloader times out, try once to claim the
head's role (the downloader may have released it) so the coalesced fetch below
populates the cache; if it committed meanwhile, serve that. If it is still led
elsewhere, the source read serves the bytes without a write. One attempt, no
waiting/reclaim loop.
Handle each tier in one pass over the writers: serve a committed head prefix
from cache, wait once on a head segment a concurrent downloader leads and serve
it if it lands, otherwise take the download role for the fetch. Fetch from
source only after the pass. Replaces the separate post-loop wait/re-claim block.
The tiers() helper took std::vector<PlanTier> and was called with a braced
list, copying the move-only PlanTier - a clang-diagnostic-error under the tidy
build (RelWithDebInfo tolerated it). Make it variadic/forwarding and drop the
braces at the call sites.
@CheSema

CheSema commented Aug 21, 2026 •

Copy link
Copy Markdown
Member Author

How ReadPlan works (updated)

ReadPlan drives the resolve: extend asks every layer itself (fastest-first), matching resolved tiers to held tiers by CacheTier — "all layers asked" is the plan's invariant, not a caller loop.

Held span, grows right / retires left as the cursor advances

        retireBefore(P)                 position P                 extend() refills to full
        releases consumed pins              │                     once < half remains ahead
                                            ▼
   ── retired ──][=========================================================]── not resolved ──
                 ^ spanStart                held ReadPlan span              ^ resolvedEnd
                                       [P .............. P + plan_look_ahead)

Per tier, one resolve() cell per segment (a hit owns a reader; a populating miss owns a writer; a read-only / detached miss has neither):

   page (whole-segment):  Hit[0,1)  Miss[1,2)  Miss[2,3)  Hit[3,5)   ...
   fs   (incremental):    Miss[0,1) Miss[1,2)  Hit[2,3)   Miss[3,5)  ...

runAt(P) returns a std::variant of the run serving P — and for a Fetch, the exact extent one source read must pull:

   ServeFromMemory → read from the plan's in-memory hold (already fetched, no tier took it) — served FIRST
   ServeFromReader → read from that tier's reader (a hit)
   ServeFromWriter → read from its writer (a miss committed since resolve)
   Fetch           → range = [fetch_start, fetch_end):
                       • right : coalesce to the nearest resident offset, capped at the window
                       • left  : down to each covering segment's committed frontier
                                 (below P when a read opens mid-segment; a whole-segment
                                  cell's frontier is its start)
                       • whole-segment head cell → out to its full end (all-or-nothing write)
   std::monostate  → P is past the resolved span (nothing to serve)

fetchFillServe — fetch the extent once, fill, serve one block:

   one pass over the writers (fastest-first):
     • committed prefix at P        → serve from cache
     • a concurrent downloader leads → waitAndRead once; serve from cache if it lands
     • else                          → take the download role (fill below)
   read [fetch_start, fetch_end) from source once → write the tiers we hold
   serve [P, P+block); hand the un-served bytes NO tier accepted (read-only / detached /
     rejected write) to the plan's memory hold — served first by a later runAt, freed as
     the cursor passes — a cold, all-writer-backed read holds nothing

So the resolve is done once per span and reused across many windows; the plan alone decides both ends of every source read (never re-reading a resident block, always covering a whole segment it must fill); and a writer-less miss (no cache / read-only / detached) is read from source, not populated, and keeps its snapshot residency for the held span.

The cache-provider API this builds on (committed() as a size_t, claimLeadRole() → Claim, fillsWholeSegment(), writer-less misses) is split into #116092.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 629784f1d with master 04f90b3b6 (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.

Object file sizes

263 object files changed (+58.24 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/IO/ReadPlan.cpp.o new 40.87 KiB +40.87 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

4039 translation units recompiled, 18495 s compile time in total, 4037 of them have a recent master baseline.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper ProfileEvents::global_counters_storage 12.56 MiB 12.62 MiB +64.00 KiB (+0.50%)
programs/clickhouse ProfileEvents::global_counters_storage 12.56 MiB 12.62 MiB +64.00 KiB (+0.50%)

Job report

The experimental `ReaderExecutor`'s plan-driven read filled a cell only over
`[pos, window)`, so a whole-segment tier (page cache) got a partial write and
stored nothing, and an incremental filesystem-cache segment opened mid-segment
was written off its frontier and dropped. Both left the cache unpopulated, so the
warm read went back to source - failing `04511_reader_executor_disk_cache` and
`test_reader_executor_page_cache`.

`ReadPlan::runAt` now returns the full source-read extent of a FETCH run:
coalesced right to the nearest resident offset (capped at the window), extended
left to each covering segment's committed frontier (below `pos` when a read opens
mid-segment), and out to a whole-segment head cell's true end. `fetchFillServe`
(renamed from `fetchAndServe`) reads that extent once, fills the tiers it spans,
and serves one block.

Also simplifies the cache-writer interface: `committed` returns the `size_t`
frontier instead of an `IntervalSet`, `claimLeadRole` returns just a `Claim`
(availability is read via `committed`), and `CacheWriter::fillsWholeSegment`
lets a writer report its own segment discipline. All head resolution
(serve-committed, or wait-for-downloader) runs in the single pass over writers.
Comment thread src/IO/ReadPlan.cpp Resolved
…ases

A coalesced fetch that bridges a segment no tier can cache (a read-only or a
detached tier) used to discard those bytes and re-read them when the cursor
arrived. Retain the un-served, un-cached part of each fetch in memory and serve
it on the next windows; it is freed as the cursor passes, and a cold read (every
cell writer-backed) holds nothing. Bounded by the window.

Adds `ReaderExecutor` gtests for the writer-less read paths - no cache, a
read-only (bypass) tier, and a detached segment - and documents that a
writer-less miss keeps its snapshot residency within the held span: it is not
re-probed, because such misses are rare (a full or detached cache) and re-probing
would add pressure to a cache that already had no room. Also makes the multi-layer
(page + filesystem) whole-cell fetch's correctness-over-fewest-bytes trade-off
explicit in the comments.
Comment thread src/IO/ReaderExecutor.cpp Resolved
`fetchFillServe` ignored what the cache accepted: it assumed a claimed writer
cached its whole range and, worse, built the retained set AFTER resetting the
claims (the `if (c.claim)` guard was always false), so it held the entire
un-served extent and never accounted for a rejected write. Record what each tier
actually committed (`committed()` after the write, which reflects no-disk-space or
a reservation failure) and retain only the un-served bytes no tier accepted, via
`cached.subtract(unserved)`.

Adds a `ReaderExecutor` gtest for a rejected write (mock `reject` state): the block
is served from the retained fetch, not re-read from source, and stays uncached.
Comment thread src/IO/ReadPlan.cpp Resolved
Bytes a fetch pulled that no tier accepted (a read-only or detached tier, or a
rejected write) were kept in a private `held_fetch` buffer, with a manual serve
fast-path and trim in `readThroughCaches`/`seek`. Move that hold into `ReadPlan`:
`runAt` serves it first as a `from_memory` run, `hold`/`readMemory` store and serve
it, and `retireBefore` frees the passed part - one lifecycle with the cache pins.
The executor just asks the plan; `fetchFillServe` hands the rejected set to `hold`.

This removes the executor-side range math and is the memory support the prefetch
slice needs (it will drop its uncacheable remainder into the same hold). Adds a
`ReadPlan` gtest for the memory hold; existing gtests and 04511/04930/page-cache
stay green.
`readThroughCaches` now retires up to the end of the block it just served, so the
block's cache pins and memory hold are freed at the end of its window instead of
one window later (at the next `ensureResolved`). The served bytes are independently
owned by the returned buffer, so dropping the plan's refs is safe; `ensureResolved`
still retires a region a forward jump skipped.
A coalesced FETCH can enter a later whole-segment (page) cell and stop inside it at
the window boundary. `runAt` only widened `fetch_end` for the cell covering the head,
so that later cell got a partial write, which a whole-segment tier rejects - it never
landed in cache and was re-read when the cursor reached it (an extra source request).
Widen `fetch_end` to the end of ANY whole-segment miss cell the fetch straddles
(fixpoint; converges on cell boundaries, one step for a single page tier).

Adds a `ReaderExecutor` gtest (a window stopping mid the second page block now costs
one source read with both blocks cached) and gives the mock writer
`fillsWholeSegment()` so it faithfully models a whole-block cache.
Condense the doc and inline comments accumulated over the ReadPlan review series
into short "why" notes: drop restatement and method docs duplicated between header
and definition, keep the non-obvious invariants. No behavior change.
`claimLeadRole` is called per-writer and every caller passed the writer's own
segment range; `PageCacheWriter` ignored it and `DiskCacheWriter` used it only to
clamp to its own segment (a no-op). Availability is read via `committed()`. Drop
the parameter - `claimLeadRole()` acquires the role for the writer's one segment.
Add two ReaderExecutor gtests:
- a file-level page block straddling two StoredObjects is fetched whole across the
  boundary, cached, and the object is read from source once (no re-fetch);
- a faster-tier hit over a slower-tier miss reads the whole file from source to fill
  the slower tier - correct, documenting the stacked-layer C-case is not the fewest
  source bytes (a gather path would read only the gap).
Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/ReaderExecutor.cpp Resolved
…populate"

`populatesOnMiss()` duplicated the per-cell signal the plan already uses: a bypass
(read-only) tier emits writer-less misses, which `writersFor` and `runAt` skip via
their `cell.writer` checks - exactly like a detached or rejected cell. Remove the
virtual and `PlanTier.populates`; each provider's `resolve` reads its own bypass
setting directly to pick `get` vs `getOrSet`. "Do not populate" is now one signal
(a writer-less miss), covering bypass, detached, and rejected identically.
…s block

The `reader_executor_plan_look_ahead` entry was recorded in the `26.8`
block. CI evaluates the pull request merged with master, where the
current version is `26.9`, so the style check requires new settings in
the current-version block. Move the entry into a `26.9` block.
`reader_executor_window_size` and `reader_executor_block_size` stay in
`26.8`; they are already recorded there on master.
…cutor

Add an incremental mode to the mock cache provider so a tier can model
append-only filesystem-cache fills, and add three tests for how the read
executor reuses a long connection over the cache path:

- page cache (whole-segment) reuses one connection across windows;
- filesystem cache (incremental) reuses one connection across windows;
- a stacked faster-hit over slower-miss tier stays correct, even though
  its partial-residency fill collapses into a single source read and
  opens no long connection.
Comment thread src/IO/ReadPlan.cpp Resolved
Comment thread src/IO/ReadPlan.h Resolved
Comment thread src/IO/ReadPlan.h Resolved
Comment thread src/IO/ReadPlan.h Resolved
Comment thread src/IO/ReadPlan.h Resolved
Comment thread src/IO/ReadPlan.h Resolved
Comment thread src/IO/ReadPlan.cpp Resolved
Comment thread src/IO/ReadPlan.cpp Resolved
Comment thread src/IO/ReadPlan.cpp Resolved
Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/ReadPlan.cpp Resolved
@CheSema

CheSema commented Sep 18, 2026 •

Copy link
Copy Markdown
Member Author

Also question from Kssenii: when the memory cache allocates: at resolve or at insertion?
if at resolve -- then we hold mem for all look ahead range, that bad
if at insertion -- then it is good and it could reject it at insertion, RE is prepared to this case, or at least we do not hold much and after we pass further the cache could evict.

PS:
PageCache::get is a RO call, it does not allocate the page.
Allocation happens in write.

On a read we pin the data in caches for look ahead window and hold it until window passes over the segments.

CheSema and others added 7 commits September 21, 2026 14:34
The read plan holds every cache cell it resolved until the cursor passes
it, so the look-ahead span is also the bound on what a single reader
pins: page-cache cells cost memory, and a held filesystem-cache segment
is not releasable, so it blocks eviction. `Context::getReadSettings`
validated only the lower bounds, so any value was accepted.

This answers the review question about limiting the held segments. The
bound belongs on the span in bytes, which covers every cache tier at
once, rather than on a per-resolve segment count, which reaches only the
filesystem cache and never binds at the default geometry.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The plan holds every cache cell it resolved until the cursor passes it,
so the look-ahead span is what one reader pins. The window and the block
already track the memory-pressure level; the look-ahead did not, so the
largest holder was the one that never shed.

`sampleWindowSizes` now derives `plan_bytes` through
`PLAN_LOOK_AHEAD_REDUCTION` ({1, 2, 8, 32} - gentler than the window,
because re-resolving a cell costs a cache probe per tier), floored at the
live block so `plan_look_ahead >= block_size` holds at every level. At the
16 MiB default that is 16 / 8 / 2 / 0.5 MiB.

`ReadPlan::dropAfter` gives back the span the smaller look-ahead no longer
covers. Without it the shrink would only stop growth, and since the window
shrinks too, a span resolved under `Normal` would stay pinned for as long
as the pressure lasted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`ReadPlan::extend` deduped whole cells: any cell starting before the held
end was skipped. But `resolve` reports a segment from its own start, so a
re-returned cell can reach past that end. Dropping it whole left the bytes
past the old `resolvedEnd` with no covering cell while `span_end` advanced
over them, so `runAt` fetched from source what the refill had just seen in
cache.

Two shapes hit this. A writer-less tier
(`read_if_exists_otherwise_bypass`) reports a hit as the segment's
committed prefix, which grows when a concurrent downloader commits more.
And a partial segment resolves as two cells from one start - the prefix
hit, then the whole extent carrying the writer - so the hit set the held
end and the writer cell behind it was dropped, leaving that segment's tail
fetched from source and never written back to the cache.

Dedup the bytes instead of the cell: skip one already wholly held, clip one
that straddles to its uncovered suffix. Cells stay disjoint and ordered,
and a clipped cell's reader or writer keeps its full segment range, which
`CacheReader::range` already allows.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review feedback on the plan's public names.

- `coversForward` -> `contains`, and it is now actually called.
  `ensureResolved`'s discontinuity test spelled the same predicate out
  by hand, so the accessor had no caller at all.
- `spanStart` / `resolvedEnd` -> `begin` / `end`.
- The covered region is a range, not a span: `span_start` / `span_end`
  -> `range_start` / `range_end`, with the prose following.
- `retireBefore` -> `dropBefore`, so it pairs with `dropAfter`.

The call site drops its `empty()` test, which `contains` subsumes: an
empty plan has `range_end <= range_start`, so no offset is contained.

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

Review feedback.

- `ChainedBuffers::contains(offset)` replaces `covers(ByteRange{offset, 1})`
  at the memory-hold check. The `!empty()` guard goes with it: `covers` is
  already false on an empty chain.
- `runAt` computes `fetch_end` and `fetch_start` in one pass over the tiers.
  The serve walk above them stays separate - it returns on the first tier
  that can serve, so folding the geometry in would compute it on every hit
  and then discard it.
- `runAt`'s doc drops from six lines to two.
- `max_fetch_ahead` -> `fetch_limit`. It is a byte count bounding one
  `Fetch`, unrelated to the plan's look-ahead, and `max_` read like a
  tunable constant.
- Its default argument is gone. Only tests relied on it; the one production
  caller always passed a value, and the default was
  `numeric_limits<size_t>::max()`, whose failure mode - an unbounded fetch
  from a caller who forgot the argument - is silent rather than a compile
  error. Tests pass `NO_LIMIT`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`dropBefore` and `dropAfter` each took an offset and used it twice: to
move a boundary, and as the cut line for a hand-rolled scan. Each scan
had its own shape - one hunted a leading run of consumed cells, the
other a trailing run - so the rule "a held cell lies inside the range"
was written twice and stated nowhere.

Both now move their boundary first and call `dropCellsOutsideRange`,
which erases every cell not overlapping `[range_start, range_end)`.
That predicate is the union of the two old rules, and a straddling or
overhanging cell still overlaps, so it survives as before.

The memory hold stays one-sided per method. Held bytes can legitimately
sit past `range_end`, because `runAt`'s whole-segment widening pushes
the fetch end beyond the cap; `dropAfter` frees them to relieve memory
pressure, while `dropBefore` must keep them, since not re-reading
already-fetched bytes is the point of the hold.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Master bumped the version to 26.10 in c9ae3d3 and opened a 26.10
block in SettingsChangesHistory.cpp. This branch recorded
`reader_executor_plan_look_ahead` under 26.9, which stopped being the
current block, so the settings_changes_history style check failed on the
merged tree from 2026-09-16 onward. Move the record to 26.10 as part of
the merge - master rewrote the same file, so it cannot be split out.
Comment thread src/IO/ReadPlan.cpp Resolved
Comment thread src/Common/ProfileEvents.cpp Resolved
Review feedback, both on text I wrote.

`reader_executor_plan_look_ahead` was documented as bounding what a
reader holds. It does not: a cache pin covers a whole segment or block -
`DiskCacheReader` holds a `FileSegmentPtr`, `PageCacheReader` a
`MappedPtr` - so a cell straddling either end of the range stays pinned
entire. Clipping `cell.range` narrows what the plan serves, never what it
holds, and dropping a straddler would force a source re-read of bytes
that are in the cache. The span therefore drives the hold rather than
capping it, with up to one overhanging segment or block per tier at each
end.

`ReaderExecutorConcurrentDownloadWaitTimeouts` claimed every counted wait
meant the query advanced at the downloader's pace. It is incremented on
any return short of the requested overlap, including the empty one that
falls through to `readSource` - the opposite case.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/IO/ReaderExecutor.cpp Resolved
CheSema and others added 2 commits September 22, 2026 16:53
`reader_executor_plan_look_ahead` got a 40 MiB ceiling while
`reader_executor_block_size` kept only a floor, and the pre-existing
`plan_look_ahead >= block_size` rule then made any `block_size` above
40 MiB unsatisfiable. `getReadSettings` runs for every query, so such a
configuration failed everything, including queries that never touch the
executor.

Put window, block and look-ahead in one `[128 KiB, 40 MiB]` band instead,
checked by a single helper. The ceiling can no longer create an
unsatisfiable pair, because `block_size` cannot exceed it either.

This rejects `reader_executor_window_size` and `reader_executor_block_size`
above 40 MiB, which were previously accepted. Deliberate: the settings are
EXPERIMENTAL and one coherent band is worth the break.

`MAX_READER_EXECUTOR_PLAN_LOOK_AHEAD` becomes `MAX_READER_EXECUTOR_SIZE`,
the counterpart of `MIN_READER_EXECUTOR_SIZE`, and the test is renamed
`05212_reader_executor_max_size` to mirror `04604_reader_executor_min_size`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
One conflict, in the `26.10` block of SettingsChangesHistory.cpp: master
appended `analyzer_compatibility_allow_cte_redefinition` where this branch
had appended `reader_executor_plan_look_ahead`. Kept both.
Comment thread src/IO/ReaderExecutor.cpp
const size_t hi = lo + piece.size;

/// The plan resolves every layer itself (all tiers asked, matched by CacheTier).
stats.add(Stats::CacheGetRequests, cache_chain.size());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ReaderExecutorCacheGetRequests and the modeled-cost KPI are described as counting cache get operations, but this increments once per provider per extend, not once per underlying probe. With the default 1 MiB page-cache blocks and a 16 MiB look-ahead, PageCacheProvider::resolve does 16 cache->get calls here while the counter only grows by 1.

That makes both the new lookup counter and ReaderExecutorModeledCostMicroseconds materially optimistic on page-cache-heavy reads. I think the accounting needs to move into the providers, or resolve needs to report how many cache lookups it actually performed.

One conflict again, same place: master appended
`parallel_replicas_for_queries_with_multiple_tables` to the `26.10` block
of SettingsChangesHistory.cpp where this branch had appended
`reader_executor_plan_look_ahead`. Kept both, and moved our row to the top
of the block - the collision only happens because both sides append at the
end, and the position within a version block carries no meaning.
@CheSema
CheSema added this pull request to the merge queue Sep 24, 2026
Merged via the queue into master with commit eeec29e Sep 24, 2026
170 of 173 checks passed
@CheSema
CheSema deleted the reader-executor-read-plan branch September 24, 2026 14:00
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@CheSema @kssenii — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@clickhouse-gh clickhouse-gh Bot added comp-io IO library: ReadBuffer / WriteBuffer and their implementations over files and memory, read and wr... and removed comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-io IO library: ReadBuffer / WriteBuffer and their implementations over files and memory, read and wr... pr-experimental Experimental Feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants