Skip to content

Fsync the parts of an INSERT once, at the end of the query - #117136

Closed
alexey-milovidov wants to merge 49 commits into
masterfrom
fsync-inserted-parts-once
Closed

alexey-milovidov wants to merge 49 commits into
masterfrom
fsync-inserted-parts-once

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

If you use fsync_after_insert to make inserted data durable, an INSERT now does the fsync once when the query finishes instead of once per part while the query is still writing. The data is durable by the time the INSERT is acknowledged, exactly as before, but the same INSERT spends 3-5x less time inside fsync, because by the end of the query the kernel has already written most of the data back in the background. The new fsync_after_insert_each_part setting 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 the INSERT completes.

Documentation entry for user-facing changes

Two MergeTree settings are involved:

  • fsync_after_insert (unchanged, default 0) — whether an INSERT fsyncs its data at all.
  • fsync_after_insert_each_part (new, default 0) — when it does it. No effect unless fsync_after_insert is 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.cpp carry the full text; the generated docs pick them up from there. SettingsChangesHistory.cpp records fsync_after_insert_each_part with previous_value = true, so compatibility with an earlier version restores the per-part fsync.


Why

fsync_after_insert = 1 fsynced every file of every part as the part was finalized. A ClickBench-sized load (100M rows of hits, 289 parts, ~350 files per part) therefore issued ~100k synchronous fdatasync calls — 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 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 the sink now collects the parts it commits and syncs them once, in onFinish(), over the set of active parts covering them.

Measurements

Caveat (2026-10-18): the numbers below count only the INSERT's own ProfileEvents, and they were taken before merges and mutations started to sync a source part that is still pending the batched fsync (syncIfPendingFsyncAfterInsert). Since then, a part merged away during the query is synced by the merge, and the covering part is synced by the query as well. So the "fewer fsyncs" effect (point 2 below) is not established for the current implementation. Point 1 (cheaper per fsync) is not affected by that, as such.

Remeasured (2026-10-23), with merges enabled and background FileSync included. This is a synthetic run, not hits: 30M rows in about 30 parts on an AWS root volume. The batched mode did about 65% more fsyncs in total (1036-1086 vs 626-629). The query's own count was the same (621 in both modes), and the batched mode's total time inside fdatasync was higher (55-160 s vs 27-45 s). INSERT wall clock was no better. The cause is that the merge syncs each pending source, and the query then also syncs the covering merged part. Details: #117136 (comment). Whether to remove one of the two syncs, which trades durability, or to keep the mode non-default is an open design question.

100M rows of hits into a MergeTree ordered by the ClickBench primary key, source parquet in tmpfs, ClickHouse 26.9 Release build, aarch64, local NVMe. fsync_after_insert = 1 in all rows; the only difference is fsync_after_insert_each_part. FileSync and the time inside fdatasync are from the INSERT's own ProfileEvents.

insert threads each_part insert (s) FileSync time in fdatasync (s)
4 1 (old) 424 / 544 100,514 / 100,338 17,093 / 14,257
4 0 (new) 418 / 494 52,472 / 54,198 3,123 / 3,278
48 1 (old) 313 / 420 100,292 / 100,162 14,687 / 17,355
48 0 (new) 312 / 1015 97,734 / 77,724 5,024 / 3,430

Two independent effects, worth separating because they behave differently:

  1. Cheaper per fsync — holds everywhere. Time inside fdatasync drops 3-5x in every configuration measured. By end-of-query the kernel has already written those pages back in the background, so the fsync finds little dirty data, instead of each fsync having to push out the file it has just written.

  2. 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 gp2 volume's IOPS, so 100k fdatasync calls are nearly free here at this scale — the fsync_after_insert = 0 control 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 on c6a.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 reason getDirectorySyncGuard() returns nullptr by default: on object storage a finalized file is already durable. Real fdatasync in DiskLocal (opens O_RDONLY, tolerates ENOENT since the caller enumerates paths from the disk, and counts FileSync / FileSyncElapsedMicroseconds exactly like WriteBufferFromFileDescriptor::sync()); delegated by DiskEncrypted and ReadOnlyDiskWrapper.
  • IDataPartStorage::syncFiles() — no-op default; DataPartStorageOnDiskBase walks the real directory rather than the part's logical file list, so a packed part syncs data.packed and projections are covered by the recursion. Goes through a new parallelSyncFiles(disk, paths) overload of the existing IO-pool helper.
  • MergeTreeData::{shouldFsyncPartsAfterInsert,fsyncPartsAfterInsert} — resolves each committed part to its active covering part under one readLockParts(), dedupes, drops the lock, then syncs. Holding the DataPartPtrs across the fsync keeps a merge that finishes meanwhile from removing the files underneath it.
  • MergeTreeSink and ReplicatedMergeTreeSink accumulate the committed parts (only when the table asks for it, so nothing accumulates in the default configuration) and call it from onFinish().
  • A streaming 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_smoke and its replicated twin gained a fsync_after_insert_each_part = 1 case, so both modes stay covered; their existing cases now exercise the new default. 02361_fsync_profile_events pins fsync_after_insert_each_part = 1 because it asserts exact per-part fsync counts from the write path. New 05052_fsync_after_insert_batched checks correctness in both modes, that the fsyncs are accounted to the INSERT itself 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]

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [18f60bd]

Summary: ✅


AI Review

Summary

This PR defers fsync_after_insert until sink completion by default, adds fsync_after_insert_each_part to restore immediate syncing, and tracks durability dependencies through deduplication and part replacement. The performance justification remains unresolved, and two previously discussed durability limitations still affect the successful-acknowledgement guarantee. No new inline findings; the fixed transaction-metadata thread was resolved.

PR Metadata

The Performance Improvement category requires evidence for the current implementation. The required changelog entry is specific and explains migration, but its claim of 3–5× less time in fsync relies on obsolete measurements and conflicts with the later merge-inclusive results. Replace it with:

Added fsync_after_insert_each_part to control when fsync_after_insert syncs inserted data. Syncing is deferred until the insert finishes by default; set fsync_after_insert_each_part = 1 to retain immediate per-part syncing and writeback-error reporting through the original file descriptors. Deferred syncing can increase total sync work when background merges overlap the insert.

Findings

❌ Blockers

  • src/Disks/DiskLocal.cpp:634 — Successful acknowledgement can hide failed writeback. [dismissed by author -- https://github.com/Fsync the parts of an INSERT once, at the end of the query #117136#discussion_r4264144742] The author accepts and documents closing/reopening files instead of retaining descriptors. If background writeback fails and the inode is evicted before reopening, the final sync can succeed despite lost data; documentation does not preserve the existing durability guarantee. This failure mode is documented by PostgreSQL. Preserve error tracking, or retain per-part syncing as the default and make the weaker guarantee an explicit opt-in.

  • src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp:1148 — A fetched local-object-storage copy does not establish durability for a deduplicated retry. [dismissed by author -- https://github.com/Fsync the parts of an INSERT once, at the end of the query #117136#discussion_r4377147720] A batched insert on A can publish an unsynced part; B fetches it onto local_blob_storage with the default fetch-sync threshold, then acknowledges a deduplicated retry after this no-op. Neither copy need be durable. The author's explanation that this backend never syncs blobs does not match LocalObjectStorage::writeObject → WriteBufferFromFileWithLogging → WriteBufferFromFileDecorator::sync: immediate insert-time syncing does reach the local file. Require a synced copy on this backend, or reject the durability-requiring retry when it cannot be established. This concern is specific to filesystem-backed object storage.

⚠️ Majors

  • src/Storages/MergeTree/MergeTreeSettings.cpp:783 — The new default has no demonstrated performance benefit with overlapping merges. The open performance thread now includes measurements: deferred mode performs 1,036–1,086 total syncs versus 626–629, with 55–160 seconds summed sync time versus 27–45 seconds and no consistent insert-time improvement. MergeTask syncs pending sources, then query completion syncs their covering parts again. Keep the mode non-default unless representative measurements justify the change, or remove redundant work while preserving durability.
Tests
  • ⚠️ The cross-replica test covers local disks, but not the dismissed local_blob_storage case. A focused two-replica regression must verify that the fetched copy is synced, or that the retry fails, while the originating insert remains unsynced.
  • ⚠️ Before changing the default, provide current before/after measurements on the intended workload and storage, including background sync counts/time and insert wall time.
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.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 30, 2026
@zlareb1

zlareb1 commented Aug 30, 2026

Copy link
Copy Markdown
Member

It looks like patch parts escape the new end-of-query fsync entirely.

MergeTreeSinkPatch::finishDelayedChunk and ReplicatedMergeTreeSinkPatch::finishDelayed override the base hooks where committed_parts is collected, and they commit their parts without collecting anything, so the inherited onFinish calls fsyncCommittedParts with an always-empty list. At the same time writeTempPatchPart routes through writeTempPartImpl, whose per-part sync is now gated on fsync_after_insert_each_part, so under the new default a patch part is not synced at finalize either.

Net effect on a table with fsync_after_insert = 1: a lightweight UPDATE/DELETE is acknowledged with its patch part never fsynced, while on current master the same patch part is synced via the finalizePartAsync sync flag. After a power loss the acknowledged update can silently revert (plain MergeTree and single-replica ReplicatedMergeTree; multi-replica setups can heal by refetching). The added tests don't exercise patch parts, so 05052/01643/02361 can't see this. Collecting the committed patch part infos in the two patch-sink overrides (or keeping the per-part sync for patch parts) would close it.

A smaller adjacent window: fsyncPartsAfterInsert skips a part when getActiveContainingPart returns nullptr, which is right for DROP/TRUNCATE, but a concurrent MOVE PARTITION TO TABLE moves the just-committed part to the destination table where nobody will fsync it, while previously it was already durable at write time. Similarly DETACH PARTITION leaves un-synced files in detached/.

alexey-milovidov and others added 2 commits September 2, 2026 05:27
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you, the patch-part gap was real — fixed in a6c930d.

MergeTreeSinkPatch::finishDelayedChunk and ReplicatedMergeTreeSinkPatch::finishDelayed now collect the committed patch part into committed_parts, so the inherited onFinish fsyncs it before the lightweight update is acknowledged, exactly like an inserted part. The test 05055_fsync_after_insert_batched was extended with a lightweight UPDATE on a table with fsync_after_insert = 1, asserting that the UPDATE query itself accounts a non-zero FileSync. Verified locally: 25 FileSync for the patch part with the fix, and the same query on a table with fsync_after_insert = 0 stays at 0, so the assertion is not satisfied by anything else.

On the second point (getActiveContainingPart returning nullptr while a concurrent MOVE PARTITION TO TABLE or DETACH PARTITION runs) I am deliberately leaving it as is. Both cases require a DDL that races with a still-running INSERT into the very partition it writes, and in both the data is no longer where the acknowledged INSERT put it: after MOVE PARTITION TO TABLE the files belong to the destination table and follow its own fsync_after_insert policy, and after DETACH PARTITION the user has explicitly taken the data out of the table. Closing that window would mean holding a DataPartPtr for every part the query committed instead of a MergeTreePartInfo, which pins outdated parts (and their disk space) for the whole duration of a long INSERT — that is exactly the cost the batched fsync is meant to avoid, and it would still not cover the moved part, which nobody in the source table can sync any more. Explicitly noting it here so the trade-off is on the record rather than accidental.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 18f60bd4f with master 9f79cc172 (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

116 object files changed (+116.19 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/UniqueKey/UniqueKeyTxnCommit.cpp.o 390.23 KiB 430.11 KiB +39.88 KiB (+10.22%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/ReplicatedMergeTreeSink.cpp.o 709.62 KiB 729.53 KiB +19.91 KiB (+2.81%)

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

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 16, 2026 08:03
`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]>
alexey-milovidov and others added 2 commits September 18, 2026 11:28
`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]>
alexey-milovidov and others added 3 commits September 19, 2026 20:44
…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]>
alexey-milovidov and others added 2 commits September 26, 2026 23:23
…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]>
alexey-milovidov and others added 4 commits October 5, 2026 03:15
… 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed. The CI failures on 4e6ae73 are unrelated to this PR:

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I am investigating the sum_map query 1 (maxMap over a Memory table) slowdown on amd_release. The same row was flagged on 11 other unrelated PRs on 2026-10-05 and on no master run, so it is not caused by this PR. I will follow up here with a PR (or my findings) shortly.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

The slowdown is in Field::operator<. In the CPU profiles of query 1 from that job it goes from 228 to 321 samples, while everything else in the query goes from 236 to 227. All of these calls come from the tree walk of the std::map<Field, Array> in AggregateFunctionMapBase::add, several per array element (5M elements per query). The PR binary and the reference have identical machine code for Field::operator< and for this add, at different addresses, so the difference comes from where this code lands in the binary, not from a code change. The arm minMap reds of the same test (query 0) have the same hot frame: 249 to 338 samples in this run.

A fix is in progress: #107554 replaces this path with typed aggregation, so these queries no longer compare Fields. In its own performance runs query 1 went from 0.168 s to 0.058 s on amd. It has no maintainer review yet.

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.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #127665. In CI's own CPU profiles of this test, the slow runs spend the extra time in ColumnArray::replicate + memcpy (the materialize(range(10))), not in has: replicateNumber called memcpy for 10 bytes per output row. The PR sizes the result once and copies short values inline; locally both queries go from 0.047 s to 0.030 s. Its own performance comparison is the real check.

alexey-milovidov and others added 2 commits October 25, 2026 08:53
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 9e2d255: merged the latest master (no conflicts) and fixed the replicated fetch case from the review (12bbbf9, see the thread). The fsync stateless tests pass locally on the merged tree.

The thread about the total fsync count with merges running during the INSERT stays open: removing the double sync trades durability, so whether the batched mode is worth it is a design decision for a human.

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 (group_by_dynamic_keys queries #0 and #2, +18-20%: GROUP BY over numbers, which does not touch the MergeTree write path that this PR changes; the same queries were reported slower on #123531 and unstable on master) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the group_by_dynamic_keys queries 0 and 2 slowdown on amd_release: both group by Dynamic values (query 2 through JSON paths), while the String control query 1 did not move, and in the last 30 days these rows were reported slower on only 3 of about 3,200 amd_release runs, none of them on master. I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

Findings: there is no code fix to send for this one. The slowdown comes with this PR's build of bf9142a9, not with any code these queries run.

  • Same code: the 21 hottest functions of queries 0 and 2 (ColumnDynamic::serializeValueIntoArena and deserializeAndInsertFromArena, the serialized-key Aggregator::executeImplBatchNoAggregates, decodeDataTypeImpl, SerializationObjectPool::getOrCreate, the hash map lookups, ...) have identical machine code in this build and in its reference (the performance reference build of db92feff), at addresses shifted by 0x1000 to 0x4000.
  • Same work, four times the branch mispredictions: the job's own hardware counters for query 0 (prewarm run, left-query-log.tsv / right-query-log.tsv in logs.tar.zst) show 28.5e9 instructions and 5.54e9 branches on both servers, but 36.7M mispredictions against 8.9M, and 11.7e9 cycles against 9.7e9.
  • Only this build: in a sample of 75 amd jobs from the last 14 days that have these counters, the other 149 server processes all had 8.8M to 9.1M mispredictions on query 0. The previous head bdd1110a ran both queries at parity (2.891 vs 2.872 s, 1.628 vs 1.633 s). Both restarts in the job repeated the result because they keep the binaries, so re-running the job would fail the same way; the new head 9e2d2556 gets a new build.
  • Rate: over 30 days on amd, query 0 was more than 10% slower than its reference in 6 of 3,238 runs and query 2 in 11, none of them on master, with a median ratio of 1.00. The Faster Adaptive Aggregator #123531 run is one of these.

Scoring such single-build reds against the spread of recent performance reference builds is what @ egor-click is looking into: #122350 (comment)

alexey-milovidov and others added 2 commits October 26, 2026 11:19
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed fc62e14: merged the latest master (no conflicts) and fixed the PreActive / late-Active fetch cases from the review (see the thread). The fsync stateless tests pass locally on the merged tree.

Both red checks on 9e2d255 are unrelated, and the merge brings in their fixes:

  • Integration tests (amd_asan_ubsan, db disk, targeted): test_merge_tree_s3/test.py::test_s3_disk_apply_new_settings was fixed by Count only the INSERT's own S3 requests in test_s3_disk_apply_new_settings #127679.
  • Upgrade check (amd_release): the settings-history check for use_query_condition_cache_for_time_conditions reflects a master state that has changed since; current master declares it with default false.

The thread about the total fsync count with merges running during the INSERT stays open. It needs a human design decision.

alexey-milovidov and others added 3 commits October 27, 2026 10:59
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed c5ad327: fixed the Style check failure on 8d5db71 (the ReplicatedMergeTree line in the new test 05452_fsync_after_insert_batched_deduplicated_other_replica now contains $CLICKHOUSE_TEST_ZOOKEEPER_PREFIX literally), and merged the latest master with no conflicts. The affected MergeTree translation units build. The open thread about total fsync work with merges enabled still needs a human design decision; the measurement is in that thread.

Comment thread src/Disks/DiskLocal.cpp Resolved
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 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 INSERT) still needs a human decision.

@groeneai

Copy link
Copy Markdown
Collaborator

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 SELECT 1 readiness probe was rejected (the old probe printed any non-2xx answer as No connection to LogCluster; during this outage the read-only service answered it with Code 241, memory limit exceeded), and has_pr_data then raised LogClusterNotReady.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 05b6f8f: merged the latest master with no conflicts. The affected MergeTree translation units (MutateTask.cpp, StorageReplicatedMergeTree.cpp, MergeTreeSettings.cpp) build.

The one open thread is still about total fsync work when merges overlap the INSERT. It needs a human design decision; the measurements are in the thread.

alexey-milovidov and others added 2 commits October 30, 2026 23:26
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failures: Logical error: Trying to deserialize data into Variant column with not global variants order (STID: 6636-4f2a) in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117136&sha=05b6f8f54d251fc7c270957b78791b55a08311fa&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel%29 and Logical error: Cannot write to canceled buffer (STID: 4158-2bb4, thrown from ClientBase::processQueryText) in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117136&sha=05b6f8f54d251fc7c270957b78791b55a08311fa&name_0=PR&name_1=Stress%20test%20%28arm_debug%29, and provide a fix in a separate PR. If the fix is already in progress, link it here. (The second one may be covered by #126142.)

@groeneai

Copy link
Copy Markdown
Collaborator

Both are already covered, no new PR needed.

  1. not global variants order (STID 6636-4f2a): the stack is MergeTreeReaderWide::readRowsWithColumnsCache -> SerializationObjectTypedSharedDataPath::deserializeBinaryBulkWithMultipleStreams -> SerializationObjectTypedSharedData::deserializeRequestedPaths -> decodeGranule -> SerializationDynamic -> SerializationVariant.cpp:548, i.e. a SHARED typed path of a JSON column read from a Wide part through the columns cache. This is fixed by Fix LOGICAL_ERROR reading SHARED paths of dynamic types of a JSON column with the columns cache #127867 (mine, open, mergeable), which is not in this build.

  2. Cannot write to canceled buffer (STID 4158-2bb4): the stack is ProgressIndication::writeProgress <- ClientBase::onProgress <- receiveEndOfQueryForInsert <- processInsertQuery <- processQueryText in the embedded client, the site fixed by Do not render the client progress into a canceled terminal buffer #127834 (merged 2026-10-30 08:05Z). The run was created at 02:42Z and tested 05b6f8f merged into master bee6deac, 15 commits before Do not render the client progress into a canceled terminal buffer #127834, so the fix was not in the build. Do not finalize the client output format into a canceled buffer #126142 is a different site (resetOutput -> IOutputFormat::finalize, STIDs 4158-307c / 4158-351e). In the ~1100 Stress test runs started after 10:10Z yesterday, CIDB has one Cannot write to canceled buffer hit, and it is that resetOutput site (4158-307c), not this one.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thanks. Both failures on 05b6f8f are accounted for: the Variant one is fixed by #127867, and the Cannot write to canceled buffer one by #127834, which is now in this branch through the latest master merge (18f60bd). CI on 18f60bd is green apart from the pending CH Inc sync.

The open review thread (total fsync work when merges overlap the INSERT) still needs a human design decision. The measurements are in that thread.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Closing as superseded by #126251 ("Group fsync of inserted parts with fsync_after_insert"), merged on 2026-11-07.

Evidence, checked against freshly fetched master at 7b5f2bf328f9:

  • The merge commit of Group fsync of inserted parts with fsync_after_insert #126251, ad9d84dc7abb, is an ancestor of master, and no later commit on master reverts it.
  • On current master, MergeTreeSink collects the parts it commits in DeferredPartsSync and fsyncs them together in onFinish (parts_to_sync.syncAll()). This is controlled by the MergeTree setting group_fsync_before_insert_finish, which defaults to auto.

That is the core of this PR: with fsync_after_insert, sync once before the INSERT is acknowledged instead of after every part. Merging master into this branch now conflicts in 8 files (MergeTreeSink, ReplicatedMergeTreeSink, ParallelSyncFiles, MergeTreeSettings, MergeTreeDataWriter), and the result would have two settings for the same behaviour (fsync_after_insert_each_part and group_fsync_before_insert_finish).

Some parts of this PR are not on master: batched fsync by default for ReplicatedMergeTree, using waitForDeduplicatedParts, and for patch parts and unique-key inserts. #126251 deliberately keeps these out because of the risk of acknowledging an INSERT deduplicated against a part that is not yet durable on another replica. If they are still wanted, they should be a follow-up on top of DeferredPartsSync. The branch fsync-inserted-parts-once stays in place for reference.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants