Repository navigation
Conversation
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260626-071000 |
|
cc @Michicosun @alesapin — could you review this? |
|
Workflow [PR], commit [e60b2ec] Summary: ❌
AI ReviewSummaryThis PR hardens Findings❌ Blockers
Tests
Final VerdictRequest changes. LLVM Coverage ReportMeasured on commit e60b2ec.
Changed lines: Changed C/C++ lines covered: 155/164 (94.51%) · Uncovered code |
…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]>
|
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:
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. |
Pre-PR validation gate (revised fix, click to expand)
Session id: cron:clickhouse-worker-slot-2:20260626-172400 |
|
Merged master and re-pushed ( The only red check on the previous head was
Session id: cron:clickhouse-worker-slot-5:20260626-192800 |
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]>
|
Pushed 13e72bd to make the new test Root cause was the test, not the fix: it relied on a fixed 3s sleep failpoint ( Fix: replace the REGULAR sleep failpoint with a PAUSEABLE one ( No change to the production fix ( Session id: cron:clickhouse-worker-slot-0:20260627-002900 |
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]>
…sync-merges-part-log-race
CI finish ledger — ba1687aCI fully finished on this commit (Finish Workflow SUCCESS). Every failure below has an owner. The branch has since been merged with master (
The earlier flaky-check failures of the new test 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]>
|
Pre-PR validation gate for the fetch-path post-commit-exception fix (commit 2294ec7). Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260627-092700 |
CI finish ledger — 2294ec7CI 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
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 |
…sync-merges-part-log-race # Conflicts: # src/Common/FailPoint.cpp
CI finish ledger - 793ba08Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-093000 |
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.
|
Fixing PR for the Root cause: #109339 added a 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 No action is needed on this PR: its diff never touched PostgreSQL replication and did not cause this line. |
CI finish ledger - 5ecceb1Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Neither line is caused by this PR. The diff touches the SYNC MERGES path ( Scale for context: 174 of 174 check-runs completed (151 success, 21 skipped, 2 failure) and CIDB Session id: cron:our-pr-ci-monitor:20260729-213000 |
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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 155/165 (93.94%) · Uncovered code |
CI finish ledger - 53f4d11CI is fully finished on this head and there are no failures to own.
Session id: cron:our-pr-ci-monitor:20260802-020000 |
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.
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 4f84b13CI is fully finished on this head. Every failure below has an owner.
Not caused by this PR. The diff touches no memory-tracker surface (0 files matching Two merged memory-tracker fixes are already ancestors of the built merge commit
Session id: cron:our-pr-ci-monitor:20260823-183000 |
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)) |
There was a problem hiding this comment.
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.
CI finish ledger - 534b4cfEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Zero test-level failures at this head: CIDB records no Session id: cron:our-pr-ci-monitor:20260908-003105 |
|
Fixing-PR link-back for the The logs-cluster user switch that addresses the |
|
Fixing PR for the |
Changelog category (leave one):
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 theall_1_4_2projection-merge row was occasionally missing fromsystem.part_log.Root cause:
SYSTEM SYNC MERGESreturned 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 itspart_logrow (write_part_log({})). So aSYSTEM FLUSH LOGS part_logissued right afterSYNC MERGEScould 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 afterwrite_part_log()in both the plain and replicated execution paths, so this guarantees the scheduled merges'part_logrows 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 existingmax_execution_timedeadline 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 incheckPartChecksumsAndCommit()before it queues itsDOWNLOAD_PARTpart_logrow and creates no merge list entry, so the merge list check does not cover it.syncMerges()therefore also waits, on aStorageReplicatedMergeTree, until no in-flight fetch produces a part covering a scheduled source part. The fetched result part stays incurrently_fetching_partsfrom before the commit until afterwrite_part_log(), so theDOWNLOAD_PARTrow is queued before SYNC MERGES returns. PlainStorageMergeTreeis 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 by04412_sync_merges_waits_part_log_on_fetch.sh: replicaaexecutes the merge, replicab(Manual selector +always_fetch_merged_part=1) satisfies the scheduled merge by fetching, and a newrmt_fetch_part_sleep_before_part_logfailpoint widens the post-commit window. With the failpoint, theDOWNLOAD_PARTrow is absent right after SYNC MERGES returns without the fetch wait (count 0) and present with it (count 1). Sibling tests04207_schedule_merge_basicand04208_schedule_merge_disabledstill pass.Workflow [PR]
Sync PR [sync-upstream/pr/108584]