Repository navigation
Read-through filesystem cache for the experimental ReaderExecutor - #110029
Conversation
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.
|
Workflow [PR], commit [d99bc0a] Summary: ✅
AI ReviewSummaryThis PR adds the filesystem read-through cache layer for the experimental Missing context / blind spots
Findings
Tests
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1011/1170 (86.41%) · Uncovered code |
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.
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.
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.
|
Update: this PR is now scoped to the interface + filesystem cache — the first of Interface + support types:
Provider — the filesystem tier: Executor — the cache path: Settings: Supporting: Tests: |
…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.
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).
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.
| @@ -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); | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
… 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.
… reader-executor-disk-cache
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (3 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_officialFlagged queries (2 of 22)
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
|
…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.
- 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.
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]>
… (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]>
First of two PRs adding a read-through cache to the experimental
use_reader_executorread path (default off), split out of the
ReaderExecutorseries (#103706), afterdecryption (#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
ICacheProviderand the FileCache-backedDiskCacheProvider, consulted andpopulated 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 anordered list of
Resolutions in one cache transaction — each hit carrying aCacheReader,each populating miss carrying its open
CacheWriter(a read-only/bypass tier returnswriter-less misses). The executor drives it with the simplest possible per-window loop:
resolvethe 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) anddecrypted 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:
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.(
ResidencyIterator,CoverageMap,MemoryPressureMonitor).ChainedBuffersis functionally unchanged frommaster(only a couple of over-long comments trimmed).use_reader_executor; the executor also falls back for thedistributed cache and async prefetch, which it does not implement.
New settings:
reader_executor_window_size(serve window, 4 MiB) andreader_executor_block_size(buffer chunk, 1 MiB), each at least 4 KiB (rejected atsettings load otherwise).
Tests:
04511_reader_executor_disk_cache(ans3_cacheMergeTree) asserts the executorengages and consults the filesystem cache;
04604_reader_executor_min_sizeasserts thesub-4-KiB window/block rejection; IO gtests cover the executor, the provider, and the
offset map.
Related: #103706
Related: #109702
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a read-through filesystem cache to the experimental
ReaderExecutorread path (use_reader_executor, disabled by default).Documentation entry for user-facing changes