Skip to content

Unify temporary part directory claim and reclaim, make part construction intent explicit - #111652

Merged
Algunenano merged 30 commits into
ClickHouse:masterfrom
Algunenano:unify-part-dir-reclaim
Aug 7, 2026
Merged

Algunenano merged 30 commits into
ClickHouse:masterfrom
Algunenano:unify-part-dir-reclaim

Conversation

@Algunenano

Copy link
Copy Markdown
Member

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, and freeze rejects a non-empty destination. This was previously handled by near-identical "remove the leftover before building" snippets at five call sites, each with plain removeRecursive, and the merge path had no handling at all: a stale tmp_merge_* directory failed merges with DIRECTORY_ALREADY_EXISTS for up to temporary_directories_lifetime (one day by default).

This PR unifies the pattern and makes it structural:

  • New 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 uses removeSharedRecursive with the same keep_shared rule as the background cleaner, so shared zero-copy blobs are preserved. Only tmp-prefixed names can be reclaimed, so names like detached/<dir> can never be removed by mistake.
  • The merge path is fixed: a stale tmp_merge_* directory is reclaimed with a warning and the merge proceeds. A true concurrent double-assignment now surfaces as a LOGICAL_ERROR exception from the claim, earlier and more accurately than the old exists check.
  • New PartDirIntent enum (OpenExisting / CreateFresh) replaces the part_may_exist_on_disk bool. Every part construction states its intent explicitly (no default): CreateFresh reads nothing from disk (granularity from settings, no packed reader seeding, no txn_version.txt probe), OpenExisting keeps the filesystem probes. Debug builds chassert that CreateFresh targets a non-existing directory and that only OpenExisting detects the part format from disk, so a misclassified or unclaimed path fails loudly in CI.
  • TemporaryParts now 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.
  • The always-true need_prefix parameter is removed, and the per-site create_empty_part_inject_stale_dir failpoint is replaced by claim_inject_stale_part_dir inside the claim, covering every write path.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Algunenano and others added 16 commits July 23, 2026 12:05
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]>
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c84b7ff]

Summary: ✅


AI Review

Summary

This PR unifies stale temporary part-directory reclaim and makes part-construction intent explicit via PartDirIntent. The direction is correct, but the current head still does not make retries reliable under low free space: the main write paths still reserve disk space before reclaiming the deterministic tmp_* directory they are about to reuse.

PR Metadata
  • Changelog category should be Bug Fix, not Not for changelog, because this change fixes user-visible MergeTree retry failures rather than internal-only refactoring.
  • A Bug Fix needs a Changelog entry. Suggested replacement: Retrying MergeTree INSERT, merge, mutation, and partition-clone operations now reclaims stale temporary part directories left by interrupted earlier attempts instead of failing on leftover tmp_* directories.
Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:10594-10612] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/111652#discussion_r3644970519] Cross-disk clone retries still call reserve before reclaimStaleTemporaryPartDirectory. On a nearly full policy, a stale tmp_replace_from_* or tmp_move_from_* directory can still consume exactly the bytes the retry needs, so the retry throws NOT_ENOUGH_SPACE before the reclaim ever runs. The same reserve-before-reclaim ordering is still present in the other new claim callers as well (src/Storages/MergeTree/MergeTreeDataWriter.cpp:864-901, src/Storages/MergeTree/MergeTask.cpp:576-587, and src/Storages/MergeTree/MutateTask.cpp:3911-3921), so the PR still does not satisfy its "write paths are structurally retryable" contract under low free space.
    Suggested fix: reclaim before reservation when the destination disk is already known, or add a reserve-failure retry path that probes and reclaims the deterministic temporary name on the candidate disk before giving up.
Tests
  • ⚠️ The new stateless regressions only inject stale directories inside claimTemporaryPartDirectory, after reservation and disk selection have already succeeded. A focused low-space regression is still needed to prove the promised retry behavior, because the current tests cannot fail on the reserve-before-reclaim ordering above.
Final Verdict

Changes required before merge.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 410/444 (92.34%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 23, 2026
Algunenano and others added 4 commits July 24, 2026 10:37
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 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: c624ea00-9f9d-4f70-95d1-de73c86d6edb
  • MIRAI run: 19d9c6a5-f3f1-4c4d-b638-9893a9c80410
  • PR check IDs:
    • clickbench_163607_1786104897
    • clickbench_163613_1786104897
    • clickbench_163625_1786104897
    • tpch_adapted_1_official_163637_1786104897
    • tpch_adapted_1_official_163650_1786104897
    • tpch_adapted_1_official_163678_1786104897

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 91.90% -0.10%
Branches 78.30% 78.20% -0.10%

Changed lines: Changed C/C++ lines covered: 363/391 (92.84%) · Uncovered code

Full report · Diff report

@alesapin alesapin self-assigned this Jul 31, 2026

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

Overall LGTM, but I would get rid of PartDirIntent::OpenExistingWithoutProbing

Comment thread src/Storages/MergeTree/MergeTreeData.h Outdated
/// 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.

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.

Too detailed comments, let's make them in 3 lines...

Comment thread src/Storages/MergeTree/PartDirIntent.h Outdated
/// 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,

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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)

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.

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

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.

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.

Comment thread src/Storages/MergeTree/MergeTask.cpp Outdated
/// 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());

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.

It looks like LOGICAL_ERROR

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); });

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.

I would put inside if and after successful removeSharedTemporaryDirectory. Because removeSharedTemporaryDirectory can throw exception. In this case we shouldn't leave garbage on disk.

Algunenano and others added 8 commits August 6, 2026 12:50
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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c84b7ff72 with master e5c489c41 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8bb9b45c8; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.17 MiB 687.13 MiB -3.03 MiB (-0.44%)

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 units

264 translation units recompiled, 2345 s compile time in total, 263 of them have a recent master baseline.

Job report

@Algunenano
Algunenano added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit 335d011 Aug 7, 2026
179 checks passed
@Algunenano
Algunenano deleted the unify-part-dir-reclaim branch August 7, 2026 16:12
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 7, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 16, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants