Repository navigation
Fsync the parts of an INSERT once, at the end of the query - #117136
alexey-milovidov wants to merge 49 commits into
Conversation
With fsync_after_insert = 1, an INSERT fsynced every file of every part as the part was finalized. A ClickBench-sized load (100M rows, 289 parts) therefore issued ~100k synchronous fdatasync calls, which is IOPS-bound and does not get faster on a bigger machine: on gp2 EBS the load time stays flat at ~270 s from 8 vCPU up to 192, while the same load without the per-part fsync is limited by the device bandwidth instead. A single INSERT does not need each part to be durable the moment it becomes visible - it needs the data to be durable when the query is acknowledged. So collect the parts a sink commits and fsync them once, in onFinish(), over the set of *active parts covering* them. That is cheaper twice over: the writeback of the parts written earlier in the query has already happened in the background, and a part that a merge has already merged away is not synced at all, only the wider part covering it. The old behavior is kept behind a new merge tree setting, fsync_after_insert_each_part (default 0, i.e. the new behavior; set it to 1 for a part to be durable at the moment it becomes visible). Both settings only have an effect together with fsync_after_insert. A streaming INSERT (input_format_max_block_wait_ms != 0) can stay open indefinitely, so it keeps syncing each flushed block as it goes rather than accumulating parts until a finish that may never come. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [18f60bd] Summary: ✅
AI ReviewSummaryThis PR defers PR MetadataThe
Findings❌ Blockers
Tests
Final Verdict❌ Block. Preserve the existing default durability guarantee, establish durability for retries fetched onto filesystem-backed object storage, and resolve the adverse merge-inclusive performance evidence before enabling deferred syncing by default. |
|
It looks like patch parts escape the new end-of-query fsync entirely.
Net effect on a table with A smaller adjacent window: |
`MergeTreeSinkPatch::finishDelayedChunk` and `ReplicatedMergeTreeSinkPatch::finishDelayed` override the hooks where the base sinks collect the parts they commit, so the patch part of a lightweight `UPDATE` / `DELETE` ended up in no list at all: the inherited `onFinish` called `fsyncCommittedParts` over an empty set, while `writeTempPatchPart` no longer syncs the part at finalization under the new default of `fsync_after_insert_each_part`. With `fsync_after_insert = 1` the update was therefore acknowledged with its patch part never made durable, which on a plain `MergeTree` (or a single-replica `ReplicatedMergeTree`) means an acknowledged update can silently revert after a power loss. Collect the committed patch part in both overrides, so it is fsynced by the end of the query exactly like an inserted part. Also fix the style check: the return value of `close` has to be consumed. Reported by @zlareb1. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Thank you, the patch-part gap was real — fixed in a6c930d.
On the second point ( |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes116 object files changed (+116.19 KiB total), 0 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 units1125 translation units recompiled, 9085 s compile time in total, 1125 of them have a recent master baseline. |
`MergeTreeData::fsyncPartsAfterInsert` re-read the live table settings and returned early if `fsync_after_insert` had been switched off or `fsync_after_insert_each_part` switched on while a long `INSERT` was still running. The sink had already skipped the per-part sync of every part in `committed_parts` based on the settings at query start, so in that race the query could succeed with parts that were synced neither when written nor when the query finished. The sink now owns the decision: it takes it once when it is created and the batched sync runs unconditionally over whatever it collected. Addresses the AI review thread on `MergeTreeData.cpp`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`master` bumped the version to `26.10`, so the records this branch put in an older block now sit in the block of a released version. The `settings_changes_history` style check requires every record a change touches to be present under the current version block: otherwise `compatibility` attributes the new default to the wrong release. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…tions The sink used to decide once, at construction, whether to collect its committed parts for the end-of-query fsync, while `writeTempPartImpl` re-read the live table settings for every part to decide the inline sync. An `ALTER TABLE ... MODIFY SETTING` of `fsync_after_insert` / `fsync_after_insert_each_part` during a long `INSERT` could therefore leave later parts synced neither inline nor at the end. Now the writer records `MergeTreeTemporaryPart::needs_fsync_on_finish` from the same settings snapshot that decides the inline sync, and the sinks (including the patch sinks) collect exactly those parts, so every part gets one of the two. `MergeTreeData::shouldFsyncPartsAfterInsert` is no longer needed. Also document in `fsync_after_insert_each_part` that patch parts of lightweight `UPDATE` / `DELETE` follow the same rule and that a streaming `INSERT` (`input_format_max_block_wait_ms` != 0) fsyncs each flushed block as it goes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…s-once Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…or the `UNIQUE KEY` SST The batched end-of-query fsync relies on `IDisk::syncFile`, which is a no-op on `DiskObjectStorage`. On `local_blob_storage` disks `isRemote` is false, so `syncFiles` walked the part and synced nothing, while the per-part path did sync through the write buffers. Add `IDisk::supportsSyncFile` (true for `DiskLocal`, delegated by `DiskEncrypted` and `ReadOnlyDiskWrapper`) and `IDataPartStorage::supportsSyncFiles`; on disks that cannot sync a finalized file the part is synced as it is written, exactly as before. `writeDenseIndexOnInsert` still received `fsync_after_insert`, so on `UNIQUE KEY` tables `unique_key_index.sst` was synced inline and then again at the end of the query. Pass `sync_this_part` instead, and add a test that an INSERT into a `UNIQUE KEY` table does exactly one more fsync than into the same table without it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… parent part With `fsync_after_insert = 1` and `fsync_after_insert_each_part = 1` the parent part was synced as it was finalized, but the projections written together with it on `INSERT` were finalized without sync, so after a power loss the part could come back without its projections. Pass the same `sync_this_part` decision into `writeProjectionPart`. In the batched mode the projections are already covered: `syncFiles` walks the part directory recursively. `writeTempProjectionPart` (used by merges and mutations) keeps not syncing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…file_events` Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
|
|
Acknowledged. I am investigating the |
|
The slowdown is in A fix is in progress: #107554 replaces this path with typed aggregation, so these queries no longer compare If you prefer a smaller change first, I can send one that only inlines the comparison of integer keys in this map, keeping the ordering and the state format. |
|
The fix is in #127665. In CI's own CPU profiles of this test, the slow runs spend the extra time in |
A fetched part replaces the local parts it covers and is synced only according to `min_compressed_bytes_to_fsync_after_fetch` (default 0), or not at all on a disk that cannot sync finalized files. A local part whose fsync is deferred to the end of an `INSERT` (`fsync_after_insert_each_part = 0`) was therefore replaced without ever being synced, and the batched fsync at the end of the query then skipped the unsyncable covering part. Call `IMergeTreeDataPart::syncIfPendingFsyncAfterInsert` on the covered active parts before `StorageReplicatedMergeTree::fetchPart` commits the fetched part, as merges, mutations and moves already do, and on the replaced parts after the commit for those that became active in between. Address review: #117136 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed 9e2d255: merged the latest The thread about the total fsync count with merges running during the The red CI on bf9142a is unrelated:
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117136&sha=bf9142a980906ae8a614927ebd5be2bb96543f12&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%205%2F6%29 ( |
|
Acknowledged. I'm investigating the |
|
Findings: there is no code fix to send for this one. The slowdown comes with this PR's build of
Scoring such single-build reds against the spread of recent performance reference builds is what @ egor-click is looking into: #122350 (comment) |
…ch replaced it `StorageReplicatedMergeTree::fetchPart` synced only the `Active` covered parts before committing the fetched part, so it missed a part of a running `INSERT` that was still `PreActive` (and later became `Outdated` at its commit because it was already covered). A part that became `Active` in between was synced only after the fetched part was published, so a finishing `INSERT` could acknowledge before that sync. In both cases `MergeTreeData::fsyncPartsAfterInsert` then synced only the fetched covering part, which can be on a disk that cannot sync finalized files. `MergeTreeData::fsyncPartsAfterInsert` now also syncs the committed part itself if it still has `pending_fsync_after_insert` set and it is not the covering part. This does not depend on the timing of the fetch. Its files are still there: an `Outdated` part is not removed while it is referenced. The pre-commit scan in `fetchPart` now includes `PreActive` parts too. Address review: #117136 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed fc62e14: merged the latest Both red checks on 9e2d255 are unrelated, and the merge brings in their fixes:
The thread about the total fsync count with merges running during the |
With `fsync_after_insert = 1` and `fsync_after_insert_each_part = 0`, a `ReplicatedMergeTree` `INSERT` publishes its block in Keeper before it syncs its part. A retry of the same block on another replica was deduplicated against that part and acknowledged, although the part may not have been durable anywhere yet: it does not exist locally, so `MergeTreeData::fsyncPartsAfterInsert` skipped it. Now the retry waits until the replication queue brings a local copy of the part (or of a part covering it) and syncs that copy before it is acknowledged. The wait is bounded by `insert_quorum_timeout` and fails with `TIMEOUT_EXCEEDED`; a part dropped in the meantime has nothing left to make durable. Address review: #117136 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…icated_other_replica` The style check requires the `ReplicatedMergeTree` engine arguments to contain `$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX` literally. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117136&sha=8d5db71d4833e674757eaafef705a7f937a43496&name_0=PR&name_1=Style%20check #117136 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed c5ad327: fixed the |
…e copy Follow-up to the review threads on #117136: - `ReplicatedMergeTreeSink`: a deduplication conflict whose part name could not be resolved (the deduplication node is gone) now fails the `INSERT` with `UNKNOWN_STATUS_OF_INSERT` when `fsync_after_insert` is set, instead of being silently filtered out with nothing to sync. - `ReplicatedMergeTreeSink`: whether to wait for a local copy of a part that the block was deduplicated against no longer depends on the retrying replica's `fsync_after_insert_each_part`, because the replica that wrote the part may have used the batched mode. Only an `Active` local copy counts, because a `PreActive` fetched part is still going to be renamed. - `DiskLocal::syncFile`: `ENOENT` is an error, not success, because a missing path (e.g. a renamed directory) does not prove that the data is gone. - `UNIQUE KEY` with `unique_key_conflict_action = 'ignore'`: the existing parts that hold the rows which won the conflicts are synced, also when the whole new part is discarded. Tests: `05453_fsync_after_insert_batched_unique_key_ignore`, `05454_fsync_after_insert_dedup_conflict_part_name_missing`, and `05452_fsync_after_insert_batched_deduplicated_other_replica` now runs the retrying replica in per-part mode. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Both CI failures on c5ad327 look unrelated to this PR:
Review feedback from 2026-10-28 is addressed in f6199bb. The open design question (the batched mode does more total fsyncs when merges overlap the |
|
This is the CI logs cluster outage from #120462, not this PR. The run on c5ad327 (2026-10-28 07:00 UTC) was inside it: every Both sides are already fixed, so no new PR is needed:
My #126200 made the same change and now conflicts with master; it is superseded by #128067. |
|
🕵 Pushed 05b6f8f: merged the latest
The one open thread is still about total fsync work when merges overlap the |
…sync `DataPartStorageOnDiskBase::syncFiles` walks the part directory and then syncs the collected files. `VersionMetadataOnDisk::storeInfoToDataPartStorage` can run concurrently (for example a transaction committing a part that a deduplicated retry syncs): it writes `txn_version.txt.tmp` and renames it to `txn_version.txt`, so the collected temporary name can be gone when `DiskLocal::syncFile` opens it, and the `INSERT` fails with `CANNOT_OPEN_FILE`. Skip `txn_version.txt` and `txn_version.txt.tmp`: they are always written through a synced temporary file, so they have their own sync protocol. Missing data files are still errors. Add the `part_sync_files_pause_after_collect` failpoint and a test which interleaves the metadata rename with the sync. Without the fix it fails with `Cannot open file .../txn_version.txt.tmp`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failures: |
|
Both are already covered, no new PR needed.
|
|
🕵 @groeneai, thanks. Both failures on 05b6f8f are accounted for: the The open review thread (total fsync work when merges overlap the |
|
🕵 Closing as superseded by #126251 ("Group fsync of inserted parts with Evidence, checked against freshly fetched
That is the core of this PR: with Some parts of this PR are not on |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
If you use
fsync_after_insertto make inserted data durable, anINSERTnow does thefsynconce when the query finishes instead of once per part while the query is still writing. The data is durable by the time theINSERTis acknowledged, exactly as before, but the sameINSERTspends 3-5x less time insidefsync, because by the end of the query the kernel has already written most of the data back in the background. The newfsync_after_insert_each_partsetting restores the old per-part behaviour for the case where a part has to be durable at the moment it becomes visible, rather than at the moment theINSERTcompletes.Documentation entry for user-facing changes
Two
MergeTreesettings are involved:fsync_after_insert(unchanged, default0) — whether anINSERTfsyncs its data at all.fsync_after_insert_each_part(new, default0) — when it does it. No effect unlessfsync_after_insertis enabled.0— once, when the query finishes, over the set of active parts covering the inserted data.1— for every part as soon as it is written (the behaviour before this PR).The setting descriptions in
MergeTreeSettings.cppcarry the full text; the generated docs pick them up from there.SettingsChangesHistory.cpprecordsfsync_after_insert_each_partwithprevious_value = true, socompatibilitywith an earlier version restores the per-part fsync.Why
fsync_after_insert = 1fsynced every file of every part as the part was finalized. A ClickBench-sized load (100M rows ofhits, 289 parts, ~350 files per part) therefore issued ~100k synchronousfdatasynccalls — a cost that is bound by device flush latency, not by the amount of data, and that consequently does not shrink when you add cores.A single
INSERTdoes not need each part to be durable the moment it becomes visible. It needs the data to be durable when the query is acknowledged. So the sink now collects the parts it commits and syncs them once, inonFinish(), over the set of active parts covering them.Measurements
100M rows of
hitsinto aMergeTreeordered by the ClickBench primary key, source parquet intmpfs, ClickHouse 26.9 Release build, aarch64, local NVMe.fsync_after_insert = 1in all rows; the only difference isfsync_after_insert_each_part.FileSyncand the time insidefdatasyncare from theINSERT's ownProfileEvents.each_partFileSyncfdatasync(s)1(old)0(new)1(old)0(new)Two independent effects, worth separating because they behave differently:
Cheaper per fsync — holds everywhere. Time inside
fdatasyncdrops 3-5x in every configuration measured. By end-of-query the kernel has already written those pages back in the background, so thefsyncfinds little dirty data, instead of eachfsynchaving to push out the file it has just written.Fewer fsyncs — only when merges keep up. The covering set shrinks only if background merges absorb parts before the query ends. With 4 insert threads and a ~500 s insert that halves the count (100k -> 52k). With 48 insert threads and a 312 s insert it is only 2.6% (100k -> 98k), because part production outruns the merge pool; the 1015 s row is the same configuration slowed down by unrelated load on the test machine, where merges got more time and the count fell to 78k accordingly.
Wall clock is a wash on this hardware, and that is expected. Local NVMe has roughly 100x a
gp2volume's IOPS, so 100kfdatasynccalls are nearly free here at this scale — thefsync_after_insert = 0control took 491-665 s, i.e. sometimes slower than the fsyncing variants. The comparable pair at 48 threads is a dead heat (312 vs 313 s). The saving should show up on an IOPS-limited volume; I have not measured that, and a run onc6a.4xlarge-class storage is the thing that would settle it. Flagging this openly: if the intent is to speed up the ClickBench load, this PR is not yet demonstrated to do so — it is demonstrated to do strictly less fsync work, with no wall-clock regression observed.Implementation
IDisk::syncFile(path)— new virtual, needed because the point is to sync files that are already finalized and closed. No-op by default, for the same reasongetDirectorySyncGuard()returnsnullptrby default: on object storage a finalized file is already durable. RealfdatasyncinDiskLocal(opensO_RDONLY, toleratesENOENTsince the caller enumerates paths from the disk, and countsFileSync/FileSyncElapsedMicrosecondsexactly likeWriteBufferFromFileDescriptor::sync()); delegated byDiskEncryptedandReadOnlyDiskWrapper.IDataPartStorage::syncFiles()— no-op default;DataPartStorageOnDiskBasewalks the real directory rather than the part's logical file list, so a packed part syncsdata.packedand projections are covered by the recursion. Goes through a newparallelSyncFiles(disk, paths)overload of the existing IO-pool helper.MergeTreeData::{shouldFsyncPartsAfterInsert,fsyncPartsAfterInsert}— resolves each committed part to its active covering part under onereadLockParts(), dedupes, drops the lock, then syncs. Holding theDataPartPtrs across the fsync keeps a merge that finishes meanwhile from removing the files underneath it.MergeTreeSinkandReplicatedMergeTreeSinkaccumulate the committed parts (only when the table asks for it, so nothing accumulates in the default configuration) and call it fromonFinish().INSERT(input_format_max_block_wait_ms != 0) can stay open indefinitely, so it cannot defer to a finish that may never come — it keeps syncing each flushed block as it goes, which also bounds the pending list.Tests
01643_merge_tree_fsync_smokeand its replicated twin gained afsync_after_insert_each_part = 1case, so both modes stay covered; their existing cases now exercise the new default.02361_fsync_profile_eventspinsfsync_after_insert_each_part = 1because it asserts exact per-part fsync counts from the write path. New05052_fsync_after_insert_batchedchecks correctness in both modes, that the fsyncs are accounted to theINSERTitself rather than left to the background, and that the batched mode still syncs at least one file per part. All four pass locally.Opened as a draft: I would like CI on it, and I would like a second opinion on point 2 above before this is considered done, since the configuration where the count saving is largest (
max_insert_threads= 4) is not the configuration where ClickHouse's load time lags most.Workflow [PR]
Sync PR [sync-upstream/pr/117136]