Skip to content

Avoid GET requests for unchanged plain-rewritable directories - #119760

Merged
alexey-milovidov merged 21 commits into
ClickHouse:masterfrom
rorylshanks:perf/plain-rewritable-etag-refresh
Oct 2, 2026
Merged

alexey-milovidov merged 21 commits into
ClickHouse:masterfrom
rorylshanks:perf/plain-rewritable-etag-refresh

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Metadata refresh reads each prefix.path object before checking its listed ETag. Keep the remote-directory-to-local-path map after a successful load, and reuse metadata when the directory ID and nonempty ETag match. Changed or missing ETags still trigger GETs; forced reloads still read every directory. Publish the map only after the load succeeds.

Refresh is not an atomic snapshot of remote metadata. Reuse validates the version observed by LIST. A rename or deletion after that listing can remain visible until the next refresh; the existing GET-based path also permits changes between a GET and publishing the resulting layout. The next listing observes a changed ETag or missing directory and refreshes/removes the cached entry.

Benchmark

The reader refreshed 100,000 packed parts every second, with no writes or statistics refresh. Values are medians of three 10-second windows after warmup.

Both 26.8-based Release builds disabled LTO and had limits of 4 CPUs and 16 GiB. An S3-compatible proxy served local NVMe data with a 2-CPU limit. The shared host used a Ryzen 9 5950X.

Per 10-second window Before After
GET requests 118,859 0
LIST requests 125 412
Reader CPU 33.30 CPU-s 8.51 CPU-s
Proxy CPU 7.96 CPU-s 2.10 CPU-s

Faster refreshes explain the extra LIST requests. This test does not measure AWS S3 performance or isolate the map's memory cost.

Validation

All 53 metadata tests passed. Coverage includes unchanged directories, rename, deletion, path reuse, missing ETags, and forced reload. Both readers passed row-count checks.

Changelog category (leave one):

  • Performance Improvement

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

Avoid object reads for unchanged directories when a plain-rewritable disk refreshes its metadata.


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

Version info

  • Merged into: 26.10.1.1252-master (included in 26.10 and later)

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... label Sep 13, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fd39ac8]

Summary: ✅


AI Review

Summary

This PR adds a prefix.path etag fast path so plain_rewritable metadata refresh can skip reading unchanged directories. That optimization is safe for backends with a truly strong directory-version token, but the current branch still enables it on LocalObjectStorage, whose prefix.path etag can stay unchanged across a same-size rewrite. That leaves one correctness blocker.

Findings
❌ Blockers
  • [src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.cpp:345] The new refresh shortcut assumes directory.metadata->isEtagUsableAsCacheKey() means prefix.path rewrites always get a new token, but LocalObjectStorage still derives that token only from (mtime, inode, size) in src/Disks/DiskObjectStorage/ObjectStorages/Local/LocalObjectStorage.cpp:78 and still performs unconditional rewrites in place at src/Disks/DiskObjectStorage/ObjectStorages/Local/LocalObjectStorage.cpp:632. A same-length rename of a directory rewrites prefix.path with the same inode and size, and if the filesystem timestamps both versions in the same tick the etag stays unchanged. Before this PR, refresh still re-read prefix.path and converged to the new local path; with the shortcut it reuses the stale cached path indefinitely until dropCache() or a later rewrite changes the token. The new test now avoids that case by renaming A to C1 solely to force a size change (src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp:249), so it masks the runtime gap rather than proving it safe.
    Suggested fix: either bring back the dropped LocalObjectStorage publish-by-rename change so its etag is actually strong for prefix.path updates, or treat LocalObjectStorage etags as non-cache-safe here and keep the old body read on that backend.
Tests
  • The added test covers only the forced-different-size rename (A -> C1). It does not cover the same-size rewrite that still collides on LocalObjectStorage and therefore misses the production failure mode above.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit fd39ac8.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 18/18 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fd39ac843 with master 001b6e36e (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 query(s) improved out of 38 analysed

Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there.

This PR only changes background refresh for the plain_rewritable metadata storage: it skips re-reading directories whose ETag has not changed, and it adds a unit test. No ClickBench SELECT runs that code while it executes. The seven flagged ClickBench improvements are all aggregation-heavy queries that used less CPU, which does not fit this diff, so six are downgraded to not_sure. Q32 (-47.0%) stays because its size locks the verdict, but it most likely comes from other changes in the newer 26.10 PR build, not from this PR.

clickbench

🟢 1 improved · ⚠️ 6 inconclusive

Flagged queries (7 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 32 improvement 1376 730 -47.0% <0.0001 aggregation: The size of the -47.0% change locks this verdict, and CPU fell by about half. The diff has no aggregation code, so the gain probably comes from other code in the newer PR build.
⚠️ 16 not_sure 628 560 -10.8% <0.0001 aggregation: This GROUP BY query does not run the plain_rewritable metadata refresh code, and its history is noisy. The -10.8% change cannot be credited to this PR.
⚠️ 18 not_sure 1101 928 -15.7% <0.0001 aggregation: This heavy GROUP BY query does not touch the metadata refresh path that the diff changes. The -15.7% change and lower CPU must come from something other than this PR.
⚠️ 23 not_sure 86 51 -40.7% <0.0001 cpu: This query is fast and has a noisy history. The -40.7% change is only 35 ms, and the PR changes nothing it executes.
⚠️ 31 not_sure 309 264 -14.6% <0.0001 aggregation: The -14.6% change on this GROUP BY query does not match anything in the diff, which only skips re-reading unchanged directory metadata during background refresh.
⚠️ 33 not_sure 1256 1135 -9.6% <0.0001 aggregation: This query does not reach the metadata refresh logic that the PR changes. The -9.6% change moves together with Q34, which points to a shared cause outside this diff.
⚠️ 34 not_sure 1259 1137 -9.7% <0.0001 aggregation: This query does not reach the metadata refresh logic that the PR changes. The -9.7% change mirrors Q33, which points to a shared cause outside this diff.

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: 6002e25f-b9fc-475f-bbbb-5d8ae78eafec
  • MIRAI run: 51c2cf3a-4ad1-4cc7-aab2-1c26d2bfbd8c
  • PR check IDs:
    • clickbench_2376325_1790683885
    • clickbench_2376331_1790683885
    • clickbench_2376337_1790683885
    • tpch_adapted_1_official_2376348_1790683885
    • tpch_adapted_1_official_2376359_1790683885
    • tpch_adapted_1_official_2376396_1790683885

A matching nonempty ETag validates the version observed by LIST. Remote
renames and deletions after that listing are observed by the next refresh.
The existing load algorithm explicitly permits concurrent-change races;
another GET would not make layout publication atomic. Clarify the contract
at the reuse point without adding a redundant remote request.

ClickHouse#119760 (comment)
@Michicosun Michicosun self-assigned this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 14, 2026
rorylshanks and others added 4 commits September 23, 2026 23:14
# Conflicts:
#	src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.cpp
The etag of `LocalObjectStorage` is `(mtime, inode, size)`. An unconditional
write truncates and rewrites the file in place, so it keeps the inode, and a
payload of the same length keeps the size. On a kernel that stamps inode times
from the coarse per-tick clock, two writes within one tick then leave the etag
unchanged, although the storage reports it as strong.

This made `MetadataPlainRewritableDiskTest.RefreshSkipsUnchangedDirectoryReads`
flaky: renaming directory `A/` to `C/` rewrites `prefix.path` with a payload of
the same length, and the refresh trusted the unchanged etag and kept `A/`.

Stamp the modification time of an unconditionally rewritten object past the
one of the version it replaces, the same way conditional writes already do.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119760&sha=e2db0d9737b586e455db2451017db57371d7acc8&name_0=PR&name_1=Unit%20tests%20%28amd_llvm_coverage%29
PR: ClickHouse#119760

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… the directory lock

Address review: an unconditional write rewrote the file in place and was stamped
past the modification time captured when its writer was opened. Two writers of one
path that are open at the same time both captured the same predecessor, so on a
filesystem that stamps inode times from the coarse per-tick clock the second one
could be stamped to the very etag the first one had already published: same
mtime, same inode, same size, different content. A `plain_rewritable` reader that
cached the first version under that etag would then skip re-reading `prefix.path`
on every later refresh, since `LocalObjectStorage` advertises its etags as strong.
A reader could also see a truncated or partially written object.

Now every write, conditional or not, is staged in a temporary file and published
by `publishVersion`, which takes the exclusive lock on the parent directory, stamps
the new version past the version it actually replaces as it stands under that
lock, and then `rename`s it into place. The etag strictly increases across the
version history of the path, readers only ever see complete versions, and a
cancelled write leaves the object untouched. Staging names are drawn from a
separate generator so that writes do not advance `thread_local_rng`, from which
object keys are generated.

The new test `InterleavedUnconditionalWritesPublishDistinctEtags` reproduces the
etag collision with the previous implementation.

Related: ClickHouse#119760

Co-Authored-By: Claude Opus 5.5 <[email protected]>
rorylshanks and others added 2 commits September 27, 2026 16:03
Address review: since every write is staged next to its target until it is
finalized, a `plain_rewritable` metadata instance that loads (or calls
`dropCache`) while a writer is open rebuilt the directory's file set from
`listObjects` and recorded the staged `.tmp_...` file as a real file of the
directory. Later refreshes skip unchanged directory bodies, so the phantom entry
stayed until the next forced reload.

Staging cannot move to a dedicated area: `rename` does not publish across
filesystems and the key prefix may span several of them (it is `/` in
`clickhouse-local`). Instead, a remote object storage never lists an unfinished
upload, and neither does `listObjects` now: it skips every name with the
reserved staging prefix `.tmp_local_object_storage_`. The name of the target is
no longer part of the staging name, so a target whose name is close to
`NAME_MAX` can still be staged.

New tests: `LocalObjectStorage.ListObjectsHidesUnfinishedWrites` and
`MetadataPlainRewritableDiskTest.LoadIgnoresUnfinishedWrite`.

Related: ClickHouse#119760

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rash_server`

The test waited for a `*.parquet` file to appear before `KILL QUERY`. Since
`LocalObjectStorage` stages every write under a temporary name until it is
finalized, like a remote object storage, a data file only shows up under its
final name on commit, so the test timed out with
`no inner sink opened its data file in time`. Count any file outside of
`_delta_log` instead, and check that the cancelled insert leaves neither a
published nor a staged file behind.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119760&sha=6abd16d3fbe008bcb017e34907dacf2830d92b85&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%202%2F8%29
Related: ClickHouse#119760

Co-Authored-By: Claude Opus 5.5 <[email protected]>
rorylshanks and others added 2 commits September 28, 2026 14:36
…r object names

`listObjects` hides every name starting with `.tmp_local_object_storage_`, so an
object written under such a name would be published but never listed. Reject
such names in `writeObject`, which every object creation (including
`copyObject`) goes through, so that hiding the prefix hides no object.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@Michicosun Michicosun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are too many unrelated changes.

mtime in most filesystems (ext4-like) has nanosecond precision. We don't need to change anything for local object storage.

rorylshanks and others added 2 commits September 29, 2026 11:59
The reviewer asked to keep the PR limited to the plain-rewritable refresh.
Restore `LocalObjectStorage`, its gtests and `test_storage_delta` to master,
and remove `LoadIgnoresUnfinishedWrite`, which only covered the staged writes.

`RefreshSkipsUnchangedDirectoryReads` was flaky because it renamed `A/` to
`C/`, so `prefix.path` was rewritten in place with a payload of the same size.
The `LocalObjectStorage` ETag is `(mtime, inode, size)`, and the kernel stamps
mtime from its coarse clock, so a rewrite within one tick could keep the ETag.
Rename to a name of a different length instead, so the ETag changes by size.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119760&sha=e2db0d9737b586e455db2451017db57371d7acc8&name_0=PR&name_1=Unit%20tests%20%28amd_llvm_coverage%29
Review: ClickHouse#119760 (review)
PR: ClickHouse#119760

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rorylshanks

Copy link
Copy Markdown
Contributor Author

Hey @Michicosun sorry you are right, the bot went a bit crazy after a flake and I didn't re-read the code.
Its back down to its original size now.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 1, 2026
Merged via the queue into ClickHouse:master with commit 569a60c Oct 2, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
@vfdavidescu

vfdavidescu commented Oct 8, 2026 •

Copy link
Copy Markdown

Hi, could this fix be backported to 26.8?

On 26.8, a read-only s3_plain_rewritable disk GETs every directory's prefix.path on each refresh, even when it hasn't changed. Our idle replica went from about 0 GETs an hour on 25.12 to about 10.4M an hour on 26.8.14.3, with the same data and settings. No setting avoids it, and it's still there in v26.8.20.9-lts.

The .cpp hunk doesn't apply as-is because master restructured load() (#121412.). The same check fits before readObject on 26.8, and isEtagUsableAsCacheKey() is already there.

Thanks!

leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 13, 2026
SipHash kept the current partial 8-byte word as a union of a UInt64 and
UInt8[8]. `update` wrote a short tail byte by byte into the byte array
(the remainder of a previous update too, which clang emits as a `memcpy`),
and `finalize` stored the `cnt` byte into the last position and then read
the whole word with one 8-byte load. An 8-byte load that overlaps several
narrower in-flight stores cannot be store-forwarded on x86: it waits until
the stores commit (`ld_blocks.store_forward`). When the hash state lives in
memory across a call, e.g. `UniqVariadicHash::apply` -> virtual
`IColumn::updateHashWithValue` -> `get128`, every row pays this. How often
the blocked load is replayed depends on code placement, so the same
machine code is fast in one build and ~55% slower in another: this is why
`entropy #2` of the performance comparison flips between ~0.33 s and
~0.52 s per build on amd (master builds 4f8c9f2..a0b6517, and
PR builds of ClickHouse#117704, ClickHouse#114690, ClickHouse#119760).

Now `current_word` is a plain UInt64 holding the received bytes of the
current word in little-endian order, the bytes not received yet being zero
(the same numeric value the union had on both endiannesses, so
CURRENT_BYTES_IDX is gone). `loadTail` assembles up to 7 bytes in a
register with overlapping 4/1-byte loads, the remainder path ORs it in at
the right shift, the main loop keeps the word in a local, and `finalize`
folds `cnt` into the top byte in a register. Every access to `current_word`
is now a whole-word store followed by a whole-word load. Hash values are
unchanged.

Validation (release build, CMAKE_BUILD_TYPE=None without ThinLTO, Xeon
6975P, `SELECT entropy(MobilePhoneModel)` over 100M rows of a 92%-empty
sparse String column, max_threads=16, medians of 18 runs):
- base 0.218 s, fix 0.150 s; official master builds 562bdc1
  0.204 s (fast layout) and 4f8c9f2 0.285 s (slow layout).
- 15 queries: ld_blocks.store_forward base 1.54e9, fix 2.7e7 (slow official
  6.07e9); cycles 1.44e11 -> 8.98e10; instructions 5.27e11 -> 4.71e11.
- `uniqExact(toString(number % 1000), toString(number % 7))` over 2e8 rows
  5.23 s -> 2.98 s; sipHash64/sipHash128 of 1..5-byte strings -6.4%/-4.8%;
  sipHash64 of 10..50-byte strings +1.1% (instructions +1.8%); GROUP BY
  two String keys unchanged.
- Hash identity: a throwaway differential gtest against the verbatim
  previous class (every length 0..80 x every 3-way split, 3 key pairs,
  get64/get128/get128Reference, double get, update after get, the
  ColumnString row shape, 300k random streams of raw and typed updates):
  2,038,362 cases, 0 mismatches; a planted mutation (wrong value for 4-byte
  tails only) gives 808,592 mismatches. 02534_keyed_siphash and
  02552_siphash128_reference (official vectors) pass, and SQL sums of
  sipHash64/128, keyed and reference variants over 2e7 strings are equal on
  both binaries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants