Repository navigation
Restore prefetch for small files read from object storage - #108872
Conversation
…ions The s3()/object-storage table-function read path skipped the small-object initial prefetch whenever the read buffer supported readBigAt, because the prefetch was gated on `!impl->supportsReadAt()`. After #71781 added readBigAt to the fs-cache buffer, reads of many tiny files became synchronous and latency-bound (e.g. low-concurrency s3() ingestion of lots of small files). readBigAt/parallel reading only helps large objects; `use_prefetch` already implies the object is small, so restore the prefetch for that case. Adds a stateless regression test.
|
Workflow [PR], commit [fe3a464] Summary: ❌
AI ReviewSummaryThis PR restores the initial small-object prefetch for object-storage reads and teaches Findings❌ Blockers
Tests
Final Verdict❌ Changes requested — the sequential tiny-file regression is fixed, but the current |
|
📊 Cloud Performance Report 🔴 AI verdict: This PR changes only the object-storage table-function read path (small-file prefetch on s3()/file() plus positioned reads for Parquet/ORC/Arrow); it does not touch the native MergeTree query execution that both ClickBench and TPC-H exercise. Because none of the flagged queries run through the changed code, the ClickBench regressions (Q30, Q31), the ClickBench Q34 improvement, and the TPC-H Q8/Q16 deltas are downgraded as run-to-run variance rather than PR effects. The two TPC-H regressions Q4 (+224%) and Q7 (+783%) are large enough to stand under the hard trust rule, but they are also off-path and Q7's baseline was very noisy (71 ms median), so both should be re-checked manually before treating them as real. clickbenchFlagged queries (3 of 43)
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 regressed · Flagged queries (4 of 22)
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
|
Addresses review: the previous change issued the small-object initial prefetch unconditionally, which tripped AsynchronousBoundedReadBuffer::readBigAt's chassert(!prefetch_future.valid()) for small Parquet/ORC/Arrow files read via the s3() table function, aborting the server. Gate the prefetch on the format's access pattern instead of the buffer's supportsReadAt() capability: random-access formats (which use readBigAt) skip the prefetch; sequential formats (TSV/CSV/JSONEachRow/Native/...) get it back. Adds FormatFactory::checkIfFormatHasRandomAccessInputCreator.
| /// But only issue it for formats that read the object sequentially. Random-access formats | ||
| /// (Parquet/ORC/Arrow) probe `supportsReadAt()` and read via `readBigAt`, which must not run | ||
| /// while an initial prefetch is in flight (see AsynchronousBoundedReadBuffer::readBigAt). | ||
| /// Gate on the format's access pattern, not on the buffer's `supportsReadAt()` capability: | ||
| /// after the buffer learned `readBigAt`, gating on the capability disabled the prefetch for | ||
| /// sequential formats too (e.g. many tiny files via the s3() table function), making them | ||
| /// fall back to synchronous, latency-bound reads. |
There was a problem hiding this comment.
May be a better way is to just support reading from prefetched buffer from readBigAt?
Since we prefetch only small files then readBigAt must read everything in a single read, so we can as well just copy what we have in prefetch into readBigAt memory.
There was a problem hiding this comment.
Good idea — done in 49f4c07. Reverted the format-based gate and instead made AsynchronousBoundedReadBuffer::readBigAt consume a pending small-object prefetch: it serves the requested range straight from the prefetched buffer when it is covered (the common case for a fully prefetched small file), and otherwise drops the prefetch and falls back to impl->readBigAt. This keeps the unconditional small-object prefetch (so small Parquet/ORC/Arrow now benefit too) and removes the FormatFactory coupling.
I kept a coverage check + fallback rather than assuming full coverage: object_too_small allows objects up to 2 * max_download_buffer_size while the prefetch reads buffer_size bytes, so a small-but-not-tiny object may be only partially prefetched.
Per review (@kssenii): instead of gating the small-object prefetch by format, keep prefetching all small objects and teach AsynchronousBoundedReadBuffer:: readBigAt to consume a pending prefetch - serve the requested range from the prefetched buffer when it is covered (the common case for a fully prefetched small file), otherwise drop the prefetch and fall back to a positioned read. This also extends the prefetch benefit to small Parquet/ORC/Arrow files and removes the FormatFactory coupling added in the previous revision.
| /// readBigAt() and the sequential prefetch must not run against impl concurrently, so consume the | ||
| /// prefetch first: serve the requested range straight from the prefetched buffer when it is covered | ||
| /// (the common case for a fully prefetched small file), otherwise drop the prefetch and read directly. | ||
| if (prefetch_future.valid()) |
There was a problem hiding this comment.
readBigAt must remain safe for concurrent positioned reads, but this branch mutates prefetch_future and last_prefetch_info without synchronization. That is reachable in the current object-storage path: createReadBuffer starts the small-object prefetch for object_size <= 2 * max_download_buffer_size, while FormatFactory::wrapReadBufferIfNeeded can wrap the same buffer in ParallelReadBuffer for file_size >= 2 * max_download_buffer_size; at the equality boundary ParallelReadBuffer launches multiple workers that call input.readBigAt concurrently. Two workers can race on prefetch_future.valid / get / reset, which violates the SeekableReadBuffer contract and can surface as undefined behavior or std::future_error. Please either serialize the pending-prefetch handoff (for example, guard the future so exactly one readBigAt consumes it before the rest delegate to impl) or make the initial-prefetch and parallel/read-at paths non-overlapping.
- 04000: read with SELECT * FORMAT Null instead of count() (count() can be answered without reading the data via optimize_count_from_files and would not exercise the prefetch path). - gtest_readbuffer_s3 HavingZeroBytes: disable remote_filesystem_read_prefetch so createReadBuffer() does not inject an automatic initial prefetch, which would change the manual prefetch/seek sequence the test asserts.
…ctive The filesystem cache manages its own read-ahead and segment ranges, so issuing an extra initial prefetch over a cached buffer is redundant and interferes with it (this is what gtest_readbuffer_s3 HavingZeroBytes characterizes). Gate the prefetch on !use_filesystem_cache; the non-cached s3()/object-storage read path (the regression) still gets it. Reverts the previous gtest workaround.
| SYSTEM FLUSH LOGS query_log; | ||
|
|
||
| -- Expect at least one prefetch per small file (> 0). Before the fix this was 0 (synchronous reads). | ||
| SELECT ProfileEvents['RemoteFSPrefetches'] > 0 |
There was a problem hiding this comment.
Better to also check RemoteFSPrefetchedReads -- to check that we actually read from prefetch.
There was a problem hiding this comment.
Done — the test now also asserts RemoteFSPrefetchedReads > 0, so it verifies the prefetch is actually consumed, not just issued.
| const size_t prefetch_end = result.file_offset_of_buffer_end; | ||
| const size_t prefetch_begin = prefetch_end - prefetched_bytes; | ||
|
|
||
| if (prefetched_bytes != 0 && range_begin >= prefetch_begin && range_begin + n <= prefetch_end) |
There was a problem hiding this comment.
There is a case that n can be bigger than prefetched_bytes but prefetched data is still inside the requested range. If missing part is just tail range from already prefetched buffer, then we can copy prefetched buffer as whole and just make one more request for the missing suffix of the range.
There was a problem hiding this comment.
Good point — handled in 686a95a. When the prefetch covers the head of the requested range but not all of it, readBigAt now copies the covered prefix from the prefetched buffer and reads only the missing suffix via impl->readBigAt (with the progress callback offset by the prefix length so it stays cumulative over the whole range), instead of dropping the prefetch entirely.
…onsumed - readBigAt: when the prefetch covers the head of the requested range but not all of it, copy the covered prefix from the prefetched buffer and read only the missing suffix via impl->readBigAt (offsetting the progress callback so it stays cumulative over the whole range), instead of dropping the prefetch. - 04000 test: also assert RemoteFSPrefetchedReads > 0 to confirm the prefetch is actually consumed, not just issued.
| if (!impl->supportsReadAt()) | ||
| throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Method readBigAt() is not implemented for a given implementation"); |
There was a problem hiding this comment.
Let's move this to the beginning of readBigAt, this is more like a general correctness check, we cannot avoid it for prefetch case
There was a problem hiding this comment.
Done in 79c20f9 — moved the supportsReadAt() check to the top of readBigAt as a general precondition.
| if (progress_callback) | ||
| progress_callback(n); | ||
| return n; | ||
| suffix_progress = [&](size_t copied) { return progress_callback(from_prefetch + copied); }; |
There was a problem hiding this comment.
Why do we need to add from_prefetch to progress? Was it not added in line 509?
There was a problem hiding this comment.
The value passed to progress_callback is cumulative, not incremental (see copyFromIStreamWithProgressCallback, and ParallelReadBuffer::on_progress ignores non-increasing values). impl->readBigAt for the suffix reports cumulative bytes relative to its own request (0 … suffix), so without the shift the caller would see the value drop back below the prefix already served. Adding from_prefetch keeps it cumulative/monotonic over the whole range.
I also removed the separate prefix progress_callback(from_prefetch) call (79c20f9), so now progress is reported only via the shifted suffix callback — no double counting.
- Move the supportsReadAt() correctness check to the top of readBigAt (it is a general precondition, needed for the prefetch path too). - Drop the separate prefix progress_callback call; only the suffix reports progress, shifted by the served prefix so the reported value stays cumulative and monotonic over the whole range.
The filesystem cache stage is only added when the object has an etag; without it we build a plain remote reader. Clear use_filesystem_cache in that branch so the flag reflects whether the cache stage was actually added. Otherwise the initial small-object prefetch guard (!use_filesystem_cache) would wrongly stay suppressed for the enable_filesystem_cache=1 + missing-etag case, reintroducing the synchronous tiny-file read path.
kssenii
left a comment
There was a problem hiding this comment.
LGTM, but will be good to fix above bot's comment
The fixture writes exactly 16 tiny files and the query reads all of them, so each must regain the initial prefetch. Assert RemoteFSPrefetches >= 16 and RemoteFSPrefetchedReads >= 16 instead of > 0, so a partial regression that prefetched only some files would still be caught.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 38/43 (88.37%) · Uncovered code |
Cherry pick #108872 to 26.3: Restore prefetch for small files read from object storage
Cherry pick #108872 to 26.4: Restore prefetch for small files read from object storage
Cherry pick #108872 to 26.5: Restore prefetch for small files read from object storage
Backport #108872 to 26.4: Restore prefetch for small files read from object storage
Backport #108872 to 26.5: Restore prefetch for small files read from object storage
Backport #108872 to 26.3: Restore prefetch for small files read from object storage
Backport #108872 to 26.6: Restore prefetch for small files read from object storage
Follow-up to ClickHouse#108872: the restored small-object prefetch was gated on `!use_filesystem_cache`, but reads via object storage table engines go through the filesystem cache when `filesystem_cache_name` is set (the ClickHouse Cloud configuration). The cache does no read-ahead of its own and fresh files (e.g. `S3Queue` ingestion) are always cache misses, so every small file still cost a synchronous, latency-bound round trip to object storage: `RemoteFSPrefetches` stayed 0 and insert latency stayed ~4-5x higher than on 25.12, where the prefetch was issued over the cached buffer. The gate existed only to keep the exact read/seek sequence asserted by `gtest_readbuffer_s3.HavingZeroBytes` stable; restore the test-side workaround (disable `remote_filesystem_read_prefetch` in that test) instead of disabling the prefetch in production code. ClickHouse/support-escalation#8093
…-file-prefetch Restore prefetch for small files read from object storage
Follow-up to ClickHouse#108872: the restored small-object prefetch was gated on `!use_filesystem_cache`, but reads via object storage table engines go through the filesystem cache when `filesystem_cache_name` is set (the ClickHouse Cloud configuration). The cache does no read-ahead of its own and fresh files (e.g. `S3Queue` ingestion) are always cache misses, so every small file still cost a synchronous, latency-bound round trip to object storage: `RemoteFSPrefetches` stayed 0 and insert latency stayed ~4-5x higher than on 25.12, where the prefetch was issued over the cached buffer. The gate existed only to keep the exact read/seek sequence asserted by `gtest_readbuffer_s3.HavingZeroBytes` stable; restore the test-side workaround (disable `remote_filesystem_read_prefetch` in that test) instead of disabling the prefetch in production code. ClickHouse/support-escalation#8093
Problem
Reading many small files from object storage via the
s3()/azureBlobStorage()/ … table functions (and object-storage reads in general) stopped prefetching and fell back to synchronous, latency-bound reads. On a single-threaded / low-concurrency read of lots of tiny files this is a large regression: every file is fetched with a blocking round-trip instead of being prefetched while the previous one is processed.It shows up clearly in
ProfileEvents:RemoteFSPrefetchesdrops to0,RemoteFSUnprefetchedReadsandSynchronousRemoteReadWaitMicrosecondsrise, andAsynchronousRemoteReadWaitMicrosecondsdisappears.Root cause
In
StorageObjectStorageSource::createReadBuffer, the initial "prefetch the first part of the file" is issued only for small objects (use_prefetchimpliesobject_too_small). It was additionally gated on!impl->supportsReadAt():Once the read buffer learned
readBigAt(parallel positioned reads) in #71781,supportsReadAt()becametrue, so this branch was skipped and the small-object prefetch was silently lost.readBigAt/parallel reading only helps large objects; a tiny file (≤2 * max_download_buffer_size) cannot be meaningfully split, so it ended up with neither prefetch nor parallelism and read synchronously.git bisectpoints to the merge of #71781 (first bad build26.2.1.1291, last good26.2.1.1290); the regression is present throughmaster.Reproduction
Reading the same 100 tiny files (
max_threads = 1):RemoteFSPrefetchesRemoteFSUnprefetchedReadsLarge objects are unaffected (they never take the small-object prefetch path).
Performance impact
The reads become synchronous and latency-bound, so the slowdown scales with object-store round-trip latency and the number of small files per query.
max_threads = 1, low-latency local object storage): wall time ~0.30s → ~0.56s (~1.8×),RemoteFSPrefetches100 → 0.INSERT ... SELECT FROM s3(...)saw single-query latency rise roughly 4–5× (e.g. ~3–4s → ~15–17s), turning steady-state ingestion into a continuously growing backlog.Raising
max_threadsonly partially compensates — it parallelizes the now-synchronous per-file reads but does not restore prefetching.Fix
Restore the small-object prefetch and make it coexist with
readBigAt:supportsReadAt()(removing the!impl->supportsReadAt()gate), on the non-cached read path.AsynchronousBoundedReadBuffer::readBigAtto consume a pending prefetch instead of requiring there be none: if the requested range is covered by the prefetched buffer (the common case for a fully prefetched small file) it is served straight from memory — so small Parquet/ORC/Arrow files benefit from the single prefetch too; otherwise the prefetch is dropped and the read falls back to the underlying positioned read.Sequential formats (TSV/CSV/JSONEachRow/Native/…) consume the prefetch via the normal sequential path; large objects are unaffected.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a performance regression (introduced in #71781) where reading many small files from object storage via the
s3()and other table functions stopped prefetching and fell back to synchronous reads, significantly slowing single-threaded / low-concurrency reads of lots of tiny files.Documentation entry for user-facing changes
Version info
26.7.1.410(included in26.7and later)26.6.2.25,26.5.6.12,26.4.5.97,26.3.17.19