Skip to content

Do not terminate the server on retryable errors while loading outdated parts - #107091

Closed
groeneai wants to merge 33 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-load-outdated-parts-retryable-terminate
Closed

groeneai wants to merge 33 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-load-outdated-parts-retryable-terminate

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

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

Do not terminate the server when a transient retryable error (such as MEMORY_LIMIT_EXCEEDED or a network error) occurs while loading outdated or unexpected data parts in the background. Such errors are not a sign of an inconsistent on-disk set of parts, so the loading task is now retried instead of aborting the whole server. The existing fail-fast behaviour is preserved for genuinely inconsistent state.

Description

Closes #106736

MergeTreeData::loadOutdatedDataParts() and the sibling loadUnexpectedDataParts() wrap their whole body in a catch (...) that calls std::terminate(), to fail fast on a genuinely inconsistent on-disk set of parts. The same catch also fires for transient runtime errors such as MEMORY_LIMIT_EXCEEDED (including the stress test memory fault injector) or network errors, which are not on-disk corruption. This takes the whole server down in the experimental serverfuzz stress jobs.

loadDataPartWithRetries() already classifies and retries such exceptions via isRetryableException(), but only around loadDataPart() itself; an exception thrown elsewhere in the loader (part removal, ZooKeeper cleanup, rename, the runner machinery, or newly memory-tracked allocations) escapes straight to the terminating catch.

The fix reuses isRetryableException() in both catch blocks: for a retryable error in the asynchronous background loader, it logs a warning and reschedules the loading task instead of terminating, so the server stays up and retries once the transient condition clears. Non-retryable errors and the synchronous drop-table path keep the existing fail-fast behaviour. The unexpected-parts loop is made idempotent so a rescheduled retry skips already-loaded parts.

A REGULAR failpoint mergetree_load_outdated_parts_inject_retryable_exception and an integration test (test_load_outdated_parts_retryable) inject a retryable error into the outdated-parts loader and verify the server survives and finishes loading.

The retry must not requeue a part whose retryable error happened after it was already published. loadDataPartWithRetries() inserts a normal Outdated part into data_parts_indexes before its post-load cleanup (preparePartForRemoval writes the removal TID and can throw retryably); requeueing it as-is made the retry reload the same directory as a fresh part, hit the duplicate-part path, and remove() could delete the directory while the published part still referenced it. The published part is now rolled back out of the index before requeueing so the retry reloads it cleanly. The unexpected-parts loop has the same shape (its optional broken-on-start detach runs after the part is set), so it now uses a separate finished marker set only after the detach succeeds. Two more failpoints exercise these post-load paths and the integration test gains a third case asserting nothing is wrongly detached.

The broken-part detach in both loaders no longer hides its errors. It used to call renameToDetached("broken-on-start", /*ignore_error=*/ replicated), and renameToDetached swallows ErrnoException and fs::filesystem_error when ignore_error is set - exactly the exception types a failing rename raises, and exactly the class isRetryableException treats as transient. On a replicated table a transient detach failure therefore never reached the new classification: the worker continued as if the cleanup had succeeded, leaving the broken outdated part on its original path with its ZooKeeper entry already removed, or setting the unexpected part's finished marker so the retry skipped it. Both call sites now pass ignore_error = false and classify the error themselves; the tolerance ignore_error gave replicated tables is preserved, but only for a permanent failure and only after the retryable case has been handled. A failpoint that throws the swallowed exception type and a regression case per loader cover it.

Provenance

Surfaced on master as the 'px != 0' failed family whose actual fatal is the loadOutdatedDataParts terminate. Latest master hit: Stress test (experimental, serverfuzz, arm_release), commit 81a8bcef7e8ba2dae3dfdc762dde87a853f40070, STID 3782-2f00.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=81a8bcef7e8ba2dae3dfdc762dde87a853f40070&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20arm_release%29


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

…d parts

MergeTreeData::loadOutdatedDataParts() and the sibling loadUnexpectedDataParts()
wrap their whole body in a catch(...) that calls std::terminate(). The intent is
to fail fast on a genuinely inconsistent on-disk set of parts. However, the same
catch also fires for transient runtime errors such as MEMORY_LIMIT_EXCEEDED from
the memory tracker (including the stress test memory fault injector) or network
errors, which are not signs of on-disk corruption. This took the whole server
down in the experimental serverfuzz stress jobs, surfacing on master as the
"Loading of outdated parts failed. Will terminate ..." fatal with a
MEMORY_LIMIT_EXCEEDED cause.

loadDataPartWithRetries() already classifies and retries such exceptions via
isRetryableException(), but only around loadDataPart() itself; an exception
thrown elsewhere in the loader (part removal, ZooKeeper cleanup, rename,
the runner machinery, or newly memory-tracked allocations) escapes straight to
the terminating catch.

Reuse isRetryableException() in both catch blocks: for a retryable error in the
asynchronous background loader, log a warning and reschedule the loading task
instead of terminating, so the server stays up and retries once the transient
condition clears. Non-retryable errors and the synchronous drop-table path keep
the existing fail-fast behaviour. The unexpected-parts loop is made idempotent
so a rescheduled retry skips already-loaded parts.

Adds a failpoint and an integration test that injects a retryable error into the
outdated-parts loader and verifies the server survives and finishes loading.

Closes ClickHouse#106736

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Added a REGULAR failpoint mergetree_load_outdated_parts_inject_retryable_exception that throws MEMORY_LIMIT_EXCEEDED inside the outdated-parts loader. SYSTEM ENABLE FAILPOINT ... then DETACH/ATTACH of a table with outdated parts fires it on demand, every time.
b Root cause explained? The catch (...) in loadOutdatedDataParts/loadUnexpectedDataParts calls std::terminate() for ANY exception, to fail fast on inconsistent on-disk parts. A transient MEMORY_LIMIT_EXCEEDED (from the memory tracker / stress fault injector) or network error thrown outside loadDataPartWithRetries (part removal, ZK cleanup, rename, runner machinery, or memory-tracked allocations added by #105580) escapes to that catch and aborts the whole server.
c Fix matches root cause? Yes. The fix reuses isRetryableException() (the same classifier loadDataPartWithRetries already uses, which covers MEMORY_LIMIT_EXCEEDED/CANNOT_ALLOCATE_MEMORY/network/etc.) in the catch blocks: a retryable error in the async background loader logs a warning and reschedules the task instead of terminating. Non-retryable errors keep the fail-fast std::terminate().
d Test intent preserved / new tests added? The fail-fast behaviour for genuinely inconsistent (non-retryable) state is preserved. New integration test test_load_outdated_parts_retryable added; it FAILS (server dies) without the fix and PASSES with it.
e Both directions demonstrated? Yes. Without the fix (catch temporarily reverted, failpoint kept): server logs <Fatal> Loading of outdated parts failed. Will terminate ... MEMORY_LIMIT_EXCEEDED and aborts at MergeTreeData::loadOutdatedDataParts (the exact CI master stack). With the fix: server logs <Warning> ... interrupted by a retryable error, will retry, stays alive (SELECT count() returns the full row set), and loading completes once the failpoint is disabled. Integration test passes via praktika (Integration tests (amd_tsan, 1/6), 0 failures).
f Fix is general, not a narrow patch? Yes. Both affected code paths are fixed symmetrically: loadOutdatedDataParts AND the sibling loadUnexpectedDataParts (issue #106736 names both). The fix roots in the existing isRetryableException() classifier rather than guarding a single symptom; it does not add a defensive null/empty check. The synchronous drop-table caller (is_async=false) keeps fail-fast since it has no task to reschedule and its caller handles the exception.

Session id: cron:clickhouse-worker-slot-8:20260610-204700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @alesapin — could you review this? It stops the server from calling std::terminate() in loadOutdatedDataParts/loadUnexpectedDataParts when a transient retryable error (e.g. MEMORY_LIMIT_EXCEEDED from the memory tracker / stress fault injector) is thrown during background part loading. Such errors aren't inconsistent on-disk state, so the loader now reschedules via isRetryableException() instead of aborting; real inconsistency keeps the fail-fast terminate. Fixes the residual loadOutdatedDataParts crash on the experimental serverfuzz stress jobs (#106736).

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [14cdd80]

Summary: ✅


AI Review

Summary

This PR hardens MergeTree background loading so retryable errors reschedule instead of calling std::terminate(), and it fixes a long list of real retry-boundary bugs in the outdated/unexpected loaders. The current head is much better than the original diff, but one concurrency hole is still open: loadUnexpectedDataParts still uses path-sensitive state without the table share lock that now protects the same invariant in loadOutdatedDataParts, so a concurrent table rename can still be misclassified as corruption and terminate the server.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:3501-3535, src/Storages/MergeTree/MergeTreeData.cpp:3585-3621, src/Storages/MergeTree/MergeTreeData.cpp:5102-5132] [dismissed by author -- https://github.com/Do not terminate the server on retryable errors while loading outdated parts #107091#discussion_r3886609650] loadUnexpectedDataParts still reads and acts on relative_data_path without the table share lock that guards that invariant in loadOutdatedDataParts. DatabaseOnDisk::renameTable takes lockExclusively() and then MergeTreeData::rename() moves relative_data_path, but in-flight unexpected parts are not in data_parts_by_info, so their storage roots are never rewritten. When a retryable detach failure then reaches the new catch, disk->existsDirectory(original_relative_path) can go false only because the table was renamed, and the loader rewrites that lifecycle race to CORRUPTED_DATA and std::terminate(). I still consider this real because the current code has no synchronization preventing that rename, and the fail-fast branch is keyed off the stale old path rather than a positive signal that this worker actually moved the directory. Suggested fix: make loadUnexpectedDataParts hold the same share lock as loadOutdatedDataParts (or stop/wait it before rename()), and use a positive post-move signal from the storage layer / detached destination instead of treating source-path absence as proof that the move already happened.
Final Verdict

Not ready to merge. The PR now handles many transient loader failures correctly, but the unexpected-parts path can still turn a concurrent table rename into a false corruption verdict and terminate the server.

LLVM Coverage Report

Measured on commit 14cdd80.

Metric Baseline Current Δ
Lines 88.60% 88.70% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 283/312 (90.71%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
groeneai and others added 3 commits June 11, 2026 03:51
Style check requires __init__.py in every integration test directory
(ci/jobs/scripts/check_style/various_checks.sh).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The test asserted the retryable-error warning was present in the log
immediately after ATTACH, but the outdated-parts loader runs on a
background scheduling-pool thread, so the line is not guaranteed to be
written yet. The bare check raced the loader and failed on the slower
msan/tsan builds while passing on the faster ones. Use
assert_logs_contain_with_retry to poll for the line.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Addresses two correctness issues in the retry path for loading
outdated/unexpected parts on a transient retryable error:

1. loadUnexpectedDataPart caught every exception, built a fake part and
   marked it broken, so the caller detached it. A transient
   MEMORY_LIMIT_EXCEEDED could detach an otherwise valid unexpected part.
   Now retryable exceptions reset any partially built part and are
   rethrown, mirroring loadDataPart, so the part is retried instead of
   detached.

2. loadOutdatedDataParts popped each node off the queue before the worker
   ran. On a retryable error the function-level catch rescheduled the
   task, but by then the queue was empty, so the next run marked loading
   finished and left those outdated parts untracked and never removed.
   The worker now puts the failed part back into the queue and the task
   is rescheduled to retry the remaining parts. Non-retryable errors and
   the synchronous path keep failing fast (std::terminate).

The regression test now clears the failpoint and waits for the same
background task to finish (SYSTEM WAIT LOADING PARTS) instead of forcing
another DETACH/ATTACH, and asserts the outdated parts are tracked again.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The worker-side catch only runs once the task is scheduled. If
ThreadPool::scheduleOrThrow throws a retryable CANNOT_SCHEDULE_TASK, the
part popped from outdated_unloaded_data_parts is never put back, so the
rescheduled task finds an empty queue, marks loading finished, and leaves
that outdated directory untracked and never removed.

Wrap the scheduling call so a retryable throw requeues the popped part and
reschedules, same as the worker-side path. Non-retryable errors and the
synchronous path still propagate and fail fast.

Add a mergetree_load_outdated_parts_inject_schedule_failure failpoint and
parametrize the regression test over both injection sites.
…e error

The retryable-error retry in loadOutdatedDataParts/loadUnexpectedDataParts
wrapped the whole per-part operation, including the cleanup that runs after the
part has already been published.

In loadOutdatedDataParts, loadDataPartWithRetries inserts a normal Outdated part
into data_parts_indexes before its post-load cleanup runs. preparePartForRemoval
then stores the non-transactional removal TID with a disk write that can itself
throw a retryable error (MEMORY_LIMIT_EXCEEDED, network). Requeueing the node
as-is made the rescheduled run reload the same directory as a fresh part, hit the
duplicate-part path, and res.part->remove() could delete the directory while the
first in-memory Outdated part still referenced it. Roll the published part back
out of data_parts_indexes before requeueing so the retry reloads it cleanly;
broken and duplicate results are never published, so they need no rollback.
Erasing only drops the in-memory object (removeIfNeeded keeps an Outdated part's
directory). num_loaded_parts is now incremented after cleanup so a requeue does
not double-count.

In loadUnexpectedDataParts the loaded part's optional broken-on-start detach runs
after state.part is assigned, so a set state.part was not a valid done-marker: a
retryable detach failure rescheduled the task, and the retry skipped the part with
the detach never redone while loading was marked finished. Track a separate
finished flag set only after the detach succeeds, and load the part only when it
is not already loaded so the retry resumes at the detach step instead of rebuilding.

Two REGULAR failpoints exercise the post-load path; the integration test gains a
third case asserting the server survives, parts recover, and nothing is detached.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Pushed commit 12d72d4 addressing the latest review (the post-load double-remove).

# Question Answer
a Deterministic repro? Yes. New REGULAR failpoint mergetree_load_outdated_parts_inject_post_load_retryable_exception throws MEMORY_LIMIT_EXCEEDED immediately after loadDataPartWithRetries returns (part already published, cleanup not yet run). With the rollback disabled, DETACH/ATTACH of a table with outdated parts logs Duplicate part 117x and detaches 3 parts; deterministic every run.
b Root cause explained? The retryable-error retry boundary wrapped post-load cleanup. loadDataPartWithRetries inserts a normal Outdated part into data_parts_indexes (MergeTreeData.cpp:2101) before preparePartForRemoval stores the removal TID with a disk write that can throw retryably. Requeueing the node as-is made the rescheduled run reload the same directory as a fresh part, hit the duplicate-part path, and res.part->remove() could delete the directory while the first published Outdated part still referenced it. The unexpected-parts loop had the same shape: state.part was used as the done-marker, but the optional renameToDetached("broken-on-start") runs after state.part is set, so a retryable detach failure skipped the part on retry while loading was marked finished.
c Fix matches root cause? Yes (bot option 2: roll back before requeue). Outdated path: in the worker catch, if res.part was published (normal, non-broken, non-duplicate) erase it from data_parts_indexes under data_parts_mutex before requeueing, so the retry reloads cleanly with no duplicate path. Erasing only drops the in-memory object (removeIfNeeded keeps an Outdated part's directory; verified at IMergeTreeDataPart.cpp:934). ++num_loaded_parts moved after cleanup so a requeue doesn't double-count. Unexpected path: added a finished flag set only after the optional detach succeeds, used as the done-marker instead of part, and the part is loaded only when not already loaded so the retry resumes at the detach step.
d Test intent preserved / new tests added? Test intent preserved and extended. Added a third parametrize case (POST_LOAD_FAILPOINT) plus a system.detached_parts == 0 assertion that specifically catches the double-remove reload.
e Both directions demonstrated? Yes, through the Docker integration harness. Fixed binary: 3/3 cases pass. Buggy binary (rollback neutralized, failpoint kept): the post-load case fails with assert 3 == 0 (3 parts detached as broken-on-start via the duplicate reload).
f Fix is general, not a narrow patch? Yes. Both symmetric loaders (loadOutdatedDataParts and loadUnexpectedDataParts) are fixed for the same post-publish class. The fix targets the source of the bad state (a too-wide retry boundary) rather than guarding the symptom: broken/duplicate results are never published so they correctly need no rollback.

Session id: cron:clickhouse-worker-slot-1:20260611-184300

groeneai and others added 2 commits June 11, 2026 21:31
…yable

loadUnexpectedDataParts has the same retry contract as loadOutdatedDataParts,
and the PR added the mergetree_load_unexpected_parts_inject_post_load_retryable_exception
failpoint, but no test exercised it.

Add a case that makes a broken unexpected part (remove a merged source part from
ZooKeeper and corrupt it on disk), injects the failpoint, and runs ATTACH
asynchronously because the replicated attach thread waits for unexpected parts to
be loaded. While the failpoint fires the loader must keep retrying the same part
and the server must stay up; once the failpoint is cleared, loading finishes, the
part is detached during the replica sanity check, and the data is intact.

The retry-count assertion discriminates the fix: with the finished marker the part
is retried every pass, while the pre-fix load_state.part marker skips it after a
single failure and marks loading finished. Verified the test passes on the fix and
fails on the pre-fix code on a local debug build.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
wait_for_log_line passes its pattern to the integration-test container's
grep -E, which does not support the PCRE \d class, so the previous
r"Loaded \d+ unexpected data parts" never matched and the case timed
out after 60s on the fixed binary even though loading had finished.

The wait was also redundant: the replicated attach thread blocks in
waitForUnexpectedPartsToBeLoaded() until loading is done, so the
preceding attach.get_answer() already guarantees the previously-failing
part was retried and loaded. Drop the fragile log poll and rely on the
ATTACH return.

Verified on a local debug build (praktika integration harness): all four
cases pass on the fixed binary; the unexpected case fails (assert 1 >= 3)
on the pre-fix load_state.part skip marker.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Follow-up to the bot's test-coverage request: commit 75b4872 fixes the unexpected-parts regression test that commit d794af01 added (test_retryable_exception_while_loading_unexpected_parts_does_not_terminate).

# Question Answer
a Deterministic repro? Yes. Pre-fix code (skip on load_state.part instead of the finished marker) + the mergetree_load_unexpected_parts_inject_post_load_retryable_exception failpoint: the broken unexpected part is retried only once, then loading is marked finished and the part is skipped. The test asserts retries >= 3 and fails deterministically (assert 1 >= 3).
b Root cause explained? The added test never ran green: wait_for_log_line(r"Loaded \d+ unexpected data parts") passes its pattern to the integration-test container's grep -E, which does not support the PCRE \d class, so the literal \d never matched Loaded 1 unexpected data parts. The case timed out after 60s on the fixed binary even though loading had finished (server log showed Loaded 1 unexpected data parts followed by Finished waiting for unexpected data parts to be loaded).
c Fix matches root cause? Yes. The fragile log poll is removed entirely. It was redundant: the replicated attach thread blocks in waitForUnexpectedPartsToBeLoaded() until loading is done, so the preceding attach.get_answer() already guarantees the previously-failing part was retried and loaded. No \d/grep -E dependency remains.
d Test intent preserved / new tests added? Preserved. The test still creates a broken unexpected part (drop from ZK + corrupt on disk), injects the post-load failpoint, asserts the loader keeps retrying (retries >= 3), the server stays up, and after clearing the failpoint the data is intact (count() == 2000) and the part reaches system.detached_parts. The discriminating retries >= 3 assertion is untouched.
e Both directions demonstrated? Yes, on a local debug build via the praktika integration harness. Fixed binary (Build ID def6d9c5): all 4 cases pass (4 passed in 31.50s). Pre-fix binary (Build ID 178d5168, load_state.part skip restored, failpoint kept): unexpected case fails assert 1 >= 3. Build IDs verified to differ between runs.
f Fix is general, not a narrow patch? N/A for the source fix (unchanged by this commit). This commit is test-only. The two production paths (loadOutdatedDataParts, loadUnexpectedDataParts) and both failpoints are now each covered by a regression case.

Session id: cron:clickhouse-worker-slot-0:20260611-210700

The parametrized test_retryable_exception_while_loading_outdated_parts case
ran assert_logs_contain_with_retry, which calls contains_in_log and scans
the whole shared server log. All three parameters (worker, schedule and
post-load failpoints) emit the same "Loading of outdated parts was
interrupted by a retryable error" line, so the later cases could be
satisfied by the line an earlier case already wrote. A regression where the
current failpoint's retry path never fired could still pass, since the
immediate system.parts check can also pass if the background loader has not
populated system.parts yet.

Snapshot the warning count right before enabling each failpoint and wait
for it to increase (wait_for_log_count_above), so every parameter proves
its own retry path fired and a never-reached failpoint times out at the
wait instead of passing. Apply the same baseline delta to the
unexpected-parts case. Drop the now-redundant assert_logs_contain_with_retry
import.

Verified on a local debug build (praktika integration harness): all four
cases pass; a regression demo where a later case's retry path is never
reached passes the old contains_in_log presence check but fails the new
count-delta assertion.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

For the latest fixup 46a71b5 (test-only: per-parameter interrupt-log count delta).

# Question Answer
a Deterministic repro? Yes. A regression demo (case 1 fires WORKER_FAILPOINT and writes the shared interrupt line; case 2's retry path is never reached) deterministically passes the old contains_in_log presence check and deterministically fails the new wait_for_log_count_above count-delta check.
b Root cause explained? assert_logs_contain_with_retry -> contains_in_log scans the entire shared module-scoped server log. All three outdated failpoints route through the same in-body reschedule warning in loadOutdatedDataParts (the line without an Exception: suffix), so SCHEDULE/POST_LOAD, running after WORKER, are satisfied by WORKER's line; a parameter whose own retry path never fires still passes (and the immediate system.parts == 0 check can also pass before the background loader populates system.parts).
c Fix matches root cause? Yes. Snapshot the warning count immediately before enabling each failpoint and require it to increase (wait_for_log_count_above), so each parameter proves its own retry path fired. This is the reviewer's option (a). A never-reached failpoint now times out at the count-increase wait instead of silently passing.
d Test intent preserved / new tests added? Preserved and strengthened. The test still asserts no-terminate + queue-not-dropped + no double-remove (detached_parts == 0) + unexpected-part resume. The assertion is now stricter: it verifies the current parameter's own retry, not merely that the line exists somewhere in the shared log. No source change, so no new regression test needed.
e Both directions demonstrated? Yes. Fixed test: 4/4 PASS (twice) on the local debug build via the praktika integration harness. Regression demo: old presence check passes (bug present), new count-delta raises AssertionError (fix catches it).
f Fix is general, not a narrow patch? Applied symmetrically to both retry tests: the parametrized outdated-parts case and the unexpected-parts case both use the baseline-delta pattern. The shared wait_for_log_count_above helper documents why presence checks are unsafe across parameters on one server log. No source/binary change (Build ID unchanged).

Session id: cron:clickhouse-worker-slot-5:20260611-223800

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary for 46a71b517c6e

CI has fully finished on this commit. One test failure, transient/unrelated to this PR:

  • Stateless tests (amd_tsan, parallel, 2/2) / 04258_except_empty_left_input — flaky, NOT caused by this PR.
    • The job's own randomized-settings diagnosis re-ran the test 61/61 PASS and reported "not reproducible (likely a transient issue)".
    • Root reason was a query-budget timeout under TSan load (Code: 159, Timeout exceeded: elapsed 2001 ms, maximum: 200 ms), not a correctness failure.
    • It is a set-operations (EXCEPT) test with no relationship to this PR's MergeTreeData outdated/unexpected-part loading change.
    • 30-day history: 3 PRs / 1 hit each (Add server setting additional_memory_tracking_per_thread #104965 via Fast test, Test set skip index OR with LowCardinality(Nullable) (issue #105938) #105990 via the same amd_tsan job, this PR), 0 master failures — scattered transient noise, below the chronic-flaky threshold.

The Mergeable Check and PR rollups are red solely because of that one flaky test; all other 141 checks passed. No PR-caused failures.

…utdated-parts-retryable-terminate

# Conflicts:
#	src/Common/FailPoint.cpp
…ectory

The outdated/unexpected part loaders requeue and reload a part when a
retryable error interrupts loading. That is safe while the part's on-disk
directory is still in place, but the broken-part (renameToDetached) and
duplicate (remove()) cleanup steps move the directory before returning:
rename updates the storage path only after moveDirectory, and remove renames
the directory to delete_tmp_ while leaving part_dir pointing at the original
name. A retryable disk/object-storage error thrown after that move leaves the
original path gone, so requeueing the part makes the retry reload a
moved/missing path. For duplicate cleanup a transient remove error then turns
into the broken-part path and a later terminate; for broken parts the retry
detaches the wrong path.

Fail fast for these side-effecting cleanup failures instead of requeueing, the
same way a genuinely inconsistent on-disk part already does. The directory has
already moved by then, so a restart reconciles it cleanly and does not loop.
The normal published-part cleanup (preparePartForRemoval) only writes the
removal TID and moves nothing, so it keeps the existing safe rollback+requeue
path.

Adds REGULAR failpoints that inject a retryable error right after the
directory-moving cleanup step in each loader, and integration cases asserting
the server fails fast (and does not log the reschedule line) for both the
outdated and unexpected loaders.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SYSTEM ENABLE FAILPOINT mergetree_load_outdated_parts_inject_post_cleanup_move_retryable_exception (or the unexpected variant) then DETACH/ATTACH fires a retryable error right after the part directory is moved, every run.
b Root cause explained? renameToDetached/remove move the part directory before returning (rename updates the storage path only after moveDirectory; remove renames to delete_tmp_ and leaves part_dir at the original name). A retryable error after that point leaves the original path gone, so requeueing my_part makes the retry reload a moved/missing path: duplicate cleanup turns a transient remove error into the broken-part path and a later terminate; broken parts re-detach the wrong path.
c Fix matches root cause? Yes. A cleanup_moved_directory flag is set right before the dir-moving step; a retryable error once it is set is rethrown as non-retryable CORRUPTED_DATA so the function-level catch fails fast (terminate) instead of requeueing. The no-move preparePartForRemoval path keeps the existing published-part rollback+requeue.
d Test intent preserved / new tests added? Yes. The 4 pre-existing cases still pass unchanged. Added 2 cases (outdated + unexpected loader) that assert fail-fast on a post-dir-move retryable error and that the reschedule-interrupt line does NOT appear.
e Both directions demonstrated? Yes (local debug build). Fixed binary: 6/6 pass. Fail-fast guards neutralised (failpoints kept): both new cases fail with assert 1 == 0 (requeue happened) and, for the outdated case, the log shows the transient-remove-becomes-later-terminate corruption you described.
f Fix is general, not a narrow patch? Yes. Covers BOTH loaders (loadOutdatedDataParts, loadUnexpectedDataParts) and BOTH directory-moving ops (renameToDetached, remove). The fix is at the requeue boundary (the source), not a guard at the throw site; the safe no-move path is left on its requeue path.

Session id: cron:clickhouse-worker-slot-0:20260617-170200

alexey-milovidov and others added 3 commits August 3, 2026 07:23
…error` swallowing them

Both part loaders detached a broken part with
`renameToDetached("broken-on-start", /*ignore_error=*/ replicated)`, and
`IMergeTreeDataPart::renameToDetached` swallows `ErrnoException` and
`fs::filesystem_error` when `ignore_error` is set. Those are exactly the
exception types a failing detach raises, and exactly the class
`isRetryableException` recognizes as transient (`ENOMEM`/`EMFILE`,
`ENOSPC`, `EROFS`, ...), so on a replicated table a transient detach
failure never reached the new retry-vs-fail-fast classification: the
worker fell through as if the cleanup had succeeded. In
`loadOutdatedDataParts` that left the broken part on its original path
with its ZooKeeper entry already removed by
`forcefullyRemoveBrokenOutdatedPartFromZooKeeperBeforeDetaching`, and
counted it as loaded; in `loadUnexpectedDataParts` it also set the
`finished` marker, so the rescheduled run skipped the part.

Both loader call sites now pass `ignore_error = false` so every detach
error is surfaced and classified. The tolerance `ignore_error` gave
replicated tables (a replica can re-fetch a part it failed to move into
`detached/`) is reproduced in the loaders themselves, but only after the
classification: a retryable error still reschedules before the move and
fails fast after it, and only a permanent `ErrnoException` /
`fs::filesystem_error` on a replicated table is logged and skipped, as
before.

The existing failpoints could not catch this because they throw a plain
`Exception`, which `renameToDetached` never swallowed. Added the
`REGULAR` failpoint
`mergetree_part_cleanup_inject_pre_move_swallowed_retryable_exception`,
which throws the swallowed `ErrnoException` type from the pre-move phase,
and a regression case per loader. Both fail on the previous code (the
outdated case logs no interrupt at all, the unexpected case retries 0
times instead of >= 3) and pass with the fix.
…omments

`Style check` / `catch_all` failed on 6943f31: the trailing `catch (...)`
of `isBestEffortDetachError` returns false without logging, rethrowing or
saving the exception, and the rule requires an explicit comment containing
`Ok` on such a block. The discard is correct here - the function only
classifies an exception its caller still owns and rethrows - so the resolution
is the comment, using the wording ClickHouse#113044 established for the same classifier
shape.

Also brought the comments this PR adds back within the <=3-lines-per-block
convention. Several blocks had grown across review rounds into rationale that
the commit messages and the linked issue already carry (why the pre/post-move
boundary exists, why only non-retryable errors may escape into a worker
future, what each injected failpoint models); those now state just the local
invariant a reader needs at that spot. 41 comment lines removed, no behavior
change. The blocks left over the budget are the ones 6943f31 added
minutes ago as its answer to a review thread, so they are left as written.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 025e727

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.

All 158 non-skipped check-runs on this head are success, including Style check and Fast test
(the Style check / catch_all red on the previous head 6943f31a0997 was PR-caused and is fixed
in this PR @ 025e727de3c43b6). One red row remains in CIDB:

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks build-telemetry infra: build_profile_hook.py -> LogCluster query failed with code 500 on the INSERT INTO build_time_trace. Non-blocking - the enclosing job is success, no build or test result is affected. 521 rows across 83 unrelated PRs in 7 days, 377 of them on master. a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260803-153000

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Dear @CheSema, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@PedroTadim

Copy link
Copy Markdown
Member

@CheSema can you review this PR to fix #106736 ?

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
Comment thread src/Common/FailPoint.cpp
ONCE(thread_group_switcher_post_attach_failure) \
PAUSEABLE(transaction_after_commit_pause) \
REGULAR(mt_mutate_task_can_skip_conversion_to_nullable_force_null_column_desc) \
REGULAR(mergetree_load_outdated_parts_inject_retryable_exception) \

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.

@groeneai do you need to add so many new failpoints in this PR?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fair question, and the answer is that they accreted one per review round rather than by design: 11 bot change-requests plus asks from @ CheSema and @ alexey-milovidov each needed a new deterministic injection point, and nothing ever went back to consolidate. 19 total (16 REGULAR + 3 PAUSEABLE).

I audited all 19 this morning. Each is enabled by at least one test case, so none is dead scaffolding. I also cannot merge the near-duplicates: SYSTEM ENABLE FAILPOINT parses a bare identifier (ParserSystemQuery.cpp:415-423) and enableFailPoint takes only the name, so there is no parameterization to fold them into. And both loaders are activated together in startOutdatedAndUnexpectedDataPartsLoadingTask (MergeTreeData.cpp:4041-4043), so a single shared name for the outdated and unexpected paths would fire in both concurrently and the test could no longer tell which path retried.

What I can cut is scope. 7 of the 19 serve the unexpected-parts loader, which is outside this PR's title and issue #106736. I can move those 7 and their 7 test cases into a follow-up PR, leaving 12 here. Want me to do that?

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 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: c809e251-de6e-4fac-ad90-91dbb4fdca11
  • MIRAI run: a2ab1580-4503-4bd0-a0aa-542a3a33fffe
  • PR check IDs:
    • clickbench_327388_1788015378
    • clickbench_327394_1788015378
    • clickbench_327400_1788015378
    • tpch_adapted_1_official_327411_1788015378
    • tpch_adapted_1_official_327422_1788015379
    • tpch_adapted_1_official_327459_1788015379

…er's Iceberg lines

Master changed `iceberg_compaction_merge_pause_in_step` from `PAUSEABLE_ONCE` to
`PAUSEABLE` and added `iceberg_compaction_pause_before_metadata_commit` right
where this pull request appends its fail points. Kept both sides: the 19 new
`mergetree_load_*` points and master's two Iceberg entries.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
{
std::lock_guard lock(unexpected_data_parts_mutex);
chassert(!load_state.part);
/// `finished` (not `part`) is the done-marker that keeps a rescheduled retry idempotent: the

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.

loadUnexpectedDataParts still does path-sensitive work without the table share lock that loadOutdatedDataParts now takes for the same relative_data_path invariant. Each worker builds DataPartStorageOnDiskFull from relative_data_path in loadUnexpectedDataPart, while MergeTreeData::rename can concurrently moveDirectory(relative_data_path, new_table_path) and only rewrites data_parts_by_info / relative_data_path under the exclusive table lock. DatabaseOnDisk::renameTable does not wait for unexpected-part loading before calling table->rename, and these in-flight unexpected parts are not in data_parts_by_info, so their storage roots are never updated.

In the broken-part branch that becomes a false corruption signal: after the rename, existsDirectory(original_relative_path) goes false simply because the whole table moved, so this catch rewrites the lifecycle race to CORRUPTED_DATA and hits the std::terminate() path. Can we give loadUnexpectedDataParts the same tryLockForShare + reschedule treatment as loadOutdatedDataParts, or otherwise stop/wait unexpected-part loading before rename moves relative_data_path?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I traced this. The asymmetry is real, but a share lock does not close the case that actually bites.

Agreed: loadUnexpectedDataParts takes no table lock, and MergeTreeData::rename only re-roots the parts in data_parts_by_info, which an in-flight unexpected part is not in.

Narrowings. DatabaseOnDisk::renameTable does take lockExclusively before table->rename; the gap is that the loader never takes the shared side, so that lock has nothing to wait on. DatabaseAtomic::renameTable never calls table->rename at all (metadata plus renameInMemory only), so relative_data_path does not move under an Atomic database. expected_parts is std::nullopt for StorageMergeTree, so unexpected parts imply a replicated table. And the missing lock is pre-existing, not introduced here: master's loadOutdatedDataParts already had lockForShare, loadUnexpectedDataParts never had one. So the carrier you describe needs a replicated table in an Ordinary database.

The wider carrier needs no rename at all. existsDirectory(original_relative_path) reading false is not positive evidence that this worker moved the directory, and the probe's own catch leaves the flag false, which the code then reads as "moved". On object storage that probe is a remote metadata call that can fail transiently by itself. isRetryableException treats ErrnoException with ENOMEM/EMFILE and filesystem_error with no_space_on_device/too_many_files_open as retryable, so a transient detach failure plus a failed probe becomes CORRUPTED_DATA and std::terminate(), where master swallowed both of those exception types via ignore_error = replicated.

Fix direction: probe the destination, not the source. DataPartStorageOnDiskBase::rename updates part_dir/root_path only after moveDirectory returns, so the detached directory's presence is positive evidence, while the source's absence is not. That closes both carriers without a table lock.

I am not making that change yet. Whether the unexpected-loader half belongs in this pull request is still open (#107091 (comment)), and this change lands with whichever pull request ends up owning that code.

@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 14cdd8062 with master 41b3bd68a (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of fb0b23675; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

44 object files changed (+136.40 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.06 MiB 4.09 MiB +36.21 KiB (+0.87%)
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.18 MiB 1.21 MiB +28.54 KiB (+2.36%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp.o 185.85 KiB 207.46 KiB +21.62 KiB (+11.63%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/DataPartStorageOnDiskBase.cpp.o 620.97 KiB 640.41 KiB +19.44 KiB (+3.13%)
src/CMakeFiles/clickhouse_common_io.dir/Common/FailPoint.cpp.o 362.17 KiB 379.12 KiB +16.95 KiB (+4.68%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 79850b6

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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) overrun, not caused by this PR: the pytest session timeout genuinely fired after 12121 s. The shard wrote 2 rows to the CI database, against 1197 / 1186 / 1687 / 1015 / 935 for its five siblings, and all five siblings are green with 0 test failures, so it died before reporting rather than failing a test #116591 (external, open)
Finish Workflow pure cascade of the row above, not an independent defect: all 102 DROPPED nodes name that one shard as their culprit, 0 unattributed, and the five Bugfix validation legs the hook reads were left skipped, so it reported them as not passed #116591 (external, open), the same owner as the row above
CH Inc sync private sync CH Inc sync (private, not actionable by me)

This PR cannot reach the shard death: the diff is 8 files confined to outdated-part loading
(MergeTreeData, DataPartStorageOnDiskBase, threadPoolCallbackRunner.h, FailPoint.cpp and
one integration test), and a session timeout is a capacity property of the shard, not of the diff.

Session id: cron:our-pr-ci-monitor:20260830-040000

The only conflict is the `ErrorCodes` declaration block, where master added
`TABLE_SIZE_LIMIT_EXCEEDED` and this branch added `DEADLOCK_AVOIDED`. Both are
used in the merged file, so both declarations are kept.

The `loadOutdatedDataParts` / `loadUnexpectedDataParts` loaders this branch
rewrites are untouched by master since the previous merge.

Same signature hit master again on 2026-09-02, now from the filesystem-cache
fault-injection failpoints BuzzHouse enables: a `FileSegment::write` failure
(`cache_filesystem_failure_non_errno` -> `MEMORY_LIMIT_EXCEEDED`, and
`cache_filesystem_failure` -> `CACHE_CANNOT_WRITE_TO_CACHE_DISK`) escapes
`loadDataPartWithRetries` once its retries are exhausted and reaches the
terminating `catch (...)`. Both codes are retryable per `isRetryableException`,
so this branch reschedules the loading task instead of terminating.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=cda48f97d9728a4601d8304ed7432c662e8849b4&name_0=MasterCI&name_1=BuzzHouse%20%28amd_msan%29

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

This is too complex.

@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed. The measurement backs it up: the first commit here was +96/-2 across three files (isRetryableException in the two loaders' catch (...), one failpoint, a 56-line test). The remaining +1714 came from 17 automated review rounds, each adding a narrower guard with its own failpoint and its own test case. When @ PedroTadim asked why there were 19 failpoints I answered that every one of them is used by a test, which is not an answer to "too many".

Cutting it back to the original shape:

  • DataPartStorageOnDiskBase.{cpp,h} and threadPoolCallbackRunner.h revert to master (86 added lines). The storage change is only a thread_local flag that arms three failpoints, so production code was carrying test plumbing. The runner change is unrelated hardening.
  • 19 failpoints down to 1: the one that injects the reported MEMORY_LIMIT_EXCEEDED into the outdated-parts loader.
  • The 1218-line integration test down to that scenario plus a non-retryable case that still fails fast.
  • Staying: the classification and the reschedule in both catch (...) blocks, which is what closes Stress test 'px != 0' residual: loadOutdatedDataParts terminate on transient MEMORY_LIMIT_EXCEEDED #106736. A retryable error in the narrow window after a part has already been published keeps today's fail-fast instead of getting a rollback path of its own, so the guards built for that window go with the rest.

Nothing else moves to a follow-up unless you ask for one. The one piece I will not decide alone is 6943f31a099, which is yours: part of the loader bookkeeping I am removing is what lets a detach error reach the loaders at all. I will keep your commit and the minimum bookkeeping it needs, so say the word if you want it out and this PR reduced to the terminate fix only.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, check #117981

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 18, 2026
…d parts

`MergeTreeData::loadOutdatedDataParts` wraps its body in `catch (...)`
that calls `std::terminate` to fail fast on an inconsistent set of parts
on disk. The same `catch` fired for transient errors that have nothing to
do with the parts: `MEMORY_LIMIT_EXCEEDED` from the memory tracker,
`TABLE_IS_BEING_RESTARTED` from `lockForShare` racing with
`SYSTEM RESTART REPLICA`, and permanent filesystem cache failpoints
enabled by BuzzHouse.

Take the table lock with `tryLockForShare` and reschedule the task when
the table is being dropped or restarted. In the per-part worker, catch
the exception from `loadDataPartWithRetries`: if `isRetryableException`
classifies it as retryable, put the part back into the queue and
reschedule the task with a backoff after all workers finish instead of
marking the loading finished. Non-retryable errors still terminate.

A simpler reimplementation of ClickHouse#107091.

Closes: ClickHouse#106736

Co-Authored-By: Claude Fable 5.1 <[email protected]>
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-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Stress test 'px != 0' residual: loadOutdatedDataParts terminate on transient MEMORY_LIMIT_EXCEEDED

4 participants