Skip to content

Fix LOGICAL_ERROR in OPTIMIZE ... DRY RUN racing a concurrent merge - #110916

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-optimize-dry-run-merge-race
Aug 31, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-optimize-dry-run-merge-race

Conversation

@groeneai

@groeneai groeneai commented Jul 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #114399

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):

Fixes a LOGICAL_ERROR exception (Temporary part ... already added) when OPTIMIZE ... DRY RUN runs concurrently with a real merge, or with another DRY RUN, on the same parts.

Description

MergeTreeData::optimizeDryRun executes a real MergeTask but, unlike the real optimize/merge paths, takes no CurrentlyMergingPartsTagger and no merge lock, so it never registers its source parts as "being merged". A concurrent real merge on the same parts computes the same result part name and reserves the same tmp_merge_<result> directory. The second reservation trips TemporaryParts::add -> LOGICAL_ERROR "Temporary part ... already added", aborting the server on debug and sanitizer builds. Seen on 17 unrelated PRs over the 30 days to 2026-08-11 (CIDB default.checks, 17 rows / 17 distinct PRs), never on master.

The dry-run part is throwaway, so its directory need not be named after the result part. It is now tmp_merge_dry_run_<uuid>, making the collision impossible on both MergeTree and ReplicatedMergeTree. A UUID rather than a counter, because the directory can live on storage shared with other servers, where a process-local counter restarts and repeats itself.

Leaving the part name out also avoids a length trap: appending a token to it can exceed the 255-byte filename limit while the real merge of the same parts still succeeds. Part names are not length-capped (an all-integral partition key spells its values out, so ten Int64 fields plus an IPv4 reach 226 bytes) and MergeTree prepends delete_tmp_ before removal, leaving 8 bytes. The new name has a fixed size.

It is never parsed back into a part name and still starts with tmp_merge_, which the cleaner and the startup skip logic select by. Only a dry_run_ suffix takes the new path, so top-level and projection merges keep byte-identical names.

Not a duplicate of the DRY RUN fix linked above (rows_sources under a soft timeout). Tracking issue: #114399.

Test 03823_optimize_dry_run_merge_race races two DRY RUNs on the same parts via a new failpoint pausing after the directory is reserved, at part-name lengths 7, 9 and 226, asserting the real merge succeeds at 226 and each DRY RUN really merged.


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

MergeTreeData::optimizeDryRun executes a real MergeTask but, unlike the
real optimize/merge paths, takes no CurrentlyMergingPartsTagger and no
merge lock, so it does not register its source parts as being merged. A
concurrent real merge (or another DRY RUN) on the same parts computes the
same result part name and reserves the same tmp_merge_<result> directory,
tripping TemporaryParts::add ("Temporary part ... already added") and
aborting the server on debug/sanitizer builds.

The dry-run part is throwaway, so give its temporary directory a unique
_dry_run_<uuid> suffix. This makes the collision impossible on both
MergeTree and ReplicatedMergeTree. Real merges are unaffected: all real
callers of mergePartsToTemporaryPart pass an empty suffix, and the
directory still starts with tmp_merge_ so cleanup and startup logic match.

Add regression test 03823_optimize_dry_run_merge_race and a test-only
failpoint that pauses right after the temporary directory is reserved.

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. A new test-only PAUSEABLE_ONCE failpoint (merge_task_pause_after_reserving_tmp_dir, scoped to dry-run merges) pauses the first OPTIMIZE ... DRY RUN right after it reserves tmp_merge_all_1_2_1, then a second DRY RUN on the same parts runs deterministically. Reproduces on every run.
b Root cause explained? MergeTreeData::optimizeDryRun runs a real MergeTask but takes no CurrentlyMergingPartsTagger/merge lock (its own comment admits it bypasses StorageMergeTree::optimize's guard). Two operations on the same source parts deterministically compute the same result part name -> getPartNameV1() -> same tmp_merge_<result> basename (no unique suffix for top-level merges). The second getTemporaryPartDirectoryHolder reservation trips TemporaryParts::add -> LOGICAL_ERROR, aborting on debug/sanitizer builds.
c Fix matches root cause? Yes. The collision is two ops claiming one temp-dir name. The dry-run part is throwaway, so it gets a unique _dry_run_<uuidv4> suffix -> its temp dir can never equal a real merge's (or another dry run's) tmp_merge_<result>. Directly removes the name collision rather than masking the assertion.
d Test intent preserved / new tests added? New regression test 03823_optimize_dry_run_merge_race added; it fails (server dies with the exact LOGICAL_ERROR) without the fix and passes with it. No existing test weakened.
e Both directions demonstrated? Yes. No-fix demo (non-unique suffix) -> server DIED: Logical error: 'Temporary part tmp_merge_all_1_2_1_dry_run_ already added'. With fix -> [ OK ], server alive. 50/50 randomized runs pass, server alive.
f Fix is general across code paths? Yes. optimizeDryRun is in the shared MergeTreeData base, so the fix covers both MergeTree and ReplicatedMergeTree. It is the ONLY dry-run-runs-a-real-MergeTask path (no mutateDryRun). Not a symptom guard — the collision is eliminated at the temp-dir naming source.
g Fix generalizes across inputs? Yes. The temp-dir basename derives only from the result part name (part-name components + level), independent of column datatypes / type wrappers / part count. The unique suffix is appended unconditionally to every dry-run merge, so it holds for any table schema, any number of parts, and any interleaving (merge-vs-dryrun, dryrun-vs-dryrun).
h Backward compatible? Yes. The suffix affects only the internal, throwaway temporary directory of a dry run (removed at the end of optimizeDryRun). No setting, on-disk, wire, replication, or metadata format changes. Real merges are byte-identical (all real callers of mergePartsToTemporaryPart pass an empty suffix). The dir still starts with tmp_merge_, so existing cleanup/startup skip logic still matches it.
i Invariants and contracts preserved? Yes. MergeTask::prepare now honors global_ctx->suffix for top-level merges (was parent_part ? suffix : ""); audited all callers — projection merges already pass .tmp_proj (identical old==new), and both real SMT and RMT merge callers pass the default empty suffix (identical old==new), so real merge temp-dir names are unchanged. TemporaryParts uniqueness invariant is upheld (that was the violated invariant). The test-only failpoint is scoped to dry-run merges (starts_with(DRY_RUN_TEMP_SUFFIX)) so it cannot perturb real/background merges.

Session id: cron:clickhouse-author-slot-2:20260717-220147

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

# Sev Finding Verdict Evidence / action
1 ⚠️ Failpoint fired unconditionally for EVERY MergeTask, so an unrelated background merge on a server-owned table could consume the PAUSEABLE_ONCE first -> nondeterministic test AGREE — fixed Scoped the pause to dry-run merges only: if (local_tmp_suffix.starts_with(DRY_RUN_TEMP_SUFFIX)) pauseFailPoint(...). Introduced MergeTask::DRY_RUN_TEMP_SUFFIX constant shared by optimizeDryRun and the scope check. No background DRY RUN merges exist, so the intended query is deterministically the one that pauses.
2 💡 Comment claimed only OPTIMIZE ... DRY RUN passes a non-empty suffix, but projection merges pass .tmp_proj AGREE — fixed Shortened/corrected the comment to note real top-level merges pass an empty suffix while DRY RUN passes a unique one.
3 ⚠️ Regression evidence (fails-without-fix / 50-run) was produced BEFORE the failpoint was scoped; final HEAD unverified AGREE — satisfied Rebuilt from final HEAD (Build ID c6c121b7...) and re-verified BOTH directions with the scoped-failpoint binary: no-fix demo -> server DIED with the LOGICAL_ERROR; with-fix -> [ OK ], server alive; restoring the real UUID line reproduced a byte-identical Build ID (proves tree == committed HEAD); 50/50 randomized -> 50 passed, server alive. No source change needed.

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-2:20260717-220147

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @alesapin — could you review this? It fixes a LOGICAL_ERROR ("Temporary part ... already added") where OPTIMIZE ... DRY RUN takes no merge guard and reserves the same tmp_merge_<result> directory as a concurrent real merge on the same parts. The throwaway dry-run part now gets a unique _dry_run_<uuid> temp-dir suffix, so real merges are unaffected.

@pufit pufit added the can be tested Allows running workflows for external contributors label Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [446c75c]

Summary: ✅


AI Review

Summary

This PR changes OPTIMIZE ... DRY RUN to reserve a distinct temporary merge directory instead of reusing the real merge basename, which removes the Temporary part ... already added collision and keeps the temporary-name length bounded for long part names. I rechecked the current head 446c75cc27a2d49b7b62f1c41829291ef631ec62 against the diff and prior discussion and did not find any remaining correctness, safety, or test-evidence issues that warrant a new review comment.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.30% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 38/38 (100.00%) · 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 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ac7cfc9

CI fully finished on this head (Finish Workflow SUCCESS). One failure, owned:

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Received signal 8 SIGFPE (STID 4141-584d) flaky (chrono duration_cast, EnabledQuota::Interval::getEndOfInterval, CREATE QUOTA FOR INTERVAL 0 SECOND divide-by-zero; 20+ unrelated PRs + master, 30d) #110346 (ours, open)

Not PR-caused (unrelated to the OPTIMIZE DRY RUN temp-dir-collision fix this PR makes; pre-existing chronic trunk signature with an open fixing PR).

Session id: cron:our-pr-ci-monitor:20260718-033000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

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

Full report · Diff report

A review round pointed out that appending a uniqueness token to the part name,
as the first version of this fix did, can push the temporary directory past the
filename limit while the corresponding real merge still fits. Part names are not
length-capped: an all-integral partition key spells its values out, so ten
`Int64` fields plus an `IPv4` give a 226-byte name, and `MergeTree` renames a
part to `delete_tmp_<dir>` before removing it, so at that length only 8 of the
255 bytes are left. `OPTIMIZE ... DRY RUN` then failed with `ENAMETOOLONG` where
an ordinary `OPTIMIZE` of the same parts succeeded.

Trying to keep the token inside that remaining room does not work either: it has
to be truncated for short part names, and a truncated token stops being unique
(two dry runs can render the same name and re-trip the collision) or loses the
marker that identifies the directory as a dry run.

So do not put the part name there at all. The dry-run part is throwaway, so its
directory is now `tmp_merge_dry_run_<uuid>`, which cannot collide with the merge
of those parts and has a fixed size, independent of the part name. A UUID rather
than a counter, because the directory can live on storage shared with other
servers, where a process-local counter restarts and repeats itself.

Nothing parses this name back into a part name, and it keeps the `tmp_merge_`
prefix, which the temporary directory cleaner and the startup skip logic select
by, so both still recognize it.

The regression test races two dry runs across the part-name range (7, 9 and 226
bytes), asserts that the real merge of the 226-byte parts succeeds -- which is
what makes a failing dry run a bug rather than a filesystem limit -- and checks
each dry run's own merge counters, so an implementation that returned success
without merging would no longer pass. It needs no blanket randomization tags:
only the counter query has to opt out of parallel replicas, since the test's
single node is not part of the randomized cluster definition.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a9d634c

Every failure below has an owner: a fixing PR (mine 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.

Both reds are one event: a pre-existing trunk ThreadSanitizer data race in the
plain-rewritable metadata snapshot killed the server in Stateless tests (amd_tsan, parallel),
and because that job is in CORE_BLOCKING_JOB_NAMES (ci/workflows/pull_request.py:16-27), the
Bugfix validation jobs it gates were DROPPED and never ran, so the new_tests_check.py
post-hook reported "No per-arch Bugfix Validation job validated the bug". The gate never measured
this PR's regression test; it validated OK on both arches at the previous head ac7cfc90d589.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel) / ThreadSanitizer: data race (STID 0250-3adb) + Server died data race in cloneFsNodeIfNotExclusive / clonePath (FsSnapshot.cpp:39, :109): shared_ptr::use_count() > 1 is used as a copy-on-write exclusivity test, so two transactions holding disjoint mutexes alias and mutate the same FsNode. Not reachable from this PR (its diff is FailPoint.cpp, MergeTask.{cpp,h}, MergeTreeData.cpp, one .sh test; zero lines under Disks/). 6 PRs in 30 days, mine and unrelated. a fix task is created (investigating at full effort - fixing-PR link to follow here)
Stateless tests (amd_tsan, parallel) / 12 further reported tests (04493_float_parsing_in_formats, 04033_tpc_ds_q61, 00050_min_max, 01415_sticking_mutations, ...) ATTEMPT_TO_READ_AFTER_EOF / NETWORK_ERROR cascade victims of the Server died above, all timestamped after it same owner as the row above (one event)
Finish Workflow / new_tests_check.py consequence, not an independent failure: Bugfix validation (functional tests, amd64/aarch64) were DROPPED because their run_after core-blocking dependency Stateless tests (amd_tsan, parallel) failed same owner as the row above

Everything else on this head is green: all 13 builds, Style check, Fast test,
Quick functional tests, all 4 flaky checks, all 6 Integration tests (amd_asan_ubsan, db disk, old analyzer) shards, all 6 Unit tests, and every other Stateless tests variant.

Session id: cron:our-pr-ci-monitor:20260729-233000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the plain_rewritable FsNode data race: #112557

That is a revert of #111883 by @ alexey-milovidov, merged 2026-07-30T09:07:30Z, which restores the
unconditional std::make_shared<FsNode>(*node) in clonePath and deletes the
use_count() > 1 copy-on-write predicate. He also opened a targeted fix, #112559, with the same
root cause; @ Michicosun closed it as fixed by #112557.

The race is verified gone on trunk, not just merged: keyed on the FsSnapshot.cpp frame plus
data race, CIDB returns 0 rows on any commit containing the revert, while in the same window the
tsan jobs ran 10160 passing plain_rewritable test rows across 255 distinct commits with 0
failures, so the silence is real and not a test that stopped running. All 7 carrier commits from
the 07-29/07-30 cluster contain the reverted helper; the last hit is 6d6b2615aff289 at
07-30 06:22 UTC, which is not a descendant of the revert.

This head predates the revert, so the red here clears once the branch picks up master.

One correction to my earlier ledger note on the onset: I flagged two possible pre-#111883 hits
(#64184 on 07-22, #95071 on 07-28). Neither is this bug. Both are Build (arm_tidy) rows whose
context merely contains the clang-tidy-cache log line for the object file FsSnapshot.cpp.o, with
no stack frame and no sanitizer report. The onset is exactly 2026-07-29, as the clonePath-keyed
sweep originally indicated.

@alexey-milovidov

Copy link
Copy Markdown
Member

The Stateless tests (amd_tsan, parallel) failure on a9d634c2 was not caused by this pull request. I have updated the branch; the job should be green on a re-run.

The run reported two failures, ThreadSanitizer: data race (STID: 0250-3adb) and Server died. They are one event: the ThreadSanitizer report aborts the server, so the harness also records Server died. The race is in the plain_rewritable metadata storage, which this pull request does not touch:

Write of size 8 ... by thread T5574 (mutexes: write M0):
  #3 DB::(anonymous namespace)::clonePath(...) src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/Metadata/FsSnapshot.cpp:109:36
  #4 DB::(anonymous namespace)::unlinkTree(...) src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/Metadata/FsSnapshot.cpp:167:47
  #5 DB::FsSnapshot::removeDirectory(...) src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/Metadata/FsSnapshot.cpp:239:12

It came from cloneFsNodeIfNotExclusive, which skipped the copy of an FsNode whose use_count was one. A reference count is not a proof of exclusive ownership here: an FsNode is reachable through the subdirectories map of its parent and a reader takes no reference of its own, so the count can drop to one while another thread is still reading the node. Hence the disjoint sets of held mutexes in the report.

The relevant timeline:

When (UTC) What
2026-07-28 08:31 #111883 merged, introducing the race
2026-07-29 21:15 the failing run on a9d634c2
2026-07-30 09:07 #112557 merged, reverting it

The fix landed about twelve hours after the run, so it could not have been present. The updated branch (936d47e8) now contains 50dc814029d4939f21c4446cacb3784bf4d65d18, and cloneFsNodeIfNotExclusive is gone from its copy of FsSnapshot.cpp.

Failing CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110916&sha=a9d634c2b833292a8bdf18686a8804c00e1393c4&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29

Related: #111883
Related: #112557

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 936d47e

Every failure below has an owner: a fixing PR (mine 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
Build (arm_release) / Post Hooks build_profile_hook telemetry INSERT rejected with LogCluster query failed with code 500; job-level status is success (the hook carries allow_failure), so no build was gated. Not caused by this diff: 816 rows / 284 distinct PRs / 463 master hits in 7 days. a fix task is created (investigating at full effort - fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260804-043000

# Conflicts:
#	src/Common/FailPoint.cpp
#	src/Storages/MergeTree/MergeTask.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8a565dd

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
Fast test / Build ClickHouse PR-caused: MergeTreeData.cpp:9687 passes 17 arguments to mergePartsToTemporaryPart, which now declares 16 PR-caused -> fixed in this PR
Build (arm_tidy) / Build ClickHouse PR-caused: same call site, reported as clang-diagnostic-error PR-caused -> fixed in this PR
Finish Workflow / new_tests_check.py Cascade: the three Bugfix validation jobs carry Dropped due to previous failure [Fast test], so no per-arch job could validate the bug PR-caused -> fixed in this PR

Root cause, for the record: need_prefix was removed from mergePartsToTemporaryPart on master
in 771c888fc443 ("Remove dead need_prefix parameter"), which is an ancestor of this head. The
optimizeDryRun call site added by this PR still passes /*need_prefix=*/ true, so the merge of
master into this branch made the call one argument too wide. Dropping that single argument line is
the whole fix; nothing else in the diff is implicated, and the three reds collapse to this one cause.

Nothing was pushed from this run: the newest commit on this branch is a maintainer's master merge,
so the branch is left to whoever is iterating on it.

Session id: cron:our-pr-ci-monitor:20260820-043000

`need_prefix` was removed from `mergePartsToTemporaryPart` on master in
`771c888fc443`, so after merging master the `optimizeDryRun` call site added by
this pull request passed one argument too many and the build failed with
`too many arguments to function call, expected at most 16, have 17`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110916&sha=8a565dd963809c062999149848fdbfe92fde5d08&name_0=PR&name_1=Fast%20test
Related: ClickHouse#110916
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 20, 2026
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Aug 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 446c75cc2 with master 0f7cac9ea (stripped binary size, per-symbol sizes and ThinLTO time; 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 710.18 MiB 707.14 MiB -3.04 MiB (-0.43%)

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

60 translation units recompiled, 715 s compile time in total, 60 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +59.0 s (+9%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Build (amd_musl) red at 257c3ed is a submodule pin moved backward

It is the only failing check at this head. Cmake configuration:

CMake Error at contrib/musl-cmake/CMakeLists.txt:1617 (add_library):
  Cannot find source file: /ClickHouse/contrib/musl/src/sched/rseq.c
  No SOURCES given to target: musl

Commit 1cc8f3f ("Drop the removed need_prefix argument from the optimizeDryRun call") moved two gitlinks backward alongside the call-site fix:

  • contrib/musl 7f52b7a53a0e (Aug 19) to adc82ccd0019 (Aug 11)
  • contrib/llvm-project c7f5fc7904a3 (Aug 18) to bcbf7dfd7f47 (Aug 10)

Both "before" values are what this PR's base and current master pin. src/sched/rseq.c exists at 7f52b7a53a0e and does not exist at adc82ccd0019, while in-tree contrib/musl-cmake/CMakeLists.txt:862 lists that file, so the musl target ends up with no sources. The same in-tree list builds green on master.

Restoring the two gitlinks to 7f52b7a53a0e and c7f5fc7904a3 should clear it.

I have not pushed anything: the recent commits here are yours and I did not want to race them.

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

I will reset the submodule changes.
The fix LGTM.

I don't remember why we have the OPTIMIZE DRY RUN feature. What was the initial motivation for adding it?

@alexey-milovidov alexey-milovidov self-assigned this Aug 20, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

I don't remember why we have the OPTIMIZE DRY RUN feature. What was the initial motivation for adding it?

It was introduced in #96122 (OPTIMIZE <table> DRY RUN PARTS <part names>). It simulates a merge of the specified parts without committing the result part. The stated motivation: verifying merge correctness on a new version before upgrading, deterministically reproducing merge-related bugs on a specific set of parts, and reliably benchmarking merge performance. Documentation was added in #97619.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1b2c23e

Every failure below has an owner: a fixing PR (mine 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
Docker server image (arm64) job cap: the head-distroless-arm64 buildx invocation went silent at 03:08:38 and the 18000s job cap fired at 07:35:45, so 16027s (4.45h) elapsed with no output and zero retries #113869 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

No test-level failure was recorded at this head (302226 CIDB rows, 0 FAIL/ERROR), and the
change itself is 6 MergeTree-only files with no docker, ci/, packages or contrib path, so
the red is not caused by this diff.

Session id: cron:our-pr-ci-monitor:20260821-083000

Address review: `tmp_merge_dry_run_<uuid>` was 54 bytes, and 65 once
`IMergeTreeDataPart::remove` renames the directory to `delete_tmp_<dir>`,
which is a larger fixed filename budget than a merge of ordinary parts
takes. Keep only the low half of the UUID, written as 16 hexadecimal
digits, so the basename is `tmp_merge_dry_run_<16 hex>` - 34 bytes, 45
after the rename - while the `dry_run_` marker that
`clearOldTemporaryDirectories` and the startup skip logic select by, and
the uniqueness the fix relies on, are both preserved.

`MergeTask` now logs the temporary directory it reserved, and the test
pins the resulting length in both directions.
`CLICKHOUSE_CLIENT` already carries `--send_logs_level` when
`CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL` is set, and the client rejects the
option twice with `option '--send_logs_level' cannot be specified more than
once`. A query-level `SETTINGS` clause overrides it either way.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2c212aa

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
Stress test (arm_tsan) / Logical error: size of reverse_flags does not match KeyDescription (STID 3072-3c97) pre-existing trunk defect, unrelated to this diff #115900 (ours, open)

One further note for the reader: Stress test (amd_debug) recorded a Hung check failed on its
first attempt at 23:50Z, but the retry at 04:03Z finished OK and that job's leaf report is green,
so it is not a failure at this head and owes no owner.

The arm_tsan signature first appeared on 2026-08-21 18:02Z on an unrelated PR, 29 h before this
head ran, and spans 20 rows across 16 unrelated PRs with 0 master rows. This PR changes
MergeTask/MergeTreeData and a failpoint; a reversed-sorting-key KeyDescription invariant is
not reachable from it. #115900 fixes exactly that assertion in getPatchPartMetadataV2.

Session id: cron:our-pr-ci-monitor:20260823-063000

…dr_<12 hex>`

The AI review asked for the temporary directory of `OPTIMIZE ... DRY RUN` to be derived from the budget of the merge it simulates, rather than pinning a larger fixed one.

A dry run cannot claim exactly that budget: reusing the name of the real merge is what collides in the first place, and the `LOGICAL_ERROR` this pull request fixes would simply be raised by the real merge instead. What can be reduced is the excess, so the marker is now `dr_` and the token 48 random bits written as 12 hexadecimal digits. The basename is `tmp_merge_dr_<12 hex>`: 25 bytes instead of 34, 36 instead of 45 once `IMergeTreeDataPart::remove` prepends `delete_tmp_`. That is 6 bytes more than a merge of the shortest possible pair of parts and no more than a merge of any part whose name is 15 characters or longer.

The `-- temporary directory budget` section of the test now merges the same pair of parts for real and prints the difference between the two directory names, instead of pinning the absolute lengths.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed 446c75cc27a2 on top of a fresh master merge.

  • AI review "Request changes" (Major, temporary directory budget) — implemented: the dry-run temporary directory is now tmp_merge_dr_<12 hex> (25 bytes, 36 after the delete_tmp_ rename), down from 34 / 45. It cannot be reduced to zero excess: reusing tmp_merge_<result part> is exactly what collides, so the LOGICAL_ERROR would simply move to the concurrent real merge. The excess is now 6 bytes for the shortest possible pair of parts and zero or negative from a 15-character part name upwards. The -- temporary directory budget section of the test now merges the same pair of parts for real and asserts the difference against that merge's directory, instead of pinning absolute lengths. Details on the review thread.
  • Stress test (arm_tsan) / Logical error: The size of reverse_flags (1) does not match the size of KeyDescription 3 — unrelated to this pull request and already fixed on master: getPatchPartMetadataV2 no longer appends _block_number / _block_offset to the ORDER BY explicitly while also passing them as additional columns. The master merge in this push pulls that in.

Built and ran 03823_optimize_dry_run_merge_race locally against this build: [ OK ].

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 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: 12048803-52bf-4627-909d-764a19b9e52c
  • MIRAI run: 235c0379-6c2a-4805-be89-84774bfcc3c5
  • PR check IDs:
    • clickbench_118193_1787881942
    • clickbench_118351_1787882049
    • clickbench_118371_1787882051
    • tpch_adapted_1_official_118555_1787882060
    • tpch_adapted_1_official_118657_1787882074
    • tpch_adapted_1_official_118759_1787882079

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 31, 2026
Merged via the queue into ClickHouse:master with commit ea1ebb0 Aug 31, 2026
179 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 Aug 31, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

pr-bugfix means not backported by default, so this fix is still master-only while the defect is live on all four supported branches.

Measured per branch, master as the positive control: 26.3, 26.6, 26.7 and 26.8 all still carry local_tmp_suffix = global_ctx->parent_part ? global_ctx->suffix : "" and build the directory as local_tmp_prefix + future_part->name + local_tmp_suffix, optimizeDryRun still calls mergePartsToTemporaryPart with no suffix (the call ends at nullptr /* txn */), DRY_RUN_TEMP_INFIX is absent from all four, and OPTIMIZE ... DRY RUN is ungated on each.

CIDB over 90 days on test_name LIKE '%Temporary part%already added%': 35 occurrences across 34 distinct refs, exactly one after the merge, on 26.7 today (Stress test (amd_debug), a5c57d48cfa2, STID 2148-4dbb). Zero hits on 26.3, 26.6 and 26.8 is not evidence they are unaffected: their pull_request_number = 0 Stress test exposure over the same window is 1875, 16929 and 3748 rows against master's 187139, so at master's pre-fix rate the expected counts there are about 0.02, 0.18 and 0.04.

Since the merge master is at 113 shas with zero occurrences, 03823_optimize_dry_run_merge_race at 7672 OK / 0 FAIL, and no new failure naming tmp_merge or a dry run.

Port cost, three-way per file (base f629aa6ad98c, theirs ea1ebb0da7b2):

branch conflict hunks note
26.8 0 clean, MergeTask.h and MergeTask.cpp come out blob-identical to master
26.7 2 context only
26.6 2 context only
26.3 3 MergeTask.cpp there has no namespace FailPoints block, so the test hook needs one added

What those hunks lack is claimTemporaryPartDirectory and sibling failpoint declarations, not anything the fix's own lines use, and the test ports to 26.3 unchanged.

@alexey-milovidov could you apply v26.3-must-backport? It expands to all four. If 26.3's extra hand-resolution is not worth a Stress-only logical error, v26.6-must-backport covers the other three.

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 groeneai-origin-unknown PR origin: unclassified (legacy task) 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 submodule changed At least one submodule changed in this PR.

Projects

None yet

4 participants