Skip to content

Do not read-and-discard the archive prefix when reading a packed part member - #112644

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-marks-cache-filesegment-hung-check
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-marks-cache-filesegment-hung-check

Conversation

@groeneai

@groeneai groeneai commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110929

Changelog category (leave one):

  • Performance Improvement

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

Avoids reading and discarding megabytes of data when reading a small file out of a packed part. Reading one marks file used to transfer the whole archive prefix ahead of it, because the read buffer was sized for the small file while remote_read_min_bytes_for_seek still described the whole session, so the skip was judged too short to be worth a seek. Now the seek threshold is clamped along with the buffer, so the prefix is seeked over instead.

Description

A packed part keeps every column file inside one data.packed archive. When a caller asks for a small member, ReadSettings::adjustBufferSize shrinks both buffer sizes to that member (MergeTreeMarksLoader passes a marks file of ~100 to ~500 bytes), but it leaves remote_fs_settings.min_bytes_for_seek at its session value of 4 MiB. PackedFilesReader::readFile then opens the whole archive with those settings, and the seek to the member lands in ReadBufferFromRemoteFSGather::seek, where a skip shorter than min_bytes_for_seek is served by ignore() rather than a real seek. So the entire archive prefix is transferred through a member-sized buffer.

The fix clamps the remote seek threshold down to the already-clamped remote buffer size in PackedFilesReader::patchSettings, mirroring StorageObjectStorageSource.cpp, which sets min_bytes_for_seek = buffer_size right after adjustBufferSize. One clamp covers all 10 readFile call sites.

Measured on an encrypted cached disk, reading a 507-byte marks member behind a 2.88 MiB prefix: 5988 reads and 3050322 bytes before, 28 reads and 36750 bytes after. Uncached, the marks path goes from 9 requests and 3050322 bytes to 12 requests and 27522 bytes. The clamp lasts for the life of the view, so gaps inside a large member are seeked over rather than bridged. Measured there, that costs one or two extra requests and saves bytes, and the extra count grows with neither the member size nor the number of disjoint ranges read, because setReadUntilPosition already bounds the reader per range.

I found this while investigating an arm_asan_ubsan stress hung check where three marks-loading queries each moved 1.1 to 3.1 MB to obtain 96 to 144 bytes of marks. This removes that amplification; it does not by itself eliminate the hung-check class, and I have filed the remaining halves separately.

The ENABLE_DISTRIBUTED_CACHE clamp guards the same field that ReadPipeline substitutes when distributed cache is active.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex) plus an independent cold review
per round, over 4 rounds with 3 fix rounds. The gate raised 7 findings (4, then 1, then 2, then
0); the cold reviews raised the rest. 29 findings adjudicated in total: 11 AGREE, all fixed and
re-verified, 12 DISAGREE with recorded evidence, 6 dropped as superseded. The final round
returned 0 gate findings and 0 actionable cold-review findings on the full scope. The table
below lists the substantive findings; several raises that resolved to the same edit are merged
into one row.

# Sev Finding Verdict Evidence / action
1 ❌ The test drops the server-global mark cache and reads a shared storage policy without declaring it, so parallel copies interfere AGREE, fixed @ b5668dd7843ae4 Added no-fasttest, no-parallel with the reason inline, and narrowed the cache drop to SYSTEM DROP FILESYSTEM CACHE 's3_cache'
2 ⚠️ The test was vacuous on a large fraction of randomized runs AGREE, fixed @ b5668dd7843ae4 Isolated three merge-tree settings that each independently mask the defect: compress_marks=0 enlarges the marks member 18x, and string_serialization_version='single_stream' or serialization_info_version='basic' move the marks member to the front of the archive. All three pinned with reasons. Pre-fix failure rate went from 11/20 to 20/20; post-fix 50/50 pass
3 ⚠️ The request-cost claim was measured only where a request cannot occur AGREE, fixed @ b5668dd7843ae4 Re-measured on an uncached encrypted disk. The clamp trades requests for bytes: on the marks path 9 requests and 3050322 bytes become 12 requests and 27522 bytes. Numbers now in the description
4 ⚠️ DiskS3GetObject needed as an explicit request guard AGREE, fixed @ b5668dd7843ae4 Column added and mutation-tested. Stated plainly in the test comment that it is a guard against a future request regression, not a discriminator for this fix
5 ⚠️ A pinned-setting comment described the mechanism backwards AGREE, fixed @ e7d1e096fd6327 Comment corrected after re-deriving the three-link chain in source
6 ⚠️ Bare std::min on the distributed-cache field requires both operands to deduce the same type, and that block is compiled by no public job AGREE, fixed @ 1d3eefeefc082e Spelled std::min<size_t>. The declaring header is absent from this tree, so a type mismatch would surface only as a private build break. The remote half keeps the bare form since both operands are size_t members of one struct
7 💡 The ReadBufferSeekCancelConnection comment claimed the column covers the HTTP case AGREE, fixed @ 1d3eefeefc082e All 6 increment sites are inside ReadBufferFromS3::seek and ReadWriteBufferFromHTTP, each on a drop-a-live-connection path. The gather's own seek never seeks its child: it either ignores the gap or drops the child. Comment now says that, and the column stays pinned at 0 as a guard
8 💡 reader_executor.min_bytes_for_seek should be clamped too DISAGREE Its only two uses are seeding the read-continuity predictor and canServeAt, which is gated on a connection already being held. With no held connection the executor takes readOneShot, which seeks directly to the target offset, so there is no discard-versus-reopen decision keyed on that threshold. Clamping it could only shorten legitimate connection reuse
9 💡 The oracle counters could be silenced by the randomized local read method DISAGREE The measured reads come from the local cache file, and CachedOnDiskReadBufferFromFile builds that reader with its own settings pinning pread, deliberately not inheriting the caller's method. Both counters therefore always fire, which the 50-run randomized pass confirms
10 💡 The fixture uses a plain point lookup where the reported failure was a text index query DISAGREE, disclosed Verified equivalent rather than merely disclosed: the text index read path builds a MergeTreeMarksLoader for its own stream, so index marks pass through the identical clamp site. A text index would add randomized surface without adding coverage. The test header states the substitution
11 💡 The std::min versus assignment row does not prove what it was asked to prove DISAGREE, reported not overclaimed Correct, and unsatisfiable for marks members: the two forms diverge only when the prefix is smaller than the buffer, and a marks member's buffer equals its own size while the archive index block alone exceeds it. The row ships as what it is, and the preserve-a-smaller-value property is proven separately by measurement

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped. Nothing was
deferred: every agreed finding was fixed and re-measured in the round that agreed to it.

One adjacent observation, deliberately not folded in: MergeTreeIndexReader::patchSettings
shrinks the remote buffer to 16 KiB for text index dictionary and postings substreams without
clamping the seek threshold, which is the same shape as this defect. It is a different clamp
site reading an index data stream rather than a packed archive member, so it is outside this
change's carrier set. Noting it so it is not mistaken for an unfixed instance of this fix.

Session id: cron:clickhouse-review-slot-9:20260730-174000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On an encrypted cached disk, reading a 507-byte marks member sitting behind a 2.88 MiB archive prefix: 5988 reads / 3050322 bytes, zero variance, and 20/20 FAIL through clickhouse-test under full randomization on the unfixed binary. The prefix must be smaller than remote_read_min_bytes_for_seek and much larger than the clamped buffer, with the filesystem cache on. Three randomized merge-tree settings each mask the bug on their own and are pinned in the DDL with the reason stated (compress_marks, string_serialization_version, serialization_info_version); each pin is proven load-bearing by a hostile-value arm.
b Root cause explained? ReadSettings::adjustBufferSize (src/IO/ReadSettings.cpp:40-49) clamps both buffer sizes to the requested member but leaves remote_fs_settings.min_bytes_for_seek at the session value of 4 MiB. PackedFilesReader::readFile (src/IO/PackedFilesReader.cpp:138) then opens the whole archive with those settings, so the seek to the member reaches ReadBufferFromRemoteFSGather::seek (src/Disks/IO/ReadBufferFromRemoteFSGather.cpp:245-258), where a skip shorter than the threshold is served by ignore() instead of a real seek. The prefix is therefore transferred one member-sized buffer at a time.
c Fix matches root cause? Yes. It clamps the seek threshold to the already-clamped buffer size at the layer that owns the archive indirection, so the two coupled quantities are clamped together. Not a widened bound, not a tag, not a data-size reduction. In-tree precedent: StorageObjectStorageSource.cpp:1367-1371 does adjustBufferSize(object_size) then sets min_bytes_for_seek = buffer_size on the next line.
d Test intent preserved / new tests added? New test 04654_packed_member_seek_threshold. It asserts transferred bytes, read count, and bytes-per-read, and carries DiskS3GetObject and ReadBufferSeekCancelConnection as request-cost guards. Bytes-per-read is the signature that separates a prefix transferred through a small buffer from a single large fetch. The test is tagged no-parallel because it issues a server-global SYSTEM DROP MARK CACHE, which has no scoped form; 6 of the 7 stateless tests that issue that statement already carry that tag, and 46 of the 49 that drop any cache do. The filesystem-cache drop is narrowed to SYSTEM DROP FILESYSTEM CACHE 's3_cache'.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (68a88a1937f27a10 unfixed, 101624f492177039 fixed; server buildId() asserted equal to the ELF on every arm). Unfixed: 5988 reads / 3050322 bytes, and the test fails 20/20 through the runner under full randomization. Fixed: 28 reads / 36750 bytes, and the test passes 50/50.
f Fix is general across code paths? One clamp in patchSettings serves all 10 PackedFilesReader::readFile call sites (DataPartStorageOnDiskBase.cpp:1136, :1150; DataPartStorageOnDiskPacked.cpp:344, :368, :690, :744, :923, :1056; IMergeTreeDataPart.cpp:1240; PackedFilesOperations.cpp:155) and all 5 consumers of remote_fs_settings.min_bytes_for_seek (ReadBufferFromRemoteFSGather.cpp:251, AsynchronousBoundedReadBuffer.cpp:414, ReadBufferFromS3.cpp:442, ReadBufferFromAzureBlobStorage.cpp:212, ReadWriteBufferFromHTTP.cpp:610). Fixed in the settings, not guarded at the discard site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified across near and far members in the same archive, 3.04 MB and 12.08 MB archives, thresholds 0 / 128 / 1024 / 64 KiB / 4 MiB / 8 MiB / 16 MiB, and both encrypted-cached S3 and encrypted-cached local object storage. The cost tracks the prefix (3.98x prefix gives 3.98x reads). std::min preserves a smaller user value: at 128 the result is identical to a threshold of 0. Request cost was also measured on an uncached encrypted disk, where a remote request can actually be issued: the clamp trades a small number of extra range requests for a large reduction in transferred bytes (marks path +3 requests for 3.02 MB less; an unclamped data read +1 request for 1.7 KB less). The extra request is a single step at the buffer size, not a per-prefix cost.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added and no default changed, so no SettingsChangesHistory.cpp entry is needed. No on-disk or serialization change: the archive layout is untouched and only the read path changes, so existing packed parts read identically, just seeked rather than scanned.
i Invariants and contracts preserved? Both pre-existing patchSettings invariants are intact and asserted (direct_io_threshold = 0, and mmap mapped to pread); they are correctness requirements because ReadBufferFromFileView cannot do mmap or direct IO. std::min can never raise a user's value. Deliberate non-changes: LocalFSReadSettings has no min_bytes_for_seek (a local seek is a real lseek), and reader_executor.min_bytes_for_seek is left alone because both of its uses bridge a gap on an already-held long connection rather than choosing discard versus reopen.

Session id: cron:clickhouse-review-slot-9:20260730-174000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @antonio2368, could you review this? Reading a small member out of a packed part clamps the read buffer to that member but leaves remote_read_min_bytes_for_seek at its session value, so the archive prefix ahead of the member is judged too short to seek and is read-and-discarded through the member-sized buffer: 3.05 MB transferred to obtain 507 bytes of marks. This clamps the seek threshold along with the buffer in PackedFilesReader::patchSettings, mirroring what StorageObjectStorageSource already does one line after adjustBufferSize.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a970a9]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, parallel) FAIL
04611_join_runtime_filters_index_analysis_skip_index FAIL cidb, issue
Unit tests (tsan) FAIL
DistributedQueryTest.ShuffleHashJoin FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

This PR clamps the packed-member read path so a small archive member no longer inherits a multi-megabyte remote seek threshold and read-and-discard the whole archive prefix. I reviewed the current diff, the touched read-buffer code paths, the existing inline thread, the top-level discussion, and the current PR state; I did not find a remaining correctness or performance issue that warrants an inline review finding.

Final Verdict

✅ No blockers or majors.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 30, 2026
Comment thread src/IO/PackedFilesReader.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This sync PR (public #112644) clamps the remote seek threshold to the buffer size in PackedFilesReader, cutting read amplification when small members such as marks are fetched from Packed part archives on object storage. That path is only exercised for Packed parts; a ClickBench single-table scan reads large Wide parts, so the changed code is not on these queries' hot path. All three flagged queries show small wall-clock improvements (up to -12.1%) with flat CPU — an I/O-shaped delta — but none are attributable to this change, and the deterministic gates correctly held them at no_change/inconclusive (the Q15 within-envelope suppression checks out). No regressions.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1331 1262 -5.2% 0.0006 io: Down -5.2% with flat CPU and mixed signals from the two tests. The packed-member seek fix isn't on this large-table scan's path, so this reads as run-to-run variance.
⚠️ 28 not_sure 1073 1019 -5.0% <0.0001 io: Down -5.0% with flat CPU and noisy underlying measurements; borderline. Off the PR's packed-archive read path, so not attributable to this change.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 4d3a6a23-7934-4067-8c11-3ec391e53535
  • MIRAI run: 0699ca00-55db-441e-867f-63c2907c2aba
  • PR check IDs:
    • clickbench_1175863_1785540682
    • clickbench_1175870_1785540682
    • clickbench_1175886_1785540682
    • tpch_adapted_1_official_1175894_1785540682
    • tpch_adapted_1_official_1175919_1785540682
    • tpch_adapted_1_official_1175933_1785540683

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.60% -0.10%

Changed lines: Changed C/C++ lines covered: 5/6 (83.33%) · Uncovered code

Full report · Diff report

… member

A packed part stores every column file inside one `data.packed` archive. Reading
a small marks member sizes the read buffer for that member, but the remote seek
threshold still described the whole session, so skipping the archive prefix ahead
of the member was judged too short to seek and was read-and-discarded through the
member-sized buffer instead. A ~500 byte marks member behind a ~2.9 MiB prefix
therefore cost the whole prefix: 3049387 bytes fetched to obtain the marks.

Clamp the seek threshold down to the buffer size in
`PackedFilesReader::patchSettings`, so the prefix is seeked over instead. The
same member then costs 27522 bytes. The clamp covers all packed `readFile`
callers and, under distributed cache, that stage's own threshold as well.

Seeking rather than bridging a gap costs an extra request, and the trade is
strongly favourable: measured on an uncached encrypted disk, the marks path goes
from 9 requests moving 3049387 bytes to 12 requests moving 27522 bytes. The extra
cost is a small constant rather than per-range, measured at +1 request with both
5 and 40 disjoint in-member ranges.

The regression test measures on an uncached disk and asserts remote bytes, so it
does not depend on whether a shared filesystem cache still holds the segment.
@groeneai
groeneai force-pushed the fix-marks-cache-filesegment-hung-check branch from d7d9dce to 606fbe1 Compare July 31, 2026 17:46
The two measured reads request the same bytes from the same path, so whichever
ran first could serve part of the second one from a read cache and halve its
counter. `CachedCompressedReadBuffer` keys on (path, offset), so with the
randomized `use_uncompressed_cache = 1` the second read measured 12398 bytes
where a read of untouched bytes measures 24796, and the lower bound of the
premise check rejected it. CI reproduced this deterministically: 122 of 122
runs failed under the drawn settings and 210 of 210 passed without them, with
the minimizer naming `use_uncompressed_cache`.

Reading the second cell from its own table means no earlier query in the test
has fetched those bytes, so no cache can pre-warm them regardless of which
cache the randomizer enables.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1a970a9

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel) / 04611_join_runtime_filters_index_analysis_skip_index randomized-settings failure, and the runner isolated the culprit itself: reproducible in 15/15 runs with the same draw, 0/21 without randomization, minimized to --join_runtime_filter_min_probe_rows 3843 #111691 (external, merged 2026-07-31T20:56:13Z), which pins that exact setting in this test. The tested build predates it: the file at this commit has 0 occurrences of min_probe_rows while master has 1, and compare/b52d957c5c08...1a970a94f5a0 reports behind_by: 1425, so the fix is not an ancestor of this head
Unit tests (tsan) / DistributedQueryTest.ShuffleHashJoin the job killed a wedged unit_tests_dbms (Thread 1 "unit_tests_dbms" received signal SIGINT, Interrupt., the whole context); the test neither asserted nor crashed. Not caused by this pull request, whose 3-file diff is src/IO/PackedFilesReader.cpp plus its own stateless test and touches nothing on the distributed-plan path. 30-day breadth: 2 rows, 2 pull requests, 0 on master, both on 2026-07-31 a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this pull request). No fixing PR exists yet: searches for ShuffleHashJoin and gtest_distributed_query in both states return nothing that touches gtest_distributed_query.cpp, and the only open pull request touching DistributedPlanExecutor.cpp is a serialization-version change, not a completion-stall fix

Session id: cron:our-pr-ci-monitor:20260801-000000

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Unit tests (tsan) / DistributedQueryTest.ShuffleHashJoin failure ledgered above: #113597.

The test left max_threads unset, so it resolved to the runner's core count and was multiplied by the per-task pipeline count; the job's 45-minute budget was consumed and the kill discarded the whole binary's gtest report. #113597 caps it in the gtest. Nothing in this pull request's diff was involved.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing as superseded by #118483: it bounds the read to the member's slice before seeking, so the archive prefix is no longer read and discarded. Measured with this PR's own test on master 6ea176fa (without this change): the far-member read fetches 25255 bytes from S3, the same as with a 128-byte threshold, against 3055165 on 4522bf6e, the commit just before #118483. On a cached encrypted disk the same read took 59279 cache-read steps before #118483 and takes 17 on master.

@groeneai groeneai closed this Nov 15, 2026
@clickhouse-gh clickhouse-gh Bot added comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
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-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants