Repository navigation
Conversation
On an object-storage disk (s3, azure_blob_storage, local_blob_storage, ...) with local metadata the MergeTree fsync setting family (fsync_after_insert, fsync_part_directory, min_rows_to_fsync_after_merge, min_compressed_bytes_to_fsync_after_merge) was silently ignored: an acknowledged INSERT issued zero fsync. The local metadata files that commit a part (the map file->blob) were only finalized, so on a real s3 disk the blob is durable but the local metadata is lost on power loss - the acknowledged part is gone and the blobs are leaked, with no error. Three independent paths, each fixed at its own layer: 1. ForkWriteBuffer (the part's blob write buffer) did not override sync, so the part's file sync landed in the base WriteBuffer::sync (a plain flush) and never reached the underlying writers. It now forwards sync to its children. For s3/azure the writer's sync is a no-op (durability is on finalize); for local-file-backed object storage it performs the fdatasync. 2. The local metadata files were only finalized, never fsynced. The write buffer's sync now requests a sync of the local metadata file via the new IMetadataStorage::syncMetadataFile. The request is latched in the buffer because a compact part syncs its stream before finalizing while a wide part syncs after. The fsync happens only once the metadata file has been committed to disk, which for a local-metadata disk is during the finalize callback (an autocommit / fake transaction). A queued transaction (Keeper metadata) has not created the file yet, and its part durability is Keeper's responsibility rather than a local fsync, so it is a no-op there. 3. DiskObjectStorage did not override getDirectorySyncGuard, so fsync_part_directory was a no-op. It now delegates to the metadata storage's local disk, but only for a fake (immediate) transaction: a queued transaction has not created the directory when the guard is requested, so returning a guard there would fail to open it. Both metadata capabilities are forwarded through MetadataStorageFromCacheObjectStorage so cache-wrapped disks are covered. Gating is the existing sync call (driven by fsync_after_insert / needSyncPart / fsync_part_directory), so there is no new setting and no change to default behavior. ISyncGuard is moved to its own header to let IMetadataStorage expose a directory-sync guard without a circular include. Closes: ClickHouse#111330 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-4:20260722-105200 |
Internal second-model review (click to expand)Independent second-model code review (two rounds: full pass on the initial diff, then a delta recheck of the fixes). All findings were adjudicated against the code; every one was AGREE and fixed + re-verified. ❌ Blockers
💡 Nits
|
|
cc @kssenii @CheSema — could you review this? It makes object-storage disks honor the MergeTree fsync settings ( |
|
Workflow [PR], commit [1ec54d2] Summary: ❌
AI ReviewSummaryThe PR forwards blob syncs and carries file-sync intent into local object-storage metadata writes, covering queued part transactions and autocommit writes. The creation paths have regression coverage, but shared metadata can lose that protection during subsequent old-part cleanup. The explicitly deferred directory-sync and remote Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ Block. Preserve the synced mapping through shared-metadata cleanup and add focused regression coverage, or explicitly track and document this remaining lifecycle limitation before treating the durability fix as complete. |
The Style check (cpp) rule "Return value of close() should be checked" flagged the bare ::close(fd) in the CANNOT_FSYNC error path. Use the codebase-idiomatic best-effort form ([[maybe_unused]] int close_err), matching ReadBufferFromFile/CounterInFile: fsync already failed and we throw CANNOT_FSYNC regardless, so close is best-effort. Also snapshot the fsync errno before close() (which may overwrite it) and report it via throwFromPathWithErrno, so the CANNOT_FSYNC exception carries the real fsync error rather than close()'s. No functional change to the success path. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — 50fd27dCI fully finished on this head with zero test failures (Finish Workflow + Mergeable Session id: cron:our-pr-ci-monitor:20260723-023000 |
The getDirectorySyncGuard and requestMetadataSync comments claimed the queued-transaction path's metadata durability is Keeper's responsibility. That is wrong for local-metadata object-storage disks explicitly configured with use_fake_transaction=false (e.g. s3_disk_no_fake_transaction, local_object_storage_disk): those have no Keeper, yet still skip the fsync. The gating behavior is unchanged (out of scope for this PR); only the comments are corrected to state the accurate local invariant and point at issue ClickHouse#111330 for the queued-path follow-up. Co-Authored-By: Claude Opus 4.8 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 51/60 (85.00%) · Uncovered code |
Master removed both foundations this fix was built on: c83fa3c replaced WriteBufferWithFinalizeCallback with WriteBufferInlineOrBlob (and added inline metadata content), and 228ca4c removed use_fake_transaction entirely. The metadata-sync latch is ported into WriteBufferInlineOrBlob, honored on both the blob and the inline finalize path, and the part-directory guard now asks appliesOperationsEagerly() instead of the removed setting. This resolves the conflict but does NOT restore the durability contract: no metadata storage is both eager and backed by a syncable local file, so the metadata fsync and the part-directory sync are now unreachable. Measured on this tree: an INSERT with fsync_after_insert=1 and fsync_part_directory=1 issues 11 fdatasync calls, all of them on blobs, and DirectorySync stays 0. The remaining two legs need a redesign against the new transaction model, deferring the metadata fsync to after the metadata transaction commits.
On an object-storage disk with local metadata, fsync_after_insert = 1 synced the
blobs and left the local commit record unsynced: WriteFileOperation::execute
finalized the metadata file, and finalize() only flushes to the OS, while
WriteBufferFromFileDescriptor::sync() is the only thing that issues fdatasync.
On power loss the blobs survived and the local file mapping the part's logical
files to those blobs did not, so an acknowledged INSERT lost its part.
The write intent has to cross two different orderings, so it is consumed twice:
* Queued writes (INSERT, merge, mutation) construct their metadata operations
inside DiskObjectStorageTransaction::commit(), when the replay loop runs
createMetadataFile / addBlobToMetadata. The intent is therefore published as
the first statement of commit() and tryCommit(), before that loop, so every
WriteFileOperation is built with it visible. Each one then fsyncs the file it
just wrote, on that file's own descriptor, inside the rollback-capable
MetadataOperationsHolder::commit sequence.
* Autocommit writes commit inside their own finalize callback, so by the time
the buffer reports the intent the metadata file already exists and commit()
will not run again. Those go straight to the new
IMetadataStorage::syncMetadataFile, which throws rather than skipping when
the file is absent, since no caller may reach it before the metadata is
recorded.
WriteFileOperation's constructor takes the flag as a required argument, so the
compiler enumerates every metadata-mutating operation that has to thread it,
including ReplaceFileOperation through its nested UnlinkFileOperation. The cache
and path metadata wrappers forward both new methods, and the path wrapper remaps
through wrappedPath() for the call that carries a path. Nothing is added to
IDiskTransaction, so FakeDiskTransaction and DiskEncryptedTransaction are
untouched.
This is exactly what a local disk does for the same setting and nothing more:
every DirectorySync producer on the part path is guarded by fsync_part_directory
and nothing else, while file fsync is guarded only by the sync bool, so a local
disk under fsync_after_insert = 1 with fsync_part_directory = 0 also syncs file
contents and no directory. Extending the directory sync to these disks needs a
separate intent threaded through IDiskTransaction, because
DataPartStorageOnDiskBase::getDirectorySyncGuard goes straight to the disk and
bypasses the transaction. That is a follow-up, so the issue is linked as related
rather than auto-closed.
Two upstream commits removed the machinery the earlier attempt on this branch was
built on: c83fa3c deleted WriteBufferWithFinalizeCallback in favour of
WriteBufferInlineOrBlob, and 228ca4c removed use_fake_transaction, which
both of its inert legs were gated on. This replaces that attempt and is a net
simplification of it: ISyncGuard.h, the getDirectorySyncGuard overrides and a
hand-rolled open/fdatasync/close block are deleted.
Validated by tracing fdatasync on the same INSERT: 0 part-metadata syncs before
the change and 11 after, with blob syncs unchanged, and 0 in both builds when the
settings are off. Two independent mutation controls redden, one per consumer, and
neither moves the other. The rewritten 04541_object_storage_disk_fsync compares
an object-storage disk against a local disk holding the same table, so it asserts
the relationship rather than a pinned syscall count; it fails on the unfixed
build and passes 50 out of 50 under randomized settings. Its previous run_nonfake
arm is deleted, as it passed use_fake_transaction = false, a removed setting that
is accepted silently, so the arm asserted nothing.
Related: ClickHouse#111330
…erings Review round 1 on the object-storage fsync fix. syncMetadataFile checked that the metadata file exists and then reopened it with WriteMode::Append, which DiskLocal maps to O_APPEND|O_CREAT|O_WRONLY. A commit removing the path between the check and the open would make the open create the file, and the fsync would then persist a zero-length metadata record over a valid mapping. MetadataStorageFromDisk already owns this invariant: every reader takes a shared lock on metadata_mutex and the mutating commit takes a unique lock, and this was the only path in the class that did not participate. A shared lock is sufficient because the function mutates nothing, and it excludes the unique-lock commit that is the only thing which removes or rewrites a metadata file. The sync callback runs after the finalize callback has returned, so the non-recursive SharedMutex cannot self-deadlock. Measured: the compact-part metadata fdatasync count and the exact set of synced files are unchanged (11), so the lock only excludes the race. The gtest harness counted metadata syncs but no arm read the counter, so the latch that makes both sync orderings correct was asserted by nothing. Assert it in both directions - sync after finalize (wide parts) and sync before finalize (compact parts and writeMetadataFile) - plus the two opt-out directions, no sync at all and cancel. Each of the six arms was confirmed to redden under a targeted mutation of the code it covers. Merges derive their sync request from min_rows_to_fsync_after_merge and min_compressed_bytes_to_fsync_after_merge independently of the insert path, so add a merge case to the stateless test in the same relative-comparison style, following 04546_text_index_merge_fsync for the pins that make an OPTIMIZE FINAL the only merger and its syncs attributable.
The flag is set for the inline branch too, whose callback only queues the write when the transaction is not autocommit, so at that point no file necessarily exists on disk. Name the actual condition - the metadata operation is recorded with the transaction - instead of implying the file is already there. Comment-only: the code is byte-identical after stripping comments.
The write intent reaches the metadata file through two orderings, and only the queued one had an end-to-end arm. Emptying syncCommittedMetadataFile left every test in the tree green. ALTER TABLE ... UPDATE is the carrier: MergeTreeMutationEntry's constructor writes tmp_mutation_<N>.txt with disk->writeFile(), which is the autocommit route, and syncs it. Reached from plain SQL through StorageMergeTree::prepareMutationEntry, so no fixture gymnastics are needed. The case keeps the relative local-vs-objstore oracle the file already uses, so it pins no syscall count and survives the s3/azure variants. It carries no negative arm: the entry's sync is unconditional, so no setting can turn it off and such an arm would assert a constant. Verified against a build with syncCommittedMetadataFile emptied and the queued route untouched: the new line is the only one that differs (objstore syncs more 1 -> 0) while every pre-existing arm stays green, so the arm is specific to this consumer rather than to the fix in general. The (local, objstore) pair is invariant at (1, 2) across 20 runs, and the test passes 50/50 with and without randomized settings.
AGENTS.md line 13 (a symlink to .claude/CLAUDE.md, added in 7f9736f) asks for names of functions and methods to be written as `f` rather than `f()` when the text refers to the function itself rather than its application. Six comment lines added by this PR spelled commit, sync and finalize with parentheses. Comment prose only, so the preprocessed output of every touched translation unit is unchanged. sources.front() in ForkWriteBuffer.cpp is left as it is: there the text names the object the call returns, which is an application and outside the rule.
Internal second-model review (click to expand)An independent model reviewed this change cold across four rounds and I adjudicated its findings Corrected in the description: a claim of mine was wrong An earlier revision of this description said blob syncs were unchanged. That is false for a Blocker, disagreed:
Blocker, disagreed: rollback durability is pre-existing
Major, disagreed: packed-part storage is untouched pre-existing plumbing The suite covers full storage only, so the packed durability chain Nit, disagreed: changelog category left as Raised twice, and the template's own wording supports it. I do not select Nit, agreed and fixed Comments spelled method references as calls ( Found in my own review and fixed before publishing Two further claims in the description that a reviewer could not verify from the diff: one One tradeoff, stated plainly rather than buried On the queued path the fsync runs inside the metadata storage's unique lock, because that is where Reviewed against: root cause, the both-directions proof, per-consumer mutation controls (one per |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260822-000900 |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units61 translation units recompiled, 565 s compile time in total, 61 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
The test grew from 3 cases over 2000 rows to 8 cases over 104000 rows while gaining the merge, ALTER and directory-only arms. The flaky check runs 50 iterations of it and several copies concurrently, so at that size it crossed the 180s per-test limit: it took 62s in July and 194s now, and "Stateless tests (amd_asan_ubsan, flaky check)" failed with "Test runs too long (> 180s)". Row count is not load-bearing for any assertion. Every fsync assertion is relative, comparing the object-storage disk's sync count against a local disk holding the same table, and a wide part's per-column file set is fixed by min_bytes_for_wide_part = 0 rather than by the number of rows. Scale the data down 10x and adjust the correctness lines in the reference. The reduced test still discriminates: against a binary without the fix it fails the three "syncs more" assertions (wide, compact and merge with fsync on), and 7 concurrent copies finish in 5s where one copy previously needed 194s.
|
The test grew from 3 cases over 2000 rows to 8 cases over 104000 rows while gaining the merge, ALTER and directory-only arms. The flaky check runs 50 iterations and several copies at once, so it went from 62s in July to 194s. Row count is not load-bearing: every fsync assertion is relative, comparing the object-storage disk's sync count against a local disk holding the same table, and a wide part's per-column file set is fixed by Verified both directions on a debug build:
No source change in this commit. |
The arm asserted DirectorySync=0 for fsync_part_directory = 1 on an object-storage disk. That pins the current gap as the expected value, so the follow-up that threads the directory-sync intent through IDiskTransaction would land as a red test. It also could not discriminate this change: measured with the fsync binary and the pre-fix binary, 2000 rows, min_bytes_for_wide_part = 0, ProfileEvents keyed by query_id, both report FileSync=0 DirectorySync=0 on the object-storage disk. Its FileSync=0 half duplicates the existing "fsync off" arms. The comment above it claimed a local disk syncs no directory for fsync_after_insert = 0. It syncs three: both MergeTreeDataWriter.cpp and MergeTreeData.cpp take a DirectorySyncGuard on fsync_part_directory alone, with no fsync_after_insert conjunct, and DiskLocal overrides getDirectorySyncGuard while DiskObjectStorage inherits the nullptr from IDisk. The remaining arms keep their full discriminating power: the pre-fix binary still fails on wide, compact and merge "fsync on" (objstore syncs more=0 against an expected 1), and the fix binary matches the reference exactly. The DirectorySync=0 column printed by the other arms is unaffected, since those leave fsync_part_directory at its default of 0 and never request the guard.
The test spent most of its time on process startup, not on the queries it measures. Each of the seven cases spawned a client for setup, one per insert, one per counter read and one for teardown, and every counter read also ran `system flush logs query_log`. Under the asan+ubsan build a client spawn costs 2-4 seconds, so the 42 spawns and 14 flushes came to about 175 seconds against the 180 second per-run budget of the flaky check, and the row counts the previous attempt reduced were never the cost driver. Each measured statement now names its case in a query level `log_comment`, and one final client flushes the log once and reads every counter in a single query, which leaves 5 spawns and 1 flush. A log comment that failed to reach query_log would come back as a missing row and be read as a sync count of 0, which is indistinguishable from a real 0, so the read requires all 14 rows. The expected output is unchanged, and the pre-fix binary still fails the three assertions that discriminate the fix.
PR-caused CI failure fixed:
|
| step | measured |
|---|---|
| client spawn + setup DDL | 3s |
insert ... numbers(2000) |
3s |
counter read (spawn + system flush logs) |
5-7s |
| teardown | 3-5s |
| one case | ~25s |
An insert of 2000 rows costs the same as a bare spawn, so seven cases x ~25s = ~175s was
structural. That is also why the previous 10x row reduction did almost nothing: rows were never the
driver. The counter reads alone were ~48% of the runtime, because each one paid a spawn and a
system flush logs query_log.
Fix: each measured statement now names its case in a query-level log_comment, and one final
client flushes once and reads every counter in a single query. 42 spawns -> 5, 14 flushes -> 1.
Verified on Build ID 255515fdbfbf57fd (asserted server-side):
- 1-2s per run, down from ~175s; stderr empty; output byte-identical to the unchanged
.reference(the reference is not touched by this commit, which is what shows the oracle did not
move). - 8 concurrent copies finish in 2s wall clock, 8/8 reference match, 0 bytes stderr, which is
the check's own--jobs 8load. - The pre-fix binary still fails on exactly the three assertions that discriminate this PR
(wide/compact/merge"fsync on":objstore syncs more=0vs expected1), so no
discriminating power was traded for the speed-up. - A batched read can hide a missing row as a sync count of 0, so it requires all 14 rows. I checked
that guard can fail: corrupting onelog_commentmakes the test throw
Code: 395 ... missing query_log rowsrather than quietly printing a 0.
Row counts and every assertion are unchanged; only the number of processes is different.
| auto sync_metadata_callback = [disk_tx = shared_from_this(), path, autocommit]() | ||
| { | ||
| if (autocommit) | ||
| disk_tx->syncCommittedMetadataFile(path); |
There was a problem hiding this comment.
syncCommittedMetadataFile now gives autocommit object-storage writes a real metadata fdatasync, which is exactly the shape RESTORE uses once BackupImpl takes the synced buffered path (destination_disk->writeFile(...); finalize(); sync(); in src/Backups/BackupImpl.cpp). But MergeTreeData::restorePartFromBackup still computes fsync_files as fsync_after_insert && !disk->isRemote() (src/Storages/MergeTree/MergeTreeData.cpp:8849-8853), so object-storage disks never call sync() there.
That leaves acknowledged RESTORE on local-metadata object-storage disks with the same durability hole this PR fixes for INSERT: the blobs may be durable, but the local metadata record committing the part is not. Now that the autocommit sync path exists, the RESTORE caller needs to pass the setting through as well.
There was a problem hiding this comment.
Agreed that the gap is real, and this PR is what creates it. Measured on local_blob_storage, fsync_after_insert = 1, 14-file part, ProfileEvents by query_id (Build IDs asserted server-side):
| binary | operation | FileSync |
|---|---|---|
base 2e68dfd8 |
INSERT | 15 |
fix 255515fd |
INSERT | 30 |
| base / fix | RESTORE (objstore) | 3 / 3 |
| fix | RESTORE (local, control) | 16 |
Before this PR neither path synced, so there was no asymmetry; now INSERT does and RESTORE does not. Worth noting because the same guard was defended on #111378 on the ground that RESTORE already matched INSERT, and that premise is what this PR falsified.
Not taking the one-term change here, though. I mutated exactly that guard to fsync_after_insert alone and rebuilt (Build ID a99c5f96):
| shape | fix | mutated |
|---|---|---|
File() -> objstore, FileSync |
3 | 31 |
Disk() objstore -> objstore, FileSync |
3 | 31 |
Disk() objstore -> objstore, native copies |
14 | 0 |
| 18.55 MiB restore, duration | 24 ms | 44 ms |
The intent does reach the new path (3 -> 31 is 14 blob + 14 metadata syncs). But sync = true also switches BackupImpl::copyFileToDisk off the whole-object route: that delegate is gated on !sync because a server-side copy exposes no buffer to fsync. On local_blob_storage the lost route is a local fs::copy and costs ~1.8x; on S3 it is copyS3File, a CopyObject that never moves bytes through the server, so the replacement is a download plus upload. I have no S3 number and will not guess one, but that is the cost being traded.
A correct fix carries the sync intent through IDisk::writeFileUsingBlobWritingFunction and IBackupReader::copyFileToDisk, neither of which takes a sync parameter today, so the native copy still runs and only the local metadata node is fsynced. That is new plumbing on two public interfaces plus their backends, which is larger than the IDiskTransaction follow-up this PR already defers. Tracked separately; leaving this PR at the INSERT scope its description states.
CI finish ledger - 4cfda50Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Detail on that row:
Session id: cron:our-pr-ci-monitor:20260822-170000 |
|
Fixing PR for the |
`Bugfix validation (unit tests)` attributes a before-build compile failure by the path on each `error:` diagnostic line, and reports XFAIL only when every such path is one of the PR's overlaid test files. Clang raises "no matching constructor" at the line that performs the construction, so when the overlaid test constructs the changed type through a template (`std::make_unique` and friends) the only `error:` line is inside libcxx and the overlaid test appears merely on a `note: in instantiation of ...` line. The guard is then false and the job fails closed with ERROR, although the failure is entirely the test adapting to the signature the fix introduces, which the PR author cannot avoid. Observed on PR ClickHouse#111391 head 4cfda50, whose 12,061-line compile log carries exactly one `error:` line, in contrib/llvm-project/libcxx/include/__memory/unique_ptr.h. The XFAIL branch that should have handled it was added by ClickHouse#115511, whose harness commit ca809a9 is an ancestor of that head, so this is a residual sub-shape of a merged feature rather than the pre-fix harness. Add a second attribution basis: the failing ninja edge's translation unit, taken from the `-c <source>` argument of the command ninja prints under `FAILED:`. The before-worktree is merge-base sources with only the PR's test files overlaid, so "which translation unit failed to compile" is exactly what attribution asks, and a broken fix source or contrib header is a different translation unit that fails its own edge. The fail-close property is therefore kept structurally rather than by heuristic. The new basis additionally requires that a parsable compiler error exists somewhere and that every failed edge is a compile whose source could be extracted, so a killed compiler and a link failure both stay ERROR. Deliberately not done: widening `_COMPILE_ERROR_LINE_RE`, and attributing from `note:` lines. The latter is unsafe because the same diagnostic also carries a `note: candidate constructor not viable:` pointing at a fix source, so such a rule would start swallowing genuine fix-source breakage; it would also contradict the invariant ClickHouse#115747 pins. `attribute_compile_errors` and the error regex are unchanged, and ClickHouse#115747's tests pass against this change. Validation: 63 tests in ci/tests/test_unit_tests_bugfix_validation.py (52 existing plus 11 new, 4 of them negative controls). Replaying the two real job logs flips ClickHouse#111391 from ERROR to XFAIL and leaves an already-attributable log's verdict and wording untouched. Each condition was mutation-checked: removing it reddens a specific test. XFAIL already counts as success in `Result.is_ok()` and ERROR was already non-blocking for the merge gate (new_tests_check.py counts only a definitive FAIL), so this changes report truthfulness, not gating.
|
Fixing PR for the That check reported Session id: cron:our-pr-ci-monitor:20260823-063000 |
Resolve the AddBlobOperation conflict: master added objects_to_remove (empty-append phantom-blob fix), this branch added sync. Keep both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…faults
Master now requires a disk defined in SQL to live inside
custom_local_disks_base_directory, so the relative `<name>/` path is
rejected; use ${CLICKHOUSE_DISKS_FILES}/<name>/ as 02714 does.
async_insert is on by default, and an async INSERT ... SELECT writes the
part in a separate AsyncInsertFlush query, so the measured INSERT reported
FileSync = 0 even on the local disk. Pin async_insert = 0 on the measured
inserts so the sync is attributed to the query the test reads back.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| { | ||
| object_metadata->ref_count -= 1; | ||
| write_operation = std::make_unique<WriteFileOperation>(path, object_metadata->serializeToString(), disk); | ||
| write_operation = std::make_unique<WriteFileOperation>(path, object_metadata->serializeToString(), disk, sync); |
There was a problem hiding this comment.
[Blocker] Preserve the synced blob mapping when removing a shared metadata file
The new flag only becomes true when a write buffer requests a sync. Old-part cleanup instead enters through DiskObjectStorage::removeSharedFiles (or removeSharedRecursive), which creates a fresh transaction with sync_metadata = false.
Consider a mutation with min_rows_to_fsync_after_merge = 1 that updates one column and hardlinks an unchanged column. Its metadata inode is shared by the old and new parts, and the mutation commit now fsyncs that inode with ref_count = 1. When cleanup removes the old part, this operation rewrites the entire mapping on the same inode with ref_count = 0: WriteFileOperation::execute opens it with O_TRUNC, but skips the new sync because this transaction has no synced write buffer. The active part's previously durable mapping is therefore exposed to power loss again, even though its mutation requested durability. RemoveRecursiveOperation::traverseFile has the same problem; this is about the surviving part, not durability of the deleted part's directory.
Standalone createHardLink and setReadOnly calls used by FREEZE also start unsynced transactions, so the same class of update can affect an otherwise unchanged, synced part.
Please preserve the durable blob mapping across these metadata-only updates and cover a synced mutation followed by old-part cleanup. If this existing lifecycle gap is intentionally deferred, explicitly track that case in a linked issue and document the limitation of the durability guarantee; the current insert/merge syscall-count assertions do not exercise it.
There was a problem hiding this comment.
Confirmed on this head with strace: after a synced mutation, old-part cleanup rewrites every shared metadata file with O_TRUNC and no fdatasync, and FREEZE does the same to the live part, while a local disk rewrites none of them. I am deferring it: syncing those rewrites unconditionally costs every cleanup and FREEZE with the settings off, and gating them needs the intent carried through IDisk::removeSharedFiles, removeSharedRecursive, createHardLink and setReadOnly, so the description now lists it as not covered and #111330 stays open.
Related: #111330
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
fsync_after_insertand themin_*_to_fsync_after_mergesettings being ignored for the local metadata of object-storage disks (s3,azure,local_blob_storage, ...). An acknowledgedINSERTcould be lost on power loss even when every blob was already durable in object storage, because the local file mapping the part's logical files to those blobs was never fsynced. On a file-backed object storage the blob contents were not fsynced either.Description
On an object-storage disk with local metadata,
fsync_after_insert = 1left the local commit record unsynced:WriteFileOperation::executefinalized the metadata file, andfinalizeonly flushes to the OS. On power loss the blobs survived and the record pointing at them did not.The intent crosses two orderings, so it has two consumers.
INSERT, merge, mutation) build their metadata operations insideDiskObjectStorageTransaction::commit, so the intent is published as the first statement ofcommit/tryCommit, before that replay loop.WriteFileOperationthen fsyncs the file it wrote, on its own fd.commitwill not run again; those fsync it through the newIMetadataStorage::syncMetadataFile.The flag is a required constructor argument of
WriteFileOperation, so every metadata-mutating operation threads it.IDiskTransactionis unchanged; the cache and path wrappers forward both methods.ForkWriteBufferalso gains asyncoverride: the inherited one flushed its own buffer, never its blob writers. On a file-backed object storage those reachfdatasync;s3andazureonly flush, unchanged.Scope is what a local disk does for the same setting, where
fsync_after_insert = 1withfsync_part_directory = 0syncs file contents and no directory. Not covered, so the issue is linked as related, not auto-closed: the part directory;RESTORE, gated on!isRemote()outside this code; and metadata-only updates (old-part cleanup,FREEZE, a mutation that does not sync), which rewrite a synced metadata file's hardlink count in place, unsynced; a local disk never rewrites it. Each needs the intent carried through the disk interfaces.Validated by tracing
fdatasyncon oneINSERT: 0 part-metadata syncs before, 11 after, 0 in both with the settings off.04541_object_storage_disk_fsynccompares an object-storage disk against a local disk holding the same table. It fails unfixed, passes 50/50 randomized.Workflow [PR]
Sync PR [sync-upstream/pr/111391]