Skip to content

Make SYSTEM SYNC MERGES wait for part_log to be written - #108584

Open
groeneai wants to merge 37 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-04040-sync-merges-part-log-race
Open

groeneai wants to merge 37 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-04040-sync-merges-part-log-race

Conversation

@groeneai

@groeneai groeneai commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

Fixes flaky 04040_commit_order_projection_merge_levels (first seen on master, Stateless tests (arm_binary, parallel)), where the all_1_4_2 projection-merge row was occasionally missing from system.part_log.

Root cause: SYSTEM SYNC MERGES returned as soon as the scheduled merges' result parts became active. A merge makes its result part active by committing the transaction (plain: MergePlainMergeTreeTask::finish(), replicated: MergeFromLogEntryTask::finalize()), which happens before the task writes its part_log row (write_part_log({})). So a SYSTEM FLUSH LOGS part_log issued right after SYNC MERGES could flush before the entry was queued, leaving the row missing. In CI only the last merge lost the race because its SYNC to FLUSH window is the tightest.

Fix: syncMerges() returns only when the scheduled parts are covered AND no merge consuming any scheduled source part is still in the global merge list. A merge task holds its merge list entry until after write_part_log() in both the plain and replicated execution paths, so this guarantees the scheduled merges' part_log rows are queued before SYNC MERGES returns, while scoping to the scheduled source parts (and skipping mutations) avoids over-waiting on unrelated in-flight work. The existing max_execution_time deadline still guards the loop.

A scheduled merge on a replicated table can also be satisfied by fetching the merged part instead of executing it locally (always_fetch_merged_part, prefer-fetch, or zero-copy contention). The fetch path commits the fetched part active in checkPartChecksumsAndCommit() before it queues its DOWNLOAD_PART part_log row and creates no merge list entry, so the merge list check does not cover it. syncMerges() therefore also waits, on a StorageReplicatedMergeTree, until no in-flight fetch produces a part covering a scheduled source part. The fetched result part stays in currently_fetching_parts from before the commit until after write_part_log(), so the DOWNLOAD_PART row is queued before SYNC MERGES returns. Plain StorageMergeTree is unaffected.

Validation. The local-merge race was reproduced with a forced sleep between the transaction commit and write_part_log: the row was missing without the fix and present with it. The fetch-path race is covered by 04412_sync_merges_waits_part_log_on_fetch.sh: replica a executes the merge, replica b (Manual selector + always_fetch_merged_part=1) satisfies the scheduled merge by fetching, and a new rmt_fetch_part_sleep_before_part_log failpoint widens the post-commit window. With the failpoint, the DOWNLOAD_PART row is absent right after SYNC MERGES returns without the fetch wait (count 0) and present with it (count 1). Sibling tests 04207_schedule_merge_basic and 04208_schedule_merge_disabled still pass.


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

SYSTEM SYNC MERGES returned as soon as the scheduled merges' result
parts became active. A merge makes its result part active by committing
the transaction in MergePlainMergeTreeTask::finish(), which happens
before the task writes its part_log entry and releases the merged parts.
So a 'SYSTEM FLUSH LOGS part_log' issued right after SYNC MERGES could
flush before the entry was queued, leaving the row missing.

Wait until all in-flight merges/mutations have finished (the merged
parts are released only after part_log is written) in addition to the
existing check that the scheduled parts are covered. currently_merging_
mutating_parts is always drained by the tagger, including on merge
failure, and the Manual selector performs no autonomous merges, so the
wait is bounded.

This fixes flaky 04040_commit_order_projection_merge_levels where the
all_1_4_2 projection-merge row was occasionally missing from part_log.

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. With the thread fuzzer forcing a sleep between the transaction commit and write_part_log in MergePlainMergeTreeTask::finish() (THREAD_FUZZER_EXPLICIT_SLEEP_PROBABILITY=1, THREAD_FUZZER_SLEEP_TIME_US_MAX=3000000), the all_1_4_2 row was missing in 8/8 runs (unique db per run so part_log rows don't carry over).
b Root cause explained? SYSTEM SYNC MERGES returns once the scheduled merges' result parts are active. finish() makes the result part active at transaction.commit() BEFORE it queues the part_log entry (write_part_log({})) and releases the merged parts (finalize()). So SYSTEM FLUSH LOGS part_log right after SYNC can drain the queue before the entry is pushed. In CI only the last merge loses the race (tightest SYNC->FLUSH window); earlier merges have slack.
c Fix matches root cause? Yes. syncMerges() now also waits until currently_merging_mutating_parts is empty before returning. Those parts are released only in the tagger's finalize(), which runs after write_part_log, so emptiness guarantees the entry was queued. Not a band-aid (no widened assertion, no retry loop in the test, no no-random-*).
d Test intent preserved / new tests added? Preserved. The test .sql/.reference are unchanged; it still verifies rebuild-vs-merge projection behaviour via part_log. The fix is in the SYSTEM SYNC MERGES primitive so all three Manual-selector tests benefit. No separate regression test added because the existing test now reliably exercises the path (and forcing this race requires the thread fuzzer, which CI already runs in stress jobs).
e Both directions demonstrated? Yes. Same thread-fuzzer conditions: without fix 8/8 missing; with fix 12/12 present. clickhouse-test harness 5/5 OK; siblings 04207/04208 exact-match; clean runs ~430ms (no timing regression).
f Fix is general across code paths? Yes. The release-after-write_part_log ordering is the same for MergePlainMergeTreeTask (success and failure paths both call write_part_log before the tagger releases the parts; the tagger destructor finalizes on any exception). Mutations go through the same currently_merging_mutating_parts set, so they are covered too.
g Fix generalizes across inputs? N/A for input types. The wait condition is independent of column/data types. Bounded across scenarios: the Manual selector performs no autonomous background merges and the test issues no mutations, so the set only holds explicitly-scheduled merges SYNC is waiting for; the existing max_execution_time deadline still guards the loop.
h Backward compatible? Yes. No setting, format, or wire/disk change. Only strengthens an existing test-only command (SYSTEM SYNC MERGES, Manual selector) to wait slightly longer; semantics unchanged for all existing callers.
i Invariants and contracts preserved? Yes. The new accessor getNumberOfPartsInCurrentMergesAndMutations() takes currently_processing_in_background_mutex (same lock the set is always used under, matching stopMergesAndWait). It is read-only. The dynamic_cast<const StorageMergeTree*> is safe because the Manual selector is StorageMergeTree-only; the !storage_merge_tree fallback keeps the prior behaviour for any other case. Orthogonal to the separate hang bug #104883 (that hang is when isAllScheduledPartsCovered never becomes true; the new check runs only after it is true).

Session id: cron:clickhouse-worker-slot-0:20260626-071000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @alesapin — could you review this? SYSTEM SYNC MERGES returned once the scheduled merges' result parts became active (transaction.commit() in MergePlainMergeTreeTask::finish()), which is before the task queues its part_log entry, so a FLUSH LOGS part_log right after SYNC could miss the row (flaky 04040_commit_order_projection_merge_levels). The fix waits until in-flight merges/mutations drain (the merged parts are released only after write_part_log), which is bounded under the Manual selector.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e60b2ec]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Cannot check whether the mutation submitted before the upgrade was finished (see mutation_across_upgrade_error.txt) FAIL cidb
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR hardens SYSTEM SYNC MERGES so it waits for part_log readiness across local merges, replicated fetches, retries, and dependent scheduled-merge chains. The main logic is consistent, but one compatibility surface is still broken: old-format MergeTree part names are normalized inconsistently, so SYSTEM SYNC MERGES can still return before the scheduled local merge's part_log row is queued on V0-format tables.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeList.h:252-260] syncMerges snapshots scheduled parts in V1 form via MergeTreePartInfo::getPartNameV1(), but MergeListElement::source_part_names still stores the raw source_part->name spelling and can therefore remain in V0 form on tables created with allow_deprecated_syntax_for_merge_tree = 1. hasUnfinishedMergeOfSourceParts compares those raw names directly, so it misses the in-flight local merge exactly on that compatibility surface. Once coverage becomes true, SYSTEM SYNC MERGES can still return before write_part_log, reopening the race this PR is supposed to close. Normalize the merge-list side to the same canonical form, or compare parsed MergeTreePartInfos instead of raw strings, and add a regression that exercises manual merges on an old-format table.
Tests
  • The new tests cover plain and replicated V1-name paths, but there is still no regression for a manual merge on a table created with allow_deprecated_syntax_for_merge_tree = 1, which is the surface this mismatch breaks.
Final Verdict

Request changes.

LLVM Coverage Report

Measured on commit e60b2ec.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 155/164 (94.51%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 26, 2026
…icated)

Address review feedback on the part_log readiness wait. The previous
revision waited for StorageMergeTree::currently_merging_mutating_parts to
drain, which (a) did not cover StorageReplicatedMergeTree (which also runs
the Manual selector via merge_selector_algorithm, where the dynamic_cast was
null so SYNC MERGES returned before MergeFromLogEntryTask::finalize wrote
part_log), and (b) over-waited on any unrelated in-flight merge or mutation.

Model the waited state on the global MergeList instead: wait until no
non-mutation merge consuming any of the scheduled source parts is still in
the merge list. A merge task holds its MergeList entry until after
write_part_log() in both the plain and replicated execution paths, so this
guarantees the scheduled merges' part_log rows are queued before SYNC MERGES
returns, covers both storage families, and does not block on unrelated
merges or mutations.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Revised per review (f293334). The wait is now modeled on the global `MergeList` instead of `StorageMergeTree::currently_merging_mutating_parts`:

`SYSTEM SYNC MERGES` returns only once `isAllScheduledPartsCovered` is true AND no non-mutation merge consuming any of the scheduled source parts remains in the merge list. A merge task holds its `MergeList` entry until after `write_part_log({})` in both `MergePlainMergeTreeTask::finish` and `MergeFromLogEntryTask::finalize`, so the scheduled merges' part_log rows are guaranteed queued before the command returns.

This fixes both points raised:

  1. Replicated path is now covered. `StorageReplicatedMergeTree` runs the Manual selector too; the old `dynamic_cast<StorageMergeTree*>` was null there and SYNC returned before `MergeFromLogEntryTask::finalize` wrote part_log. The `MergeList` hook covers both families.
  2. No over-wait. The check skips `is_mutation` entries and is scoped to the scheduled source parts, so an unrelated in-flight merge or mutation no longer blocks SYNC MERGES.

Scheduled source parts are captured once before the loop (`ManualMergeSelector::getScheduledPartNames`) because `isAllScheduledPartsCovered` drains the pending set as parts get covered.

Verified with a deterministic ThreadFuzzer repro that injects a sleep between `transaction.commit()` and `write_part_log`: 10/10 missing without the wait, 12/12 present with it. clickhouse-test 04040 + 04207_schedule_merge_basic + 04208_schedule_merge_disabled: 15/15 OK, no timing regression.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (revised fix, click to expand)
# Question Answer
a Deterministic repro? Yes. Server-side ThreadFuzzer (THREAD_FUZZER_EXPLICIT_SLEEP_PROBABILITY=1, THREAD_FUZZER_SLEEP_TIME_US_MAX=3000000) injects a sleep at the maybeInjectSleep() between transaction.commit() and write_part_log in MergePlainMergeTreeTask::finish. Baseline binary: 10/10 runs missing the all_1_4_2 part_log row.
b Root cause explained? SYSTEM SYNC MERGES returned as soon as isAllScheduledPartsCovered was true, i.e. once the merge result part became Active at transaction.commit(). That is BEFORE the task calls write_part_log({}). So system flush logs part_log right after SYNC could drain the SystemLog queue before the row was pushed, leaving it missing.
c Fix matches root cause? Yes. The wait now ends only after the scheduled merges have left the global MergeList, and a merge holds its MergeList entry until after write_part_log() in both execution paths, so the row is guaranteed queued before SYNC returns.
d Test intent preserved / new tests added? Yes. No test file changed; 04040 still verifies projection merge-vs-rebuild behavior via part_log. The fix is to the SYNC MERGES sync primitive, which is what the test relies on.
e Both directions demonstrated? Yes. Without the wait: 10/10 missing (baseline). With the wait: 12/12 present, under identical server-side ThreadFuzzer. clickhouse-test 04040 + 04207_schedule_merge_basic + 04208_schedule_merge_disabled: 15/15 OK.
f Fix is general across code paths? Yes, and this is the core of the revision. The previous dynamic_cast<StorageMergeTree*> covered only the plain path; StorageReplicatedMergeTree also runs the Manual selector and writes part_log after commit in MergeFromLogEntryTask::finalize. The MergeList is the single hook populated by both families, so both are now covered.
g Fix generalizes across inputs? Yes. Works for any scheduled merge (single/multi-part, projection or plain). Mutations are excluded by design (is_mutation skipped), and the check is scoped to the captured scheduled source parts, so unrelated concurrent merges/mutations neither block nor short-circuit it.
h Backward compatible? Yes. No setting, on-disk, wire, or protocol change. SYSTEM SYNC MERGES is a test-sync primitive; behavior is strictly more correct (part_log guaranteed queued; no longer over-waits on unrelated mutations). No SettingsChangesHistory impact.
i Invariants and contracts preserved? Yes. MergeList::hasUnfinishedMergeOfSourceParts reads entries under the same mutex that get()/cancelPartMutations use; no new lock or lock-ordering. It only reads stable members (is_mutation, table_id, source_part_names). The part-name comparison uses getPartNameV1(), consistent with the existing isAllScheduledPartsCovered. The old StorageMergeTree::getNumberOfPartsInCurrentMergesAndMutations accessor is removed (no other callers).

Session id: cron:clickhouse-worker-slot-2:20260626-172400

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master and re-pushed (f29333451ad -> 21c93a83aee) to re-run CI on a current base.

The only red check on the previous head was Fast test / 02669_alter_modify_to_nullable, which is not caused by this PR:

  • This PR's new code (ManualMergeSelector::getScheduledPartNames, MergeList::hasUnfinishedMergeOfSourceParts) is reached only from InterpreterSystemQuery::syncMerges(), i.e. only the SYSTEM SYNC MERGES statement. 02669 uses SET mutations_sync = 2 + ALTER TABLE ... MODIFY COLUMN ... Nullable(String) and never issues SYSTEM SYNC MERGES / SCHEDULE MERGE / merge_selector_algorithm = 'Manual', so the changed code path is statically unreachable from that test.
  • The failing diff is the ALTER MODIFY to Nullable metadata-only optimization in MutateTask.cpp (canSkipConversionToNullable): part 1_1_1_0_3 occasionally took the full-rewrite path (Nullable(String) / 10000 rows) instead of the metadata-only path (String / 0 rows). That is a pre-existing flaky in the mutation path, unrelated to merge scheduling.
  • CIDB shows 02669 failing the same way on unrelated PRs (#108055 2026-06-22, #106586 2026-06-18) and on #106734 (amd_tsan/debug/asan).
  • Locally on this PR's binary it passes 60/60 with --no-random-settings --no-random-merge-tree-settings (the Fast test configuration); it only flakes under randomized settings.

04040 plus siblings 04207/04208 pass 60/60 on the merged binary, and master did not touch any of the merge-execution files this fix relies on (MergePlainMergeTreeTask, MergeFromLogEntryTask, MergeList, ManualMergeSelector).

Session id: cron:clickhouse-worker-slot-5:20260626-192800

groeneai and others added 2 commits June 26, 2026 22:50
A scheduled merge on a replicated table can be satisfied by fetching the
merged part instead of executing the merge locally (always_fetch_merged_part,
prefer-fetch, or zero-copy contention). The fetch path commits the fetched
part active in checkPartChecksumsAndCommit() before it queues its DOWNLOAD_PART
part_log row, and it creates no merge list entry. So the existing readiness
check (scheduled parts covered and no scheduled merge left in the merge list)
returned before the fetch path's part_log row was queued, leaving the same
SYNC MERGES -> FLUSH LOGS part_log race the PR fixes for the local-merge path.

syncMerges() now also waits, on a StorageReplicatedMergeTree, until no in-flight
fetch produces a part covering a scheduled source part. The fetched result part
stays in currently_fetching_parts from before the commit until after
write_part_log() returns, so this guarantees the DOWNLOAD_PART row of the
scheduled parts is queued before SYNC MERGES returns. Plain StorageMergeTree is
unaffected (the dynamic_cast is null).

Adds a focused replicated regression test that forces the fetch branch via
always_fetch_merged_part and asserts the DOWNLOAD_PART row is present right
after SYNC MERGES returns. A new failpoint widens the post-commit window so the
race is deterministic.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The new regression test 04412 was itself flaky under the flaky check: it
depended on a fixed 3s sleep failpoint (rmt_fetch_part_sleep_before_part_log)
landing inside a race window, which under load gave count=0 (SYNC MERGES
observed the part via a route other than the instrumented fetch, e.g. the
checkExistingPart short-circuit) or exceeded the 180s per-test cap.

Replace the REGULAR sleep failpoint with a PAUSEABLE one
(rmt_fetch_part_pause_before_part_log): the fetch now blocks after the fetched
part is committed active but before its DOWNLOAD_PART part_log write, holding
that window open until the test releases it, independent of machine load. The
test waits until the fetch is paused (part active on the fetching replica),
then runs SYSTEM SYNC MERGES with a background releaser: SYNC MERGES returns
only after the part_log write, so the immediately-following count is 1 with the
fix and 0 without it. Also pin insert_keeper_fault_injection_probability=0 to
keep the part name deterministic.

No change to the production fix (hasInFlightFetchCoveringParts wait in
syncMerges); only the failpoint mechanism and the test are made deterministic.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 13e72bd to make the new test 04412_sync_merges_waits_part_log_on_fetch deterministic. The flaky check found the test itself was flaky (3 FAIL on amd_asan_ubsan, 1 on amd_debug, all count 1 vs 0, plus one >180s timeout).

Root cause was the test, not the fix: it relied on a fixed 3s sleep failpoint (rmt_fetch_part_sleep_before_part_log) landing inside the commit-to-part_log race window. Under load that was fragile in both directions: if the fetched part reached replica b via a path other than the instrumented fetch (e.g. the ReplicatedMergeMutateTaskBase::checkExistingPart short-circuit) there was no DOWNLOAD_PART row so count was 0, and stacked retries could push the script past the 180s per-test cap.

Fix: replace the REGULAR sleep failpoint with a PAUSEABLE one (rmt_fetch_part_pause_before_part_log). The fetch now blocks after the part is committed active but before its DOWNLOAD_PART write, holding the window open until the test releases it, independent of machine load. The test waits until the fetch is paused (part active on b), then runs SYSTEM SYNC MERGES with a background releaser, so SYNC MERGES returns only after the part_log write: the immediately following count is 1 with the fix and 0 without it. Also pinned insert_keeper_fault_injection_probability = 0 for a deterministic part name.

No change to the production fix (hasInFlightFetchCoveringParts). Validated both directions on Build-ID-verified binaries (fixed 9643defd: count=1 and SYNC MERGES blocks until release; revert b2b445ff with the fetch-wait clause removed: count=0) and ran the new test 40+ times locally with randomization, 0 flakes.

Session id: cron:clickhouse-worker-slot-0:20260627-002900

groeneai and others added 2 commits June 27, 2026 02:39
The test only polled for the fetched part to become active, then fell
through after 600 attempts. If the fetch finished (its DOWNLOAD_PART
part_log row already written) before the poll observed the part, the
final count could be 1 without the fetch wait being what made it pass,
so the regression test could go green even with the fix absent.

Replace the active-part poll with
SYSTEM WAIT FAILPOINT rmt_fetch_part_pause_before_part_log PAUSE,
which blocks until a thread is parked at the failpoint. Wrap it in
timeout 60 and fail loudly if no fetch reaches the post-commit
pre-part_log window. The active-part query stays as a secondary
sanity check after the failpoint is known paused, and a cleanup trap
disables the failpoint on exit.

No production code change. Validated both directions on Build-ID
verified binaries: with the fetch wait the test passes (count 1) and
SYNC MERGES blocks until the part_log write; with the fetch wait
removed it fails (count 0). 90/90 runs with randomization, no flakes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ba1687a

CI fully finished on this commit (Finish Workflow SUCCESS). Every failure below has an owner. The branch has since been merged with master (c3eb815fe2dd) to pick up the merged RefreshTask fix, so CI will re-run on the fresh base.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) + (arm_asan_ubsan) / Unexpected exception in refresh scheduling (STID 2508-34af) chronic trunk crash (RefreshTask::doScheduling; 147 hits / 119 PRs / 11 master in 30d; not PR-caused — this PR touches SYSTEM SYNC MERGES / part_log only) #105588 (ours, merged 2026-06-26) — merged master @ c3eb815 to pick it up
Stress test (amd_debug) + (arm_asan_ubsan) / Cannot start clickhouse-server + Check failed downstream cascade of the STID 2508-34af crash (server aborted → restart failed) #105588 (ours, merged) — same as above
Upgrade check (amd_release) / Error message in clickhouse-server.log chronic upgrade-check log noise: background-mutation Cannot parse string 'x' as UInt64 (intentional test data; 0 master, ~49 PRs) #108563 (ours, open)

The earlier flaky-check failures of the new test 04412_sync_merges_waits_part_log_on_fetch were on superseded heads 7dd8704 / 13e72bd and were fixed in 13e72bd (pause failpoint) + ba1687a5 (SYSTEM WAIT FAILPOINT). The 02669_alter_modify_to_nullable Fast test on stale head f29333451ad was proven not-PR-caused (pre-existing MutateTask::canSkipConversionToNullable flaky, statically unreachable from this PR's SYNC MERGES code).

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

The MergeList-entry wait that SYNC MERGES relies on assumes a merge keeps its
merge list entry until after write_part_log. That holds on the success path but
not on a post-commit exception: in MergePlainMergeTreeTask::finish (and the
replicated MergeFromLogEntryTask::finalize) the result part is committed active
and then the post-commit work (memory limit injection, cache prewarming) can
throw before write_part_log. The background executor then cancels the task and
destroys its merge list entry with no part_log row, while the part stays active.
At that point isAllScheduledPartsCovered is true and hasUnfinishedMergeOfSourceParts
is false, so SYNC MERGES can return before the part_log row is queued and a
following FLUSH LOGS part_log can miss it.

Guard the post-commit work on both local-merge paths so a throw queues the
(failed) part_log row before unwinding, making the merge list entry a reliable
proxy for part_log readiness on every path. The fetch path already writes its
part_log row on a post-commit throw and is covered separately by
hasInFlightFetchCoveringParts.

Adds failpoint merge_throw_after_commit_before_part_log and a regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The replicated fetch path (StorageReplicatedMergeTree::fetchPart) commits the
fetched part active via checkPartChecksumsAndCommit and then runs throw-capable
post-commit work (quorum updates, cache prewarming) before it queues the
DOWNLOAD_PART part_log row. A DB::Exception there was caught by the first
catch (const Exception &), which rethrows every non-DIRECTORY_ALREADY_EXISTS
exception without writing part_log; the SCOPE_EXIT then erases the part from
currently_fetching_parts. At that point the part is active (covers the scheduled
sources) and no fetch is in flight, so SYSTEM SYNC MERGES can return before the
DOWNLOAD_PART row is queued and a following FLUSH LOGS part_log can miss it.

This mirrors the local-merge fix: track that the fetched part has been committed
and, for post-commit exceptions, queue the (failed) DOWNLOAD_PART row before
rethrowing. The catch-all already logged for non-DB::Exception throwables; the
DB::Exception catch did not. Pre-commit failures are unaffected (the part never
became active, so SYNC MERGES never sees it covered).

Adds failpoint rmt_fetch_throw_after_commit_before_part_log and a replicated
regression test that forces the fetch branch and throws in the post-commit window.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the fetch-path post-commit-exception fix (commit 2294ec7).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Failpoint rmt_fetch_throw_after_commit_before_part_log makes the fetch throw deterministically in the post-commit/pre-part_log window. Harness: replica a merges, replica b (Manual selector + always_fetch_merged_part=1) fetches; SYSTEM SCHEDULE MERGE b + OPTIMIZE a + SYSTEM SYNC MERGES b + FLUSH LOGS part_log.
b Root cause explained? fetchPart commits the part active (checkPartChecksumsAndCommit) then runs throw-capable post-commit work (quorum update, cache prewarm) before write_part_log. A DB::Exception there hit the first catch (const Exception &), which rethrows every non-DIRECTORY_ALREADY_EXISTS exception without writing part_log; SCOPE_EXIT then erases currently_fetching_parts. Part active + no in-flight fetch -> isAllScheduledPartsCovered true and hasInFlightFetchCoveringParts false -> SYNC MERGES returns with no DOWNLOAD_PART row for FLUSH LOGS to surface.
c Fix matches root cause? Yes. A part_committed flag is set right after commit; the catch (const Exception &) now calls write_part_log(fromCurrentException) before rethrowing when the part was already committed. This queues the failed DOWNLOAD_PART row inside the window where currently_fetching_parts still holds the part, so SYNC MERGES's fetch wait is a true proxy for part_log readiness.
d Test intent preserved / new tests added? New regression test 04414_sync_merges_waits_part_log_on_fetch_exception.sh (+ .reference). Existing 04412/04413 unchanged and still pass.
e Both directions demonstrated? Yes, Build-ID-verified binaries. Fixed (eade2004): failed DownloadPart all_0_1_1 row present after SYNC MERGES, count 1. Proof-revert (9e676647, fix clause removed, failpoint kept): count 0 (result differs -1 +0) -> the race reproduced.
f Fix is general across code paths? Yes. The two local-merge paths (MergePlainMergeTreeTask::finish, MergeFromLogEntryTask::finalize) were closed in the previous commit; this commit closes the symmetric fetch path. The other fetch helper fetchExistsPart (zero-copy/restore) does not write DOWNLOAD_PART and is not on the merge-satisfaction path. The catch-all catch (...) already logged for non-DB::Exception throwables.
g Fix generalizes across inputs? Yes. The guard keys on commit state (part_committed), not on a specific exception type or part shape, so it covers every post-commit DB::Exception source (quorum ZK errors, MEMORY_LIMIT_EXCEEDED from prewarm, etc.) and any part. The failpoint is placed at the earliest post-commit point, so the test exercises the whole window, not one step.
h Backward compatible? Yes. No setting, on-disk, wire, or replication-format change. Adds a failpoint (test-only) and one failed-part_log row on an otherwise-silent post-commit fetch failure, which is the correct, more-informative behavior. No SettingsChangesHistory change needed.
i Invariants and contracts preserved? Yes. Upholds the invariant the PR documents (MergeList.h: a task makes its part_log row queryable before its readiness signal clears) on the fetch path too: currently_fetching_parts holds the part from before commit until after write_part_log, so once the failed row is queued before rethrow, hasInFlightFetchCoveringParts stays a reliable proxy. No lock-ordering or part-state change; the part stays active exactly as before, only the missing part_log row is added.

Session id: cron:clickhouse-worker-slot-0:20260627-092700

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2294ec7

CI fully finished on this commit (Finish Workflow + Mergeable Check SUCCESS, 0 checks queued/in_progress, >20 min buffer). Every failure below has an owner. None is PR-caused (this PR only touches SYSTEM SYNC MERGES / part_log readiness on the merge/fetch paths).

Check / test Reason Owner / fixing PR
Stress test (arm_msan) / Hung check failed, possible deadlock found deadlock (chronic trunk: 347 master / 491 PRs / 1133 hits in 30d; dumped stack is QueryAnalyzer::resolveTableFunction + arrayReduceInRanges, unrelated to this PR) #101680 / #105905 (ours, open)
CH Inc sync private fork mirror CH Inc sync (not actionable)

The prior dominant stress crash on this branch (RefreshTask "Unexpected exception in refresh scheduling", STID 2508-34af) is gone on this head: the merged fix #105588 is now an ancestor of 2294ec7297b5.

…sync-merges-part-log-race

# Conflicts:
#	src/Common/FailPoint.cpp
@groeneai

groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 793ba08

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky under parallel replicas; a fresh trunk regression, with dozens of unrelated PRs and master hits in the last 24h #112385 (mine, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6) / test_postgresql_replica_database_engine/test_0.py::test_many_concurrent_queries one server death, not an independent test failure: the row carries Code: 210 ... Connection refused raised inside the suite's autouse setup_teardown fixture. Trunk bug, 12 unrelated PRs and 10 master hits in 30d a fix task is pending (investigating at full effort - fixing-PR link to follow here)
Sync - CH Inc sync (private, not actionable by me)

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

groeneai added 3 commits July 29, 2026 13:54
MergeFromLogEntryTask::finalize commits the result part active and then does
post-commit work (the zero-copy unlock, cache prewarming) that can throw.
finish_callback, which schedules merge_selecting_task, was armed only after that
work. On a throw it stayed unset, and the retry hit checkExistingPart (the part
is already committed) and retired the queue entry without ever reaching the
arming point, so nothing rescheduled the selector. The next merge in a scheduled
chain then waited for whatever backoff the previous selector pass had left
behind, up to max_merge_selecting_sleep_ms, and SYSTEM SYNC MERGES could hit
max_execution_time even though its prerequisite part already existed.

Arm finish_callback as soon as the commit succeeds, before any throw-capable
post-commit statement, so the wakeup happens on both the success and the failure
path. This is safe because the callback only schedules the selecting task, and it
still runs after merge_mutate_entry is destroyed: that ordering comes from the
member declaration order in ReplicatedMergeMutateTaskBase, not from where the
callback is assigned.

The failpoint moves to the top of the guarded block so it stands in for the
earliest throw-capable statement in that window (the zero-copy unlock) rather
than for a statement after the arming site.

The ordering predates this pull request and the same shape exists in
MutateFromLogEntryTask, which is left alone here.
…test

SYNC_OK alone would also be produced if the failpoint silently stopped firing,
because then both merges of the chain succeed and each arms the wakeup on its
normal success path. Assert the part_log rows instead: both merges leave exactly
one MergeParts row and it carries a non-zero error, neither gets a successful row
(the retry finds the part already committed and retires the queue entry via
checkExistingPart without re-running the merge), and the dependent merge's result
part is active, which confirms the chain completed rather than SYSTEM SYNC MERGES
returning on a partial state.
The mechanism and the user-visible consequence belong in the commit message, not
beside the code.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_postgresql_replica_database_engine Connection-refused cascade dispositioned to a fix task on this PR's CI finish ledger: #112381 (merged), with the re-land #112382.

Root cause: #109339 added a materialized_tables traversal to DatabaseMaterializedPostgreSQL::getTablesIterator. The asynchronous-metrics thread reaches that iterator (ServerAsynchronousMetrics.cpp:447, and this database reports isExternal() == false so it is not skipped) while stopReplication clears the same map holding only handler_mutex, never tables_mutex. That is a heap-use-after-free on the stored wrappers, it killed the server, and every remaining test in the module then failed inside the autouse setup_teardown fixture with Code: 210 Connection refused. One server death per job, not N independent flaky tests.

Timeline: #109339 merged 2026-07-28 13:16 UTC, the master cascade began the same evening, #112381 reverted it 2026-07-29 01:39 UTC. Every failing build contained the introducing commit and lacked the revert. True-master runs since the revert are clean: 0 failures against 6804 passing rows across 23 distinct commits. #112382 re-lands the feature with tables_mutex taken on all materialized_tables touch points, including the swap-and-destroy-outside-the-lock form in stopReplication.

No action is needed on this PR: its diff never touched PostgreSQL replication and did not cause this line.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5ecceb1

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
Fast test (arm_darwin) / Server died + 02381_client_prints_server_side_time one event, two rows: the macOS hang, not two independent test failures. The victim row is Reason: Timeout! unwinding through clickhouse-test:3752 _cleanup -> :3826 _cleanup_database, i.e. it timed out during teardown against an already-dead server #112267 (external, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky under parallel replicas, failed 3 of 3 reruns on this build #112385 (mine, merged 2026-07-29T15:37:40Z) - this head was cut at 15:15:45Z, 22 minutes before that merge, so the build predates the fix. GitHub compare of this head against the merge commit reports diverged, confirming the fix is not an ancestor here. It lands on the next master merge

Neither line is caused by this PR. The diff touches the SYNC MERGES path (FailPoint.cpp,
InterpreterSystemQuery.cpp, ManualMergeSelector, MergeFromLogEntryTask, MergeList.h,
MergePlainMergeTreeTask, StorageReplicatedMergeTree) plus ten new 0450x/046xx stateless
tests; 01666_merge_tree_max_query_limit and 02381_client_prints_server_side_time are not
among the changed files.

Scale for context: 174 of 174 check-runs completed (151 success, 21 skipped, 2 failure) and CIDB
recorded 288382 passing rows across 155 checks for this commit against the 3 failing rows above.

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

groeneai and others added 2 commits August 1, 2026 20:33
StorageReplicatedMergeTree::fetchPart committed the fetched part active and only
then did the quorum updates, which talk to Keeper and can throw, before calling
merge_selecting_task->schedule(). On a throw in that window the wakeup was
skipped: this PR now keeps the part active and queues the failed DownloadPart
row there, so the retry finds the part already committed, retires the queue
entry through checkExistingPart / removeProcessedEntry, and never reaches the
wakeup again. A dependent scheduled merge on the fetching replica then waited
for the selector's backoff timer instead of being assigned at once, so SYSTEM
SYNC MERGES could still hit max_execution_time even though the prerequisite
part already existed.

Hoisting the single existing call to immediately after the commit covers the
success and the failure path with one wakeup, mirroring what 04652 pinned for
MergeFromLogEntryTask::finalize. schedule() only takes the task's own mutex and
is a hint, not a state change: the selector already runs asynchronously and can
wake at any instant, and a pass that starts before the quorum work finishes
builds a fresh merge predicate which re-reads the quorum node and skips a part
still pending quorum.

The ordering itself is pre-existing on master, where a post-commit throw loses
the part_log row anyway; making that path complete is what turns the missing
wakeup into a reachable defect.

New test 04688 is the fetch-path counterpart of 04652: both replicas use the
Manual selector, the replica under test satisfies each scheduled merge by
fetching and throws in the post-commit window, and its backoff is pinned at
300s so only an explicit wakeup can produce a selector pass. Reverting the
hoist turns its SYNC_OK into SYNC_TIMEOUT while 04652 stays green.

Co-Authored-By: Claude Fable 5 <[email protected]>
The rationale belongs in the previous commit message, not next to the call.

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

clickhouse-gh Bot commented Aug 2, 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.80% +0.10%

Changed lines: Changed C/C++ lines covered: 155/165 (93.94%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 53f4d11

CI is fully finished on this head and there are no failures to own.

Check / test Reason Owner / fixing PR
(none) all 174 check-runs completed, 0 failures n/a
Sync - CH Inc sync (private, not actionable by me)

Finish Workflow succeeded. Liveness for this commit: CIDB records 396096 OK rows across 135
checks and 0 FAIL/ERROR, so the full matrix ran. This head clears the three failures the
previous ledger for 5ecceb128b2f9590bfcc60cf7e9cc28d82062ed6 had to attribute.

Session id: cron:our-pr-ci-monitor:20260802-020000

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
One conflict, in InterpreterSystemQuery::syncMerges(): master rewrote the
loop's timing while this branch rewrote the loop's exit predicate.

Master (1b6fc35, eafb23f) replaced the absolute
`now + max_execution_time` deadline with an elapsed-time comparison in
microseconds, because the absolute form is not representable for the largest
values `max_execution_time` accepts and would time the command out early.

This branch replaced the single-clause `isAllScheduledPartsCovered(table_id,
active_set)` exit with a three-clause wait (snapshot coverage, merge list, and
in-flight replicated fetch) plus the scoped `clearScheduledParts`, so the
command does not return before the part_log rows are queued.

The two changes are orthogonal, so both are kept: master's `start` /
`max_execution_time_us` / `while (true)` timing, and this branch's snapshot
capture and three-clause predicate. The branch's own `max_execution_time_ms` /
`timeout` / `deadline` lines are dropped as superseded by master's timing.

Net diff against master is unchanged by the merge: 31 files, +1299/-50, same
file set as before.
@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit e60b2ecabf4db0c57f3668d746980776eef1e1d6 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4f84b13

CI is fully finished on this head. Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Hung check failed, possible deadlock found Code-241 memory-accounting drift: 180 probe connections refused with would use 66.67 GiB (attempt to allocate chunk of 0.00 B), current RSS: 2.67 GiB, maximum: 47.49 GiB, and zero stacks collected a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

Not caused by this PR. The diff touches no memory-tracker surface (0 files matching
MemoryTracker|MemoryWorker|CurrentMemoryTracker|ThreadStatus), and the signature is
trunk-wide: 1235 rows / 547 distinct PRs / 130 master rows in 30 days.

Two merged memory-tracker fixes are already ancestors of the built merge commit
cd23ffd20f3f0ac5bdae380286d4b5ff4dbe024f (#110708, #110784), so neither resolves this and
neither can be linked as the owner.

Finish Workflow succeeded; 151 of 175 praktika nodes OK, 21 SKIPPED, and the only failing
leaf is the one above.

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

@abashkeev abashkeev added the comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. label Sep 4, 2026
One conflict, in the `namespace FailPoints` extern block of
StorageReplicatedMergeTree.cpp: both sides appended three declarations at the
same insertion point, so this is the registry class of conflict, where taking
either side wholesale deletes the other side's entries.

Master added `rmt_mutation_prune_pause_before_analysis`,
`rmt_mutation_prune_pause_before_block_allocation` and
`rmt_mutation_prune_pause_before_zk_partition_list`; this branch added
`rmt_fetch_part_pause_before_part_log`, `rmt_fetch_detached_part_pause` and
`rmt_fetch_throw_after_commit_before_part_log`.

All six are kept. Each is referenced by a call site in this same translation
unit and defined in FailPoint.cpp, so dropping master's three would leave
master's own call sites naming undeclared symbols, and dropping this branch's
three would remove the failpoints the new tests wait on. Master's three are
kept in master's position and this branch's three follow, so the diff against
master stays a plain insertion.

FailPoint.cpp merged automatically as a strict superset carrying both sets.

Net diff against master is unchanged by the merge: 31 files, +1299/-50, same
file set as before. The removal set is identical to the pre-merge branch's,
so no master code was dropped.
if (merge_element.is_mutation || merge_element.table_id != table_id)
continue;
for (const auto & source_part_name : merge_element.source_part_names)
if (source_part_names.contains(source_part_name))

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.

The new merge-list wait is intersecting different part-name forms. InterpreterSystemQuery::syncMerges builds scheduled_part_names from MergeTreePartInfo::getPartNameV1(), but MergeListElement still stores source_part->name verbatim and explicitly falls back to MERGE_TREE_DATA_OLD_FORMAT_VERSION when the table uses V0 names (src/Storages/MergeTree/MergeList.cpp:39-56).

On a manual table created with allow_deprecated_syntax_for_merge_tree = 1, this helper will never recognize the in-flight local merge it is supposed to keep behind the part_log barrier, so this PR still does not enforce the promised SYSTEM SYNC MERGES contract on that compatibility surface. Please normalize the merge-list side to the same name form (or compare parsed MergeTreePartInfos) and add a V0-format regression.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 534b4cf

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 profile diff CI logs cluster ACL, not a build or test problem: has_pr_data at ci/jobs/build_profile_diff_job.py:721 selects from default.binary_sizes and the cluster answers Code: 497. DB::Exception: ci: Not enough privileges ... (ACCESS_DENIED) after WARNING: LogCluster select failed with code 403, so query raises RuntimeError: CI logs cluster query failed at :232 and the job exits 1. It reads none of this PR's build or test output, so no diff can influence it a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

PR is the praktika aggregator over the row above, so it does not get its own line.

Zero test-level failures at this head: CIDB records no FAIL or ERROR row for
534b4cf2d5979c4afa36a03886a7dcaf7e9a80da, all 170 check runs are complete, and
Build profile diff is the only red among them. Integration tests (amd_asan_ubsan, targeted)
is skipped, not failed.

Session id: cron:our-pr-ci-monitor:20260908-003105

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing-PR link-back for the Build profile diff row in the CI finish ledger above: #118685 fixes the repo-side defect that failure exposed, namely that a failing first cluster read left an earlier commit's comparison pinned to the pull request, presenting an older revision as the current one.

The logs-cluster user switch that addresses the ACCESS_DENIED trigger itself is linked from that PR's description. CIDB still shows Build profile diff as error on all 7 runs started after that switch merged, with no success rows in the window, so this row's check may stay red until the cluster side is provisioned.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_release) / Hung check failed, possible deadlock found row in the CI finish ledger for 4f84b138: #122154 (mine, open). In that run the AST fuzzer called mergeTreeAnalyzeIndexesUUID with a vector search limit of 2147483647 at 18:20:32.5 (server time), and the first (total) memory limit exceeded followed 1.5 s later at 67.24 GiB. The mechanism is in #117681 (comment). #118094 (external, merged) additionally makes the global tracker re-baseline from measured memory on every tick.

@clickhouse-gh clickhouse-gh Bot added comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... and removed comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... groeneai-origin-unknown PR origin: unclassified (legacy task) pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants