Skip to content

Introduce ReadPipeline for declarative read buffer composition - #103234

Merged
CheSema merged 110 commits into
masterfrom
read-pipeline-redesign
May 24, 2026
Merged

CheSema merged 110 commits into
masterfrom
read-pipeline-redesign

Conversation

@CheSema

@CheSema CheSema commented Apr 21, 2026 •

Copy link
Copy Markdown
Member

Introduce ReadPipeline — a declarative builder for the read buffer chain that replaces imperative "matryoshka" nesting in DiskObjectStorage::readFile and StorageObjectStorageSource::createReadBuffer.

Problem

Multiple places manually constructed chains of nested read buffers (CachedOnDiskReadBufferFromFile, ReadBufferFromRemoteFSGather, AsynchronousBoundedReadBuffer, CachedInMemoryReadBufferFromFile, ReadBufferFromDistributedCache) with ad-hoc coupling logic. Each had to get use_external_buffer flags, buffer sizes, settings propagation, and seek restrictions right on its own. The chains differ structurally — MergeTree reads use Gather with per-object caching, table engine reads (s3(), url()) wrap a single object directly — but they share the same stages and coupling rules. This led to coupling bugs that are hard to catch in review and hard to test in isolation.

Solution

Callers declare what stages they need; ReadPipeline::build() owns how to couple them. One place to get buffer ownership right.

// DiskObjectStorage::prepareRead — declares stages
pipeline.setSource(object_storage, storage_objects, read_hint);
pipeline.needGather();
pipeline.needDiskCache(cache, cache_log);
pipeline.needAsyncPrefetch(reader, counters, prefetches_log);

// ReadPipeline::build() — assembles the chain with correct coupling
auto buf = pipeline.build();

IDisk::readFile is now a thin non-virtual wrapper: prepareRead() + pipeline.build(). All 117+ callers of readFile go through the pipeline without any migration.

Stages implemented

Stage Description
Source ObjectStorageSource, LocalFileSource, BackupSource, CustomSource
DiskCache CachedOnDiskReadBufferFromFile with correct use_external_buffer coupling
Gather ReadBufferFromRemoteFSGather for multi-blob logical files
DistributedCache ReadBufferFromDistributedCache with fallback
MemoryCache CachedInMemoryReadBufferFromFile (page cache)
AsyncPrefetch AsynchronousBoundedReadBuffer
Encryption ReadBufferFromEncryptedFile (supports multiple layers for double encryption)

Entry points migrated

  • DiskObjectStorage::prepareRead — MergeTree reads on object storage disks
  • StorageObjectStorageSource::createReadBuffer — table engine reads (s3(), url(), etc.)
  • DiskEncrypted::prepareRead — encrypted disk reads (delegates + adds decryption stage)
  • CachedObjectStorage::prepareRead — adds disk cache stage to the pipeline
  • CachedObjectStorage::readObject — now a pass-through (caching moved to pipeline stage)

Tests

19 unit tests + 6 integration tests with real DiskObjectStorage on local blob storage. All 23 existing DiskObjectStorageTest tests pass through the new code path.

Ref: #102282

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

High Risk
High risk because it refactors core read-buffer construction across local disks, object storage, encrypted disks, backups, and MergeTree part reads, affecting caching, seeking, and async-prefetch behavior in performance- and correctness-critical paths.

Overview
Introduces IO/ReadPipeline as a declarative builder for composing read-buffer chains (source, filesystem cache, gather, distributed cache, page cache, async prefetch, decryption) and adds extensive unit/integration tests validating stage ordering, seeking, cloning, and encrypted/object-storage reads.

Refactors the read API by making IDisk::readFile a non-virtual wrapper over new virtual prepareRead, and migrates DiskObjectStorage, DiskLocal, DiskEncrypted, DiskBackup, and MergeTree IDataPartStorage/MergeTreeReaderStream to populate a ReadPipeline instead of manually nesting buffers.

Updates object-storage interfaces to pass explicit use_external_buffer/restrict_seek flags, moves filesystem-cache composition into pipeline stages (including CachedObjectStorage::prepareRead), splits cache-related settings out of ReadSettings, and adjusts async/gather/cache buffer implementations accordingly (including a regression test preventing mmap+page-cache on local disks).

Reviewed by Cursor Bugbot for commit a309b2d. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.119

Replace the imperative "matryoshka" nesting in DiskObjectStorage::readFile
with a declarative ReadPipeline that subsystems annotate with stages.
The build method assembles the buffer chain in a fixed order.

Stages: Source, DiskCache, Gather, MemoryCache, AsyncPrefetch.
Encryption and decompression stages will follow in later PRs.

DiskObjectStorage::readFile now delegates to prepareRead + pipeline.build.
A new prepareRead method is exposed for callers who need pipeline access
(e.g. for cloning per-column in MergeTree readers).

Ref: #102282

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

clickhouse-gh Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8878073]

Summary: ✅
Keeper Stress Tests (PR): Grafana: Run details (this run), Grafana: 1vs1 Comparison, Grafana: Historical progression


AI Review

Summary

This PR refactors read-buffer composition into ReadPipeline and migrates the major read entry points to prepareRead + build (IDisk, IDataPartStorage, DiskObjectStorage, StorageObjectStorageSource, DiskLocal, DiskEncrypted, and DiskBackup). I reviewed the current diff, current code, and all existing thread replies; I did not find unresolved correctness, safety, or compatibility issues that require new inline comments.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Apr 21, 2026
…cache stage

DiskObjectStorage::prepareRead now detects CachedObjectStorage, extracts
its FileCache via needDiskCache, and sets the underlying storage as
source. Disk cache is now assembled by ReadPipeline::build instead of
being implicitly wrapped inside CachedObjectStorage::readObject.

Also simplifies ReadPipeline API: removes cache_log, async_read_counters,
and prefetches_log parameters — these optional diagnostics can be added
back when needed.

Adds CachedObjectStorage::getFileCache accessor.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/IO/ReadPipeline.cpp Resolved
…line

Add `needDecryption` stage to ReadPipeline: at build time, reads the
encryption header, finds the key via a callback, and wraps with
`ReadBufferFromEncryptedFile`.

`DiskEncrypted::prepareRead` delegates to the inner disk's `prepareRead`,
then adds the decryption stage. This allows the full pipeline
(source + cache + gather + async + decrypt) to be built declaratively.

Add virtual `IDisk::prepareRead` with default NOT_IMPLEMENTED.
Add `DiskLocal::prepareRead` so `DiskEncrypted` wrapping `DiskLocal` also
works through the pipeline.

Add `CachedObjectStorage::getFileCache` accessor.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/IO/ReadPipeline.cpp Resolved
DiskEncrypted::readFile now delegates to prepareRead + pipeline.build
instead of manually wrapping with ReadBufferFromEncryptedFile.

Support chained decryption for double-encrypted disks: decryption_stages
is now a vector, each needDecryption call appends a stage. build applies
them in order (inner decryption first, then outer).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Disks/DiskEncrypted.cpp Resolved
MergeTreeReaderStream::init now creates read buffers through
IDataPartStorage::prepareRead + ReadPipeline::build instead of calling
readFile directly. This makes the pipeline visible at the MergeTree
reader level, enabling future RRM integration.

Add IDataPartStorage::prepareRead (virtual, default NOT_IMPLEMENTED)
and DataPartStorageOnDiskFull::prepareRead (delegates to disk).

Handle empty storage objects (zero-byte columns during OPTIMIZE)
by returning ReadBufferFromEmptyFile when pipeline has no source.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
DiskObjectStorage::prepareRead now always sets a source, even for empty
files (sets a creator that returns ReadBufferFromEmptyFile). This removes
the need for hasSource checks in callers.

Add needDistributedCache stub to ReadPipeline — the stage sits between
Gather and MemoryCache. Implementation requires ENABLE_DISTRIBUTED_CACHE
module; the build integration is marked as TODO for the sync PR.

Restore the use_page_cache condition that accounts for distributed cache
(use_page_cache_with_distributed_cache).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The impl_creator lambda inside the gather creator captured
pipeline_creator and object by reference. CachedOnDiskReadBufferFromFile
stores this lambda and calls it lazily — after the outer lambda returns,
making the references dangling. This caused segfaults in CI fast tests.

Fix: capture by value instead of reference.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/IO/ReadPipeline.cpp Resolved
…nd empty source

Revert MergeTreeReaderStream::init to use data_part_storage->readFile
instead of prepareRead + pipeline.build. The pipeline path caused
segfaults in CI fast tests — likely due to ReadBufferFromRemoteFSGather
wrapping local file buffers in a way that corrupts heap metadata.

The prepareRead API and IDataPartStorage::prepareRead remain available
for future integration after ASan/TSan validation.

Also fix: capture by value in disk cache impl_creator lambda (was
dangling reference), and use bytes_size=0 for empty source objects.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/IO/ReadPipeline.cpp Resolved
…r size logic

Restore parameters that were previously simplified away but are needed
for correct behavior:

- DiskCacheStage: restore cache_log (FilesystemCacheLog) — needed for
  system.filesystem_cache_log to have data
- AsyncPrefetchStage: restore async_read_counters and prefetches_log —
  needed for system.filesystem_read_prefetches_log
- DiskObjectStorage::readFile: restore prefer_bigger_buffer_size logic —
  avoids filesystem cache fragmentation by choosing larger buffers

These were causing CI test failures in filesystem cache, prefetch log,
and buffer size tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…x describe

DiskEncrypted::readFile now catches NOT_IMPLEMENTED from
delegate->prepareRead and falls back to the old readFile-based code
path. This handles delegates like ReadOnlyDiskWrapper and DiskBackup
that don't override prepareRead.

Remove DistributedCache from describe() output since build() doesn't
implement the stage yet — avoids misleading diagnostics.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/IO/ReadPipeline.cpp Resolved
CheSema and others added 2 commits April 22, 2026 12:46
…rStream

Re-enable MergeTreeReaderStream::init to use prepareRead + pipeline.build
instead of readFile. This was reverted in commit 8 due to CI segfaults,
which turned out to be caused by dangling reference captures in the disk
cache lambda (fixed in commit 9).

The gather-wrapping-local-buffers pattern works correctly — SwapHelper
exchanges buffer pointers regardless of whether the inner buffer is
local or remote.

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

Address review comments:

1. Remove updateIOSchedulingSettings from readFile — prepareRead is the
   single owner of IO scheduling setup. readFile passes raw settings to
   both prepareRead and build. IO scheduling links are baked into the
   source creator by prepareRead; build only uses buffer sizes and flags
   which are unaffected by IO scheduling.

2. Propagate restricted_seek into the disk cache impl_creator lambda.
   Previously cache_settings had restricted_seek=true from
   withNestedBuffer but ignored the per-call restricted_seek parameter
   from the gather. Now source_settings applies the parameter before
   creating the inner reader.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
CheSema and others added 4 commits April 22, 2026 13:37
The gather stage (ReadBufferFromRemoteFSGather) is now opt-in via
needGather instead of always being created in build. Only
DiskObjectStorage::prepareRead calls needGather — object storage files
may be split across multiple blobs that need joining.

DiskLocal::prepareRead does NOT request gather. The source buffer is
returned directly from build, preserving local disk read features:
O_DIRECT alignment, page cache wrapping, mmap, io_uring, etc. These
are incompatible with the gather's SwapHelper pattern which swaps
internal buffers and breaks alignment guarantees and external buffer
mode assumptions.

This fixes CI fast test crashes (EINVAL from pread with O_DIRECT into
gather's unaligned buffer, heap corruption from page cache double
external-buffer wrapping).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
MergeTreeReaderStream::init now catches NOT_IMPLEMENTED from
prepareRead and falls back to readFile. This handles DiskBackup and
other disk types that don't override prepareRead.

Fixes: 03277_database_backup_database_file_engine test failure in CI.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
DiskBackup now has prepareRead — sets source from backup->readFile,
no gather (single file, not object storage). This handles the backup
database read path properly through the pipeline instead of relying
on the try/catch fallback in MergeTreeReaderStream.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The prefer_bigger_buffer_size logic was in DiskObjectStorage::readFile,
but MergeTreeReaderStream calls prepareRead + build directly, bypassing
readFile. The buffer size override was not applied.

Move the logic into prepareRead via pipeline.setBufferSize. build uses
the override for both gather and async prefetch buffer sizes.

Fixes: 03553_prefetch_buffer_size, 02963_remote_read_small_buffer_size_bug,
03552_filesystem_read_prefetches_log test failures.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…ead`

The `self` name was misleading — this isn't Python, and `IObjectStorage`
doesn't use `enable_shared_from_this`. The caller passes its own
`shared_ptr` to the storage explicitly so the pipeline can hold shared
ownership via `ObjectStorageSource { storage, ... }`. Renaming the
parameter to `storage` makes that obvious.

Also expands the docstring to explain what a pipeline "source" is — a
descriptor of where base bytes come from, not an actual buffer — and
that `ReadPipeline::build()` materializes the descriptor into a base
`ReadBufferFromFileBase`.

Per review comment from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
"needs to know" → "needs to be known" — `prefer_bigger_buffer_size` is a
variable, not an entity.

Per review suggestion from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…uffer_size`

The expression `storage->supportsCache() && read_settings.enable_filesystem_cache`
was duplicated in `prepareRead`: once inline in `prefer_bigger_buffer_size`
and once a few lines below as `file_cache_enabled`. Hoist the named flag
above its first use and substitute it into `prefer_bigger_buffer_size`.

Per review suggestion from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…reRead`

`IBackup::readFile(file_name)` does not accept a `read_hint`, so the disk
layer has no way to plumb one through. Matches pre-existing behavior of
`DiskBackup::readFile` on master, which also discarded its `read_hint`
parameter unnamed.

Per review comment from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…ine`

The "disk cache" name was ambiguous — "disk cache" colloquially also
refers to the OS kernel page cache. The rest of the codebase consistently
uses "filesystem cache" for this concept (`FilesystemCache`,
`FilesystemCacheSettings`, `enable_filesystem_cache`, the
`comp-filesystem-cache` issue label).

Renames:
  needDiskCache       -> needFilesystemCache
  DiskCacheStage      -> FilesystemCacheStage
  disk_caches         -> filesystem_caches
  describe-string "DiskCache" -> "FilesystemCache"

Per review comment from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
If two different `set*Source` methods are called on the same pipeline,
the second silently overwrites the first — typically a bug (e.g. a
delegation chain calling `setSource` from two places). Add `chassert`
at the start of each setter so this misuse is caught in debug/sanitizer
builds.

Per review suggestion from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Validate-then-use ordering: do the empty-objects check immediately after
the `!source` check, then bind the local `settings` reference. Avoids
the appearance of "we already started using `source->...` before we
checked the invariant".

Per review suggestion from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
`getFileCache()` was added in an earlier iteration of the pipeline
refactor when the plan was for `DiskObjectStorage::prepareRead` to
extract the cache out of `CachedObjectStorage`. The design later moved
to having `CachedObjectStorage::prepareRead` add its own cache stage,
leaving this accessor with no callers.

Per review comment from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…dCache`

`ReadBufferFromDistributedCache` stores the first arg as `filename` and uses
it for `getFileName()` and `distributed_cache_log`. Master passed the
logical disk path (the `readFile` `path` argument) here, which is the
`local_path` of a `StoredObject`. This PR was passing `remote_path`
(the blob key) — a regression that would surface as confusing filenames
in DC logs.

Fix both DC callsites in `ReadPipeline::build` (gather and non-gather).

Per review comment from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Master's `DiskObjectStorage::readFile` treated `storage_objects.empty()`
as a valid empty-file case and returned `ReadBufferFromEmptyFile` directly.
This PR was preserving that via an awkward workaround in
`DiskObjectStorage::prepareRead` — injecting a dummy `StoredObject` and a
custom creator lambda that produced `ReadBufferFromEmptyFile`.

Move the empty-objects handling into `ReadPipeline::build` so callers don't
need workarounds. `DiskObjectStorage::prepareRead` now calls
`setSource(storage, StoredObjects{}, settings)` and lets `build()` produce
the empty buffer.

The `!source` check remains: it still catches the "forgot to set source"
programming error.

Per review comment from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Add a comment explaining that the Stage 5 (`AsynchronousBoundedReadBuffer`)
wrap is only applied when the caller explicitly requests it via
`needAsyncPrefetch` — today only `DiskObjectStorage::prepareRead` (remote
reads) and `StorageObjectStorageSource`. Local reads don't use it; they
rely on `createReadBufferFromFileBase`, which can be async at the
file-descriptor level via `pread_threadpool` / `io_uring`.

Per review question from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
In the single-object (no-gather) path, `const auto & object = source->objects[0]`
is already declared at the top of the block. Use it for the DC fallback's
`captured_object` and for the DC filename argument instead of repeating
`source->objects.at(0)`.

Per review suggestions from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Capture `CurrentThread::getQueryId()` once at the top of `build()`,
reuse for all three `CachedOnDiskReadBufferFromFile` constructions
(gather lambda, no-gather inner stacked-cache lambda, no-gather
outermost). The lambdas capture it by value.

Besides DRY, this is a correctness improvement: the lambdas may be
called lazily from threadpool workers (gather creator on the prefetch
pool, impl_creator on read/seek) without query context, where
`CurrentThread::getQueryId()` would return an empty string. Capturing
on the calling thread (which has the query context) keeps the tag
consistent across all buffers in the chain.

Per review suggestion from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
The `std::visit` helper template (`overloaded`) was at file scope, polluting
the global namespace. Move it into an anonymous namespace inside `namespace DB`
for translation-unit-local linkage and to match the project's case-style
convention (`Overloaded`).

Per review comment from @kssenii on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…torage::prepareRead`

Master's `CachedObjectStorage::readObject` always called `patchSettings`
before invoking the inner storage's `readObject`. Our `prepareRead` was
passing the un-patched settings, which silently bypassed mandatory tweaks
applied by inner storages (`LocalObjectStorage::patchSettings` forces
`local_fs_method = pread` and zeros `direct_io_threshold`).

Patch the settings first, then delegate. Matches master's contract.

Per Cursor Bugbot review on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…avior

Commit 7aea02b4964 changed `ReadPipeline::build()` to return
`ReadBufferFromEmptyFile` for empty objects instead of throwing — to
match master's `DiskObjectStorage::readFile` and remove the dummy-object
workaround.

The corresponding gtest was still expecting a throw. Rename it to
`BuildWithEmptyObjectsReturnsEmptyBuffer` and assert that build()
returns a buffer reading zero bytes.

Per Cursor Bugbot review on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
`StorageObjectStorageSource` constructed `StoredObject(remote=path, local="")`.
After 251feaedd7c switched `ReadPipeline::build` to pass `local_path` to
`readWithDistributedCache` (matching master), this caused an empty filename
in `getFileName()` / `system.distributed_cache_log.filename` for table-engine
reads going through DC.

Set `local_path` to `object_info.getPath()` — same value master passed
directly to `readWithDistributedCache`.

Per Cursor Bugbot review on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
`AsynchronousBoundedReadBuffer` detects a `CachedInMemoryReadBufferFromFile`
inner buffer and uses `page_cache_block_size` as the prefetch buffer size to
align with cache blocks. That alignment must match the block size the
memory-cache stage was configured with — not the (possibly different)
`settings.page_cache_block_size` from the source `ReadSettings`.

When `memory_cache` stage is set, pass its
`page_cache_settings.page_cache_block_size` into the async wrapper.
Otherwise fall back to `settings.page_cache_block_size`.

Per Cursor Bugbot review on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Master had a defensive `if (!impl) impl = read_from_object_storage_gather();`
fallback after the DC call. `DistributedCache::readWithDistributedCache`
actually throws on errors (never returns null), so the master fallback was
unreachable in practice. Add `chassert(impl, ...)` to document the invariant
and crash loudly in debug builds if the contract ever changes.

Applied to both DC callsites in `ReadPipeline::build` (gather and non-gather).

Per Cursor Bugbot review on ClickHouse#103234.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
The original `build` method was ~450 lines with two nested branches
(gather / non-gather), each containing its own filesystem-cache and
distributed-cache logic, followed by three shared post-impl stages
(memory cache, async prefetch, decryption). The stage taxonomy was
already documented in `//` comments but was buried in one function.

Extract one private helper per logical stage group:
  - `buildGatherStage`        (stages 1+2+3 +3.5 DC)
  - `buildSingleObjectStage`  (stages 1+2 +2.5 DC)
  - `wrapMemoryCache`         (stage 4)
  - `wrapAsyncPrefetch`       (stage 5)
  - `wrapDecryption`          (stage 6 / encryption)

`build` is now a 28-line linear driver matching the documented
pipeline. Each helper is the body of one stage with one purpose.

Gather and single-object are deliberately NOT unified: their
per-object vs single-object creator lifetimes (multi-call vs
single-call) differ, and forcing them into one shape would obscure
that. They remain ~150-205 lines each, but each is now self-contained.

Pure structural refactor — no behavior change. All 14 ReadPipeline
unit tests pass on the private fork.

Per Kseniia's review on
ClickHouse#103234 (comment)
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Per review feedback: once this PR lands on `master`, comments that say
"on master ..." or "master used to ..." become noise — readers no longer
have a "before" to compare against, and the historical framing obscures
the actual invariant.

Rewrite the affected comments to state the invariant or constraint
directly, dropping the comparison to prior behavior. The WHY remains
explicit; only the "vs. master" framing is removed.

Files touched:
  src/IO/ReadPipeline.cpp                                  (3 comments)
  src/Disks/DiskLocal.cpp                                  (1 comment)
  src/Disks/DiskObjectStorage/ObjectStorages/Cached/CachedObjectStorage.cpp (1 comment)
  src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp          (1 comment)
  src/Storages/ObjectStorage/StorageObjectStorageSource.cpp (2 comments)

Per Kseniia's review on
ClickHouse#103234 (comment)
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Previously the function built an `impl` buffer in the filesystem-cache
or source-only branch, then unconditionally overwrote it with a DC
buffer when distributed cache was active. When DC was on, the source
reader (e.g. `ReadBufferFromS3`) was constructed and immediately
discarded — wasted object allocation per read call.

Restructure into three mutually exclusive branches, each returning its
own final `impl`:
  1. distributed_cache  → DC owns the chain, source impl is never built
  2. filesystem_caches  → stacked `CachedOnDiskReadBufferFromFile`
  3. neither            → source impl directly

The DC branch moves to the top of the function and consolidates its
validation (ObjectStorageSource required, filesystem-cache + DC + no
gather rejected) with its construction. The other two branches now
return directly instead of assigning to a shared `impl`.

No behavior change beyond avoiding the discarded source allocation.
All 14 `ReadPipeline.*` unit tests pass.

Per Cursor Bugbot review on
ClickHouse#103234 (comment)
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Per Kseniia's review:
- Drop the second sentence on the empty-objects branch — the code line
  immediately below already says `return ReadBufferFromEmptyFile`.
- Add a FIXME above the throw for "filesystem cache + DC without gather":
  describe what would need to change (feed the FS-cache-wrapped source
  into DC's fallback creator) so the limitation is not forgotten.

Per
ClickHouse#103234 (comment)
ClickHouse#103234 (comment)
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…design

Introduce ReadPipeline for declarative read buffer composition
@groeneai groeneai mentioned this pull request Jun 9, 2026
1 of 19 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants