Repository navigation
Make part metadata rewrite durable to prevent data loss on power loss - #111414
alexey-milovidov merged 13 commits into
Conversation
IMergeTreeDataPart::writeMetadata rewrote checksums.txt / columns.txt in place with finalize() only, without an fsync or an atomic rename. It backs the CHECK TABLE checksums repair and the checksums.txt / columns.txt backfills in loadChecksums / loadColumns, which run in an already-committed part directory with no enclosing directory rename. On a local disk the write is therefore neither atomic nor durable: after the repair is acknowledged, an unrelated durable write plus a power loss can leave a zero-byte checksums.txt. loadChecksums treated an empty checksums.txt as fatal and detached the whole part as broken, losing every row of an otherwise-intact part. An absent checksums.txt self-heals (it is recalculated), so the acknowledged repair made the on-disk state strictly worse. - writeMetadata writes to a temporary file, fsyncs it, and atomically renames it into place (fsyncing the directory when fsync_part_directory is set), mirroring VersionMetadataOnDisk::storeInfoToDataPartStorage. The final file is never empty or partial. - loadChecksums treats an existing-but-empty checksums.txt like an absent one: it removes the empty file (and any leftover temporary file) and recalculates, which also recovers parts already left in this state. - checkDataPart skips temporary .tmp files during its directory walk so a leftover temporary file from an interrupted rewrite is not checksummed and cannot invalidate the recalculated checksums. Closes: ClickHouse#111373 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-4:20260722-132500 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; bounded: 1 full pass + 1 fix round + 1 delta recheck).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-4:20260722-132500 |
|
cc @tiandiwonder @azat — could you review this? It makes the part metadata rewrite ( |
|
Workflow [PR], commit [89b978f] Summary: ✅
AI ReviewSummaryThis PR makes Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block
LLVM Coverage ReportMeasured on commit 89b978f.
Changed lines: Changed C/C++ lines covered: 25/32 (78.12%) · Uncovered code |
| try | ||
| { | ||
| auto out = data_part_storage.writeFile(filename, 4096, settings); | ||
| auto out = data_part_storage.writeFile(tmp_filename, 4096, settings); |
There was a problem hiding this comment.
writeMetadata is a shared helper for every part storage type, but this rewrite only works for flat on-disk files. On MergeTreeDataPartStorageType::Packed, checksums.txt and columns.txt are archived inside data.packed (DataPartStorageOnDiskPacked::files_written_separately only covers delete-on-destroy.txt and txn_version.txt), and DataPartStorageOnDiskPacked::writeFile only accepts archived writes after beginTransaction() initializes the packed writer. With the old transaction removed here, writeFile(tmp_filename, ...) will throw NOT_INITIALIZED, so the load-time backfill paths and the CHECK TABLE repair path stop working for packed parts. Please keep the part-storage transaction / packed-writer initialization around the temp-write flow, or special-case packed storage before switching this helper over.
There was a problem hiding this comment.
Packed part storage is not reachable in OSS, so this path is not exercised here. DataPartStorageOnDiskPacked.h is only included under #if CLICKHOUSE_CLOUD (MergeTask.cpp:74-78) and the header is not present in this tree; the only on-disk storage class here is DataPartStorageOnDiskFull. MergeTreeData::choosePartFormat returns PartStorageType::Full on every path (MergeTreeData.cpp:5335, 5346), so an OSS server never creates a packed part and writeMetadata only ever runs against flat files.
For Full storage the previous beginTransaction/commitTransaction used FakeDiskTransaction (no atomicity), which is the in-place truncate window this PR closes. Making the rewrite durable for packed storage would be a Cloud-side change that cannot be compiled or tested from this OSS PR, so it is out of scope here.
…omization The test captures the single part directory once and manipulates checksums.txt there by absolute path across detach/attach and CHECK TABLE cycles. It assumed a single active part that never moves, but max_insert_threads and block-size randomization can split the INSERT into several parts, so SELECT path ... WHERE active returned several rows and the shell variable became multi-line, breaking every stat and integer test (line: [: : integer expression expected; stat: cannot statx .../checksums.txt). Collapse to a single part with a single insert thread plus OPTIMIZE FINAL, assert exactly one active part, select its path with LIMIT 1, and stop merges afterwards so the captured directory does not move. OPTIMIZE runs before SYSTEM STOP MERGES because stopping merges cancels a concurrent OPTIMIZE. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Fixed the PR-caused flakiness in the new test Root cause: the test captures the single part directory once and manipulates Fix (test-only): single insert thread + Validated locally: the exact culprit settings reproduce 15/15 before the change and pass 20/20 after; 50/50 with full randomization pass. No source change. |
|
CI Triage (bot) — head Verdict: REAL FAILURE — test Flaky check (amd_debug, msan) both show PR title: "Make part metadata rewrite durable to prevent data loss on power loss" — the failing test relates to checksums and MergeTree part durability, suggesting this may be a regression introduced by the PR's changes to metadata rewrite. Action needed: Investigate whether the PR changes alter behavior that Run IDs: 29934368355 |
The test inspects a single local MergeTree part's checksums.txt via an absolute on-disk path and reads system.query_log for the CHECK TABLE repair. Without the no-parallel-replicas tag the CI runner's adjust_settings_for_autopr forces enable_parallel_replicas=1 + cluster_for_parallel_replicas=parallel_replicas + parallel_replicas_for_non_replicated_merge_tree=1, routing those queries onto the parallel-replicas path. That desyncs the local single-part file inspection, so the checksums.txt stat fails intermittently (stat: cannot statx checksums.txt; line: [: : integer expression expected) even though the data is intact. The test is a single-node local durability regression test; parallel replicas is meaningless here, so opt it out. Reproduced locally: with parallel replicas 9/40 fail, without it 40/40 pass; with the tag 50/50 pass under full randomization.
The test captures one part's checksums.txt by an absolute path and manipulates it across DETACH/ATTACH/CHECK cycles. Randomized min_insert_block_size_rows and max_block_size split the INSERT into hundreds of parts even single-threaded; the prior OPTIMIZE FINAL collapsed them to one active part but left every original part on disk as a covered directory (392 total dirs observed under adversarial splitting). Under the parallel flaky-check runner, background outdated-part cleanup churns those directories concurrently with the test's path manipulation, so the captured directory can vanish (statx: No such file) while rows stay intact. Stop merges before the insert so no covering part is ever produced, pin the block-size settings so the single insert yields exactly one part regardless of randomization, and drop the OPTIMIZE. The table then holds exactly one part directory with no covered sibling. Test intent unchanged: empty checksums.txt is still recalculated, absent still self-heals, and CHECK repair still recounts and fsyncs. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed 9a0ce5b: re-stabilized Root cause of the remaining flakiness: randomized Fix (test-only): |
| /// The temp name carries the thread id so two concurrent repairs of the same part (from | ||
| /// separate CHECK TABLE queries) do not rename each other's half-written file. It keeps the | ||
| /// .tmp suffix so checkDataPart skips it if a crash leaves it behind. | ||
| const String tmp_filename = fmt::format("{}.{}.tmp", filename, getThreadId()); |
There was a problem hiding this comment.
writeMetadata is shared by both writeChecksums and writeColumns, but only loadChecksums got the new empty-file recovery. A zero-byte columns.txt still goes through readFileIfExists("columns.txt") and loaded_columns.readText(*in), which throws immediately on the pre-fix corruption state.
For wide parts where require == false, that is still strictly worse than the missing-file case: the else branch already rebuilds columns.txt from table metadata and persists it. So parts that were left with an empty columns.txt by the old in-place rewrite remain unloadable even though this helper is the shared fix point for both metadata files. Please mirror the empty-vs-absent handling in loadColumns for the same cases that already self-heal when columns.txt is missing.
There was a problem hiding this comment.
Confirmed a real gap. writeColumns shares the now-durable writeMetadata with writeChecksums, so a zero-byte columns.txt is reachable the same way, and NamesAndTypesList::readText throws on it (assertString("columns format version: 1\n") at Core/NamesAndTypes.cpp:90) where an absent columns.txt self-heals via the metadata rebuild. Verified both directions on a wide part: pre-fix an empty columns.txt detaches the part (0 rows), a mirrored loadColumns empty->rebuild fix restores all rows.
Tracking it as a separate fix rather than folding it into this PR: this PR is scoped to the checksums.txt durability/repair path, and a loadColumns regression test additionally surfaces two pre-existing engine issues (ColumnsSubstreams::validateColumns mismatch when a merged part carries persistent _block_number/_block_offset columns and the metadata-rebuild fallback omits them; and a SIGBUS reading a metadata file under local_filesystem_read_method=mmap) that deserve their own investigation. Follow-up PR to come.
…tat-ing part files The test verified checksums.txt recovery by stat-ing the on-disk file of a live part after externally truncating/removing it. Under CI setting randomization and parallel execution the server's own reads, writes and cache prewarming race that external stat, so the size checks flapped (checksums.txt seen as zero-byte or missing) even though every row survived and the fix worked. Assert the properties through the server instead: the part still returns all its rows, a fresh DETACH/ATTACH reloads it (forcing the recovered checksums to be read back from disk), a full CHECK TABLE reports the part as passed with no recount message (proving the backfill was persisted, not merely recovered in memory), and the CHECK repair write is fsynced (ProfileEvents['FileSync'] > 0). This is strictly stronger than checking the file is merely non-empty and removes the external-stat race. The regression coverage is unchanged: on the pre-fix behavior the empty-checksums reload returns 0 rows and the test fails.
|
Pushed 14b9e9d: the flaky Root cause of the flakiness (not a data-loss regression - rows always survived): the test verified recovery by New assertions (all server-side, no external
This is strictly stronger than the previous "file is non-empty" check. Regression coverage is unchanged: on the pre-fix behavior the empty- Internal second-model review adjudication (click to expand)Second-model review of the change (codex), 6 findings, ledger 1 AGREE / 5 DISAGREE:
Session id: cron:clickhouse-maint-slot-11:20260723-074501 |
…sums_txt_not_fatal The flaky check for this new test failed ~15-25% across all sanitizers on the single assertion "check table repair fsynced (FileSync > 0)": it read 0 instead of 1. Every other line (row counts, CHECK results) was stable; only this line differed. The CHECK TABLE checksums repair runs writeChecksums on a pipeline worker thread (InterpreterCheckQuery builds num_streams = max(max_threads, 1) worker processors), and out->sync() there increments the FileSync ProfileEvent on that worker thread. Under CI parallelism the worker's thread-local counter is not reliably merged into the query's ThreadGroup before the QueryFinish row is written to system.query_log, so the per-query FileSync count intermittently reads 0 even though the fsync happened. Locally FileSync is a stable 1 in 60+ runs (isolation and under concurrent load with max_threads=16) because out->sync() is unconditional, so the assertion never catches a real regression and only adds flakiness. The durability the test guards is already covered without the ProfileEvents proxy: after the CHECK TABLE repair the part is reloaded from disk (DETACH + ATTACH) and must still return all 1000 rows, which fails if the repair wrote an empty or partial checksums.txt. Case 1 likewise proves the empty-checksums backfill persisted by reloading and running CHECK with no recount message. Drop the FileSync assertion and its query_id plumbing; keep the reload-based checks. Verified 50/50 passes with full randomization.
The previous commit removed the flaky FileSync assertion and its system.query_log query, but left the literal string "system.query_log" in the explanatory comment. check_style/various_checks.sh greps test files for that literal and requires a current_database = currentDatabase() predicate, so the stale mention in the comment tripped the rule even though the query was gone. Reword the comment to describe the server-side assertion approach without naming the system table. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Style check |
CI finish ledger — 7ef376aCI fully finished on head
Session id: cron:our-pr-ci-monitor:20260723-183000 |
|
The fix task for the AST-format |
…-check-table-checksums-fsync # Conflicts: # src/Storages/MergeTree/IMergeTreeDataPart.cpp
CI finish ledger — 41a1b62Every failure has an owner: a fixing PR, or a full-effort fix task. Only
Not PR-caused: this PR makes part-metadata rewrite durable (fsync); it cannot affect the Session id: cron:our-pr-ci-monitor:20260724-193000 |
CI finish ledger - 41a1b62Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260726-163000 |
…-check-table-checksums-fsync One conflict, in the include block of IMergeTreeDataPart.cpp: master added <unordered_set> where this branch had added <base/getThreadId.h>. Both sides are purely additive, so both includes are kept. The durable metadata rewrite (writeMetadata tmp -> fsync -> rename) and the empty-checksums.txt recovery in loadChecksums are unchanged, and master's new invalidated-system-columns bookkeeping and per-substream extension ownership in the same file are preserved. The storage API those hunks call (writeFile, replaceFile, removeFileIfExists, getDirectorySyncGuard) is unchanged on master.
|
Merged master to resolve the conflict ( Master's new invalidated-system-columns bookkeeping and per-substream extension ownership in that file are preserved, and the four storage calls this fix makes ( Re-verified on the merged tree: build clean, and both directions still hold. Reverting the I also rechecked the packed-storage question against current master rather than my earlier claim that packed parts were Cloud-only, which was wrong. Packed parts are reachable in OSS and Session id: cron:clickhouse-maint-slot-20:20260731-164300 |
The test plants and removes a standalone checksums.txt at an absolute path inside
the part directory. Only Full part storage keeps that file on its own: on Packed
storage checksums.txt lives inside the single data.packed blob, and both
existsFile and readFileIfExists resolve it through the archive reader rather than
by stat-ing the directory. So on a Packed part the manipulations touch an ignored
side file, every assertion still answers exactly as it does for Full, and the test
reports a pass without exercising the repaired metadata path at all.
min_rows_for_wide_part / min_bytes_for_wide_part only pin PartType;
MergeTreeData::choosePartFormat picks PartStorageType from the separate
min_*_for_full_part_storage thresholds. tests/clickhouse-test randomizes
min_bytes_for_full_part_storage to 512MiB, which selects Packed for a part this
small, so roughly seven runs in ten were silently vacuous. Measured on this build:
with that value forced the part directory contains only data.packed, no standalone
checksums.txt exists, and the runner still reports OK.
Pin all three min_*_for_full_part_storage thresholds to 0 in the CREATE TABLE, and
assert part_storage_type = 'Full' before touching the path so a future change that
defeats the pin fails loudly instead of vacuously. The client only injects a
randomized MergeTree setting the query does not already set, so the explicit values
win over the injected one.
The underlying bug is unreachable on Packed storage (the repair branch is gated on
!existsFile("checksums.txt"), which the archive answers affirmatively), so this is
test liveness hardening rather than a missed code path.
Validation: with the pin, the test still fails on a build with the empty-checksums
recovery guard reverted (rows 1000 -> 0 on all three reload assertions) and passes
with it; forcing min_bytes_for_full_part_storage=512MiB now keeps Full storage and
passes, while removing the pin makes the new assertion fire; 50/50 runs under full
randomization pass.
CI finish ledger - ae6e16eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260801-073000 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 25/32 (78.12%) · Uncovered code |
CI finish ledger - 9316d98Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task No failures on this head. All 174 check-runs completed, Session id: cron:our-pr-ci-monitor:20260801-203000 |
|
Closing out the That red was the job-level mode: the macOS runner job is killed mid- Detector: an arm_darwin job completing at The cause was queue saturation, not code. Queue wait for successful arm_darwin jobs had a median of 288.6 minutes on 07-31 and 0.1 minutes on every adjacent day, while run time itself stayed at a ~20 minute median throughout. The kill threshold sits near 29 minutes and the nearest in-repo timeout is praktika's 300 minute default, so there is no repo-side bound to change; whatever recycles those runners is configured outside the repository. Details and the full measurements are in #106231 (comment). If the mode returns I will pick it up again with the same detector. Nothing in this comment changes this PR's diff. |
…fsync Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Public master gained `server_data_manipulation_in_stateless_tests` after this branch was cut, and it flags this test for reading a part path from `system.parts` and then truncating `checksums.txt`. The check's hazard is copying or moving part data on a disk where the local layout does not mean what the test assumes - on a remote disk a raw copy duplicates metadata without incrementing blob reference counts. This test copies nothing: it truncates one metadata file to zero bytes, which is precisely the post-power-loss state the fix must survive, and it is already tagged `no-object-storage` and `no-shared-merge-tree`, pins `part_storage_type = 'Full'`, asserts the path is absolute, and detaches the table around the edit. Without this the check fails both here and in the private sync once master is merged, which is what surfaced it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/KQLFunctions.cpp.o |
new | 741.46 KiB | +741.46 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLBinAt.cpp.o |
new | 528.11 KiB | +528.11 KiB |
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/KQLParser.cpp.o |
new | 479.86 KiB | +479.86 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLBin.cpp.o |
new | 449.58 KiB | +449.58 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLParameterCast.cpp.o |
new | 435.89 KiB | +435.89 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLDivide.cpp.o |
new | 376.06 KiB | +376.06 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLRangeCount.cpp.o |
new | 263.43 KiB | +263.43 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLToTimespan.cpp.o |
new | 246.68 KiB | +246.68 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLMultiply.cpp.o |
new | 235.82 KiB | +235.82 KiB |
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/KQLTranslator.cpp.o |
new | 204.36 KiB | +204.36 KiB |
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/KQLLexer.cpp.o |
new | 54.46 KiB | +54.46 KiB |
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/parseKQLQuery.cpp.o |
111.50 KiB | 59.20 KiB | -52.30 KiB (-46.91%) |
750 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
26 translation units recompiled, 173 s compile time in total, 26 of them have a recent master baseline.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
Closes: #111373
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix possible data loss when a part's
checksums.txtis repaired (recalculated and written on load, or byCHECK TABLE) and the server loses power afterwards. The metadata rewrite is now durable and atomic (write to a temporary file, fsync, atomically rename), and an emptychecksums.txtis now recalculated on load instead of detaching the whole part as broken.Description
Reported in #111373.
IMergeTreeDataPart::writeMetadatarewrotechecksums.txt/columns.txtin place withfinalize()only, without an fsync or an atomic rename. This backs theCHECK TABLEchecksums repair and thechecksums.txt/columns.txtbackfills inloadChecksums/loadColumns. On a local disk these run without an enclosing directory rename, so the write is neither atomic nor durable: after the repair is acknowledged, an unrelated durable write plus a power loss can leave a zero-bytechecksums.txt. On the next loadloadChecksumstreated the empty file as fatal and detached the entire part as broken, losing every row of an otherwise-intact part (an absentchecksums.txtself-heals, so the acknowledged repair made the state strictly worse).Fix:
writeMetadatanow writes to a temporary file, fsyncs it, and atomically renames it into place (fsyncing the directory whenfsync_part_directoryis set), mirroringVersionMetadataOnDisk::storeInfoToDataPartStorage. The final file is never empty or partial.loadChecksumstreats an existing-but-emptychecksums.txtlike an absent one: it removes the empty file (and any leftover temporary file) and recalculates, which also recovers parts already left in this state.checkDataPartskips temporary*.tmpfiles during its directory walk so a leftover temporary file from an interrupted rewrite cannot be checksummed and then invalidate the recalculated checksums.Reproduces deterministically on ext4/XFS (dm-flakey harness in the issue). Added a stateless regression test that truncates
checksums.txtto zero bytes and verifies the part still loads with all rows; it fails onmasterand passes with this change.Workflow [PR]
Sync PR [sync-upstream/pr/111414]
Version info
26.10.1.2104-master(included in26.10and later)