Skip to content

Read-through filesystem cache for the experimental ReaderExecutor - #110029

Merged
CheSema merged 75 commits into
masterfrom
reader-executor-disk-cache
Aug 14, 2026
Merged

CheSema merged 75 commits into
masterfrom
reader-executor-disk-cache

Conversation

@CheSema

@CheSema CheSema commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

First of two PRs adding a read-through cache to the experimental use_reader_executor
read path (default off), split out of the ReaderExecutor series (#103706), after
decryption (#109702). This PR adds the cache-provider interface and the filesystem cache
tier; the page cache and the richer, coordinated driver follow in a second PR.

Adds ICacheProvider and the FileCache-backed DiskCacheProvider, consulted and
populated per read window. The interface and provider are adopted from #103706's redesigned
head: a whole-range resolve(object, offset, range) returns the window's residency as an
ordered list of Resolutions in one cache transaction — each hit carrying a CacheReader,
each populating miss carrying its open CacheWriter (a read-only/bypass tier returns
writer-less misses). The executor drives it with the simplest possible per-window loop:
resolve the window start, serve a cache hit straight from the tier's buffer (zero-copy),
or on a miss claim the covering cell(s), fetch from the source, populate, and serve one
block. The miss read goes through the long connection, so a cold sequential scan streams
from one held connection; the window is returned as a ChainedBuffers (block-chunked) and
decrypted per node on an encrypted disk.

Concurrent readers of the same cold cell elect a single downloader via a claim taken
before the fetch, so only one populates each cell; a cell another reader is already
downloading is fetched through from the source (its populate lands zero bytes) rather than
waited on. Coordinated waiting arrives with the page cache PR.

Scope of this PR:

  • The filesystem cache serves known-size sources only — an FS cache is never attached to
    an unknown-size object, so the cache path is never entered for one. The executor's
    handling of unknown-size sources is otherwise unchanged from master.
  • No page cache, no cross-window plan, no prefetch, and none of ReaderExecutor: pipeline-based read orchestration #103706's plan machinery
    (ResidencyIterator, CoverageMap, MemoryPressureMonitor).
  • ChainedBuffers is functionally unchanged from master (only a couple of over-long comments trimmed).
  • Everything is gated behind use_reader_executor; the executor also falls back for the
    distributed cache and async prefetch, which it does not implement.

New settings: reader_executor_window_size (serve window, 4 MiB) and
reader_executor_block_size (buffer chunk, 1 MiB), each at least 4 KiB (rejected at
settings load otherwise).

Tests: 04511_reader_executor_disk_cache (an s3_cache MergeTree) asserts the executor
engages and consults the filesystem cache; 04604_reader_executor_min_size asserts the
sub-4-KiB window/block rejection; IO gtests cover the executor, the provider, and the
offset map.

Related: #103706
Related: #109702

Changelog category (leave one):

  • Experimental Feature

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

Added a read-through filesystem cache to the experimental ReaderExecutor read path (use_reader_executor, disabled by default).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Add a per-window cache chain to the experimental `use_reader_executor` read
path (default off). At each window the executor probes the chain top-down,
serves a full hit and promotes it into the faster tiers that missed, or on a
miss reads the range from the source once -- aligned to the top tier's segment
boundary -- populates every tier, and serves the requested slice.

New `ICacheProvider` (per-window `tryRead` / `write` / `missAlignment`) and
`CacheChain`; `ReaderExecutor::serveThroughCaches` is wired into
`readNextWindow`, gated by an empty-by-default chain so the production path is
unchanged. This is a deliberately simpler abstraction than the plan-then-stream
cache design; the FileCache-backed provider and pipeline wiring follow.

gtests cover full-hit (no source read), cold-miss populate + warm re-read,
segment-aligned miss fetch, and hit promotion to a faster tier.
@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d99bc0a]

Summary: ✅


AI Review

Summary

This PR adds the filesystem read-through cache layer for the experimental use_reader_executor path, along with the new reader_executor_window_size / reader_executor_block_size settings and coverage for the basic cold/warm flow. The default path stays unaffected, but the executor cache path still drops one existing read contract and still leaves two cache/long-connection inefficiencies in supported configurations, so I would not merge it as-is.

Missing context / blind spots
  • ⚠️ The Praktika performance-comparison shards were skipped because the PR is not labeled pr-performance, so the remaining cache-hierarchy concerns are only code-reviewed. A focused benchmark or regression test on use_reader_executor = 1 would close that gap.
Findings
  • ⚠️ Majors
    [src/IO/ReadPipeline.cpp:228,248] ReadPipeline still carries read_hint in LocalFileSource / ObjectStorageSource, but the executor path drops it when it constructs LocalSourceReader / ObjectStorageSourceReader. That changes buffer sizing and read-method selection under createReadBufferFromFileBase / IObjectStorage::readObject: a small read on a large file can now allocate the large-file buffer or cross the mmap / O_DIRECT thresholds purely because use_reader_executor forgot the hint. Suggested fix: store read_hint in the source-reader wrappers and pass it through on every open.
    [src/IO/ReaderExecutor.cpp:388-403] In a stacked cache chain, readThroughCaches keeps only the first Resolution that reaches window_offset in each tier and returns as soon as any tier hits. If the faster filesystem cache misses the head but a slower tier is warm later in the same window, those later warm bytes are invisible and get re-fetched from source. That breaks the front-to-back cache contract for supported cache-on-cache setups such as s3_cache_multi. Suggested fix: keep subtracting faster-tier coverage from slower tiers and plan the whole served range instead of collapsing each tier to a single head run.
    [src/IO/ReaderExecutor.cpp:398-430] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/110029#discussion_r3603624559] A partially warm window still leaves the held long source connection positioned before the cached prefix, so the next miss-side call bridges that cached prefix with skipForward and re-downloads it from source. The bytes returned stay correct, but cache hits can increase ReaderExecutorBytesFromSource on sequential scans instead of decreasing it. Suggested fix: when a cache hit advances the logical position inside an existing long connection, either advance/drop the connection in sync with the served prefix or reopen from the cold tail instead of skipping through already-served cached bytes.
Tests
  • ⚠️ Add a focused ReadPipeline regression test that sets a small read_hint, enables the executor, and proves the source reader still sees that hint (for example by asserting the selected local buffer size or by using a mock object-storage reader that records the read_hint passed to readObject).
  • ⚠️ Add a cache + long-connection regression test where a cached prefix is followed by a cold tail on the same held source connection; ReaderExecutorBytesFromSource should not include the already-served cached prefix.
  • ⚠️ Add a stacked-filesystem-cache regression test for the supported s3_cache_multi shape: faster tier misses the head, slower tier is warm later in the same served range, and the executor should not re-fetch the slower-tier hit bytes from source.
Final Verdict

⚠️ Needs changes before merge. The default path is unaffected, but the experimental executor cache path still drops read_hint and still mishandles partially warm / multi-tier cache scenarios in ways that directly undercut the feature this PR is adding.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 1011/1170 (86.41%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 10, 2026
The src/IO style check forbids std containers without a
-WithMemoryTracking alternative or an explicit marker. `CacheChain` is a
tiny setup-time vector (one entry per cache tier), so mark it with
STYLE_CHECK_ALLOW_STD_CONTAINERS rather than pull a tracked container
into a widely-included header.
Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/ReaderExecutor.cpp Resolved
CheSema added 10 commits July 10, 2026 19:39
Implement `ICacheProvider` over the filesystem cache for the read-through
cache chain: `tryRead` serves a window only when the whole range is already
downloaded (a cache-only `getDownloadedContiguousOrEmpty` probe + pread);
`write` populates the covering segments synchronously (`getOrSet` -> become
downloader -> reserve -> write -> complete), best-effort. `missAlignment` is
the cache boundary alignment.

Strictly foreground: no prefetch, no held cross-window buffers, no downloader
election -- the concurrent cache-write path is not part of this slice. Not yet
wired into ReadPipeline; that follows in a later commit.
Build a `DiskCacheProvider` per configured filesystem-cache stage and hand the
resulting cache chain to the executor for object-storage reads, so
`use_reader_executor` now engages WITH the filesystem cache instead of falling
back to the legacy path. Page cache, distributed cache, async prefetch and a
per-object custom cache key still force a fallback (not implemented here).

Add `04511_reader_executor_disk_cache`: reads an `s3_cache` MergeTree table
through the executor and asserts its cache-chain ProfileEvent fired (proving it
engaged and consulted the cache) with correct data.
…ndow

Replace the simplified per-window ICacheProvider (tryRead/write) with the
plan-based interface and providers from the ReaderExecutor PR (#103706),
verbatim: ICacheProvider (CacheReader/CacheWriter/CacheView/FillClaim/
planResidencyView/openWriteBuffers + tier knobs), DiskCacheProvider
(FileCache-backed), PageCacheProvider (userspace page cache), and IntervalSet.
Two small FileSegment additions the providers need come along:
notifyDownloadProgress, and the complete() branch that lets a reader safely
hold a partially-downloaded segment.

The executor drives them simply -- per window, no prefetch or cross-window
plan: for each tier top-down, planResidencyView the window, serve it when a
tier fully covers it (promoting into the faster tiers that missed), else keep
the tier's aligned miss cells; on a full miss read once from the source
(expanded to the kept cells, clamped to the object) and populate via
openWriteBuffers/claim/write. Views and writers live only for the window.

ReadPipeline builds the chain once the source is chosen: page cache first
(file-level), then the filesystem cache(s) outer-first -- for object-storage
and local (page-cache) reads. Distributed cache and async prefetch still fall
back.

Tests: 04511 (disk cache over s3_cache) and 04513 (page cache via
clickhouse-local) assert the executor engages and consults each tier. The old
tryRead/write mock gtests are removed (superseded by the functional tests).
…p readable

Track the big PR's removal of CacheReader::readable -- a hit is readable in full
(planResidencyView splits a partial segment at its write offset, so the hit range
is the committed prefix, and growth is the writer's story). Re-port ICacheProvider
/ DiskCacheProvider / PageCacheProvider to match.

Serve the miss remainder of a window through the long connection instead of a
one-shot read, so a cold sequential scan streams from one held connection rather
than a GET per window. serveThroughCaches now serves the contiguous cached prefix
(fastest tier holding each byte), reads the remainder via the shared readSource
helper (long connection / open / one-shot), then populates every tier's miss cells
with the assembled window -- filling the miss and promoting the prefix up. Both
readNextWindow paths route source reads through readSource. This drops the
head-alignment cell expansion: the miss is read forward as-is.
…prediction

Re-port ReadContinuityTracker: the reach estimator now predicts an ABSOLUTE
run-anchored end (predictedEnd) instead of a forward length from the caller's
offset (predictedForwardLength). Anchoring at the run rather than the cursor
avoids re-anchoring the prediction forward as the cursor advances -- which
inflated it at ~twice the consumption rate; the predicted end is now identical
wherever a caller asks from. Includes the continuation-checkpoint fold and the
live-run blend fix.

Adapt the executor: clampReach bounds the absolute predicted end to
[position, file end]; shouldOpenLongConnection and the held-GET bound use
predictedEnd. Re-port the tracker gtest for the new API.
Drop change-log/rationale prose, cross-references and counterfactuals from the
cache-path comments; keep the class/method docs and the few genuine invariants
(file-level coordinates, a hit is readable in full). No code change.
…-param

Make Segment public and return `const Segment *` (the object plus its file
offset) from findObjectAt, replacing the `StoredObject*` + `size_t*` out-param.
Callers read `segment->object` / `segment->logical_offset`.
… returns

- window_size (default 4 MiB) is the serve window; block_size (1 MiB) sizes buffers.
- serveThroughCaches/readSource return a ChainedBuffers instead of writing one
  large `want` buffer: cache hits are zero-copy (reader buffers), source reads
  allocate block_size nodes filled from one connection -- no upfront window buffer.
- A short return is normal: serveThroughCaches returns the cached prefix run or the
  fetched miss; readNextWindow advances by got and no longer throws on got < want.
  Truncation is caught when a known-size source ends (got == 0) before its total.
- Rename continuity_tracker -> fetch_tracker, fed the physical fetched ranges (not
  the served bytes); clampReach/shouldOpenLongConnection/tryOpenLongConnection/seek
  work in physical coordinates (matches the big PR).
- decryptWindow decrypts each node into a fresh copy (never through aliased cache
  buffers); the plaintext path returns the window zero-copy.
Drop comments that restate what the code does; keep only non-obvious context
and cases (coordinate system, the readable-in-full invariant, truncation, the
physical->logical rebase, the decrypt-copy rationale). No code change.
The style check forbids a global `SYSTEM FLUSH LOGS`; flush `query_log` by name.
@CheSema
CheSema marked this pull request as ready for review July 16, 2026 11:35
Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/ReaderExecutor.cpp Resolved
CheSema added 2 commits July 16, 2026 13:46
Cut the verbose narration on `ReadContinuityTracker` and `DiskCacheProvider`
down to short non-obvious notes. Declarations and logic are unchanged.
Expose the serve window and buffer chunk sizes of the experimental
`ReaderExecutor` as the SQL settings `reader_executor_window_size`
(4 MiB) and `reader_executor_block_size` (1 MiB), threaded through
`ReaderExecutorSettings` and `Context::getReadSettings`. `ReadPipeline`
now feeds them to the executor `Options` instead of deriving the block
size from the filesystem buffer size.
@CheSema

CheSema commented Jul 16, 2026 •

Copy link
Copy Markdown
Member Author

Update: this PR is now scoped to the interface + filesystem cache — the first of
two cache PRs. The foundation (physical/logical coordinates, OffsetMap, the run-anchored
ReadContinuityTracker reach, the serve-to-bound long connection) merged separately in
#111088. The provider API is adopted from the redesigned #103706 head: a position-driven
cursor (probe() -> IProbeCursor::lookAt -> Resolution) replaced the old batch
planResidencyView/CacheView/openWriteBuffers. The page cache tier and the richer,
coordinated driver
(sibling waits, unknown-size streaming) move to a follow-up PR, and
this PR keeps ChainedBuffers unchanged. Reading order:

Interface + support types:

  1. src/IO/ICacheProvider.h — the cursor contract: probe() -> IProbeCursor::lookAt(pos) ->
    Resolution{Hit|Miss|End}, per-cell openWriter, and the fill surface
    CacheReader/CacheWriter/FillClaim (claim/write; waitAndReadSiblingLed is unused
    until the follow-up), tier knobs (populatesOnMiss/fillsWholeCell).
  2. src/IO/IntervalSet.{h,cpp} — the resident/committed-range set the writers report through.
  3. src/IO/OffsetMap.{h,cpp} — map(ByteRange) -> [ObjectRange], splitting a window across
    object boundaries.

Provider — the filesystem tier:
4. src/IO/DiskCacheProvider.{h,cpp} — FileCache-backed tier: the ProbeCursor
(roll/lookAt classify -> boundary-align -> tile), openWriter, the writer's downloader
claim/write, and the deferred-LRU DiskCacheTouchBook.

Executor — the cache path:
5. src/IO/ReaderExecutor.{h,cpp} — serveThroughCaches: per window, resolve the window start
block by block; serve a cache hit straight from the tier, else claim the miss cell(s), fetch
across objects through the long connection, populate, and serve one block. A cell a sibling is
already downloading is fetched through (its write lands 0), not waited on. Plus the
multi-object readSource and the cache_chain wiring.
6. src/IO/ReadPipeline.cpp — builds the cache chain and passes it into the executor Options.

Settings:
7. src/Core/Settings.cpp + src/IO/ReadSettings.h — reader_executor_window_size /
reader_executor_block_size (min 4 KiB).
8. src/Interpreters/Context.cpp — maps them into ReadSettings and rejects values < 4 KiB at
load; src/Core/SettingsChangesHistory.cpp registers them.

Supporting:
9. src/Interpreters/FileCache/FileSegment.{h,cpp} — notifyDownloadProgress + the
non-downloader-last-holder complete branch DiskCacheWriter needs.

Tests:
10. src/IO/tests/gtest_reader_executor.cpp (cache + cross-object + fetch-through tests),
gtest_offset_map.cpp (map).
11. tests/queries/0_stateless/04511_reader_executor_disk_cache.sql,
04604_reader_executor_min_size.sql.

CheSema added 3 commits July 16, 2026 17:34
…ersion

The read path mixed physical (header-inclusive file) and logical (payload)
offsets with scattered inline `+/- data_start_offset` arithmetic, which is
easy to get wrong. Route every conversion through two helpers, `toPhys` and
`toLogical`, whose doc-comment states the invariant: the offset map, object
offsets, cache coordinates and the source `file_base` are physical; `position`,
`read_until`, `totalSize` and served windows are logical; the only raw
`data_start_offset` use left is the consumer-exit `chain.shift`, which needs a
signed delta rather than a coordinate.

Also rename `OffsetMap::Segment::logical_offset` to `file_offset`: it was always
a physical file offset, so the old name collided with the executor's "logical"
(payload) vocabulary. No behavior change.
… draining and re-reading

On a forward sequential scan, when a window crossed the held connection's
`read_until` bound the reuse gate rejected the whole window, so
`dropLongConnection` drained the sub-window residual `[pos, read_until)` and the
next connection re-read those same bytes -- pure over-read. Replace the
all-or-nothing `canContinue` with `canServeAt`, which serves the window up to
the bound (a short window, already normal in this path); the connection then
resets cleanly at the bound with no drain, and the next call reopens at the
bound. `fill` takes an explicit limit so the reuse path can serve the clamped
amount. A genuine discontinuity still drops and drains as before.

Also make the tests actually exercise this. The long-connection tests set
`max_read_buffer_size` for small windows, but since the serve window became the
separate `reader_executor_window_size` (default 4 MiB) the test tables fit in
one window and the connection never opened; pin `reader_executor_window_size`
small in `04341`/`04342`, and pin `window_size` in the metric gtest fixture so
reuse (and the now-zero cold-scan over-read) is measured.
…tings history

The two experimental settings added in the window/block-size commit were missing
from the 26.7 block of SettingsChangesHistory.cpp, so 02995_new_settings_history
flagged them as unregistered new settings. Add them next to the sibling
reader_executor_* entries.
Comment thread src/IO/ReadPipeline.cpp Resolved
CheSema added 2 commits July 17, 2026 10:33
The PipelineReadBuffer gtests predate the window/block-size split: makeBuffer set
only block_size, so window_size defaulted to 4 MiB and a whole small test file was
served as one multi-block window. ChainedBufferBytesReturnToBaselineAtEOF then saw
the full window buffered (1024/768/512 bytes) instead of one block, failing its
<= 256 bound. Pin window_size = block_size so a window is one block, matching what
these tests assert.
A file-level page-cache block that straddles two stored objects was never populated:
serveThroughCaches clamped each fetch to the current object, so the block only ever got one
object's half and PageCacheWriter's whole-block covers-check failed -- warm rereads around
every blob boundary kept missing the page cache (the disk cache is unaffected; its key is
per-object).

Adopt OffsetMap::map(ByteRange) -> [ObjectRange] (from #103706) so a read window may span
objects. readSource maps the fetch range to its objects, reads each slice through the
single-object readObjectSlice, and concatenates them at file offsets; serveThroughCaches is
now file-level and plans/populates per ObjectRange -- the per-object filesystem cache from
each object's slice, the file-level page cache from whole blocks fed by the cross-object
fetch. readNextWindow no longer clamps a window to the object boundary; truncation of a
known-size source is detected there as a got==0 re-read.

Tests: OffsetMap::map (within-object, spanning, clamp); a window spanning a boundary; and a
page-cache block straddling two objects populated by the cross-object fetch (an in-memory
file-level mock cache asserts the covering write and a warm hit).
Comment thread src/IO/ReaderExecutor.cpp Resolved
CheSema added 2 commits July 17, 2026 23:35
Cut the verbose narration added with the OffsetMap::map cross-object fetch down to
terse, non-obvious notes, per the project comment style. No code change.
…bject base

ICacheProvider::resolve took `object_file_offset` (the object's file base), which
the executor pre-computed as `window_offset - object_offset`. Pass `object_offset`
(the object-local position of `range.offset`, straight from OffsetMap::map) instead
and let resolve derive the base (`range.offset - object_offset`). The file<->object
coordinate translation now lives entirely in the provider that owns it; the caller
passes the raw map() outputs with no subtraction.
…der call

DiskCacheWriter::claim called isDownloader() three times. getOrSetDownloader
returns the current downloader id, which equals getCallerId() exactly when we win
the role, so derive `captured` from that one call and reuse `mine = already_mine ||
captured` for the later checks. Behaviour-preserving; one isDownloader() call now.
Arm the downloader-role release on `!already_mine && captured` rather than
`captured` alone. `captured` is already false when `already_mine` (it is only set
in that branch), so behaviour is unchanged, but the explicit guard states the
intent and won't silently break if the `captured` computation ever moves.
Comment thread src/IO/ReadPipeline.cpp
Comment on lines 224 to 248
@@ -243,7 +246,6 @@ std::unique_ptr<ReadBufferFromFileBase> ReadPipeline::tryBuildReaderExecutor() c
LOG_DEBUG(log, "build: using ReaderExecutor for object storage, {} objects, gather={}",
source->objects.size(), gather);
source_reader = std::make_shared<ObjectStorageSourceReader>(obj_src->storage, settings);

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.

ReadPipeline is still carrying read_hint in LocalFileSource / ObjectStorageSource, but the executor path drops it here by constructing LocalSourceReader / ObjectStorageSourceReader without that hint. The legacy local-file path forwards read_hint into createReadBufferFromFileBase, which uses it to shrink the working buffer and avoid large-file mmap / O_DIRECT decisions for small reads; LocalObjectStorage::readObject forwards the same hint too. As soon as use_reader_executor is enabled, those callers fall back to full-file heuristics instead of the requested small-read policy.

Please thread source->read_hint through the executor source readers, otherwise small reads on local disks and LocalObjectStorage change their I/O method and buffering just by switching to the experimental path.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The experimental executor does not thread read_hint into its source readers yet; wiring it through LocalSourceReader/ObjectStorageSourceReader (so small reads keep the requested buffer size and mmap/O_DIRECT policy) is a later improvement. The executor is experimental and off by default, so this only affects opt-in use_reader_executor runs on local / LocalObjectStorage disks.

Comment thread src/IO/DiskCacheProvider.h Resolved
Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/DiskCacheProvider.cpp Resolved
Comment thread src/IO/DiskCacheProvider.cpp Resolved
Comment thread src/IO/DiskCacheProvider.cpp Resolved
Comment thread src/IO/ICacheProvider.h Resolved
CheSema and others added 5 commits August 12, 2026 16:20
… holder

Replace FileSegmentsHolder::release with popHolder, which moves the first
segment into its own single-segment holder and returns it as a shared pointer.
resolve now pops one holder per segment and hands it to that segment's reader; a
partial segment's reader and writer share the same holder. The holder completes
its segment on destruction, so DiskCacheReader/DiskCacheWriter no longer call
FileSegment::complete or touch the hold gauge by hand: the reader keeps only a
`served` flag for the deferred priority bump, and DiskCacheWriter drops its
destructor. Add a FileSegmentsHolderSharedPtr alias for the shared holder.

Fold in the review round:
- Hoist the empty-ask check to one early return in resolve, protecting both the
  bypass and populate paths symmetrically.
- Factor the shared hit emission into emit_hit used by both paths, and give the
  populate path its own emit_miss.
- Remove the now-dead `!holder` guards; the single-segment invariant is asserted
  in both constructors and on every access via a small segment() accessor, which
  popHolder also asserts on the produced holder.
- Assert in each constructor that the range lies inside the segment's span.
- Rename the reader/writer member holder to segment_holder, the executor locals
  m/r/c to miss_tier/resolution/claimed_tier, and ICacheProvider::Resolution to
  CacheResolution.
The segment-holder refactor moved the hold-gauge accounting into
FileSegmentsHolder's constructor and destructor, so DiskCacheProvider.cpp no
longer references CurrentMetrics::FilesystemCacheHoldFileSegments. Remove the
now-unused extern declaration that the style check flagged. CurrentMetrics.h
stays for CurrentMetrics::end().
claim is the sole role-acquisition site and is never nested — a caller holds
exactly one claim per write — so it is always a fresh acquire. Drop the
already_mine / mine handling for re-claiming a role we already hold, assert
!isDownloader() instead, and decide the role with a single getOrSetDownloader()
== getCallerId() call (role_captured). Matches the simplification in #103706.

The release is still armed the moment the role is won, before the throwable
available push, so a throw on unwind cannot leak the DOWNLOADING role.
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This change adds experimental ReaderExecutor tunables (reader_executor_window_size/block_size), a new DiskCacheProvider, a couple of FileSegment helpers, and a ProfileEvent rename — all gated behind use_reader_executor, which defaults off, plus comment-only and test edits. The benchmarks run on the untouched default read path, so none of the five flagged improvements (clickbench Q16/Q17/Q23, tpch Q7/Q8) can be attributed to this PR; all are downgraded to not-sure as run-to-run variance. Q23 in particular was already noisy with highly variable source runs. No real per-query effect is expected until the executor is enabled.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 793 712 -10.2% <0.0001 io: This PR only touches the experimental ReaderExecutor read path (use_reader_executor), which defaults off, so the benchmark ran on the untouched default read path. The -10.2% is run-to-run variance, not a PR effect.
⚠️ 17 not_sure 556 483 -13.1% <0.0001 io: The changed code (ReaderExecutor settings, DiskCacheProvider, a ProfileEvent rename) is all gated behind use_reader_executor, which is off by default. This query never executes it, so the -13.1% is variance.
⚠️ 23 not_sure 167 79 ×2.1 faster <0.0001 io: Nothing in this PR touches the default query path; the executor read path is default-off. Combined with this query's already-noisy history and highly variable source runs, the x2.1 faster reading is not attributable to this change.

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

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 574 71 ×8.1 faster <0.0001 io: The diff adds only experimental ReaderExecutor plumbing gated behind use_reader_executor (default off), so the benchmark's default read path is unchanged. The x8.1 faster result is run-to-run variance, not a PR effect.
⚠️ 8 not_sure 175 80 ×2.2 faster <0.0001 io: Same off-path reasoning: the changed read/cache code only runs when use_reader_executor is enabled, which it isn't here. The x2.2 faster delta cannot plausibly come from this change.

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.

Debug info
  • StressHouse run: 237eb82d-d2cb-4058-a42e-369eb7714d42
  • MIRAI run: 2826a208-c966-4a2c-9fbe-9bf49041f925
  • PR check IDs:
    • clickbench_1127164_1786663407
    • clickbench_1127170_1786663407
    • clickbench_1127182_1786663407
    • tpch_adapted_1_official_1127202_1786663407
    • tpch_adapted_1_official_1127234_1786663407

Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/DiskCacheProvider.cpp Resolved

@kssenii kssenii left a comment

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.

LGTM

Comment thread src/IO/DiskCacheProvider.cpp Resolved
Comment thread src/IO/DiskCacheProvider.cpp Resolved
…dRole

Take the reworked claim interface from #103706. Replace FillClaim {available,
to_fetch, release} and claim with:
- a move-only RAII Claim (held + release; the destructor completes and releases
  the downloader role),
- Lead {available, claim} returned by claimLeadRole, and
- write(ChainedBuffers, const Claim &) — the claim is the caller's proof it holds
  the role, so write no longer self-filters on isDownloader() but asserts it.

The caller derives the uncommitted tail as [available.end(), range.end()) and
fetches it only when bool(claim); to_fetch is gone. In the executor, a Claimed
tier now carries a Claim and is written only when the claim is held; a tier led
by a concurrent downloader is skipped.

claimLeadRole checks the (monotonic, role-free) write offset first: if the
committed prefix already covers the range it reports available and takes no role
at all, avoiding a needless acquire+release. It acquires the role only for a
genuine uncommitted tail, and still releases at once in the rare race where a
sibling commits that tail between the check and the acquire. The release path and
the release closure both assert we hold the role rather than re-checking it.

frontierInPartial is not taken (it only gates a read-ahead failpoint this PR does
not have), and waitAndRead keeps its name.
Comment thread src/IO/ReaderExecutor.cpp Resolved
Comment thread src/IO/DiskCacheProvider.cpp Resolved
- claimLeadRole: guard the won-but-not-yet-armed window with a SCOPE_EXIT that
  releases the role unless the Claim is armed (safe_guard_armed); it also
  subsumes the nothing-to-fill release. Assert (chassert(false)) in the release
  catches — completePartAndResetDownloader must not throw.
- ReaderExecutor: fold `claim` into `MissTier` and drop the duplicate `Claimed`
  struct/vector; reset each claim right after its write to free the downloader
  role early (the writer is finalized when miss_tiers is destroyed).
- Bypass path: read the exact uncached extent whole and serve all of it (nothing
  is cached inside it and we store nothing), instead of chunking into blocks.
@CheSema
CheSema added this pull request to the merge queue Aug 14, 2026
Merged via the queue into master with commit bb1112c Aug 14, 2026
182 checks passed
@CheSema
CheSema deleted the reader-executor-disk-cache branch August 14, 2026 09:57
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
CheSema added a commit that referenced this pull request Aug 14, 2026
Reconcile the experimental ReaderExecutor cache subsystem with the first
upstreamed slice (#110029) now in master, and bring the branch up to current
master.

- Collapse `ReaderExecutorRequestedBytes` into #110029's
  `ReaderExecutorDeliveredBytes` so the modeled-cost-per-byte KPI denominator is
  populated again.
- Adopt #110029's `ChainedBuffers` `logical_offset`, keeping our deliver-once
  `slice`.
- Adopt the object-local `object_offset` `resolve` contract in the executor.
- Restore the `virtual` on `Throttler::sleep` for the Silk fiber override.
- Drop the past-`total_size` assert in `OffsetMap::map` (the plan over-reads by
  design).
- Migrate the disk/page cache-provider gtests to the object-local, exact-extent
  contract.
- Point `contrib/silk` at `78aab9d` and share one Silk gtest environment (no
  double-init).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
CheSema added a commit that referenced this pull request Aug 14, 2026
… (CI)

The `origin/master` catch-up merge left the 26.8 `SettingsChangesHistory` block
with duplicate `reader_executor_window_size` (ours 8 MiB + #110029's 4 MiB) and
`reader_executor_block_size` entries; the trailing 4 MiB entry broke
`03999_stateless_settings_history` (current default 8388608 != last-recorded
4194304). Drop the duplicate #110029 entries so the single 26.8 entry records our
8 MiB default.

Also fix a stale `/*object_file_offset=*/` argument comment in
`gtest_residency_equivalence.cpp` to `/*object_offset=*/`, matching
`ICacheProvider::resolve`'s parameter (bugprone-argument-comment fails arm_tidy
under -warnings-as-errors).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants