Skip to content

Do not re-read a partially cached segment's committed prefix from the source (in experimental reader executor) - #115664

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-reader-executor-refetches-cached-prefix
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-reader-executor-refetches-cached-prefix

Conversation

@groeneai

@groeneai groeneai commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

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):

...

Description

ICacheProvider.h:107-109 puts the derivation of a tier's uncommitted tail on the caller: given
Lead::available, fetch [available.end(), range.end()). readThroughCaches bound lead.available to a
local, used it only for the covers-the-head early return, then dropped it - MissTier had no field for
it. fetch_lo came from the miss range instead, and on the populating path a partial segment's miss
spans its whole extent from seg_left (DiskCacheProvider.cpp:651), that range being the writer's fill
geometry. So a partially cached read re-read that prefix; write's append-only check discarded those
bytes, making it wasted I/O, not wrong data. The read-only sibling emits the miss from committed_end
(:600-601).

This carries available into MissTier and derives the tail once, for fetch_lo/fetch_hi and the write
loop. A tier whose prefix spans its range yields an empty tail and is skipped, so it cannot pull fetch_lo
back to the segment start.

The new coverage is a unit test because a segment committed to an arbitrary mid-point is not
deterministically reachable from SQL - which is why 04511 was flaky rather than failing. Its five cases
each fail on master; the suite is 44/44 here.

Measured on s3_cache_04511, ReaderExecutorBytesFromSource on the warm reread:
1,325,913 -> 276,057 bytes, cold unchanged at 1,588,547. With
reader_executor_use_long_connections a held connection can still bridge over the prefix; untouched here.

Surfaced by two 04511_reader_executor_disk_cache
failures on 2026-08-20, one on master, both diffing only warm_served_from_cache 1 -> 0. That test and
its .reference are unchanged: its warm < cold assertion was correct and was reporting this bug,
having been adjusted for flakiness four times. It passes 50/50 under randomized settings and under those
runs' settings. #115643 pins it to one thread so its oracle can be strict; measured here, the two
compose - warm = 0 needs the pin, and this cuts the multi-thread warm read it leaves.

Validation detail: warm-read source bytes per configuration, and the release-branch check

Same fixture and probe each time; warm/cold ratio of ReaderExecutorBytesFromSource. The test's
assertion is warm < cold, so a ratio near 1.0 is a near-failure.

threads / window master this PR
8 / 1 MiB 0.835 0.174
8 / 256 KiB 0.668 0.448
8 / 64 KiB 0.575 0.377
4 / 1 MiB 0.504 0.174
16 / 256 KiB 0.502 0.116
worst case 0.835 0.504

Build IDs: master c877fb06499b8acdfd053c38051b7fd4c7e79737, this PR
2ffe0b96223a5b47c2099d92b26cbbb4768786fd; server identity asserted with SELECT lower(buildId())
before each arm.

readThroughCaches, DiskCacheProvider.cpp and ICacheProvider.h are absent from
every active release branch (26.7 / 26.6 / 26.5 / 26.3 / 25.8), so the read-through cache path has never
shipped. use_reader_executor was added in 996c1850 (2026-06-09), defaults to false, tier
EXPERIMENTAL. No backport.


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

… source

ICacheProvider's Lead contract puts the derivation of a tier's uncommitted tail
on the caller: given `available`, fetch [available.end(), range.end()).
ReaderExecutor::readThroughCaches bound `lead.available` to a local, used it only
for the covers-the-head early return, and then discarded it, because MissTier had
no field for it.

fetch_lo was therefore computed from the miss range, and on the populating path a
partially downloaded segment's miss spans its whole extent starting at seg_left,
because that range doubles as the fill geometry handed to DiskCacheWriter. So
every partially cached read through the executor re-read the already-cached
prefix from the source. DiskCacheWriter::write's append-only offset check then
discarded those bytes, which is why the defect produced wasted source I/O rather
than incorrect data. The read-only sibling path is unaffected: it emits the miss
from the committed frontier.

Carry `available` into MissTier and derive each tier's tail once, using it for
fetch_lo/fetch_hi and for the write loop. A tier whose committed prefix already
spans its range yields an empty tail and is skipped, so it cannot pull fetch_lo
back to the segment start. The existing totalSize() and next_resident caps are
unchanged, as is the claim/release lifecycle.

Measured over an s3_cache_04511 table read with 4 streams (which leaves the
segment partially populated), ReaderExecutorBytesFromSource on the warm reread of
the same data drops from 1325913 to 276057 bytes; the cold read is unchanged at
1588547.

04511_reader_executor_disk_cache and its reference file are untouched and serve
as the SQL-level regression test. Its `warm < cold` assertion was correct and was
reporting this defect; the test had been adjusted for flakiness four times. Its
worst-case margin across a threads-by-window sweep improves from 16.5% to 49.6%.

The new gtest coverage is a unit test rather than SQL because a segment committed
to an arbitrary mid-point is not deterministically reachable from SQL, which is
precisely why the SQL test was flaky instead of failing. It needs a cache mock
shaped like the filesystem cache (append-only segments, a partial segment
resolving as a prefix hit plus a whole-extent miss with an open writer); the
existing mock is page-cache shaped and cannot express that state. Three cases
cover the partial prefix, a read starting inside the tail, and a fully committed
neighbouring segment.
…or cache tests

The partial-segment cases could not reach the empty-tail branch of the miss loop:
MockSegmentCacheProvider emits a Miss only while a segment is incompletely
committed, so a fully committed one never becomes a MissTier and the guard that
keeps it from pulling the fetch back to the segment start went unexercised.

Give MockSegmentState a late-commit frontier that resolve ignores and the writer
reports, following MockCacheState::late_committed, and add a case where a segment
misses at resolve but is fully available at claim time. Deleting the guard fails
that case and nothing else. The case that claimed to cover this is renamed after
what it does assert, a resolve-time hit served from cache across segments.

Also record what a held source connection does here. It reaches an offset ahead
of its parked position by reading the gap through a scratch block, so with the
fetch anchored at a committed frontier those bytes cross the wire and land in
ReaderExecutorBytesFromSource: 8092 against a 7580 byte tail, versus exactly the
tail once no gap is bridgeable and again with connection reuse off. That is a
property of connection reuse rather than of the fetch range, and it is unchanged
here, but no test combined connection reuse with a cache chain before.

No change to src/IO/ReaderExecutor.cpp.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 2 findings, both fixed)

Before opening this I reviewed the change against an independent model and adjudicated every finding.
Both findings were about the honesty of the PR's scope, not the mechanism; both were fixed in a second
round, and neither is outstanding.

# Finding Verdict Resolution
❌ 1 With reader_executor_use_long_connections a held connection bridges forward over the committed prefix (LongConnection::skipForward), so those bytes still cross the wire and are still charged to ReaderExecutorBytesFromSource - the counter this PR measures. The fix makes that path more reachable, since canServeAt requires the target offset to be at or ahead of the parked position. No test in the tree combined long connections with a cache chain. AGREE Measured first, then matched the claim to the measurement. Excess is exactly the segment's committed prefix (8092 vs a 7580 B tail); attributed twice - with no bridgeable gap, and with long connections off, the same read transfers exactly 7580 - so it is the bridge and not a wider fetch. Added HeldConnectionBridgesOverACommittedPrefix asserting the measured numbers, and narrowed the claim in the description. Narrowing the bridge itself is a change to the long-connection cost model and is deliberately not attempted here.
❌ 2 FullyCommittedTailAcrossSegmentsIsNotReFetched never reached the empty-tail branch it was named for: the mock emits a miss only while a segment is incomplete, so a fully committed segment never becomes a MissTier. The test was live but mis-scoped, which is the shape that lets a regression in that branch ship green. AGREE Gave the segment mock a late-commit frontier that resolve ignores and the writer honours, following the existing late_committed precedent, and added FullyAvailableTierAtClaimTimeContributesNoSourceBytes. Proved live: deleting only the if (!tail.size) continue; line makes it the sole failure of 44 (924 bytes instead of 412). The mis-scoped case was renamed to what it actually asserts and kept.

Also checked and found sound, so recorded rather than actioned: no underflow in the narrowed source
read (both seeds are the window offset, and the change only raises a min candidate); no path where a
skipped tier fakes an early EOF; no under-write, since the writer appends at its live frontier so the
narrowed range lands on it instead of being discarded; the derivation is tier-generic, and the
page-cache tier reports availability all-or-nothing so it is correct under it; the multi-object
straddling case is unchanged.

Five suite failures reproduce identically on the base binary, including one that is the subject of a
separate open PR, so they are pre-existing and not claimed here.

04511_reader_executor_disk_cache and its .reference are byte-identical to master.

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [58e8009]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) ERROR
Build (amd_darwin) ERROR
Build (arm_darwin) ERROR
Build (arm_v80compat) ERROR
Build (amd_freebsd) ERROR
Build (ppc64le) ERROR
Build (amd_compat) ERROR
Build (amd_musl) ERROR
Build (riscv64) ERROR
Build (s390x) ERROR

AI Review

Summary

This PR narrows ReaderExecutor source fetches to the uncommitted tail of partially cached filesystem-cache segments and adds focused unit coverage for the affected partial-prefix, late-commit, cross-segment, and long-connection cases. I did not find a correctness, safety, or contract regression in the current diff, and the prior PR discussion does not leave an unresolved technical issue that still reproduces in the code as reviewed.

Final Verdict

✅ No new blockers or majors found.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, two: the five new gtests (no server, no S3), and SELECT count(), sum(k) twice over an s3_cache_04511 table at max_threads = 4, which leaves the segment partially populated on every run. The CI flake is stochastic; the defect is not.
b Root cause explained? Yes. readThroughCaches discarded Lead::available (no field on MissTier), so fetch_lo came from the miss range, which on the populating path spans the segment's whole extent from seg_left (DiskCacheProvider.cpp:651) because it doubles as the writer's fill geometry. The cached prefix was therefore re-read from source, violating the contract at ICacheProvider.h:107-109.
c Fix matches root cause? Yes. It supplies the missing tail derivation at the four coupled sites (field, claim loop, fetch geometry, write loop). No widened bound, no no-random-* tag, no reduced dataset, no guard at the symptom site. Test-side alternatives were rejected because they hide the defect.
d Test intent preserved / new tests added? Yes. 04511_reader_executor_disk_cache and its .reference are untouched; its warm < cold assertion now holds with a ~50% margin instead of 16.5%. Five deterministic gtests added. No test weakened or removed; one existing case of mine was renamed to match what it asserts.
e Both directions demonstrated? Yes. Unit: all five new tests fail on pristine ReaderExecutor.cpp (39 others pass) and pass with the fix (44/44); deleting only the empty-tail guard kills exactly one of them. SQL: warm-read source bytes 1,325,913 -> 276,057 on two binaries whose Build-IDs were asserted server-side via SELECT lower(buildId()).
f Fix is general across code paths? Yes for the fetch path, with the connection-reuse path measured rather than assumed. Both claimLeadRole overrides checked: DiskCacheWriter (partial prefixes, the affected tier) and PageCacheWriter (PageCacheProvider.cpp:110-126, all-or-nothing available, correct under the same tier-generic derivation). With reader_executor_use_long_connections a held connection still bridges forward over the committed prefix (LongConnection::skipForward), which transfers those bytes; measured at 8092 against a 7580-byte tail, identical on master, and covered by a characterization test rather than left implied.
g Fix generalizes across inputs? Yes: nothing committed (empty tail, behaviour unchanged), partial prefix, prefix spanning the whole range (tier skipped), a segment that becomes fully available only at claim time, fully committed neighbouring segment, read starting inside the tail, object-straddling block, multi-segment window, long connections on and off. Byte ranges only, so no type-wrapper surface.
h Backward compatible? Yes. No setting, no default change, no serialized format, so no SettingsChangesHistory.cpp entry. use_reader_executor defaults to false and is experimental; the touched files exist on no active release branch.
i Invariants and contracts preserved? Yes. The append-only fill still completes (the new tests assert one write at the frontier and a fully committed segment afterwards, so no under-write), fetch caps and the claim/release lifecycle are unchanged, and a zero-size tail is skipped rather than participating in min()/max(). The derivation is a pure function, so error and early-return paths are unaffected.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @kssenii, could you review this? readThroughCaches dropped Lead::available instead of deriving the uncommitted tail from it, so fetch_lo fell back to the miss range, which on the populating path is the whole segment extent, and a partially cached read re-fetched its already-committed prefix from the source.

The Config Workflow hook parsed a prose line in the description that began
"Changelog category:" as a second template field and exited 1, which dropped
all 169 downstream jobs. The line is reworded; the workflow does not re-run on
a body edit alone, so this empty commit restarts it.

No change to the tree.
@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 20, 2026
clang-tidy runs with -Werror and readability-isolate-declaration, so the four
counters declared in one statement failed Build (arm_tidy).

Reproduced with clang-tidy-22 -p build: the one-line form reports the violation
at gtest_reader_executor.cpp:991 and exits 1, the split form reports none and
exits 0. unit_tests_dbms is 44/44.
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 58e80094b with master 0cba27059 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 710.14 MiB 707.09 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

7 translation units recompiled, 6 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1322705

CI fully finished and 0 checks failed, so no failure needed an owner.

Measured on the deduped check set (newest attempt per name): 172 unique names, 0 incomplete,
0 non-green, 147 success, 25 skipped by the selected-tests gate. The raw check-run list matched
total_count (173/173), so nothing was silently truncated. Finish Workflow completed
success.

Not a void run: Config Workflow = success and Style check = success. The praktika report
also shows 0 DROPPED nodes, so the skipped names are the ordinary selected-tests gate rather
than a build-gate cascade hiding an unvalidated matrix.

Independent CIDB confirmation at this commit: 299,428 ingested rows, 0 FAIL/ERROR, with the
status distribution read alongside the count so the zero is a measurement rather than an empty
predicate.

This also clears the Config + Finish Workflow blocker that was caused by the PR body itself: a
prose line beginning "Changelog category:" inside a <details> block was being parsed as a
second changelog category. Both checks are green at this head.

Session id: cron:our-pr-ci-monitor:20260821-023000

@kssenii kssenii assigned kssenii and CheSema and unassigned kssenii Aug 21, 2026
@kssenii kssenii changed the title Do not re-read a partially cached segment's committed prefix from the source Do not re-read a partially cached segment's committed prefix from the source (in experimental reader executor) Aug 21, 2026
@CheSema

CheSema commented Aug 21, 2026

Copy link
Copy Markdown
Member

The code in readThroughCaches is not production ready code. I will rewrite it completly soon. So stay tuned and do not fuzz until RE would be in b-test stage.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, standing down. I will not push anything further here, and I will leave readThroughCaches alone until you say the rewrite is in b-test stage.

Do you want this PR left open as a record of the prefix re-fetch, or closed in favour of your rewrite?

Master compacted `MissTier` onto one line and renamed the "bypass tier" wording
to "writer-less miss" in the comment right where this pull request adds the
`available` field. Kept master's wording and the field this fix needs; the
translation unit was syntax-checked after the resolution.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. label Sep 4, 2026
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 13, 2026
The test asserted that the warm reread of a cold-populated table touches the
source not at all, and started failing on master right after
ClickHouse#118483:

    -warm_served_from_cache	1
    +warm_served_from_cache	0

`min_bytes_for_full_part_storage` is randomized by the test harness, so about
two thirds of the runs store the part with the Packed storage: every file of the
part lives in ONE object, hence ONE filesystem-cache segment. Inside a single
query the marks streams and the data stream each build their own
`ReaderExecutor` over that object (`max_threads = 1` does not serialize them -
the marks load on their own pool threads) and race for the segment's single
downloader role. Only the role winner writes; the losers read through from
source and discard.

Before ClickHouse#118483 this was invisible: a whole-file read inside `data.packed` was an
open-ended range request, so the role winner's fetch ran to the end of the
archive and populated the whole segment. ClickHouse#118483 bounds each read to the file's
slice, so the winner now fills only that slice and the cold read leaves the
segment with holes. The warm read then re-fetches such a segment from its start
(`claimLeadRole`'s `available` prefix is deliberately unused - see the "Coarse
by design" note in `ReaderExecutor::readThroughCaches`), so `warm` is the whole
extent rather than 0.

Pin `min_bytes_for_full_part_storage = 0`: with the Full storage every stream is
its own object and therefore its own cache key, so each segment has exactly one
writer and the cold read populates all of them. That is also what the test means
to cover - the executor's read-through contract - rather than whether concurrent
streams over one shared segment converge.

Verified against a local minio with the failing run's randomized settings, on
26.9.1.1234 (the SHA below): the test as it stands fails 97/200, the patched
test passes 350/350. Cross-checked on 26.9.1.1193 (just before ClickHouse#118483), where
the unpatched test passes 100/100 and the cold read pulls 4064344 bytes from
source for a 1630734-byte archive - the over-read that ClickHouse#118483 removed is what
used to fill the segment.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=1d0999bf07898241e1229af5b6c1717aec5d275c&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20sequential%2C%202%2F2%29

Caused by: ClickHouse#118483
Related: ClickHouse#115664

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

clickhouse-gh Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Dear @CheSema, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@clickhouse-gh clickhouse-gh Bot added the comp-io IO library: ReadBuffer / WriteBuffer and their implementations over files and memory, read and wr... label Nov 19, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. label Nov 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-io IO library: ReadBuffer / WriteBuffer and their implementations over files and memory, read and wr... groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants