Skip to content

Fsync projection parts to survive power loss - #111392

Open
groeneai wants to merge 31 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111318-projection-fsync
Open

groeneai wants to merge 31 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111318-projection-fsync

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111318

Changelog category (leave one):

  • Improvement

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

Projection parts are now fsynced together with the rest of a data part. Previously projection files (under <part>/<projection>.proj/) were never fsynced on INSERT (with fsync_after_insert), ALTER TABLE ... MATERIALIZE PROJECTION, or a row-rewriting mutation (with the *_to_fsync_after_merge thresholds), so a power loss right after an acknowledged operation could leave the projection as all-zero-byte files, marked broken on load and reported by CHECK TABLE as BROKEN_PROJECTION.

Description

MergeTreeDataWriter::writeProjectionPartImpl finalized every projection part with a hardcoded no-sync flag (finalizePartAsync(..., false)), while the parent part's own files received the correct sync flag. That function serves the INSERT path (writeProjectionPart) and the mutation / merge path (writeTempProjectionPart), so under fsync_after_insert = 1 (INSERT) or the merge/mutation fsync thresholds (MATERIALIZE PROJECTION, ALTER ... DELETE/UPDATE), the projection files were written but never fsynced. After a power loss the parent rows survived but the projection directory could end up all-zero-byte, broken on load and never self-healed.

Fix: propagate the caller's sync decision into writeProjectionPartImpl and its two wrappers. INSERT passes fsync_after_insert; mutation and merge pass their need_sync decision. When a projection sub-merge re-merges several temporary parts, the final part is produced by a nested MergeTask, so the parent's decision is carried through MergeProjectionPartsTask to that task via a force_sync flag; the single-temp-part case is covered by the temp write itself, since it is only renamed into place (rename preserves the fsynced content). The merge-path need_sync is now computed before the projection temp parts are written. With group_fsync_before_insert_finish (#126251) an INSERT fsyncs its parts, projections included, only when it finishes, so the projection follows the part's decision and is not fsynced inline as well.

Behavior only changes when a durability setting is enabled; with the settings off the behavior is unchanged, and there are no on-disk, wire, or setting format changes.

Report URL for the fsync-coverage finding: #111318

Verified two ways (details in the pre-PR validation gate comment): strace -e fsync,fdatasync on the INSERT path shows 0 projection-file fsyncs on master HEAD and 10 with this fix; the new stateless test 04684_projection_fsync reads ProfileEvents['FileSync'] from system.query_log and fails on master HEAD (insert projection adds file syncs 0) and passes with the fix (1). Mutation and merge paths verified via strace (all pr.proj files fsynced) plus CHECK TABLE and force_optimize_projection.


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

groeneai and others added 3 commits July 22, 2026 12:49
Projection parts were finalized with a hardcoded no-sync flag in
MergeTreeDataWriter::writeProjectionPartImpl, so an acknowledged INSERT
(fsync_after_insert), MATERIALIZE PROJECTION, or row-rewriting mutation left
every file under <part>/<projection>.proj/ un-fsynced while the parent part's
files were fsynced. A power loss shortly after the acknowledgment could leave
the projection directory as all-zero-byte files, marking the projection broken
on load and keeping it broken indefinitely (CHECK TABLE fails with
BROKEN_PROJECTION, force_optimize_projection queries fail).

Fix: propagate the caller's sync decision into writeProjectionPartImpl and its
two wrappers. The INSERT path passes fsync_after_insert; the mutation and merge
paths pass their need_sync decision. For a projection sub-merge that re-merges
multiple temporary parts, the final part is produced by a nested MergeTask, so
the parent's sync decision is threaded through MergeProjectionPartsTask into
that task via a force_sync flag; the single-temp-part case is covered by the
temp write (the part is only renamed into place, which preserves the fsynced
content). The merge-path need_sync is now computed before the projection temp
parts are written.

Behavior only changes when a durability setting is enabled; the default
(settings off) is unchanged, and no on-disk, wire, or setting format changes.

Closes: ClickHouse#111318

Co-Authored-By: Claude Fable 5 <[email protected]>
…merges

Address two durability gaps found in code review of the projection fsync fix:

- Merge-path projection temp parts are written while streaming rows in
  executeImpl(), before finalize() ran, so need_sync still held its default
  false. Compute need_sync in prepare() (right after the input size bounds are
  known) so it is correct for every projection write, including the streaming
  pre-calculate flush whose sole temp part is only renamed into place.

- MergeProjectionsStage::prepareProjections merges projections that already
  exist in all source parts via a child MergeTask that did not inherit the
  parent merge's sync decision. Pass the parent's need_sync as force_sync so
  the merged projection is fsynced whenever the parent part is.

Extend 04548_projection_fsync with an OPTIMIZE (merge) FileSync assertion so the
merge paths are exercised, and condense the header comment.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment-only and test-text changes (no functional change):
- prepare(): executeImpl() -> executeImpl in the comment.
- test: "rebuilt" -> "merged" for the OPTIMIZE section (existing projection
  parts are merged, not rebuilt); backtick INSERT / MATERIALIZE PROJECTION /
  ALTER in comments.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 7 findings across 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ Approach: sync only the temp write, not the final projection produced by the merge task AGREE Both mutation and merge route the final projection through MergeProjectionPartsTask (single-part rename / multi-part nested re-merge). Threaded the parent's sync decision through MergeProjectionPartsTask -> mergePartsToTemporaryPart via a force_sync flag.
2 ❌ Merge single-part rename preserves the hole if callers stay at false AGREE The hardcoded false was one bug across all callers. Merge temp writes now pass need_sync; the sole-temp-part rename preserves the fsynced content.
3 ❌ Merge need_sync computed in finalize(), but projections are written during executeImpl streaming AGREE Verified: calculateProjections runs in the executeImpl pull loop before finalize(). Moved need_sync computation to prepare() (after the input size bounds).
4 ❌ MergeProjectionsStage::prepareProjections (existing-projection merges) builds a child MergeTask without force_sync AGREE Verified: this is the common merge path. Now passes the parent's need_sync as force_sync.
5 ⚠️ Regression test observes fsync only for INSERT AGREE (partial) Added an OPTIMIZE (merge) FileSync assertion + readability checks. Note: the merge assertion is 1 on both pristine and fixed binaries (the reported bug's merge path already synced via the nested-merge threshold), so it guards the durability invariant going forward rather than discriminating this bug; the INSERT assertion is the discriminating regression (0 vs 1).
6 ❌ fsync_part_directory=1 does not recursively sync the nested projection directory DISAGREE Out of scope for #111318 and diverges from the accepted sibling precedent. The issue reproduces as "names intact, 0-byte files" — the projection directory entries survived (parent-dir fsync + journal); only file CONTENT was lost, which this PR fixes. The issue's "Expected behavior" is "all files ... are fsynced" (content). Sibling fsync PR #111335 (text index) likewise syncs only file contents and adds no nested-directory sync. Recursive part-directory fsync (also touching mutation-hardlink and fetch paths) is a separate, pre-existing concern; bundling it would violate one-concern-per-PR.
7 💡 Comment/test literal-name conventions ("rebuilt" vs "merged"; backtick SQL command names) AGREE Fixed the wording and backticked INSERT / MATERIALIZE PROJECTION / ALTER.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-0:20260722-105200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. INSERT with fsync_after_insert=1 under strace -e fsync,fdatasync: 0 fsync on pr.proj files on master HEAD, 10 with the fix, every run.
b Root cause explained? Yes. writeProjectionPartImpl finalized every projection part with a hardcoded false sync flag, so neither fsync_after_insert nor need_sync reached projection files; power loss then leaves pr.proj as 0-byte files, broken on load.
c Fix matches root cause? Yes. Threads the caller's real sync decision into writeProjectionPartImpl and its wrappers, so every projection final producer fsyncs when the parent part does.
d Test intent preserved / new tests added? Yes. New test 04548_projection_fsync asserts the FileSync delta (projection vs no-projection) for INSERT and OPTIMIZE, plus projection readability after MATERIALIZE PROJECTION. No existing test weakened.
e Both directions demonstrated? Yes. insert projection adds file syncs is 0 on rebuilt-pristine master (test FAILS) and 1 with the fix (PASSES); strace shows 0 -> 10 projection-file fsyncs.
f Fix is general across code paths? Yes. Covers all three non-merge final producers (INSERT direct write, mutation temp write, merge single-part rename) AND the multi-part nested re-merge and the existing-projection merge path; no sibling projection write left at false.
g Fix generalizes across inputs? Yes. The change is at the sync-flag plumbing, independent of projection column types/wrappers or aggregate-vs-normal projections; Compact and Wide parent parts both covered (projection now mirrors the parent's existing fsync path).
h Backward compatible? Yes. No default, setting, or on-disk/wire format change. Behavior changes only when a durability setting is already enabled, and only ADDS the missing fsync. Settings-off behavior is byte-identical; no SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. Only adds fsync calls; no change to part structure, checksums, block structure, lock ordering, or the finalizer contract. force_sync defaults to false, so all non-projection MergeTask / mergePartsToTemporaryPart callers are unaffected.

Session id: cron:clickhouse-author-slot-0:20260722-105200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @alesapin — could you review this? Projection parts were finalized with a hardcoded no-sync flag in writeProjectionPartImpl, so fsync_after_insert / the merge-and-mutation need_sync never reached projection files and a power loss could leave the projection broken. It threads the caller's sync decision to every projection final producer (INSERT direct write, mutation/merge temp write, and the nested projection re-merge via a force_sync flag).

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4237f28]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR propagates the parent operation's fsync decision to projection writes and sub-merges, adds projection-directory syncs, and covers inline and deferred insert fsync, merges, and mutations. Reviewed head: 4237f28661bdf62539ae600ab0004d0175c0e7e5. One previously reported durability failure remains; there are no new inline findings.

Findings

❌ Blockers

  • MergeTreeDataWriter.cpp:479, also MergeTask.cpp:2770: Directory-fsync failures still permit successful completion. [dismissed by author -- https://github.com/Fsync projection parts to survive power loss #111392#discussion_r4594670804] The new guards rely on LocalDirectorySyncGuard destruction, which catches and logs exceptions. An EIO therefore lets the insert publish its part, or the merge finish, without establishing projection-directory durability; a subsequent power loss can leave the projection broken. The author's measurement confirms the parent-directory guards have the same pre-existing defect, but does not establish durability for these new projection guards. Explicitly call sync on each non-null guard before proceeding, following VersionMetadataOnDisk.
Tests
  • ⚠️ Add focused coverage using local_directory_sync_fail to verify that projection-directory sync errors propagate from insert and merge finalization. The current DirectorySync assertions count attempts, including failed attempts, so they cannot detect this failure.
Final Verdict

❌ Block — propagate the projection-directory sync errors and cover the failure path. The existing author-dismissed finding is retained here without a duplicate inline comment or thread reply.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2b85f39

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. This PR's own diff (projection-part fsync in MergeTreeDataWriter / MergeTask) does not touch any of the failing paths (Replicated-DB DDLWorker init, test_check_all_tables, arm perf report build), so none are PR-caused.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables flaky (198 PRs / 30d, 33 master) a fix task is moved to pending (investigating at full effort; fixing PR link to follow here)
Upgrade check (amd_release) / Error message in clickhouse-server.log (rdb_test DDLWorker Mapping for table with UUID ... already exists, TABLE_ALREADY_EXISTS) flaky (30 PRs / 30d, 0 master) #107126 (ours, open)
Performance Comparison (arm_release, master_head, 1/6) arm perf report-build error (job ERROR, no report produced; not query rows) a fix task is moved to pending (investigating at full effort; fixing PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260723-040000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_check_all_tables flaky (Integration amd_asan_ubsan, db disk, old analyzer): #111353 (merged 2026-07-22, backported to 26.7 by #111574).

The failure is the plain-rewritable metadata_dropped concurrent-create race, not anything in this PR. Every occurrence after that merge is on a build whose base predates it: I checked all 49 distinct commits that produced this failure since 2026-07-22 17:31Z, and 49 of 49 lack the fix. Merging master into this PR picks it up. Details: #111477 (comment)

…-projection-fsync

Resolve two conflicts in MergeTreeDataWriter, both in writeProjectionPartImpl
and its two wrappers. Master added a `try_adaptive_codec` parameter to the same
parameter lists this branch adds `sync` to; the two are orthogonal, so both are
kept in declaration order (`sync`, then `try_adaptive_codec`) and every caller
passes both explicitly.

Also renumber the regression test 04548 -> 04684: master gained
04548_compact_multi_codec_dedup and 04548_part_storage_type_column while this
branch was open. 04684 is free on master, in all open pull requests, and across
the local worktrees. CI's check_gaps_in_tests_numbers only flags gaps, never
collisions, so a collision would have shipped silently.

Verified after the merge that the sync decision is still propagated at every
call site rather than falling back to the parameter default: the four projection
write sites pass fsync_after_insert / need_sync, and the four projection
sub-merge sites pass force_sync. Only the top-level parent merges keep the
default, which is correct because they compute need_sync from the thresholds
themselves.
The merge fsync thresholds were both set to 1, which made that half of the test
vacuous. An aggregate projection holds one row per group, so the projection part
carries 7 rows where the parent carries 5000. At a threshold of 1 the projection
sub-merge clears needSyncPart on its own and syncs regardless of whether the
parent's decision is propagated to it, so the assertion could not observe the
force_sync plumbing at all.

Measured with force_sync removed from ExecuteAndFinalizeHorizontalPart::prepare
while leaving the rest of the fix in place: at thresholds of 1 the test still
passed, so it would not have caught a regression in that plumbing.

Raise min_rows_to_fsync_after_merge to 1000, which sits above the projection part
and below the parent part, and set min_compressed_bytes_to_fsync_after_merge to 0
so the byte arm cannot satisfy the check by itself (needSyncPart ORs the two
arms). The projection sub-merge now syncs only because the parent's decision
reaches it. With that change the same force_sync-removed build reports a merge
delta of 0 and fails, while the full fix reports 1 and passes.

Verified stable over repeated runs and with three concurrent copies of the test,
so it stays parallel-safe and needs no no-parallel tag.

Also wrap the literal MATERIALIZE PROJECTION in the writeTempProjectionPart
comment in inline code, per the repository conventions.
The materialization block only checked that rows and the projection were readable,
which passes whether or not the mutation propagates its sync decision. The
mutation's fsyncs run on the IO thread pool, so they are not attributed to the
ALTER in system.query_log, which is why the earlier version gave up on measuring
them. They are, however, attributed to the produced part in system.part_log,
which makes the delta observable after all.

Add a row-rewriting ALTER ... UPDATE next to the MATERIALIZE PROJECTION so both
temp-projection mutation writes are exercised, apply the same
threshold-between-projection-and-parent reasoning as the merge case, and assert
on MutatePart FileSync in system.part_log.

The assertion is an absolute bound on one table rather than a comparison against
a projection-less table: a plain row-rewriting UPDATE touches a different set of
files than a projection rebuild, so a cross-table comparison would not be
meaningful. Measured with both MutateTask sync arguments reverted to false, the
two mutations report 6 and 9 file syncs (min 6); with the fix they report 7 and
10 (min 7). The bound of 6 therefore separates the two, and the reverted build
now fails this assertion.

Verified stable over repeated runs and with three concurrent copies.
The file-sync counts the test asserts on only exist for Full part storage. A
Packed part is a single blob, so there are no per-file syncs to count and the
deltas read 0 even when the projection is correctly synced.

min_bytes_for_wide_part controls Wide versus Compact, not Full versus Packed, so
the fixtures were not actually pinned. min_bytes_for_full_part_storage is
randomized by the test runner over 0..512 MB, so roughly a third of CI runs would
have placed these 10000-row parts in Packed storage and failed the test.

Reproduced by forcing min_bytes_for_full_part_storage to 512 MB, a value inside
the randomized range: system.part_log reports part_storage_type = Packed and the
mutation assertion drops to 0, failing the test. With the setting pinned to 0 the
same parts are Full and it passes. The sibling test
04546_text_index_merge_fsync.sql pins this setting for the same reason.

Re-checked that the test still fails when the mutation sync propagation is
reverted, so pinning the storage type did not weaken the assertion.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master to resolve the conflict (the branch was ~7950 commits behind). Two conflicts, both in MergeTreeDataWriter: master added a try_adaptive_codec parameter to the same parameter lists this PR adds sync to. They are orthogonal, so both are kept and every caller passes both explicitly.

Since the parameter threading is the whole fix, I re-checked after the merge that the sync decision is actually propagated at every call site rather than silently falling back to a parameter default: the four projection write sites pass fsync_after_insert / need_sync, and the four projection sub-merge sites pass force_sync. Only the top-level parent merges keep the default, which is correct since they compute need_sync from the thresholds themselves.

Re-verified the fix in both directions on the merged tree: with the one-line root cause reverted the regression test reports an insert file-sync delta of 0 and fails, with the fix it reports 1 and passes.

Three test changes while re-validating, all of which make the test strictly harder to pass:

  • Renumbered 04548 to 04684. Master gained 04548_compact_multi_codec_dedup and 04548_part_storage_type_column while this PR was open. check_gaps_in_tests_numbers only flags gaps, never collisions, so this would have shipped silently.
  • The merge assertion was vacuous. An aggregate projection holds one row per group, so the projection part carries 7 rows where the parent carries 5000; with both merge thresholds at 1 the projection sub-merge cleared needSyncPart on its own and the assertion could not observe whether the parent's decision reached it. Verified by removing force_sync and leaving the rest of the fix in place: at thresholds of 1 the test still passed. Raising min_rows_to_fsync_after_merge to 1000 and setting min_compressed_bytes_to_fsync_after_merge to 0 puts the threshold between the projection and the parent, and the same build now reports a merge delta of 0 and fails.
  • The materialization block was readability-only, which passes whether or not the mutation propagates its sync decision. Its fsyncs are not attributed to the ALTER in system.query_log, but they are attributed to the produced part in system.part_log, so the delta is observable after all. Added a row-rewriting ALTER ... UPDATE alongside the MATERIALIZE PROJECTION and an assertion on MutatePart FileSync: with both mutation sync arguments reverted the two mutations report 6 and 9 syncs, with the fix 7 and 10.

Also pinned min_bytes_for_full_part_storage = 0 in all three fixtures. min_bytes_for_wide_part controls Wide versus Compact, not Full versus Packed, and the runner randomizes min_bytes_for_full_part_storage over 0..512 MB. A Packed part is a single blob with no per-file syncs to count, so roughly a third of runs would have read a delta of 0 and failed. Reproduced by forcing 512 MB: part_storage_type reads Packed and the mutation assertion drops to 0.

The test stays parallel-safe (verified with three concurrent copies) and needs no no-parallel tag.

groeneai and others added 6 commits August 1, 2026 17:12
Syncing the files inside <part>/<projection>.proj/ does not make that
directory's own entries durable: fsync of the parent part directory
persists only the .proj entry itself. After a power loss the projection
directory could come back empty or partial even though every one of its
files had been fdatasynced, leaving the projection broken on load, which
is the failure this PR set out to fix.

Measured with strace on an INSERT into a table with an aggregate
projection and fsync_after_insert = 1, fsync_part_directory = 1: all 14
pr.proj files were fdatasynced, the parent tmp_insert_ and final part
directories were fdatasynced, and pr.proj itself was never fsynced.

Take a directory sync guard on the projection storage, gated on
fsync_part_directory, mirroring what writeTempPartImpl already does for
the base part. The guard is released when the function returns, after
every projection file has been created, so the fsync observes a complete
directory.

Only the INSERT path needed this. The mutation and merge paths route the
final projection through MergeProjectionPartsTask, whose renameTo already
syncs the renamed directory and its parent under the same setting; that
was confirmed by the same strace measurement.

The regression test asserts DirectorySync rather than FileSync, since
DirectorySync counts directory fsyncs only and so cannot be satisfied by
the projection file syncs the existing assertion already covers.

Co-Authored-By: Claude Fable 5 <[email protected]>
The mutation assertion counts files, so anything unrelated that adds one
satisfies it without any projection file being synced. Implicit
statistics add exactly one such file to the mutated part.

Both settings that produce them are randomized by the test runner, and
materialize_statistics_on_insert is set to true in 95% of runs. Measured
on a build with the mutation projection sync propagation reverted: the
minimum FileSync per mutated part is 6 with statistics off, so the
assertion fails as intended, but 7 with materialize_statistics_on_insert
enabled, so it passes. The assertion could therefore not detect the
regression it guards in nearly every CI run.

Pin both settings off. Re-checked on the same reverted build with the
runner forcing materialize_statistics_on_insert = 1 that the pinned test
still fails, so this restores discrimination rather than silencing the
assertion.

Co-Authored-By: Claude Fable 5 <[email protected]>
The projection directory guard was taken in writeProjectionPartImpl and
released when that function returned. On Packed storage the projection's
data.packed is not created there: finalizePartAsync only buffers the logical
files, and the archive dentry appears later, when the part's transaction is
precommitted. Measured with strace on an INSERT into a Packed table, the
fdatasync of pr.proj therefore ran before pr.proj/data.packed existed, so the
archive was still not durable after a power loss even though the directory was
synced.

Move the projection directory sync into MergeTreeTemporaryPart::finalize, right
after each projection's precommitTransaction, so it observes a complete
directory on both Full and Packed storage. Extend the regression test with a
Packed fixture, asserting on ProfileEvents['DirectorySync'] and pinning
min_bytes_for_full_part_storage high so the fixture really produces a Packed
part (verified via system.part_log part_storage_type).

Co-Authored-By: Claude Fable 5 <[email protected]>
The Packed fixture only compared ProfileEvents['DirectorySync'], which the
directory guard increments. On Packed storage a projection file sync merely sets
FinalizePlan::need_sync and data.packed is synced later only when that flag is
set, so the assertion stayed green with the projection sync argument dropped.
Measured: with that argument forced false the directory assertion still reported
1 while the archive was never fsynced.

A Packed part has exactly one file to sync, so assert a FileSync delta of exactly
one against the projection-less table. That reddens on the dropped sync argument
and on a stray extra sync.

Co-Authored-By: Claude Fable 5 <[email protected]>
The mutation assertion was an absolute bound on one table's FileSync count, but
the number of files a part holds depends on the serialization layout, and CI
randomizes it: serialization_info_version = 'basic' drops serialization.json and
string_serialization_version = 'single_stream' drops the key.size pair. Measured
parent-part file counts of 13, 14, 16 and 20 across four randomized arms, so no
constant can be right. The CI runner's minimizer reported the test failing 17/17
and 56/56 with those settings and 0/63 and 0/76 without randomization.

The bound was also vacuous in the other direction: on one of fourteen randomized
combinations it still read above the threshold with the fix removed.

Compare against an identical projection-less table running the same mutation
instead, so a layout change moves both readings and cancels out. The two
mutations have to sit at the same position in their part's mutation chain: a
mutation's sync count depends on that position, not only on the files it writes
(on a table with no projection at all, the same UPDATE syncs 7 files as the
first mutation and 9 as the second), so the plain table gets a matching no-op
mutation. The remaining delta is one per rebuilt projection and does not track
how many files the projection holds, so it is asserted exactly.

Verified with the fix present on 14 seeded MergeTreeSettingsRandomizer
combinations, both settings sets the runner blamed, and 3 concurrent copies; and
with the mutation sync argument forced false, where all 14 combinations report 0.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

The 04684_projection_fsync failure on the previous head was mine: the mutation assertion was an absolute bound (min(FileSync) > 6) on a single table, and the number of files a part holds depends on the serialization layout, which CI randomizes. serialization_info_version = 'basic' drops serialization.json; string_serialization_version = 'single_stream' drops the key.size.* pair. I measured parent-part file counts of 13, 14, 16 and 20 across four randomized arms, so no constant can be correct. That matches the runner's own minimizer (17/17 and 56/56 failing with those settings, 0/63 and 0/76 without randomization), and I reproduced the exact diff locally.

The bound was also vacuous in the other direction: on 1 of 14 randomized combinations it still read above the threshold with the fix removed, so it could have missed a real regression.

The assertion is now a delta against an identical projection-less table running the same mutation, so a layout change moves both readings and cancels out. One thing that is not obvious: the two mutations have to sit at the same position in their part's mutation chain. A mutation's sync count depends on that position and not only on the files it writes. On a table with no projection at all, the same UPDATE syncs 7 files as the first mutation and 9 as the second, so the plain table gets a matching no-op mutation. The remaining delta is one per rebuilt projection and does not track how many files the projection holds (unchanged when the projection grows from 14 files to 24), so it is asserted exactly and a stray extra sync reddens too.

Validation, with the Build ID read from the running server in each arm:

arm 14 seeded MergeTreeSettingsRandomizer combinations both settings sets the runner blamed
fix present 14/14 pass pass
mutation sync argument forced false 14/14 report 0 reddens

Also 3 concurrent copies pass, so no no-parallel tag is needed. The other four assertions are unchanged and were green throughout.

One method note, in case it is useful to anyone reading this later: my first sweep was itself vacuous. A quoting bug left the settings string empty, so all 14 runs passed with no randomization at all. I caught it only by adding the old test as a control arm, on the principle that a sweep in which the known-bad version never fails is not exercising the settings.

Session id: cron:clickhouse-maint-slot-13:20260801-221100

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
A merged projection is written straight into the final <part>/<projection>.proj of
the result part: prepareProjections builds a child MergeTask whose parent_part is
set, which makes local_tmp_prefix empty, and finalizeProjectionsAndWholeMerge only
commits the transaction. On a local disk that commit is FakeDiskTransaction::commit,
a no-op, so unlike the temp-rename flow MergeProjectionPartsTask uses there was no
fsync of the nested projection directory.

Syncing the files inside pr.proj does not make the directory's own entries durable,
so with fsync_part_directory = 1 an OPTIMIZE or background merge where every source
part already has the projection could still come back after power loss with a durable
pr.proj entry in the parent part but missing entries inside pr.proj, even though the
files themselves were fdatasynced. Measured with strace on such a merge: 15 fdatasync
calls on the result part's pr.proj files, one on the parent part directory, none on
pr.proj itself, and no .tmp_proj rename to piggyback on.

The guard sits below commitTransaction because that is where Packed storage finalizes
data.packed; taken any earlier it would sync a directory that does not hold the
archive yet. Ordering confirmed by trace on both Full and Packed storage.

The test asserts a DirectorySync delta for the OPTIMIZE against an identical
projection-less table, matching the two insert arms. Disabling the guard reddens that
assertion, and only that assertion, on all 14 seeded settings-randomizer combinations.
The merge directory-sync assertion ran only on a table pinned to Full storage, but the
ordering of the guard is storage-sensitive: data.packed is finalized when the projection's
transaction is committed, so a guard taken before that would sync a directory that does not
hold the archive yet. A regression affecting only Packed merge finalization would have
passed.

The two Packed tables also needed the merge fsync thresholds the Full fixtures carry,
otherwise the projection sub-merge clears its sync decision on its own and the assertion
measures nothing.
…directory

The directory guard runs independently of whether the projection sub-merge inherited the
parent's sync decision, so the directory assertion alone stays green if that propagation is
dropped: data.packed is synced only when the sub-merge asked for it. A Packed projection is
one archive, so the delta against the projection-less table is exactly one and a missing or
stray sync both redden.
@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @Ergus, all four of your open review threads are addressed in the current head (978f3de), and each has a reply from the author:

  • 04684_projection_fsync.sql line 328: the mutation arm no longer asserts an exact delta of 1. It now asserts that the mutation on the projection table syncs more files than the same mutation on the projection-less table.
  • need_sync computed in prepare: a new arm covers it. It rebuilds the projection on merge (materialize_projections_on_merge = 1) and checks RebuiltProjections = 1 to confirm the rebuild happened. Moving the computation back to finalize turns that line red.
  • multi-temp-part projection sub-merge: a new 1.1M-row arm checks MergeSourceParts > 1 to confirm the sub-merge really has several parts. Passing false there turns the line red.

CI shows no failures so far. Could you take another look and resolve the threads or update your review?

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111392&sha=978f3def1ae1ca265565692c17b38009d9203a7c&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The Upgrade check (amd_release) failure is MutatePlainMergeTreeTask: Unknown expression identifier b (UNKNOWN_IDENTIFIER). It is unrelated to this PR: the same error failed the job on about 45 other PRs between 2026-10-01 and 2026-10-19. It matches #120975, and the fix in #125293 is still open.

@groeneai

Copy link
Copy Markdown
Collaborator Author

This is #120975, and #125293 is the fix in progress. All 162 lines of upgrade_error_messages.txt in this run are the mutation of the empty part all_1_1_1 of test_7.t_stale_part_type_5 (04653_mutation_rewrite_stale_part_column_type), retried 54 times from 11:40:07 until cleanup dropped the part at 11:40:42.

#125293 alone will not stop this failure, though. It changes master's copy of 04653, and this check does not run that copy: the stress phase runs the previous release's tests against the previous release's server (tests/docker_scripts/upgrade_runner.sh, clone at --branch=$previous_release_tag on line 44, clickhouse-test --queries="previous_release_repository/tests/queries" on line 162). This run used v26.9.21.9-stable, and 04653 on 26.9 and 26.10 has no old_parts_lifetime = 0. So the fix reaches this check only once it is backported to 26.9 and 26.10 (26.10 becomes the previous release when its first stable is tagged) and a release with it is tagged from each. StorageMergeTree::dropPart and dropPartNoWaitNoThrow are identical on 26.9 and master, so the backported test behaves the same on the old server.

#125293 has had no review since 2026-10-12. The route that needs no backports is a server-side fix, because the upgraded server is the PR's own build: my #118499 (skip mutating an empty part that cleanup is about to drop) did that, and was closed when #125293 was opened. I can resubmit it as a new PR if you prefer that route.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 978f3de

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log not from this PR (it fsyncs projection parts): after the server restart MutatePlainMergeTreeTask logs Unknown expression identifier b (UNKNOWN_IDENTIFIER), the signature of the stale empty part that DETACH PART leaves in 04653_mutation_rewrite_stale_part_column_type; same error on 64 other PRs in the last 30 days #125293 (external, open)
Mergeable Check, PR praktika rollups of the row above #125293 (the owner of the first row)
Sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261019-120004

Resolve the conflict in `MergeTreeDataWriter::writeProjectionPart`: keep the
PR's `sync` argument and master's new `context` argument to
`writeProjectionPartImpl`.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (9a348d8) and resolved the conflict in MergeTreeDataWriter::writeProjectionPart (kept this PR's sync argument together with master's new context argument to writeProjectionPartImpl). The merged tree builds, and 04684_projection_fsync passes against it locally.

The only red check on the previous head was Upgrade check (amd_release): Unknown expression identifier \b`fromMutatePlainMergeTreeTask`. That is the known, unrelated #120975, and its fix is in progress in #125293.

I resolved the four review threads: each one is covered by the code and test changes from 59f7d84 and 6cdee91 that the replies describe (the need_sync move is covered by the rebuilt-projection arm, the multi-temp-part force_sync path by the 1.1M-row mutation arm, and the exact = 1 mutation assertion was relaxed to a comparison). @Ergus, could you take another look?

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111392&sha=67c87fe087cef18057570cdb74274349ab2d7e1c&name_0=PR&name_1=Build%20profile%20diff and provide a fix in a separate PR. If the fix is already in progress, link it here.

The only red check on 67c87fe was Build profile diff, which failed with LogClusterNotReady: the endpoint never became ready while it queried the CI logs cluster. That failure comes from CI infrastructure and is not related to this PR. It matches #120462. The candidate fixes in #126200 and #126296 are still open.

I merged master (b4fae47) without conflicts. It does not touch any MergeTree file in this PR. The merged tree builds, and 04684_projection_fsync passes against it locally (pushed as 46c15f1). There are no unresolved review threads. @Ergus, your CHANGES_REQUESTED review from 2026-10-07 is still pending; the changes it asked for are in the PR, so please re-review when you can.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Build profile diff red on 67c87fe is not caused by this PR. Its job log shows all 8 SELECT 1 readiness probes failing (No connection to LogCluster) until has_pr_data raises LogClusterNotReady. The read-only CI logs service is at its total memory limit and rejects every query, the probe included: HTTP 500, Code: 241 ... current RSS: 212.80 GiB, maximum: 212.40 GiB (re-checked at 2026-10-28 01:52 UTC). No Build profile diff run in CIDB has been green since 2026-10-26 22:42 UTC.

The fix for this signature is my open PR #126200: a readiness probe that the server rejects for its own load (exception code 202 or 241) ends the job green with CI logs cluster unavailable, nothing compared, while every other not-ready cause stays red. #126296 covers a different symptom (the build jobs' profile upload hook when the writer endpoint gives no HTTP answer at all) and does not change this check. The memory exhaustion of the read-only service itself is on the cluster side.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (06dbd3d) without conflicts and pushed fdf9e16. The merged tree builds, and 04684_projection_fsync passes locally twice with randomized settings.

The only red check on the previous head (46c15f1) was Build profile diff (LogClusterNotReady), a CI infrastructure failure tracked in #120462, with the fix in #126200.

@Ergus, all review threads are resolved. Your 2026-10-07 review still shows as changes requested; could you take another look?

@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Dear @Ergus, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@Ergus Ergus self-assigned this Nov 9, 2026

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove the "(this isn't important though)" From the PR title before merging.

@groeneai groeneai changed the title Fsync projection parts to survive power loss (this isn't important though) Fsync projection parts to survive power loss Nov 9, 2026
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, removed the suffix from the title. The changelog category stays Improvement.

alexey-milovidov and others added 2 commits November 16, 2026 23:27
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

The master merge brought in #126251: with group_fsync_before_insert_finish an INSERT fsyncs every file of its parts, projections included, when it finishes, so a projection written with fsync_after_insert was fsynced twice (Fast test: packed insert projection adds exactly one file sync read 2). Fixed in c3ee34c: the projection now follows the part's decision, the INSERT arms of 04684_projection_fsync pin group_fsync_before_insert_finish = 0 (the inline path, the default for replicated tables), and a new arm covers the group fsync.

@clickhouse-gh clickhouse-gh Bot added comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 17, 2026
The test counts fsyncs, so its run time is mostly the disk's fsync latency, and on the
Fast test runner that latency varies several times between runs. 04684 took 0.8-2.8 s
on every earlier head of this PR and 19.9 s on c3ee34c, where every statement that
fsyncs ran slower (a 10000-row INSERT with `fsync_after_insert` took 1.5 s, the
1.1M-row INSERT without it 0.2 s) and `04622_detach_partition_fsync_part_directory`
went from 0.6-1.0 s to 4.9 s in the same job. The 15 s limit for a new test cannot hold
with that tail, and removing fsyncs would weaken what the test checks. It still runs in
every other stateless job, like `01643_merge_tree_fsync_smoke`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
projection->getDataPartStorage().precommitTransaction();

if (fsync_projection_directory)
{ SyncGuardPtr projection_sync_guard = projection->getDataPartStorage().getDirectorySyncGuard(); }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] Propagate projection-directory fsync failures before committing the part

This guard is destroyed without calling sync explicitly. LocalDirectorySyncGuard catches every sync exception in its destructor and only logs it, so an EIO while syncing the projection directory does not fail MergeTreeTemporaryPart::finalize. MergeTreeSink::finishDelayedChunk then commits the part, allowing an INSERT with fsync_after_insert = 1, fsync_part_directory = 1 to succeed without establishing durability of the projection's directory entries. A subsequent power loss can still leave the projection incomplete. The identical new guard in MergeTask.cpp:2770 lets merges complete after the same failure.

Please call sync explicitly on each non-null projection guard before proceeding, as VersionMetadataOnDisk already does, so the exception reaches the insert/merge caller. Add focused coverage using local_directory_sync_fail: the current DirectorySync assertions cannot detect this failure because the counter increments before the sync succeeds.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured on master fdc4389b67de: with local_directory_sync_fail enabled, an INSERT with fsync_after_insert = 1, fsync_part_directory = 1 succeeds after the parent part's own guard in MergeTreeDataWriter::writeTempPartImpl logs the injected EIO, so the projection guards match the existing part-directory behaviour. Failing the query on a directory-sync error would have to cover the part-directory and rename guards too, so this PR keeps the existing idiom.

@Ergus

Ergus commented Nov 17, 2026

Copy link
Copy Markdown
Member

@groeneai Merge master, tyhe CI error seems unrelated with this PR changes

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master in 4237f28, no conflicts; 04684_projection_fsync passes locally, 20/20 with randomized settings.

The red check on the previous head was Review Threads, not a test: the clickhouse-gh [Blocker] thread on MergeTreeDataWriter.cpp:479 is still unresolved (I answered it with a measurement and kept the existing idiom, and I leave bot threads for the bot to resolve). So the new head again runs only the limited CI suite. If you agree with the answer there, resolving that thread re-runs the full suite.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). groeneai-origin-unknown PR origin: unclassified (legacy task) pr-improvement Pull request with some product improvements

Projects

None yet

4 participants