Repository navigation
Unify temporary part directory claim and reclaim, make part construction intent explicit - #111652
Conversation
Add `MergeTreeData::claimTemporaryPartDirectory` (claim the name plus reclaim a stale leftover before the part storage is constructed) and `reclaimStaleTemporaryPartDirectory` (the reclaim alone, for callers that claim before the destination disk is known). Reclaim uses `removeSharedRecursive` with the same `keep_shared` rule as `clearOldTemporaryDirectories`. Also add the `claim_inject_stale_part_dir` failpoint inside the primitive. No callers yet. Co-Authored-By: Claude Fable 5 <[email protected]>
Replace the three hand-rolled claim-plus-reclaim snippets with the primitive. The `create_empty_part_inject_stale_dir` failpoint is superseded by `claim_inject_stale_part_dir` inside the primitive; the stale temporary directory test now uses the new one. Co-Authored-By: Claude Fable 5 <[email protected]>
The claim stays where it is (taken before the destination disk is known); only the per-branch reclaim lambda now delegates to the primitive, which also preserves shared zero-copy blobs. Co-Authored-By: Claude Fable 5 <[email protected]>
Merge was the only write path without reclaim: a stale `tmp_merge_<part>` directory failed the merge with `DIRECTORY_ALREADY_EXISTS` for up to `temporary_directories_lifetime`, and packed storage seeded its reader from the stale contents before the check. Take the claim before the builder via `claimTemporaryPartDirectory` and keep the post-build exists check only for projection merges, which write nested inside the parent's directory and have no claim. Co-Authored-By: Claude Fable 5 <[email protected]>
The fetch path keeps its bespoke reclaim because it also covers the `to_detached` flavor rooted at `detached/`, which `MergeTreeData::reclaimStaleTemporaryPartDirectory` does not support. Co-Authored-By: Claude Fable 5 <[email protected]>
Cover the insert, mutation and merge (plain and packed) paths using the `claim_inject_stale_part_dir` failpoint and verify the `Removing stale temporary directory` warning in `system.text_log`. Co-Authored-By: Claude Fable 5 <[email protected]>
Every part construction now states whether it opens an existing directory (`OpenExisting`, which probes the mark type and seeds the packed archive reader) or creates a fresh one (`CreateFresh`, which initializes granularity from settings and reads nothing from disk). The enum has no default, so misclassified call sites fail to compile, and a debug `chassert` in the builder verifies that `CreateFresh` targets were claimed and reclaimed first. This also simplifies the projection write path: the reclaim moves after construction with no ordering subtlety. Co-Authored-By: Claude Fable 5 <[email protected]>
It was always `true` at every call site, so temporary part names are always `tmp`-prefixed. This is now structural since `MergeTreeData::claimTemporaryPartDirectory` validates the prefix. Co-Authored-By: Claude Fable 5 <[email protected]>
The `claim_inject_stale_part_dir` failpoint now fires only when the caller passes `may_have_leftover = true`. Otherwise the injected directory would never be reclaimed and its dummy file would end up inside the new part. Co-Authored-By: Claude Fable 5 <[email protected]>
Deduplicate the zero-copy keep_shared rule into removeSharedTemporaryDirectory and move the temporary-name validation to the destructive primitive (reclaimStaleTemporaryPartDirectory now fails close in release builds). Move the nested projection leftover reclaim into getProjectionPartBuilder so it happens before builder construction like every top-level path, which also lets the builder chassert cover projection parts and makes the writeProjectionPart log parameter dead. Rename may_exist to may_have_leftover, inline dead single-use locals, and clean up stale comments. Co-Authored-By: Claude Fable 5 <[email protected]>
`VersionMetadataOnDisk` now takes the part's `PartDirIntent` and only probes the directory for `OpenExisting` parts. A `CreateFresh` directory is guaranteed clean by claim-and-reclaim, so the probe is skipped, completing the no-disk-reads contract of `CreateFresh`. Co-Authored-By: Claude Fable 5 <[email protected]>
…terministic The new test fills `tmp_merge_<part>` with the genuine contents of an existing packed part and verifies the merge reclaims it without contaminating the result. The existing merge reclaim test now stops merges around the inserts so the OPTIMIZE deterministically merges two parts. Co-Authored-By: Claude Fable 5 <[email protected]>
The background cleaner now takes a per-name cleanup hold in `TemporaryParts` for the exists-recheck and removal, and `claimTemporaryPartDirectory` waits out a concurrent hold. This closes the window where the cleaner could delete a freshly recreated temporary directory under an active operation. Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Covers exclusive cleanup claims, duplicate operation claims, and that `add` blocks while the background cleaner holds the name. Co-Authored-By: Claude Fable 5 <[email protected]>
Use plain wording for why the fetch keeps its own removal logic, and make explicit that seeding in-memory state from a stale leftover requires a misclassified call site and is independently prevented by the claim-and-reclaim layer. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [c84b7ff] Summary: ✅
AI ReviewSummaryThis PR unifies stale temporary part-directory reclaim and makes part-construction intent explicit via PR Metadata
Findings❌ Blockers
Tests
Final VerdictChanges required before merge. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 410/444 (92.34%) · Uncovered code |
…laim # Conflicts: # src/Storages/MergeTree/IMergeTreeDataPart.cpp # src/Storages/MergeTree/MergeTask.cpp # src/Storages/MergeTree/MergeTreeData.cpp # src/Storages/MergeTree/MergeTreeDataWriter.cpp # src/Storages/StorageReplicatedMergeTree.cpp
The test landed on master in parallel with the enum and pre-creates the part directory, so `OpenExisting` preserves the probing default it was written against. Co-Authored-By: Claude Fable 5 <[email protected]>
The throw expectations abort in debug and sanitizer builds because constructing a LOGICAL_ERROR exception aborts there. Replace with a positive re-claim assertion and drop the duplicate-add test. Co-Authored-By: Claude Fable 5 <[email protected]>
Move the claim_inject_stale_part_dir failpoint from claimTemporaryPartDirectory into reclaimStaleTemporaryPartDirectory so the direct reclaim callers (the clone-based REPLACE/MOVE PARTITION paths) are injectable too, and add a stateless test covering the tmp_replace_from_ and tmp_move_from_ reclaims. Co-Authored-By: Claude Fable 5 <[email protected]>
For part objects constructed over an existing directory whose metadata is provided by the caller (deserialized from another replica) instead of being probed from disk: construction reads nothing, and the clean-directory assertion does not apply. Only the builder `chassert` and doc comments change; no public call site uses it yet. Co-Authored-By: Claude Fable 5 <[email protected]>
|
📊 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
|
The part object is not usable as built: the caller must supply the part format and populate the storage and part state from its out-of-band source before use. Co-Authored-By: Claude Fable 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 363/391 (92.84%) · Uncovered code |
alesapin
left a comment
There was a problem hiding this comment.
Overall LGTM, but I would get rid of PartDirIntent::OpenExistingWithoutProbing
| /// referenced by other replicas (same rule for the background cleaner and the claim-based reclaim). | ||
| void removeSharedTemporaryDirectory(const DiskPtr & disk, const String & relative_path) const; | ||
|
|
||
| /// Removes a stale leftover directory `relative_data_path / part_dir_name` on `disk`, if any. |
There was a problem hiding this comment.
Too detailed comments, let's make them in 3 lines...
| /// part is used; otherwise the first read fails (e.g. a packed file read throws). Unlike | ||
| /// `CreateFresh`, the directory may legitimately exist, so the clean-directory assertion does | ||
| /// not apply. | ||
| OpenExistingWithoutProbing, |
There was a problem hiding this comment.
I don't understand how we use this one... Looks like there is one-off case related to transactions... But I don't understand either why we cannot use txn_version received from another replica.
There was a problem hiding this comment.
Yes, it's used only for SMT transactions. It can be done by checking txn_version existence, but not from data from a different replica since that one does not contain txn_version. We'd need to bump the protocol version to include it. I think i'll got with existsFile for now and we can add it to the version metadata in the wire later if we want to
| ctx->disk = single_disk_volume->getDisk(); | ||
|
|
||
| std::string prefix; | ||
| if (ctx->need_prefix) |
There was a problem hiding this comment.
Good catch. I had to add it in early version of SMT, because uncommitted transaction rename was not supported. Now we should be able to get rid of it.
| /// cannot see inside part directories), so a retried materialization reclaims the leftover of | ||
| /// a previously interrupted attempt here; the non-initializing handle above guarantees that | ||
| /// nothing was seeded from it. | ||
| LOG_WARNING(storage.log, "Removing stale temporary projection directory {}", projection_storage->getFullPath()); |
There was a problem hiding this comment.
I would add assert that it has tmp_ prefix in name or is_temp_projection flag or something like this. I cannot understand how it can happen for normal committed projection.
| /// nested directory means a logic bug; this check is the release-build backstop for the builder's | ||
| /// debug `chassert`. | ||
| if (global_ctx->parent_part && data_part_storage->exists()) | ||
| throw Exception(ErrorCodes::DIRECTORY_ALREADY_EXISTS, "Directory {} already exists", data_part_storage->getFullPath()); |
| LOG_INFO(LogFrequencyLimiter(log.load(), 10), "{} is in use (by merge/mutation/INSERT) (consider increasing temporary_directories_lifetime setting)", full_path); | ||
| continue; | ||
| } | ||
| SCOPE_EXIT({ temporary_parts.releaseCleanupClaim(basename); }); |
There was a problem hiding this comment.
I would put inside if and after successful removeSharedTemporaryDirectory. Because removeSharedTemporaryDirectory can throw exception. In this case we shouldn't leave garbage on disk.
The reclaim rationale was repeated at every call site; keep it once on the `MergeTreeData` declarations and in `PartDirIntent`, and shorten the test headers. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A fresh projection is only written into a temporary parent directory or as a `.tmp_proj`, so anything else reaching the nested reclaim is a logic bug. Throw instead of removing, the same rule `reclaimStaleTemporaryPartDirectory` enforces. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The check now only covers projection merges, whose directory this same operation just created, so hitting it is a logic bug rather than a directory conflict. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`tryHoldForCleanup` now returns a `scope_guard`, so the hold spans exactly the removal and is released on every path, including a failed one, where a leaked hold would block both the next cleanup pass and any operation claiming the name. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`createDisk` defaulted to the relative path `tmp/` and `destroyDisk` removed it recursively, so running `unit_tests_dbms` from a directory with a `tmp` scratch directory deleted it. Create a fresh unique directory under the system temporary directory instead, and remove only what the helper created. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
It had no user in this repository, and the intent left the part object unusable as built, which is a bad thing to offer in the builder contract. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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 units264 translation units recompiled, 2345 s compile time in total, 263 of them have a recent master baseline. |
…test Stateless tests must not modify table data on disk: the suite runs against arbitrary server configurations (object storage, shared merge tree, encrypted disks), where direct manipulation of part directories is either impossible or corrupts shared state. The scenario moves to `test_packed_io::test_merge_over_stale_packed_tmp_dir` unchanged: a merge must reclaim a stale `tmp_merge_` directory left by an interrupted attempt and must not seed any data from it. See ClickHouse#113978 (review) Related: ClickHouse#113978 Related: ClickHouse#111652 Co-Authored-By: Claude Fable 5 <[email protected]>
Every MergeTree write path (insert, merge, mutation, empty part, clone) creates its part under a deterministic temporary directory name (
tmp_insert_*,tmp_merge_*,tmp_mut_*, ...). An interrupted or rolled-back operation can leave a stale directory behind, and a retry then hits it: packed part storage would seed its archive reader and mark layout from the stale contents at construction, andfreezerejects a non-empty destination. This was previously handled by near-identical "remove the leftover before building" snippets at five call sites, each with plainremoveRecursive, and the merge path had no handling at all: a staletmp_merge_*directory failed merges withDIRECTORY_ALREADY_EXISTSfor up totemporary_directories_lifetime(one day by default).This PR unifies the pattern and makes it structural:
MergeTreeData::claimTemporaryPartDirectory: claims the temporary directory name (exclusive) and reclaims a stale leftover before the part storage is constructed. All write paths use it; the removal now usesremoveSharedRecursivewith the samekeep_sharedrule as the background cleaner, so shared zero-copy blobs are preserved. Onlytmp-prefixed names can be reclaimed, so names likedetached/<dir>can never be removed by mistake.tmp_merge_*directory is reclaimed with a warning and the merge proceeds. A true concurrent double-assignment now surfaces as aLOGICAL_ERRORexception from the claim, earlier and more accurately than the old exists check.PartDirIntentenum (OpenExisting/CreateFresh) replaces thepart_may_exist_on_diskbool. Every part construction states its intent explicitly (no default):CreateFreshreads nothing from disk (granularity from settings, no packed reader seeding, notxn_version.txtprobe),OpenExistingkeeps the filesystem probes. Debug buildschassertthatCreateFreshtargets a non-existing directory and that onlyOpenExistingdetects the part format from disk, so a misclassified or unclaimed path fails loudly in CI.TemporaryPartsnow also arbitrates against the background cleaner: the cleaner takes a transient per-name hold and claims wait it out, closing a race where the cleaner could delete a freshly recreated temporary directory under an active operation.trueneed_prefixparameter is removed, and the per-sitecreate_empty_part_inject_stale_dirfailpoint is replaced byclaim_inject_stale_part_dirinside the claim, covering every write path.Changelog category (leave one):