Skip to content

Make part metadata rewrite durable to prevent data loss on power loss - #111414

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111373-check-table-checksums-fsync
Oct 11, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111373-check-table-checksums-fsync

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111373

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix possible data loss when a part's checksums.txt is repaired (recalculated and written on load, or by CHECK 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 empty checksums.txt is now recalculated on load instead of detaching the whole part as broken.

Description

Reported in #111373. IMergeTreeDataPart::writeMetadata rewrote checksums.txt / columns.txt in place with finalize() only, without an fsync or an atomic rename. This backs the CHECK TABLE checksums repair and the checksums.txt / columns.txt backfills in loadChecksums / 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-byte checksums.txt. On the next load loadChecksums treated the empty file as fatal and detached the entire part as broken, losing every row of an otherwise-intact part (an absent checksums.txt self-heals, so the acknowledged repair made the state strictly worse).

Fix:

  • writeMetadata now 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 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.txt to zero bytes and verifies the part still loads with all rows; it fails on master and passes with this change.


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

Version info

  • Merged into: 26.10.1.2104-master (included in 26.10 and later)

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Truncate a committed part's checksums.txt to 0 bytes, then DETACH/ATTACH. Fails 100% on master, passes 100% with the fix.
b Root cause explained? Yes. IMergeTreeDataPart::writeMetadata rewrote checksums.txt in place with finalize() only (no fsync, no atomic rename); on a local disk the part-storage transaction is a no-op (FakeDiskTransaction). An acknowledged repair + a later durable journal commit + power loss leaves a 0-byte checksums.txt; loadChecksums then treated the empty file as fatal (checksums.read throws) and detached the whole part as broken, losing all rows.
c Fix matches root cause? Yes. The write is made atomic+durable (temp file, fsync, atomic rename), and the load treats an empty checksums.txt as absent (recalculate) rather than fatal — directly addressing both the durability mechanism and the fatal load symptom.
d Test intent preserved / new tests added? Yes. New stateless regression test 03599_empty_checksums_txt_not_fatal: (1) empty checksums.txt no longer bricks the part, (2) absent still self-heals, (3) CHECK TABLE repair recounts, fsyncs (ProfileEvents['FileSync'] > 0), and the repaired part reloads. No existing test weakened.
e Both directions demonstrated? Yes. On master: "rows after empty checksums.txt reload: 0" (1000 rows lost) → test FAILS. With fix: 1000 rows preserved, 50/50 randomized runs pass.
f Fix is general across code paths? Yes. Fixed at the owning helper writeMetadata, covering all three callers: the CHECK TABLE repair and the checksums.txt / columns.txt backfills in loadChecksums / loadColumns.
g Fix generalizes across inputs? Yes. Applies to checksums.txt and columns.txt, compact and wide parts; the empty→absent recovery is scoped to the exact 0-byte state (a non-empty corrupt file still correctly stays broken). Object storage: replaceFile/sync route through the same storage API and the directory guard is a no-op there.
h Backward compatible? Yes. No format/setting/protocol change. The directory fsync is gated on the existing fsync_part_directory (default off), matching renameTo. Content fsync is unconditional (the bug reproduces under the default config). No SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. The final checksums.txt / columns.txt is only ever the complete old or complete new content (atomic replaceFile); the "absent checksums.txt is recomputable" invariant is extended to "empty == absent"; checkDataPart's file enumeration only gains a skip of non-data .tmp files. No concurrency/ownership/format invariant touched.

Session id: cron:clickhouse-author-slot-4:20260722-132500

@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; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ Concurrent repairs could rename another writer's unsynced fixed-name temp file, recreating the zero-byte state AGREE — fixed Per-part writes are serialized within one CHECK TABLE query (DataValidationTasks::next()), so only two separate queries could race; for a P0 data-loss fix the cheap remedy is worth it. writeMetadata now uses a per-thread-unique temp name (filename + "." + getThreadId() + ".tmp", still .tmp so checkDataPart skips it).
2 💡 Helper comment restated the incident narrative rather than the invariant AGREE — fixed Trimmed to the atomic-write requirement + sibling reference.
3 ⚠️ Case 3 never exercised the CHECK TABLE repair write (the ATTACH backfilled checksums.txt before CHECK ran, so it took the verify-only branch) AGREE — fixed Confirmed the branch behavior. Rewrote Case 3 to remove checksums.txt while the table is attached (so CHECK TABLE takes the recount-and-write branch) and added a direct durability assertion: ProfileEvents['FileSync'] > 0 for the CHECK query (0 on master). 50/50 randomized runs pass, no flakiness.

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-4:20260722-132500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tiandiwonder @azat — could you review this? It makes the part metadata rewrite (IMergeTreeDataPart::writeMetadata, used by the CHECK TABLE checksums repair and the checksums.txt/columns.txt load-time backfills) atomic and durable (temp file, fsync, atomic rename), and treats an empty checksums.txt as absent (recalculate) instead of detaching the part as broken. Fixes the #111373 power-loss data-loss path.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [89b978f]

Summary: ✅


AI Review

Summary

This PR makes IMergeTreeDataPart::writeMetadata rewrite checksums.txt / columns.txt through tmp -> fsync -> replace, teaches loadChecksums to treat an empty checksums.txt like a missing one, skips leftover *.tmp files during checkDataPart, adds a stateless regression test, and exempts that test from the server-data-manipulation style check. The main checksums.txt power-loss bug is addressed for full-storage parts, but the current head still leaves two correctness gaps in the metadata-rewrite surface, so I cannot approve it as-is.

Findings

❌ Blockers

  • [src/Storages/MergeTree/IMergeTreeDataPart.cpp:2022] [dismissed by author -- https://github.com/Make part metadata rewrite durable to prevent data loss on power loss #111414#discussion_r3632872568] writeMetadata now assumes the target can be rewritten as a standalone temp file, but packed parts still store checksums.txt / columns.txt inside data.packed. On MergeTreeDataPartStorageType::Packed, checksums.txt.<tid>.tmp is not isWrittenSeparately, so DataPartStorageOnDiskPacked::writeFile falls into the archive-writer path and throws NOT_INITIALIZED once beginTransaction() is gone. That regresses supported recovery paths like StorageMergeTree::checkDataNext's missing-checksums.txt repair and the missing-columns.txt / missing-checksums.txt backfills on packed parts into load/repair failures instead of recovering the intact part.
    Suggested fix: keep the part-storage transaction / packed-writer lifecycle around writeMetadata, or branch packed storage to rewrite the archive through its existing data.packed.tmp commit path.

⚠️ Majors

  • [src/Storages/MergeTree/IMergeTreeDataPart.cpp:2512] writeMetadata is shared by both writeChecksums and writeColumns, but only loadChecksums learned the new empty-file recovery. A zero-byte columns.txt still goes straight into loaded_columns.readText(*in), so wide parts already left in that pre-fix corruption state still detach even though the missing-columns.txt branch right below already knows how to rebuild and persist the metadata.
    Suggested fix: mirror the empty-vs-absent handling from loadChecksums in loadColumns for the same non-compact, non-patch cases that already self-heal when columns.txt is absent.
Tests
  • ⚠️ Add focused coverage for the two remaining metadata-recovery surfaces: a packed-part case that exercises missing checksums.txt / columns.txt through writeMetadata, and a wide-part case with zero-byte columns.txt. The current stateless test only proves the full-storage checksums.txt path.
Final Verdict

Status: ❌ Block
Minimum required actions:

  1. Restore a working metadata-rewrite path for packed parts instead of calling writeFile(tmp_filename, ...) without a packed writer.
  2. Teach loadColumns to recover zero-byte columns.txt the same way it already recovers a missing columns.txt.

LLVM Coverage Report

Measured on commit 89b978f.

Metric Baseline Current Δ
Lines 88.40% 88.50% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.80% +0.10%

Changed lines: Changed C/C++ lines covered: 25/32 (78.12%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
try
{
auto out = data_part_storage.writeFile(filename, 4096, settings);
auto out = data_part_storage.writeFile(tmp_filename, 4096, settings);

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.

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.

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.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the PR-caused flakiness in the new test 03599_empty_checksums_txt_not_fatal @ f6a6a59.

Root cause: the test captures the single part directory once and manipulates checksums.txt there by absolute path. With randomized max_insert_threads (2/3 in every failing CI debuglog) plus block-size randomization, the INSERT splits into several parts, so SELECT path ... WHERE active returned multiple rows and the shell variable became multi-line, breaking every stat/integer test ([: : integer expression expected, stat: cannot statx .../checksums.txt). Rows stayed 1000 because the real parts were untouched.

Fix (test-only): single insert thread + OPTIMIZE FINAL to collapse to one part, assert exactly one active part, select its path with LIMIT 1, then SYSTEM STOP MERGES so the captured directory does not move (OPTIMIZE runs before STOP MERGES because stopping merges cancels a concurrent OPTIMIZE). The part stays Wide with a standalone checksums.txt, so the empty-checksums recovery path is still exercised.

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.

@StackSlayerAI

Copy link
Copy Markdown
Contributor

CI Triage (bot) — head f6a6a597 — 2026-07-22

Verdict: REAL FAILURE — test 03599_empty_checksums_txt_not_fatal failing consistently in flaky check

Flaky check (amd_debug, msan) both show 03599_empty_checksums_txt_not_fatal failing on all 50 runs (~22–25 seconds each). This test is not in the known-flake registry.

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 03599_empty_checksums_txt_not_fatal relies on, and fix accordingly.

Run IDs: 29934368355

groeneai and others added 2 commits July 22, 2026 23:25
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 9a0ce5b: re-stabilized 03599_empty_checksums_txt_not_fatal (PR-caused flaky check).

Root cause of the remaining flakiness: randomized min_insert_block_size_rows / max_block_size split the single INSERT into hundreds of parts even single-threaded, and the prior OPTIMIZE FINAL collapsed them to one active part while leaving every original part on disk as a covered directory (392 total dirs observed under adversarial splitting). The parallel flaky-check runner's background outdated-part cleanup then races the test's manipulation of its one captured absolute path, so all_1_1_1 can vanish (statx: No such file) while rows stay intact.

Fix (test-only): SYSTEM STOP MERGES before the insert so no covering part is ever produced, pin the block-size settings so the insert yields exactly one part regardless of randomization, and drop the OPTIMIZE. The table then holds exactly one part directory with no covered sibling. Verified 20/20 under adversarial block-splitting; reference output unchanged (empty -> recalc, absent -> self-heal, CHECK repair recounts + FileSync>0).

/// 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());

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.

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.

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.

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

Copy link
Copy Markdown
Collaborator Author

Pushed 14b9e9d: the flaky 03599_empty_checksums_txt_not_fatal now asserts recovery server-side instead of by stat-ing the live part's on-disk checksums.txt.

Root cause of the flakiness (not a data-loss regression - rows always survived): the test verified recovery by stat-ing checksums.txt on a live part right after externally truncating/removing it. Under CI setting randomization and parallel execution the server's own reads/writes/cache-prewarming race that external stat, so the size checks flapped (file seen as zero-byte or missing) even though every row survived and the fix worked. The earlier setting/part-layout pins could not fix it because the external-stat pattern is the fragility, not any single setting.

New assertions (all server-side, no external stat):

  • part still returns all rows after an empty/absent checksums.txt reload (the anti-brick property);
  • a fresh DETACH/ATTACH reloads the part (forces the recovered checksums to be read back from disk);
  • a full CHECK TABLE reports the part passed with an empty message, proving the backfill was persisted rather than re-recovered in memory (an unpersisted backfill would report "Checksums recounted and written to disk.");
  • the repair write is fsynced (ProfileEvents['FileSync'] > 0).

This is strictly stronger than the previous "file is non-empty" check. Regression coverage is unchanged: on the pre-fix behavior the empty-checksums.txt reload returns 0 rows and the test fails (verified locally by reverting the recovery guard and rebuilding).

Internal second-model review adjudication (click to expand)

Second-model review of the change (codex), 6 findings, ledger 1 AGREE / 5 DISAGREE:

  • durability-mechanisms-untested (major) - AGREED (persistence) + fixed: the reviewer noted the test could pass even if the backfill were recovered in memory but never persisted. Addressed by asserting a full CHECK TABLE reports passed with an empty message (an unpersisted backfill would report a recount). The remaining sub-asks (stale-.tmp fault injection, fsync_part_directory+DirectorySync assertions) are DISAGREE: a stateless .sh test has no power-loss/fault-injection harness, and the fsync durability is already asserted server-side via FileSync > 0 on the repair query.
  • replicated-empty-still-fatal (blocker) - DISAGREE (code-cited): require_part_metadata=true (ReplicatedMergeTree) treats absent and empty checksums.txt symmetrically (both throw -> detach broken-on-start -> re-fetch from a healthy replica), so no rows are lost. The acked local recount exists only in StorageMergeTree. The absent-heals/empty-bricks asymmetry the PR fixes is unique to require_part_metadata=false. Recalculating locally under require=true would bless possibly-corrupt local data over the authoritative replica.
  • packed-write-contract (blocker) / packed-randomization (major) - DISAGREE (code-cited): PartStorageType::Packed and DataPartStorageOnDiskPacked do not exist in OSS; choosePartFormat returns Full on all paths and never reads min_bytes_for_full_part_storage. Packed storage is Cloud-only, uncompilable/untestable from this OSS PR.
  • metadata-comment / stale-tmp-description (nits): touch the C++ commit, out of this test-only change's scope.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Style check various fix (7ef376a). The prior commit removed the flaky FileSync/query_log assertion but left the system-table name in the explanatory comment; check_style/various_checks.sh greps test files for that literal and requires a currentDatabase() predicate, so the stale mention tripped the rule. Reworded the comment; no query_log query remains, test logic unchanged. Reproduced the rule locally: fails on 3f535c1, passes on 7ef376a.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7ef376a

CI fully finished on head 7ef376a8bfe6. The 03599 flaky-check regression (the PR-caused work from prior heads) is now GREEN across all four sanitizers (247 OK, 0 FAIL in CIDB). The one remaining red is a pre-existing trunk crash unrelated to this PR's diff; it has a full-effort fix task and the two neighbours in the same job are its victims.

Check / test Reason Owner / fixing PR
Stateless (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error '!part.empty()' (STID 5217-5b3d) trunk crash (dotted-lambda AST-format chassert(!part.empty()), 52 PRs/30d + master, not in this PR's diff) a fix task is created (investigating at full effort; fixing-PR link to follow)
Stateless (amd_llvm_coverage, ...) / 02465_limit_trivial_max_rows_to_read victim of the !part.empty() server abort above (same job) same as above
Stateless (amd_llvm_coverage, ...) / Server died victim of the !part.empty() server abort above (same job) same as above
PR / Mergeable Check aggregators reflecting the crashed coverage job same as above
CH Inc sync - CH Inc sync (private, not actionable)

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

The fix task for the AST-format !part.empty() misattribution on this PR is resolved as a CI-tooling fix: #111708. Investigation showed the underlying engine bug (STID 2508-2ef2) was already fixed on master by #108735 (merged 2026-07-21); the residual !part.empty() rows on this PR were a crash-reporter misattribution - the failure NAME was read from a regression test's SQL comment quoting the signature, while the STID/stack came from an unrelated crash. #111708 fixes that scraper (ci/jobs/scripts/log_parser.py) so the failure is named after the genuine <Fatal> record.

…-check-table-checksums-fsync

# Conflicts:
#	src/Storages/MergeTree/IMergeTreeDataPart.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 41a1b62

Every failure has an owner: a fixing PR, or a full-effort fix task. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log trunk regression (system.metric_log_0 metadata > max_query_size -> QUERY_IS_TOO_LARGE; 214 PRs, 0 master, onset 2026-07-23) #111703 (external, merged 2026-07-24T17:24:53Z)
CH Inc sync private sync CH Inc sync (private, not actionable)
Mergeable Check / PR rollup of the above owned via #111703

Not PR-caused: this PR makes part-metadata rewrite durable (fsync); it cannot affect the system.metric_log rotation ALTER. The Upgrade-check leak is a fresh trunk regression fixed by #111703, merged after this head was built.

Session id: cron:our-pr-ci-monitor:20260724-193000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 41a1b62

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.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (SystemLog (system.metric_log): Failed to mark the rotated system log table as readonly, Code 229) trunk error-log leak, not PR-caused #111703 (external, merged 2026-07-24T17:24:53Z) - NOT on this branch (git merge-base --is-ancestor eb577ff401a3 41a1b628bfeb4eb9700795b58fa3a40d5752aeb2 is false), so this build predates the fix; merging master will pick it up

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

Copy link
Copy Markdown
Collaborator Author

Merged master to resolve the conflict (41a1b628 -> d5319580). One conflict, in the include block of IMergeTreeDataPart.cpp: master added <unordered_set> where this branch had added <base/getThreadId.h>. Both sides are additive, so both includes are kept. The diff against the merge parent is still the same four files, 151 insertions and 8 deletions, with no contrib drift.

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 (writeFile, replaceFile, removeFileIfExists, getDirectorySyncGuard) are unchanged on master.

Re-verified on the merged tree: build clean, and both directions still hold. Reverting the loadChecksums empty-file guard back to if (buf) reproduces the data loss exactly (rows after empty checksums.txt reload: 1000 -> 0); restoring it makes the test pass again. 03599_empty_checksums_txt_not_fatal is 50/50 green under full setting randomization.

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 min_bytes_for_full_part_storage is randomized in CI, so I built one and planted this bug's precondition on it (a zero-byte standalone checksums.txt). It is inert there: rows survive, CHECK TABLE passes with an empty message, and no exception is logged, because checksums.txt lives inside data.packed and both existsFile and readFileIfExists resolve it through the archive. The repair branch is gated on !existsFile("checksums.txt"), so writeMetadata is never reached for a packed committed part. The durability fix therefore applies to storage that keeps checksums.txt as its own file, which is what the PR claims and what the test exercises.

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

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ae6e16e

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 04612_join_runtime_filters_index_analysis_multi_key_anti randomized-settings flaky; the runner's own diagnosis names the culprit --join_runtime_filter_min_probe_rows 3783 and reports 163/163 failures with that value against 200/200 passes without randomization #111691 (external, merged 2026-07-31 20:56Z) - this build predates the pin: the test file at this head has no min_probe_rows pin, live master has it
Fast test (arm_darwin) job-level runner kill at 33.9 min (the Run step ends with a null conclusion, result_pr.json reports status: ERROR with an empty info, results: [] and no artifacts, and CIDB ingests no rows at all) a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260801-073000

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 25/32 (78.12%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9316d98

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. Only CH Inc sync is exempt.

No failures on this head. All 174 check-runs completed, Config Workflow and Finish Workflow are green, 0 queued or in progress, and CIDB reports 0 FAIL/ERROR test rows for this commit.

Session id: cron:our-pr-ci-monitor:20260801-203000

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Closing out the Fast test (arm_darwin) line on my CI finish ledger for this PR.

That red was the job-level mode: the macOS runner job is killed mid-Run, so the report node is ERROR with an empty info and no test rows, and no test actually failed. I said a fixing-PR link would follow here. There will not be one, and no fix is owed: I re-measured the class from the Actions API and it has stopped occurring.

Detector: an arm_darwin job completing at minute % 5 == 0, seconds <= 25, after more than 25 minutes. Result by day, with 100 percent coverage of every failing PR-workflow run: 2026-07-31 had 192 such kills, 08-01 had 1 (the last one anywhere, 18:55:25Z), and 08-02, 08-03, 08-04 and 08-05 each had 0 across 1026 arm_darwin jobs. The zeros are load bearing because the same detector recovers 8 of 8 of the kills I had previously recorded, plus 184 more on 07-31 that I had missed. On two of the clean days I also checked every run regardless of its conclusion, in case a kill on attempt 1 was hidden by a passing retry: no arm_darwin job even exceeded 25 minutes.

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.

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
alexey-milovidov and others added 2 commits August 29, 2026 21:25
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]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 89b978f2a with master 200be2d5c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2af4f37af; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

12 object files changed (+3.89 MiB total), 11 added.

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.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

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
  • StressHouse run: c70738ce-4f80-4d37-8bfb-912c3eb380a5
  • MIRAI run: ac93b28f-071e-4ac3-857e-e82e45431adc
  • PR check IDs:
    • clickbench_380057_1788045622
    • clickbench_380063_1788045622
    • clickbench_380074_1788045622
    • tpch_adapted_1_official_380080_1788045622
    • tpch_adapted_1_official_380114_1788045622
    • tpch_adapted_1_official_380128_1788045622

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

This is good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 11, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 11, 2026
Merged via the queue into ClickHouse:master with commit 6d45d0d Oct 11, 2026
177 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 11, 2026
@clickhouse-gh clickhouse-gh Bot added comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
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-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding manual approve Manual approve required to run CI pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Power loss after CHECK TABLE repairs checksums.txt bricks the part: the repair write is never fsynced

4 participants