Repository navigation
Compact snapshot files for plain_rewritable disks - #121431
Conversation
Initialization of a `plain_rewritable` disk listed the `__meta` directory, read every `prefix.path` and listed every directory: tens of thousands of requests even for a disk with a single table. The disk that writes the data now also writes `__meta/snapshot.bin`: the whole state (directories with their logical paths and ETags, and the files in them) serialized with a version field and compressed with `ZSTD` in the native framing. It is rewritten right after every commit by default, or in a `BackgroundSchedulePool` task not more often than `metadata_snapshot_write_delay_ms`, and on shutdown. It is removed when the disk becomes empty. `metadata_snapshot_enabled` turns the feature off. On startup the writer reads the snapshot and reconciles it with a listing of the `__meta` directory (one request per thousand directories): only the directories created, removed or renamed after the snapshot are loaded. A read-only disk uses the snapshot on startup and on every refresh, skipping the refresh when its ETag did not change. The incremental refresh now reuses unchanged directories by the remote path and the ETag from the listing, without reading their `prefix.path`, and the move operation records the new ETag of the rewritten `prefix.path` in memory, so a renamed part is not reloaded on the next start. Closes: #121416 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [cd555a5] Summary: ✅
AI ReviewSummaryThe PR publishes compressed, versioned metadata snapshots for read-only Missing context / blind spots
Findings
Tests
Final VerdictStatus: |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
…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]>
`cppcoreguidelines-pro-type-member-init` failed the `arm_tidy` build: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121431&sha=119fdb7f9ea1527afb723d9ea15ed1aa77986614&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: #121431 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… snapshot writes by default Two review findings from `clickhouse-gh` on #121431: 1. A read-only disk trusted `snapshot.bin` alone: an unchanged ETag skipped the refresh, so a snapshot that lagged behind (a failed write, which does not fail the commit, or a delayed one) hid committed parts forever, and a stale snapshot read after a listing could roll the state back. Now the reader reconciles the snapshot with the listing of `__meta`, as the writer does at startup: with a new snapshot it is the base, with an unchanged one the state in memory is the base and the file is not read again. Only the directories that changed after the base are loaded. 2. With `metadata_snapshot_write_delay_ms = 0` by default, every commit serialized the metadata of the whole disk in the committing thread, making commit latency proportional to the disk size. The default is now `1000`, so the snapshot is written in the background. When the disk becomes empty, the snapshot is removed right away regardless of the delay (a single cheap request), so nothing is left behind after the last `DROP`. The unit tests and the `disk_snapshot` disk of the integration test keep the delay at `0`. The new `test_readonly_replica_does_not_trust_stale_snapshot` checks that a reader sees the parts committed after a snapshot that is not rewritten. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…apshot-file Conflict resolution: master added skipping of `prefix.path` reads for unchanged directories on refresh (`local_paths_by_remote_directory`, gated on `isEtagUsableAsCacheKey`). This branch already reuses unchanged directories from the base layout (the snapshot or the state in memory) by ETag, which covers the same case, so master's map is dropped and its strong-ETag requirement is applied to the base reuse instead. The new `RefreshSkipsUnchangedDirectoryReads` gtest constructs its reader with the snapshot disabled, because it counts the `prefix.path` reads done by the listing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…from a snapshot The ETag of `prefix.path` changes only when a directory is renamed, not when files are added, removed or replaced inside it (e.g. `mutation_*.txt` of a table, delete bitmaps, or the `.sql` files of a database on a database disk). Taking the file list of such a directory from a stale snapshot hid these changes after a restart, which resulted in the `file_offset_of_buffer_end <= getFileSize()` exception in the integration tests with the database disk. Now a directory with an unchanged `prefix.path` takes only its local path from the snapshot (saving a read of `prefix.path` per directory), and its files are always listed. The snapshot is used only at startup: a periodic refresh of a read-only disk reconciles the state in memory with the listing, as on master, so the ETag check of the snapshot file and `DiskPlainRewritableSnapshotUnchanged` are removed. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121431&sha=b9b444df0e99b07c05d47960fea865599ab1c208&name_0=PR #121431 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes107 object files changed (+275.28 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1847 translation units recompiled, 11702 s compile time in total, 1845 of them have a recent master baseline. Translation units without a recent master baseline:
|
In the `db disk` CI variant, every instance gets a `plain_rewritable` database disk, which reads and writes its own snapshot. That changes the global `DiskPlainRewritableSnapshotWritten` profile event of the read-only server and adds `had changes after the snapshot` to the log, which the test checks for the disk under test. Disable the remote database disk for these instances. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121431&sha=3e3fab5124eaa52027946bd48b7b2011129e36c1&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20targeted%29 #121431 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e snapshot file `readPlainRewritableSnapshot` reserved the directory and file hash tables from the counts read from `snapshot.bin` before validating them, so a corrupted file could request a huge allocation instead of failing to parse and falling back to a full listing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…apshot-file Reconcile the snapshot file with the hard links of `plain_rewritable` disks, which landed on master: - The snapshot file stores whether a directory lists its files explicitly in `prefix.path` and the blob key of every file, so a state loaded from it keeps the hard links (blob link counts are recalculated from it by `FsMetadata::applyLayout`). - A directory in the explicit form whose `prefix.path` has the same ETag as in the snapshot takes its files from the snapshot: the list of files is the contents of `prefix.path`, and the blobs under its prefix are not its files. - The root is compared as a whole to decide whether the state differs from the snapshot, as it can now have a `prefix.path` in the explicit form. - The constructor takes both `enable_hard_links` and the snapshot settings. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ists Without taking the files of an unchanged directory in the explicit form from the snapshot, the restarted state loses the hard link (the directory gets only the blobs under its own prefix). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged |
…ainRewritableSnapshotRead` With `metadata_snapshot_write_delay_ms = 0`, every committer waited for the snapshot write lock and then rewrote the whole snapshot, even when a write that finished meanwhile already included its change. Track a generation of the state changes and the generation of the last written snapshot, so a committer whose change is already written returns right away: at most one write follows the one in progress. The `DiskPlainRewritableSnapshotRead` description now says that the snapshot is used as the base and is still reconciled with the object storage listing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The snapshot writer read the change generation before taking the tree, while commits publish the tree before bumping the generation, so a write could contain commit `N+1` but record generation `N`, and the committer of `N+1` did another full rewrite. Now `FsMetadata` keeps a version incremented under its own mutex when a tree is applied, and the writer takes the tree and its version atomically with `takeReadOnlySnapshotWithVersion`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ct storage `LocalObjectStorage` rewrote an existing object in place (truncate, then write), so a read-only disk loading `__meta/snapshot.bin` while the writer was rewriting it read a torn file and logged `Cannot read the snapshot file ... ATTEMPT_TO_READ_AFTER_EOF` before falling back to the listing. Object storages like S3 publish an object at once, so this only affects local disks. Add `WriteSettings::object_storage_write_atomically`: `LocalObjectStorage` then writes to a temporary file and renames it over the target, under the same directory lock and with the same strictly increasing mtime (ETag) as a conditional write. The writer of the snapshot sets it. The name of the temporary file no longer comes from `thread_local_rng`, which tests seed to get predictable directory names. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121431&sha=a37633ce5f9f8d7fbe1e1127cbcfc4d3d48ff191&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 #121431 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed 7b37258: merged
The open review thread about stale snapshots after a completed file replacement was already answered (it is the existing staleness model of readers, now documented); it is left for a human to resolve. |
The snapshot file is rewritten while readers download it, and a download can consist of several GET requests (ranged reads, retries). Without an expected ETag they could splice bytes from two snapshots. Now a changed generation fails the read, and the reader falls back to listing the object storage. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121431&sha=7b37258d607ebc0d1840daec1e943b434e1a74e8&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 ( |
|
The fix is my open #125562. It passes This run has the same chain as the earlier one on this PR. The previous release (26.9.21.9) retried the #125562 has green CI and still merges cleanly, but it has had no review since 2026-10-13. CIDB shows this failure, or its |
| { | ||
| /// The tree and its version are taken together, so the recorded generation is exactly the state that is written. | ||
| auto [tree, generation] = fs.takeReadOnlySnapshotWithVersion(); | ||
| auto remote_layout = getLayoutOf(*tree); |
There was a problem hiding this comment.
[P2] Build the layout without locking the live metadata snapshot
takeReadOnlySnapshotWithVersion returns the live latest_snapshot. getLayoutOf then calls FsSnapshot::getSubtreeRemoteInfo, which holds that snapshot's mutex throughout the traversal and deep copy of every directory's file map (FsSnapshot.cpp:390-405). Transaction creation and publication need the same mutex in getRoot; FsMetadata::takeReadWriteSnapshot and FsMetadata::applyJournal wait for it while holding the disk-wide FsMetadata mutex. Once a transaction waits there, other metadata reads also queue behind it.
Thus the default background writer still pauses foreground reads and commits for work proportional to the entire disk's metadata, potentially every second. This matters particularly for the large disks this change targets; moving serialization out of the committing thread does not isolate this copy.
Please capture the immutable root and version under short locks, then traverse an independent snapshot (or release the live snapshot's lock after capturing the root). A focused large-layout measurement with concurrent transactions should verify that foreground latency no longer scales with the snapshot copy; the reader request-count test does not exercise this contention.
There was a problem hiding this comment.
Ok for a follow-up.
…metadata snapshot The reader disk is created right after the insert into the writer, while the writer rewrites the snapshot with the default delay of 1 second. So the reader could load the snapshot written before the insert and see no parts (`sum(a)` returned 0 instead of 6). Rewrite the snapshot right after every commit, as the other tests with such a reader do. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121431&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel) #121431 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ithout atomic writes `HDFSObjectStorage::writeObject` truncates the destination, and the ADLS Gen2 (OneLake) path of `AzureObjectStorage` creates the destination before appending to it. Rewriting `__meta/snapshot.bin` there would expose an incomplete snapshot to the readers and lose the previous one on a failed write. Add `IObjectStorage::supportsAtomicWrite` (true for S3, Azure Blob Storage except ADLS Gen2 endpoints, local; forwarded by the cache) and do not write or read the snapshot when it is false. The writer removes a snapshot left from before on startup, as with `metadata_snapshot_enabled` set to `false`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
After merging master, the incremental refresh from #121431 takes unchanged directories from the base layout keyed by the normalized path (`a/b`), while directories read anew are keyed by the logical path from `prefix.path` (`a/b/`). When two `prefix.path` objects claim the same directory - which happens when several servers sharing the disk under `leader_election` each create the directory of a table - one copy was reused and the other reloaded under a different key, and `FsSnapshot::recordDirectoryPath` threw `DIRECTORY_ALREADY_EXISTS` ("was already recorded") on every refresh, so no node could take over the lease. Key both the same way, as before #121431. Related: #121431 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tings The test measured the S3 write requests of one INSERT by diffing the server-global `S3WriteRequestsCount` in `system.events`. In the `db disk` flavour the database disk is a `plain_rewritable` S3 disk, which since ClickHouse#121431 rewrites `__meta/snapshot.bin` from a background task `metadata_snapshot_write_delay_ms` (1000 ms) after a layout change such as the test's own CREATE TABLE. That PUT belongs to no query but bumps the global counter; when it landed in the first window the single-part count became 17 (16 data requests + 1 snapshot write) while the multi-part INSERT still took 48 = 16 * 3, failing `48 == 17 * 3` on master (Integration tests (amd_asan_ubsan, db disk, 1/8), d7b58a4 and f2c1ac3). Read each INSERT's own `ProfileEvents['S3WriteRequestsCount']` from `system.query_log` by `query_id` instead, which no background S3 traffic of the server can reach, and require the single-part count to be positive so the comparison cannot pass as `0 == 0 * 3`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_blob_storage_plain_rewritable `test_insert_select` creates a second writer on the location of `node`: `other_node` attaches an inline `plain_rewritable` disk with the same `endpoint_subpath`, so that its initial listing runs with the `plain_rewritable_object_storage_azure_not_found_on_init` failpoint. Since ClickHouse#121431 every writer publishes `__meta/snapshot.bin` `metadata_snapshot_write_delay_ms` (1 s by default) after a change. `other_node` keeps the directories of `node` it listed and never sees them dropped, so its delayed write can land after the last `DROP` on `node` has removed the snapshot ("as the disk is empty") and before the test lists the container. That is the leftover `node/__meta/snapshot.bin` seen once on master (Integration tests (amd_llvm_coverage, 2/8), 981 bytes, written by `other_node` 45 ms after the removal on `node`). The snapshot has one writer per location by design, so disable it on the disk of `other_node`. Its listing (and the failpoint) still runs; the only snapshot operation left there is the removal of a stale snapshot at its own `CREATE TABLE`, before the `DROP`s on `node`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflict in gtest_metadata_plain_rewritable_disk.cpp: keep the 26.10 side of the `ErrorCodes` declarations and add only `DIRECTORY_ALREADY_EXISTS`. The conflicting master line, `INCORRECT_DATA`, comes from #121431, which is not on 26.10 and is not needed by these tests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #121416
Related: #118490
Related: #121412
Initialization of a
plain_rewritabledisk listed the__metadirectory, read everyprefix.pathand listed every directory: tens of thousands of requests even for a disk with a single table.The disk that writes the data now also writes a compact snapshot of the whole state to
__meta/snapshot.binfor the read-only disks pointing to the same location: every directory with its logical path, the ETag of itsprefix.pathand its files, serialized with a version field and compressed withZSTDin the native ClickHouse framing (CompressedWriteBuffer). The format is described inPlainRewritableSnapshotFile.h.Reader (a disk with
readonlyset). Readers already work on a delayed state: they refresh it periodically (refresh_parts_interval) and rely on the lifetime of old parts ofMergeTreetables. A snapshot is a delayed state of the same kind, so the reader trusts it fully: on startup and on every refresh it reads only the snapshot (aHEAD, and aGETonly if the ETag changed since the last load), without listing the metadata directory or reading anyprefix.path. The one exception is a replacement of a file that the writer is doing right now: the target is overwritten in place and its committed content is only in the backup, so the reader lists the markers of unfinished operations (a single request, as there are none most of the time) and reads such targets from their backups, as the listing of the object storage does. If there is no snapshot (the writer has it disabled or runs an older version) or it cannot be read, the reader lists the object storage as before.Writer. It has to have the latest and precise state, which it fully controls, so it never reads the snapshot: it lists the object storage on startup and on reloads as before, and writes the snapshot after that. By default the snapshot is rewritten in a
BackgroundSchedulePooltask not more often thanmetadata_snapshot_write_delay_ms(default1000), as long as there were modifications, and on shutdown. Serializing the whole state in the committing thread would make every commit as expensive as the size of the whole disk, so0(rewrite right after every commit, coalescing concurrent commits) is opt-in. A failed write is logged, counted inDiskPlainRewritableSnapshotWriteFailedand retried; it never fails the commit. The snapshot is removed right away (regardless of the delay) when the disk becomes empty, so a dropped-everything disk leaves no garbage behind.metadata_snapshot_enabled(defaulttrue) turns the feature off. Older versions ignore__meta/snapshot.bin(they skip everything under__metathat is not aprefix.path), whichtest_plain_rewritable_backward_compatibilityexercises with real old releases.A related change in the existing code: the incremental refresh (of a reader without a snapshot) reuses an unchanged directory by its remote path and the strong ETag from the listing, without reading its
prefix.pathfirst (the previous code read everyprefix.pathand only then compared). It is combined with the sharded listing of__metafrom #121412: the directories are enumerated by prefix shards, the unchanged ones are taken from the base, and the whole-disk prelisting of files is used only when many directories are left to load.New events:
DiskPlainRewritableSnapshotRead,DiskPlainRewritableSnapshotWritten,DiskPlainRewritableSnapshotWriteFailed. Documented in theplain_rewritablesection ofstoring-data.mdx.Tests: the new
test_plain_rewritable_snapshotcovers the write after commits, the writer not reading the snapshot on restart and recreating it when deleted, the removal on an empty disk, a writer ignoring a stale snapshot, a read-only replica loading from the snapshot and seeing the changes through the refresh, a read-only replica trusting a snapshot that lags behind until the writer rewrites it, the delayed write with the flush on shutdown, and the disabled setting. The unit testReaderTrustsSnapshotchecks that a reader makes one read and no listings of the metadata, does not re-read an unchanged snapshot, and falls back to the listing without a snapshot;ReadOnlyLoadOfPendingReplacenow goes through the snapshot reader;WriterIgnoresStaleSnapshotchecks that a writer restarted with a stale snapshot sees the latest files.test_s3_plain_rewritableandtest_plain_rewr_legacy_layoutare adjusted for the new object under__meta.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The disk that writes to a
plain_rewritablelocation now publishes a compact snapshot of its metadata in__meta/snapshot.bin, and read-only disks pointing to the same location load their state from it on startup and on every refresh instead of listing the object storage and reading everyprefix.path, which took tens of thousands of requests. Controlled by the disk settingsmetadata_snapshot_enabledandmetadata_snapshot_write_delay_ms. Closes #121416.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/121431]
Version info
26.11.1.683-master(included in26.11and later)