Skip to content

Speed up loading of plain_rewritable disk metadata - #121412

Merged
alexey-milovidov merged 1 commit into
masterfrom
speedup-plain-rewritable-metadata-load
Sep 22, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
speedup-plain-rewritable-metadata-load

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

Motivation

Attaching a database whose tables live on a large s3_plain_rewritable disk and running a single SELECT took minutes. Reproducer against a public dataset:

ATTACH DATABASE datasets UUID 'e053c139-f7b8-4c82-acb7-6b259c5b19e8' ENGINE = Atomic
SETTINGS disk = disk(type = 's3_plain_rewritable',
                     endpoint = 'https://data.clickhouse.com/public-datasets/db/',
                     no_sign_request = true, readonly = true),
         lazy_load_tables = true;

SELECT * FROM datasets.census2012_rdns LIMIT 100;

lazy_load_tables works as intended here — the ATTACH DATABASE itself takes 2.2 seconds. The cost is in the SELECT, which instantiates the table's own disk, and that disk's metadata is loaded in full:

19:24:10.892  Loading metadata
19:26:06.577  Loaded metadata for 36401 directories     <- 116 s of the 142 s total

MetadataStorageFromPlainRewritableObjectStorage::load ran one task per directory, and each task made two requests: a GetObject for __meta/{directory}/prefix.path (the logical path is stored in the object body, so it has to be read) and a ListObjects for the files of that directory. On top of that, __meta itself was enumerated by a single listing, whose pages can only be fetched one after another.

Profile events for the whole reproducer: S3ListObjects = 36468, S3GetObject = 45644, of which 36401 are prefix.path reads and the rest is real part metadata.

The object storage is the limit, not the CPU or the thread count. Measured against that endpoint: a small GetObject takes about 70 ms and about 1350 of them per second complete at concurrency 100; a ListObjects page of 1000 keys takes about 1.0 s and returns 261 KB; the prefix holds 501234 objects. Raising max_io_thread_pool_size from 100 to 1000 brings the load from 116 to 54 seconds, but it scales sub-linearly and produces 1834 retried SSL_read timed out failures, so the answer has to be fewer requests rather than more threads.

Approach

Directory names in this layout are random strings from getRandomASCIIString, so they are uniformly distributed over a-z and the key space can be split by leading characters and listed in parallel.

  • __meta is enumerated by 26 prefix shards instead of one sequential listing, plus two boundary shards covering whatever sorts before and after the alphabet, so a directory written by another implementation is never silently dropped.
  • The files of all directories are collected by a few listings of the whole disk instead of one listing per directory: 716 requests covered all 501234 objects. These listings are interleaved with the prefix.path reads rather than scheduled ahead of them, because the pool takes tasks in order and neither kind of request saturates the object storage on its own.

This requires the object storage to treat its argument as an arbitrary key prefix and to honour start_after. LocalObjectStorage walks a real directory tree and returns nothing for a prefix that is not a directory, and AzureObjectStorage ignores start_after — both would fail silently, so the new path is gated on IObjectStorage::supportsPrefixListing, currently true only for S3. A disk with few directories keeps the previous single-request path, since sharding a listing that fits in one page only adds requests.

Results

metadata load whole reproducer
before 116 s (36401 directories) 2m22s
before, max_io_thread_pool_size = 1000 54 s 1m21s
after 37 s (36870 directories) 1m05s

The directory counts differ because the dataset is live and grew during the measurements (__meta went from 36401 to 37166 objects over the session).

Correctness was checked against the same dataset: count() over census2012_rdns returns 10575805741, and a read of one partition returns 49720453 rows with correct column aggregates, which exercises the prelisted file sizes on real reads. On a local plain_rewritable disk (the non-sharded path), insert, merge, SYSTEM RESTART DISK, DROP PARTITION and detach/attach all produce consistent results.

Remaining cost

About 30 of the remaining 37 seconds are the 36401 prefix.path reads, which cannot be avoided while the logical path lives in the object body. Removing them needs either encoding the logical path in the __meta object key, so that a listing alone yields the mapping, or persisting the resolved layout for read-only disks. A smaller related improvement is to key the unchanged-directory check in refresh on the remote directory name instead of the resolved local path, so that a periodic refresh does not have to read every prefix.path before it can consult the snapshot.

MIN_DIRECTORIES_TO_LIST_IN_PARALLEL is a compile-time constant, which makes the sharded path awkward to cover by a functional test; promoting it to a server setting would make it testable and give an escape hatch.

Changelog category (leave one):

  • Performance Improvement

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

Loading the metadata of a large s3_plain_rewritable disk is several times faster. Previously it made one ListObjects request per directory and enumerated the __meta directory by a single paginated listing, so a disk with tens of thousands of directories needed tens of thousands of sequential-ish requests. The listings are now split by key prefix and run in parallel, and the files of all directories are collected by a few listings of the whole disk. For a disk with 36 thousand directories holding half a million objects, the load time dropped from 116 to 37 seconds.

🤖 Generated with Claude Code


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

Version info

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

Loading the metadata of a `plain_rewritable` disk took one `ListObjects`
request per directory, plus a sequential scan of `__meta` whose pages can
only be fetched one after another. For a disk with 36401 directories that
is 36401 `ListObjects` plus 36401 `GetObject` requests and ~37 sequential
listing pages, which took 116 seconds on
`https://data.clickhouse.com/public-datasets/data/census2012/`.

Directory names in this layout are random strings from `getRandomASCIIString`,
so they can be grouped by their first characters and listed in parallel:

- `__meta` is enumerated by 26 prefix shards, plus two boundary shards so a
  name outside of the alphabet is not silently dropped;
- the files of all directories are collected by a few listings of the whole
  disk instead of one listing per directory (716 requests for 501234 objects),
  interleaved with the `prefix.path` reads so both run at the same time.

The metadata load of that disk goes from 116 to 37 seconds, and the query
that triggers it from 2m22s to 1m05s.

This needs the object storage to list by an arbitrary key prefix and to honour
`start_after`, which `LocalObjectStorage` and `AzureObjectStorage` do not, so
it is gated on the new `IObjectStorage::supportsPrefixListing`. A disk with
few directories keeps the previous single-request path.

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

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20fdf11]

Summary: ✅


AI Review

Summary

This PR parallelizes plain_rewritable metadata loading on large s3_plain_rewritable disks by sharding __meta listings and prelisting file objects across directory-name prefixes. The overall approach makes sense, but the new cutover/shard sizing bakes in the default 1000-key S3 page size, so supported non-default list_object_keys_size configurations can switch at the wrong point and do extra listing work.

Findings

⚠️ Majors

  • [src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.cpp:75] MIN_DIRECTORIES_TO_LIST_IN_PARALLEL and DIRECTORIES_PER_LISTING_SHARD hard-code assumptions about the default list_object_keys_size = 1000. On disks configured with smaller pages (for example list_object_keys_size = 1, which we already use in tests to force pagination), the probe burns 4096 sequential ListObjects calls before sharding and then re-reads the same keys; with larger page sizes it can overshard a path that still fits in one page. That breaks the PR’s performance contract on supported S3 settings.
    Suggested fix: derive the cutover and shard sizing from the storage’s actual list_object_keys_size, or expose the thresholds as settings so tests and operators can tune them.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: make the cutover/shard sizing depend on the actual S3 listing page size (or expose the thresholds as tunable settings) so the large-disk path does not regress supported list_object_keys_size configurations.

LLVM Coverage Report

Measured on commit 20fdf11.

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

Changed lines: Changed C/C++ lines covered: 74/143 (51.75%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 21, 2026
/// The point of the sharded listing is to replace many sequential pages with a few parallel ones,
/// so it only pays off once a plain listing would need many pages. Until then a plain listing costs
/// a single request while a sharded one costs one request per shard.
constexpr size_t MIN_DIRECTORIES_TO_LIST_IN_PARALLEL = 4096;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

list_object_keys_size is a supported S3 disk setting, but these cutover/shard constants bake in the default 1000-key page size.

On a disk configured with a smaller page size (for example list_object_keys_size = 1, which we already use in tests to force pagination), the sequential probe above burns 4096 ListObjects requests before it even switches to the sharded path, and then the sharded loaders re-read the same keys. With a larger page size, the same constants can overshard a path that still fits in one page. That makes the “large disk” optimization depend on an unstated setting value and can regress supported configurations.

Can this derive its cutover and shard sizing from the storage’s actual list_object_keys_size, or at least expose the thresholds as settings so they can be tuned and tested?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not a problem.

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 6f5a193c-6c8c-43a5-9ad0-a46b886b4e6a
  • MIRAI run: bcf56cc0-dfa3-4249-acac-799f1c701bc0
  • PR check IDs:
    • clickbench_1236679_1790022971
    • clickbench_1236782_1790023005
    • clickbench_1236935_1790023189
    • tpch_adapted_1_official_1237036_1790023197
    • tpch_adapted_1_official_1237209_1790023241
    • tpch_adapted_1_official_1237310_1790023247

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 20fdf11ac with master c4aba0e37 (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.

Object file sizes

47 object files changed (+62.18 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFro… 404.54 KiB 464.54 KiB +59.99 KiB (+14.83%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-multidisk Multiple disks/volumes storage policies, disk abstractions. label Sep 22, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The implementation is good.

@alexey-milovidov alexey-milovidov self-assigned this Sep 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

I'm afraid it is not covered by tests, but in this case it is acceptable.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 22, 2026
Merged via the queue into master with commit 1ca7698 Sep 22, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the speedup-plain-rewritable-metadata-load branch September 22, 2026 21:22
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 22, 2026
alexey-milovidov added a commit that referenced this pull request Sep 26, 2026
…apshot-file

Resolve the conflict in `MetadataStorageFromPlainRewritableObjectStorage.cpp` with
#121412, which reworked the listing of the
metadata directory (prefix shards, prelisted files, per-directory result slots).

`listRemoteLayout` now enumerates the directories with the sharded listing from master, then
takes the directories whose `prefix.path` ETag matches the base (the snapshot or the current
state) without reading, and loads only the rest. The whole-disk prelisting of files is used
when there are many directories left to load, instead of being tied to the refresh flag that
no longer exists.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... and removed comp-multidisk Multiple disks/volumes storage policies, disk abstractions. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... 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.

2 participants