Skip to content

Group fsync of inserted parts with fsync_after_insert - #126251

Merged
alexey-milovidov merged 30 commits into
masterfrom
insert-fsync-load
Nov 7, 2026
Merged

alexey-milovidov merged 30 commits into
masterfrom
insert-fsync-load

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Speed up large INSERTs into MergeTree with fsync_after_insert on slow disks, as on ClickBench (EBS gp2, 250 MB/s). ClickBench creates the table with fsync_after_insert = 1 and runs sync inside the measured window. The load is bound by disk throughput, not CPU.

With fsync_after_insert, every part was fsynced right after it was written, so the insert threads waited for the disk after every part (about 340 fsyncs per wide part on ClickBench). This PR adds group fsync: if the table is on local disks, MergeTreeSink (and ReplicatedMergeTreeSink, if enabled explicitly) write and commit parts without fsync, and fsync the files of all their parts together in onFinish, before the INSERT is acknowledged. Meanwhile the OS writes the data back in the background, so the final fsync is cheap. The sink holds references to its parts, which prevents their removal if they are merged in the meantime. Parts committed more than 30 s ago are fsynced while the INSERT is still running, so a long INSERT doesn't keep parts around longer than old_parts_lifetime already does. The parts can become visible to queries before they are durable, but the INSERT is acknowledged only after they are. Object storage disks, patch parts and unique-key inserts keep the inline fsync.

The new MergeTree setting group_fsync_before_insert_finish turns the group fsync on or off. Its default value auto enables it only for non-replicated tables: for replicated tables, another replica could deduplicate an INSERT against a part that is committed but not yet fsynced on the first replica, and acknowledge it before the data is durable. It can be set to 1 or 0 explicitly for any table. With group_fsync_before_insert_finish = 0, every part is fsynced right after it is written, as before.

The choice of the insert codec by the block size, which was also part of this PR, moved to #127652, as requested in #126251 (comment).

Related: #127652

Measurements

These are on an emulation of the ClickBench machine (c6a.4xlarge, 500 GB gp2): a cgroup with 16 CPUs, 32 GB RAM and io.max of 250 MB/s and 3000 IOPS, on top of a dm-delay (1 ms write and flush latency) over a RAM disk. The load is the ClickBench load script: INSERT INTO hits SELECT * FROM file('hits_*.parquet') with max_insert_threads = 4, followed by sync.

To isolate the fsync, with merges stopped and ZSTD(3) on insert: 63.5 s with an fsync after every part, 46.7 s with the group fsync, and 44.7 s with no fsync at all.

The full load (with merges) takes 112.6 s instead of 129.7 s on master with this change and the one from #127652 together.

Changelog category (leave one):

  • Performance Improvement

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

Faster inserts with fsync_after_insert: when the table is on local disks, an INSERT writing many parts no longer waits for the fsync after every part. Instead, the files of all its parts are fsynced together before the INSERT is acknowledged. This is controlled by the new MergeTree setting group_fsync_before_insert_finish, enabled by default for non-replicated tables.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1635-master (included in 26.11 and later)

alexey-milovidov and others added 3 commits October 16, 2026 07:16
With `fsync_after_insert`, every part was fsynced right after it was written,
so an `INSERT` writing many parts waited for the disk after every part.
Now, if the table is stored on local disks, `MergeTreeSink` writes and commits
the parts without fsync, and fsyncs the files of all its parts together in
`onFinish`, before the `INSERT` is acknowledged. Meanwhile the OS writes the
data back in the background, so the final fsync is cheap. Parts committed
more than 30 seconds ago are fsynced while the `INSERT` is still running, so a
long `INSERT` does not hold its parts (holding them prevents their removal
after they are merged).

On an emulated EBS gp2 volume (250 MB/s, 3000 IOPS, 1 ms latency; 16 cores,
32 GB RAM), loading the ClickBench dataset with merges stopped took 46.7 s
instead of 63.5 s, the same as without fsync at all (44.7 s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The size-aware default codec (`LZ4` below 100 MB, `ZSTD(3)` above) was chosen
with the size `0` for every inserted part, so all inserted data was written
with `LZ4` and then rewritten with `ZSTD(3)` by merges. Now the uncompressed
size of the inserted block is used as the estimate: small inserts still use
`LZ4`, and large inserts (such as `INSERT SELECT` with the default
`min_insert_block_size_bytes` of 256 MB) use `ZSTD(3)` right away.

On ClickBench, the inserted parts take 8.85 GiB instead of 14.27 GiB, which
matters when the disk throughput is the bottleneck.

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

The deferred fsync of inserted parts is now controlled by the new `MergeTree`
setting `defer_fsync_after_insert` (enabled by default), and the logic is moved
to `DeferredPartsSync`, shared by `MergeTreeSink` and `ReplicatedMergeTreeSink`.

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

mintlify Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 30, 2026, 1:34 AM

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [858def8]

Summary: ✅


AI Review

Summary

The PR groups local part fsyncs before insert completion, enables this by default for non-replicated tables, and quarantines parts after sync failures. Reviewed head 858def82f7e9adadfb4272cc3c4ebdbe68932014. The latest deduplication-log fix addresses the reported evicted-record case, but one previously discussed restart durability violation remains. No new inline findings.

Findings

❌ Blockers

  • src/Storages/StorageMergeTree.cpp:3491: Failed durability can be forgotten after a restart when a mutation retains the failed inode. [dismissed by author -- https://github.com/Group fsync of inserted parts with fsync_after_insert #126251#discussion_r4407770335] The author explicitly leaves parts involved in merges or mutations protected only by the in-memory failure record. This remains unsafe for partial mutations: an insert publishes a wide part, a mutation hardlinks an unchanged column, and that column's deferred sync fails. Quarantine returns here because the original part is being mutated or is already outdated. The replacement can retain the failed inode and the original deduplication token. Restarting clears FailedFiles; startup checks file sizes rather than all data hashes, and a deduplicated retry can then acknowledge potentially corrupt data. A new descriptor's successful sync does not repair an earlier failed write; see the kernel writeback-error contract.
    Suggested fix: persist the failed durability state for retained files and their hardlinked replacements, and reject dependent retries after recovery until the affected data is repaired or rewritten.
Tests
  • ⚠️ Cover an injected sync failure on an unchanged column retained by a partial mutation, followed by a server restart and an identical deduplicated insert. Verify that the retry cannot succeed against the failed data. The current sequential quarantine tests do not exercise this path, and DETACH TABLE / ATTACH TABLE does not clear the process-wide failure registry. This recovery trace was assessed statically; no local runtime reproduction was run.
Final Verdict

Status: ❌ Block. Preserve the failed durability state across restart for parts that cannot be quarantined, including hardlinked mutation results, and add focused recovery coverage.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 16, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 16, 2026
alexey-milovidov and others added 2 commits October 20, 2026 06:57
…keep the parts alive while syncing, skip temporary files

A deduplicated `INSERT` relies on a part committed by another `INSERT` that may not be synced yet,
so the existing part is synced before the deduplicated `INSERT` is acknowledged.

`DeferredPartsSync` now keeps the parts alive until their files are synced, and skips the temporary
`.tmp` files, such as `txn_version.txt.tmp`, that may disappear at any moment.

Make the test `05404_fsync_after_insert_many_parts` faster: it ran longer than 180 s in the flaky check.

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

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 858def82f with master 31bebf957 (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

18 object files changed (+182.52 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/DeferredPartsSync.cpp.o new 97.46 KiB +97.46 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/ParallelSyncFiles.cpp.o 123.80 KiB 168.96 KiB +45.17 KiB (+36.49%)

719 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

433 translation units recompiled, 4123 s compile time in total, 432 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Storages/MergeTree/DeferredPartsSync.cpp: 7.4 s

Job report

alexey-milovidov and others added 3 commits October 23, 2026 14:48
# Conflicts:
#	src/Storages/MergeTree/ReplicatedMergeTreeSink.h
…EY`, remember failed deferred fsyncs

- `DeferredPartsSync::add` ignores a part that is already queued, so a retry of a coalesced
  async insert with many deduplicated blocks of the same part syncs its files once.
- `DeferredPartsSync::isEnabled` returns false for tables with `UNIQUE KEY`: their parts are committed
  by `MergeTreeSink::commitUniqueKeyPart`, which did not register them for the deferred fsync,
  so they were written without fsync at all.
- If the deferred fsync of a file fails, its part is remembered, and a later insert that relies on
  this part (e.g. a retry deduplicated against it) fails instead of syncing it again with a new file
  descriptor, for which the kernel may report success after the writeback error was consumed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…uilds read the written files

- `test_default_compression_codec` expected every inserted part to use the codec for size 0.
  Now the codec of an inserted part is chosen by the size of the inserted block (an intended change
  of this PR), so the parts with large blocks get `LZ4HC(5)` and `LZ4` right away.
- `05404_fsync_after_insert_many_parts` compared `FileSync` with `FileOpen`, but debug builds read the
  columns of wide parts back to validate them (`validateColumnOfFixedSize`), so it failed with
  `min_bytes_for_wide_part = 0`. Compare the number of fsynced files of the deferred and the inline fsync instead.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126251&sha=latest&name_0=PR
#126251

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

Copy link
Copy Markdown
Member Author

Split into two PRs:

  1. Default compression codec estimation for freshly inserted parts.
  2. Group fsync. Introduce a setting to enable or disable group fsync.

This PR now only contains the group fsync of inserted parts.

#126251 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov changed the title Defer the fsync of inserted parts and choose the insert codec by block size Group fsync of inserted parts with fsync_after_insert Oct 23, 2026
The fsync is not done after the insert, but before it finishes.

#126251

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 25, 2026 10:11
…e them

A failed deferred fsync was remembered per part object, which missed two cases:
an insert that started syncing the part before the failure was recorded could
open a new file descriptor that does not see the consumed writeback error, and a
mutation that hardlinks the files of the failed part produced a new part object
that was not considered failed.

Now `parallelSyncPaths` remembers the failed files by their inodes (shared by
hardlinks) and keeps them open, so that the inodes are not reused. The attempts
to sync the same inode are serialized under a sharded mutex, so the check, the
fsync and the recording of a failure are atomic with respect to other attempts.
The remaining files of a batch are still synced after a failure, so that all
failed files are remembered.

Add the failpoint `parallel_sync_paths_fail_fsync` and a test with a failed
fsync followed by a deduplicated retry, and by a partial mutation and a retry.

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

The style check rejects test names containing 'fail' and requires tests
enabling a failpoint to be tagged `no-fasttest`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 30, 2026 00:50
The record of the files that failed to sync lives only in memory, while the
part and its deduplication record survive a restart of the server. After a
restart, a retry of the insert could be deduplicated against a part whose
data may not be durable, and be acknowledged.

Now, when the deferred fsync of a part of a non-replicated `MergeTree` table
fails, the part is removed from the deduplication log and moved to
`detached` with the prefix `fsync-failed`, so that a retry writes the data
again, also after a restart. A part that is being merged or mutated is left
as is, and the in-memory record still fails the inserts relying on it.
`parallelSyncPaths` now reports which files failed to sync.

The test checks the retry after `DETACH TABLE` / `ATTACH TABLE`, which
reloads the parts and the deduplication log.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126251&sha=1b11c2d71d6973b0fdbf250867b76371d1cc979f&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 (Received signal 6 (internal) (STID: 1202-2b88), a libc++ hardening abort in DB::highlight called from ClientBase::echoQuery; it also fails on master and in many other PRs) and provide a fix in a separate PR. If the fix is already in progress, link it here. The 05397_clickhouse_local_locked_path_untouched failure on arm_darwin is fixed on master by #128088, which is now merged into this branch.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is #127906, merged 2026-10-29 13:17 UTC. A malformed UTF-8 lead byte in an echoed string literal made highlight step past the end of the query, so both the bracket color write and the render loop (the string_view frame in this stack) indexed out of bounds. The failing run on 1b11c2d7 does not contain it, and every occurrence of STID 1202-2b88 in CIDB so far (master and other PRs) comes from a workflow started before the merge. The current head e241a0b7 includes it.

alexey-milovidov and others added 2 commits October 30, 2026 21:14
…at failed to sync

`StorageMergeTree::detachPartAfterFailedFsync` removed the block ids of the part from
the deduplication log, but the `DROP` records were only flushed, not fsynced, while the
detach itself is durable with `fsync_part_directory`. After a power loss, the old `ADD`
record could be restored for a detached part, and a retry of the `INSERT` would be
acknowledged without its rows.

`MergeTreeDeduplicationLog::dropPart` now takes `sync_to_disk`: it syncs the log after
every record (before a rotation, which only logs a failure to sync), and the logs
directory at the end. A failure propagates, and the part is not detached then.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e as failed

An `fdatasync` that returns `EINTR` says nothing about the data of the file, but it was
recorded as a permanent failure, so the part was detached, including an already durable
part that a retry of an `INSERT` was deduplicated against. Retry the sync on `EINTR`.

Add the failpoint `parallel_sync_paths_interrupt_fsync` and the test
`05459_fsync_interrupted_deduplicated_insert`.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126251&sha=e241a0b7e82fbfb8c33d0416ef4fa045eb1adc74&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%204%2F6%29 (Performance Comparison (amd_release, master_head, 4/6) ended with ERROR while waiting for the performance dashboard, which kept returning HTTP 404 performance comparison run not found; no query result is involved, so it is unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is #128236, merged today at 21:07Z, after this run (03:01 to 05:02Z).

On e241a0b the 4/6 shard finished its uploads at 04:54:46, about 113 minutes into its 7200 s timeout. perf_dashboard_gate then polled the 404 29 times until praktika killed the job at 05:02:10 (Timeout exceeded [7200], exit -15), so the shard never reached the fallback that judges by its own report. #128236 ends the dashboard wait 300 s before the job timeout (about 04:57 here); the shard's own report (9 too long, 1 unstable, 0 slower) would then have given OK.

The 404 was the dashboard outage after the CIDB switch (2026-10-29 to 2026-10-30); the dashboard serves pr-126251-e241a0b7... now (HTTP 200). The run queued for a24a4c7 at 21:15Z uses a merge commit that already contains #128236.

…log after one failed

`MergeTreeDeduplicationLog::dropPart` with `sync_to_disk` removes the block ids from memory
before syncing the log. If the sync failed, a later quarantine attempt found nothing to write,
skipped the sync, and `StorageMergeTree::detachPartAfterFailedFsync` detached the part, so after
a power loss the detach could be durable while the earlier `ADD` record was restored.

Now a failed durable removal sets a sticky flag, and every later `dropPart` with `sync_to_disk`
throws `CANNOT_FSYNC`, so no part is detached after it. Syncing the log again would not prove
the earlier records durable. The new failpoint `deduplication_log_fail_durable_drop_sync` and the
test `05460_fsync_error_dedup_log_sync_failure` cover a second attempt after the injected failure.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126251&sha=a24a4c75e26ac5b898a412a26955e472ebcc75ad&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29 (Logical error: 'ReadBuffer is canceled. Can't read from it.' (STID: 2508-2bbd) in DB::ask called from ClientBase::initOutputFormat in the embedded client, followed by Server liveness check failed; unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here. It looks like #128090 may be the fix.

@groeneai

Copy link
Copy Markdown
Collaborator

This is STID 2508-2bbd, the same abort as on #80263: ask (Ask.cpp:17) reads the embedded client's input again after an earlier failed read canceled it, and the LOGICAL_ERROR takes the server down, which is the Server liveness check failed row. a24a4c7 contains #127912, which made the client ask the binary-format question again for the next Data packet.

The fix is #128090 (open). #128238 (open) also stops the client from building the output format again after a local format error, as asked in the #128090 review. This PR is not involved.

alexey-milovidov and others added 3 commits November 1, 2026 23:06
…th no records

`MergeTreeDeduplicationLog::dropPart` with `sync_to_disk` synced the log only when
it wrote a `DROP` record. If the records of the part had already been evicted from
the window by newer, unsynced records, nothing was synced, and after a power loss
the old `ADD` records could be restored for a detached part, so a retry would be
deduplicated against it.

Now a durable removal always syncs the current log and the logs directory, so the
eviction is durable too. A failure to flush or sync a log (which `rotate` only logs)
sets `records_may_be_lost`, and durable removals fail after that, so the part is not
detached.

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

@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.

Now it looks alright.

@alexey-milovidov alexey-milovidov self-assigned this Nov 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 7, 2026
Merged via the queue into master with commit ad9d84d Nov 7, 2026
187 checks passed
@alexey-milovidov
alexey-milovidov deleted the insert-fsync-load branch November 7, 2026 23:01
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 7, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 17, 2026
Since ClickHouse#126251 an INSERT with `fsync_after_insert` defers the fsync of its parts
(`group_fsync_before_insert_finish`, `auto` = on for non-replicated tables on local
disks): the part is written without fsync and `DeferredPartsSync` fsyncs every
regular file under the part directory, projections included, before the INSERT
finishes. The projection write still took `fsync_after_insert` alone, so with the
group fsync each projection file was fsynced inline and then once more. Measured
with strace on a Packed part: `tmp_insert_all_1_1_0/pr.proj/data.packed` inline,
then `all_1_1_0/pr.proj/data.packed` deferred. The projection now follows the
parent part's decision.

`04684_projection_fsync` caught it on the master merge (`packed insert projection
adds exactly one file sync` read 2). Its INSERT tables now pin
`group_fsync_before_insert_finish = 0`, the inline path that replicated tables use by
default: under the group fsync master already syncs the projection files (Full parts
on master: 31 vs 17 file syncs with it, 17 vs 17 without), so those arms would no
longer fail without the fix. A new Packed arm with the group fsync asserts the
projection adds exactly one file sync.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.

3 participants