Repository navigation
Fix a mutated part losing files to the temporary directory cleanup - #111992
Conversation
`MutateFromLogEntryTask::finalize` released `mutate_task` - and with it the RAII
guard that registers `tmp_mut_<part>` in `MergeTreeData::TemporaryParts` - before
calling `MergeTreeData::Transaction::renameParts`, which is what actually renames
the directory on disk. Between those two points the temporary directory of a part
that is already precommitted was not protected from `clearOldTemporaryDirectories`.
When the cleanup thread hit that window it started removing the directory while
`renameParts` was moving it to the persistent name, so the part became active with
part of its files already deleted while `checksums.txt` still listed all of them:
19:34:46.048315 Renaming temporary part tmp_mut_97_0_0_0_7 to 97_0_0_0_7
19:34:46.049102 Removing temporary directory .../tmp_mut_97_0_0_0_7/
19:34:46.049168 Renaming part to 97_0_0_0_7
Reads of such a part fail with
Code: 1001. DB::Exception: std::filesystem::filesystem_error: filesystem error:
in file_size: No such file or directory [".../97_0_0_0_7/foo2.cmrk2"]
because `MergeTreeMarksLoader` derives the marks path from the part's checksums,
and every following mutation of the part fails permanently with
Code: 424. DB::ErrnoException: Cannot link .../97_0_0_0_7/foo2.bin to
.../tmp_mut_97_0_0_0_8/num2.bin ... (CANNOT_LINK)
Rename the part while `mutate_task` is still alive, the way
`MergeTreeDataMergerMutator::renameMergedTemporaryPart` already does for merges
("Explicitly rename part while still holding the lock for tmp folder to avoid
cleanup"). The reset of `mutate_task` stays where it was relative to
`checkPartChecksumsAndCommit`, so the fallback fetch on a checksum mismatch still
runs without the guards being held.
The window was introduced by #96376, which moved the reset in front of
`renameParts`. Every other caller of `renameTempPartAndReplace` with
`rename_in_transaction=true` renames immediately afterwards.
The new stateless test pauses a mutation right before the rename with a failpoint
and checks that the cleanup thread reports the directory as in use instead of
removing it.
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=423ec1ba3ac4288ce5b934235be0c6700e0f7c14&name_0=MasterCI&name_1=Integration%20tests%20%28amd_msan%2C%201%2F8%29
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ir-cleanup-race # Conflicts: # src/Common/FailPoint.cpp # src/Storages/MergeTree/MutateFromLogEntryTask.cpp
|
Workflow [PR], commit [2b09dc7] Summary: ✅
AI ReviewSummaryThis PR moves Final VerdictStatus: ✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 19/19 (100.00%) · Uncovered code |
…ir-cleanup-race # Conflicts: # src/Storages/MergeTree/MutateFromLogEntryTask.cpp
|
🕵 @groeneai, the only red on commit |
The AI review pointed out that the test only observed the temporary directory while the mutation task, and with it the `TemporaryParts` guard, was still alive: the `rmt_mutate_task_pause_before_rename_part` failpoint fires before both `transaction_ptr->renameParts()` and `mutate_task.reset()`, so the assertion held for the old ordering as well and the test could not detect a reintroduced race. Add a second pauseable failpoint, `rmt_mutate_task_pause_after_temporary_part_released`, right after `mutate_task.reset()` — exactly the window the fix is about. With the fix, the temporary directory has already been renamed under the guard and there is nothing left to remove; with the old ordering it is still on disk and no longer registered in `TemporaryParts`, so the cleanup thread deletes it. The test now synchronizes on the failpoints with `SYSTEM WAIT FAILPOINT ... PAUSE` instead of polling for the first cleanup log line, and waits for a counted number of finished cleanup iterations (`Scheduling next cleanup` in `system.text_log`) before sampling the decision, so both phases observe at least one full pass of `clearOldTemporaryDirectories`. Verified locally on a `ReplicatedMergeTree` server: the test passes three times in a row with the fix, and fails deterministically (`removed_after_release` becomes `1`) when `renameParts` is moved back below `mutate_task.reset()`.
|
🕵 @groeneai, the only red on commit |
|
A fix is already in progress: #110338. It is the same defect, so no separate PR is needed. One correction: this is not the #112315 class. Both share the error message, but the throw The carrier here is Deterministic on current master (90042b2): SET enable_analyzer = 1;
CREATE TABLE t_1611 (t UInt32, INDEX t_set t % 19 TYPE set(4) GRANULARITY 2)
ENGINE = MergeTree ORDER BY tuple()
SETTINGS index_granularity = 2, min_bytes_for_wide_part = 0;
INSERT INTO t_1611 SELECT number FROM numbers(20);
SELECT count() FROM t_1611 WHERE (t % toNullable(19)) = 16 SETTINGS use_skip_indexes_on_data_read = 1;Master aborts; with #110338 applied on top of the same commit it returns 1. I also checked Agreed it is unrelated to this PR: 11 distinct PRs plus one master hit (2026-07-10, #110338 has been open since 2026-07-14 and is unreviewed. Its CI is currently stuck on a |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 19/19 (100.00%) · Uncovered code |
Both `rmt_mutate_task_pause_before_rename_part` and `rmt_mutate_task_pause_after_temporary_part_released` are server-global and pause every `ReplicatedMergeTree` mutation. Under `set -e` a timed-out `SYSTEM WAIT FAILPOINT ... PAUSE` or a failing `wait_for_cleanup_iterations` exited the script before the explicit `SYSTEM DISABLE FAILPOINT` calls, leaving the failpoints armed for the rest of the stateless run. Disable them unconditionally from an `EXIT` trap; disabling a pauseable failpoint also resumes the threads paused at it.
|
🕵 @groeneai, the only red on |
|
Measured it, and "the arm shards are systematically unstable" does not hold. Base rate over 30d of Two things do explain why it looks arm-specific from a PR:
So the query-level instability is real but arch-neutral, and it is concentrated, not systemic: 261 distinct tests produce arm PR unstable rows over 14d, and the top 10 account for 67.4%, the top 20 for 82.6%. The worst are I also tested the one arch-specific mechanism I could find and it does not survive: Conclusion: no PR to widen thresholds, since the data does not support one and widening would reduce coverage. The two defects worth fixing are the reporting one above (green job rendering red children, and double-counted rows) and right-sizing the handful of concentrated offenders so the harness can resolve a difference, per the usual approach of increasing work per iteration rather than weakening the assertion. Say the word and I will send a PR for the reporting defect first, since that is what actually cost you the triage time here. |
Capture a `start_time` before creating the table and filter both the
cleanup-row and cleanup-iteration queries over `system.text_log` by
`event_time_microseconds >= toDateTime64('$start_time', 6)`, so stale
rows from a previous run (e.g. under a fixed --database, where the
logger names are the same) cannot satisfy or break the assertions.
Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 The only red on |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units8 translation units recompiled, 20 s compile time in total, 8 of them have a recent master baseline. |
A Performance Comparison shard that passed rendered a list of red rows, and every affected query was listed twice. On PR ClickHouse#111992 shard "arm_release, master_head, 1/6" was OK and its own message said "11 unstable", yet the report showed 22 red rows that had to be hand-verified before the PR could be attributed. Two causes, both in the block building the "Check Results" rows: The rows exist only to carry a per-query "query history" link, and each was constructed with a hardcoded FAIL, demoting the slower/unstable verdict to info. The job status was unaffected because "Check Results" is passed an explicit status and Result.create_from aggregates children only when no status is given, so a green job rendered red children. json.html already classifies both statuses natively in shouldShowRow and getStatusPriority, so passing the real verdict through is sufficient; getStatusClass was the only one of the three maps with no case for "slower", which is why a slower query rendered gray. One line added there. compare.sh emits one row per side, array join map('old', left, 'new', right), naming them "<query> #<idx>::old" and "::new", so 11 queries became 22 rows. Only the candidate side is listed now, and only its displayed name is stripped: the history query filters test_name on an exact match and the CI database stores the suffixed name, so the row keeps its original name for the link. compare.sh is left alone deliberately, because its per-side rows are what the CI database stores; changing the emission would fork that history and break every existing per-query history link. Verified that the rows inserted into the CI database are byte-identical before and after, and that the links still resolve. The loop is extracted into build_check_results_children so it can be tested; behaviour is otherwise unchanged. Tests are driven by two trimmed real shard artifacts: the one from ClickHouse#111992, and a failing release_base shard as a negative control that must stay red. The parent's own message states the query count, which is an independent oracle for the row count. Related: ClickHouse#111992
The Check Results rows were selected by skipping every "::old" row, which assumes compare.sh's "::new" mate always arrives. It does not. compare.sh writes ci-checks.tsv last, so a failure there (most often a full disk) leaves a byte prefix, and read_ci_checks_results deliberately imports the intact rows of a torn file rather than killing the job before praktika uploads the artifacts. Rows are emitted "::old" before "::new" per query, so a cut tail always keeps the reference side and loses the candidate one. Such a query was then dropped from the report entirely: it lost the query history link that is the only reason these rows exist, and the row count stopped matching the query count the parent message states. Group the rows by query instead and represent each group by the side that survived, preferring "::new". The history link is built from the represented row's own name, so a reference-only row links to the history CIDB actually stores for it. Measured through the importer: a file cut inside its last row parses to [q_a::old, q_a::new, q_b::old] and listed q_a alone; it now lists both. Reported in ClickHouse#111992
|
Backporting to fix CI |
Every conflict is master-only context the cherry-pick drags along, not a divergence in the change itself. Kept only what it contributes and dropped: - `new_part->getDataPartStorage().commitTransaction();` after `renameTempPartAndReplace`. No release branch has it; they only `precommitTransaction` above. - The `rmt_mutate_task_pause_after_zero_copy_lock` and `merge_tree_background_task_marked_for_deletion` failpoints, and the matching `extern`. Neither is registered on the older branches, and nothing in this file uses them, so taking the `extern` would not link. Note that a blank line among the `PAUSEABLE(...) \` entries would silently end the macro list, so the two new entries are appended without one. - The `MutateFromLogEntryTask::~MutateFromLogEntryTask` destructor and `Stopwatch commit_watch;`, both master-only and unused here. What lands is the fix itself: the two new failpoints, and `transaction_ptr->renameParts()` moved out of the `try` block to before `mutate_task.reset()`, so the rename happens while the `TemporaryParts` guard still keeps `clearOldTemporaryDirectories` off the `tmp_mut_<part>` directory. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Every conflict is master-only context the cherry-pick drags along, not a divergence in the change itself. Kept only what it contributes and dropped: - `new_part->getDataPartStorage().commitTransaction();` after `renameTempPartAndReplace`. No release branch has it; they only `precommitTransaction` above. - The `rmt_mutate_task_pause_after_zero_copy_lock` and `merge_tree_background_task_marked_for_deletion` failpoints, and the matching `extern`. Neither is registered on the older branches, and nothing in this file uses them, so taking the `extern` would not link. Note that a blank line among the `PAUSEABLE(...) \` entries would silently end the macro list, so the two new entries are appended without one. - The `MutateFromLogEntryTask::~MutateFromLogEntryTask` destructor and `Stopwatch commit_watch;`, both master-only and unused here. What lands is the fix itself: the two new failpoints, and `transaction_ptr->renameParts()` moved out of the `try` block to before `mutate_task.reset()`, so the rename happens while the `TemporaryParts` guard still keeps `clearOldTemporaryDirectories` off the `tmp_mut_<part>` directory. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Every conflict is master-only context the cherry-pick drags along, not a divergence in the change itself. Kept only what it contributes and dropped: - `new_part->getDataPartStorage().commitTransaction();` after `renameTempPartAndReplace`. No release branch has it; they only `precommitTransaction` above. - The `rmt_mutate_task_pause_after_zero_copy_lock` and `merge_tree_background_task_marked_for_deletion` failpoints, and the matching `extern`. Neither is registered on the older branches, and nothing in this file uses them, so taking the `extern` would not link. Note that a blank line among the `PAUSEABLE(...) \` entries would silently end the macro list, so the two new entries are appended without one. - The `MutateFromLogEntryTask::~MutateFromLogEntryTask` destructor and `Stopwatch commit_watch;`, both master-only and unused here. What lands is the fix itself: the two new failpoints, and `transaction_ptr->renameParts()` moved out of the `try` block to before `mutate_task.reset()`, so the rename happens while the `TemporaryParts` guard still keeps `clearOldTemporaryDirectories` off the `tmp_mut_<part>` directory. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Cherry pick #111992 to 26.3: Fix a mutated part losing files to the temporary directory cleanup
Cherry pick #111992 to 26.6: Fix a mutated part losing files to the temporary directory cleanup
Cherry pick #111992 to 26.7: Fix a mutated part losing files to the temporary directory cleanup
…orary directory cleanup
…orary directory cleanup
…orary directory cleanup
Backport #111992 to 26.3: Fix a mutated part losing files to the temporary directory cleanup
Backport #111992 to 26.6: Fix a mutated part losing files to the temporary directory cleanup
Backport #111992 to 26.7: Fix a mutated part losing files to the temporary directory cleanup
The cleanup thread writes `... is in use (by merge/mutation/INSERT)` at most once per 10 seconds per table (`LogFrequencyLimiter` in `MergeTreeData::clearOldTemporaryDirectories`), so the row about the paused mutation's temporary directory can be held back by an earlier row about another directory of the same table. In both failures the INSERT's own `tmp_insert_all_1_1_0` was flagged first, because its rename on object storage took about 1.4 s. Phase 1 waited only two cleanup iterations and then read `system.text_log`, which had no row for the mutation's directory yet (or had it written but not flushed), so it printed `0 0` instead of `1 0`. Phase 1 now flushes and polls, bounded by 60 seconds of wall clock, until the row about the mutation's directory is in `system.text_log`. Phase 2, the regression check for ClickHouse#111992, is unchanged. CI reports: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121216&sha=ef01f2e8d8d7c0d86a1893f72eb4a2a7ba7bc455&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20sequential%29 (ClickHouse#121216, which does not touch this test) https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=ecf87398fcafe260f22e26909bda0b6a84c67b36&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20sequential%2C%201%2F2%29 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #107150
Related: #96376
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a race between a
ReplicatedMergeTreemutation and the removal of old temporary directories that could publish a mutated part with some of its files missing, making reads of that part and all its later mutations fail.Description
MutateFromLogEntryTask::finalizereleasedmutate_task- and with it the RAII guard that registerstmp_mut_<part>inMergeTreeData::TemporaryParts- before callingMergeTreeData::Transaction::renameParts, which is what actually renames the directory on disk. Between those two points the temporary directory of an already precommitted part was not protected fromclearOldTemporaryDirectories.When the cleanup thread hit that window it started removing the directory while
renamePartswas moving it to the persistent name, so the part became active with part of its files already deleted whilechecksums.txtstill listed all of them. From the failing job'snode1log, the three events are 850 µs apart:Reads of such a part fail, because
MergeTreeMarksLoaderderives the marks path from the part's own checksums and therefore expects the file to exist:and every following mutation of the part fails permanently, because it hardlinks the source part's files by the names listed in its checksums:
This is the flaky
test_rename_column/test.py::test_rename_distributed_parallel_insert_and_select. That test setstemporary_directories_lifetime = 1, which makes the window easy to hit; it has failed this way 12 times in the last two months, including twice onmaster. #107150 reported the same symptom from the reader's side and improved the error message without fixing the race.Now the part is renamed while
mutate_taskis still alive, the wayMergeTreeDataMergerMutator::renameMergedTemporaryPartalready does for merges ("Explicitly rename part while still holding the lock for tmp folder to avoid cleanup").mutate_taskis still reset beforecheckPartChecksumsAndCommit, so the fallback fetch on a checksum mismatch (#96376) still runs with the guards released.Every other caller of
renameTempPartAndReplacewithrename_in_transaction=truerenames immediately afterwards;MutateFromLogEntryTaskwas the only one that did not.Testing
04512_mutation_temp_dir_cleanup_racepauses a mutation right before the rename with a new pauseable failpoint and checks that the cleanup thread reports the directory as in use instead of removing it. It fails on the unfixed code (0 1- the directory is removed, and the mutation then dies withCannot set modification time to file) and passes with the fix (1 0), verified locally on a debug build in both directions.Reported by: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=423ec1ba3ac4288ce5b934235be0c6700e0f7c14&name_0=MasterCI&name_1=Integration%20tests%20%28amd_msan%2C%201%2F8%29
Documentation entry for user-facing changes
Version info
26.8.1.1360(included in26.8and later)26.7.11.11,26.6.9.11,26.3.33.99