Skip to content

Make SYSTEM SYNC REPLICA and OPTIMIZE of ReplicatedMergeTree cancellable while they wait for the replication queue - #129283

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-replicated-wait-for-queue-cancellation
Nov 5, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-replicated-wait-for-queue-cancellation

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118476 (comment)

Changelog category (leave one):

  • Improvement

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

SYSTEM SYNC REPLICA and OPTIMIZE of a ReplicatedMergeTree table now stop waiting for the replication queue when the query is killed, when the server shuts down, or when max_execution_time is exceeded. Before, they kept waiting until receive_timeout (300 seconds by default), which also delayed server shutdown when such a query ran on the distributed DDL worker.

Description

Failure. 2 La Casa Del Dolor Server shutdown reds: PR 111932, arm_asan_ubsan and PR 128210, amd_debug. The main thread joins the DDL worker in DDLWorker::shutdown, while the worker runs OPTIMIZE ... PARTITION (111932) or SYSTEM SYNC REPLICA ... STRICT (128210) parked in StorageReplicatedMergeTree::waitForProcessingQueue, so the harness force-kills the server after 30 s.

Root cause. waitForProcessingQueue blocked on one Poco::Event for the whole timeout. Only the queue or the table's partialShutdown sets it, and the query's status was never checked. killAllQueries marks the DDL worker's query killed before DDLWorker::shutdown joins, but the wait ignores that, and tables are shut down only after the join. KILL QUERY and max_execution_time were ignored the same way.

Change. Wait in 1 s slices and call checkTimeLimit of the current query before each slice, as tryWaitForReplicaToProcessLogEntry (#113228) does. It checks in throw mode even with timeout_overflow_mode = 'break': the wait has no partial result, and the callers' timeout errors name receive_timeout. This covers every query that waits there: SYSTEM SYNC REPLICA, the merge selection retries of OPTIMIZE, and the two lightweight update waits. A refreshable view syncs its dependencies before its refresh query is registered, so that wait has nothing to check.

Validation. The new test fails on a master build, where the waits are still running 35 s after the kill or the time limit, and passes with the fix in ~8 s, also with random settings. With an OPTIMIZE ... ON CLUSTER parked in the DDL worker, SIGTERM took 270 s on a master build and 14 s with the fix.


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

Version info

  • Merged into: 26.11.1.1417-master (included in 26.11 and later)

groeneai and others added 2 commits November 4, 2026 13:22
`StorageReplicatedMergeTree::waitForProcessingQueue` blocked once on a
`Poco::Event` for the whole timeout. Only the replication queue or the
table's `partialShutdown` sets the event, and the query status was never
checked, so `KILL QUERY`, `max_execution_time` and server shutdown did not
stop `SYSTEM SYNC REPLICA` or the merge selection retries of `OPTIMIZE`
until `receive_timeout` had passed.

On shutdown, `killAllQueries` marks the distributed DDL worker's query
killed before `DDLWorker::shutdown` joins its thread, but the wait ignored
that and tables are shut down only after the join. La Casa Del Dolor then
force-killed the server (PR 111932 arm_asan_ubsan with `OPTIMIZE ...
PARTITION`, PR 128210 amd_debug with `SYSTEM SYNC REPLICA ... STRICT`).

Wait in 1 s slices and call `checkTimeLimit` of the current query before
each slice, as `tryWaitForReplicaToProcessLogEntry` and
`StorageMergeTree::waitForMutation` already do. This covers every caller:
`SYSTEM SYNC REPLICA`, `OPTIMIZE`, and the two lightweight update waits.

With an `OPTIMIZE ... ON CLUSTER` parked in the DDL worker, SIGTERM took
270 s before and 14 s after the change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Make the waitForProcessingQueue header line accurate for timeout_overflow_mode = 'break'.

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

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ❌ A coordinated refreshable view's dependency sync (RefreshTask.cpp:1477) can still hold shutdown DISAGREE (out of scope, separate PR) It runs before the refresh registers any query status (:1491-1511), so no wait at that point can be cancelled, including the non-replicated waitForLatestTargetTable; the fix belongs in RefreshTask. Unchanged by this PR; named in the description.
2 💡 Header comment says it always throws; break mode returns false AGREE fixed: header comment reworded
3 💡 Test discriminates by the wait_for_queries_to_finish 60 window (35-50 s measured) vs the unfixed 108-120 s wait AGREE noted, not blocking; the fixed server ends ~1 s after the kill

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05498_replicated_wait_for_queue_cancellable (r2 with stopped replication queues and a queued fetch) fails on every run of a master build: each of the three waits is still in system.processes 35 s after the kill or the 2 s max_execution_time. End to end: SIGTERM with an OPTIMIZE ... ON CLUSTER parked in the DDL worker took 270 s.
b Root cause explained? waitForProcessingQueue blocked once on a Poco::Event that only the queue or the table's partialShutdown sets, and never checked the query status. On shutdown killAllQueries marks the DDL worker's query killed before DDLWorker::shutdown joins, but the wait ignores it, and partialShutdown comes after the join.
c Fix matches root cause? Yes. The wait itself now checks QueryStatus::checkTimeLimit every second, the pattern of tryWaitForReplicaToProcessLogEntry (#113228) and StorageMergeTree::waitForMutation. No timeout or tag is changed.
d Test intent preserved / new tests added? New test with an arm per CI shape: OPTIMIZE merge selection retry (max_execution_time and KILL QUERY) and SYSTEM SYNC REPLICA (KILL QUERY).
e Both directions demonstrated? Master build: FAIL (337 s, all three arms). Fix: OK in ~6 s; 50/50 at 10 jobs and 50/50 at 50 jobs with random settings. Shutdown: 270 s vs 14 s, the DDL query ending 0.6 s after SIGTERM.
f Fix is general across code paths? One function serves all callers: SYSTEM SYNC REPLICA, OPTIMIZE retries, waitForCommittingOpsToFinish and DETACH PARTITION with lightweight updates, all in the query thread.
g Fix generalizes across inputs (params/datatypes/wrappers)? Timeout 0 still does one tryWait(0), other timeouts are still honoured in full, all sync modes share the loop (PULL returns before it), timeout_overflow_mode = 'break' returns false like a timeout. No data types involved.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only a killed or time-limited query now gets QUERY_WAS_CANCELLED / TIMEOUT_EXCEEDED instead of waiting.
i Invariants and contracts preserved? The subscription is still taken before waiting; handler is destroyed before the event on every exit, including the new throw; the auto-reset event keeps a set between slices; the OPTIMIZE locks unwind by RAII with no merge entry created; both error codes are non-retriable in DDLWorker::tryExecuteQuery; no process list means no check, as before.

Session id: cron:clickhouse-impl-slot-7:20261104-123500

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3775ddf]

Summary: ✅


AI Review

Summary

The PR makes replication-queue waits in ReplicatedMergeTree respond to query cancellation and max_execution_time, including timeout_overflow_mode = 'break', so blocked SYSTEM SYNC REPLICA and OPTIMIZE queries can also release the distributed DDL worker during shutdown. No actionable findings in commit 3775ddfd2307722b135cbe986296c352c3f8b0ff.

Missing context / blind spots
  • ⚠️ Latest-head CI is still running and targeted regression tests are pending. The regression test passed 50/50 runs under ASan/UBSan at the preceding commit 009f7422ac703cabf0f823048d60fa1c9e8fc433; the author reports 20/20 local runs after adding the break case. No local build or runtime tests were run during this review. Completion of the latest targeted CI job would independently validate the final revision.
Final Verdict

✅ Approve — no code changes requested; latest-head CI remains pending.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 4, 2026
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @PedroTadim, could you review this and add the can be tested label so CI runs? StorageReplicatedMergeTree::waitForProcessingQueue now waits in 1 s slices and checks the current query status, so KILL QUERY, max_execution_time and the killAllQueries of server shutdown stop SYSTEM SYNC REPLICA and the OPTIMIZE merge selection retries instead of waiting up to receive_timeout; this is the La Casa Del Dolor Server shutdown failure where DDLWorker::shutdown joined such a query.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. labels Nov 4, 2026
clang-tidy `google-runtime-int` rejects the explicit `static_cast<long>` in
the sliced `Poco::Event::tryWait` call (Build (arm_tidy)). The argument is at
most `cancellation_check_period_ms` (1000), so passing the `UInt64` directly,
as the pre-existing call did, is equivalent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3775ddfd2 with master 6398cafb6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 6e1a5e4e1; 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.

Compile time of recompiled translation units

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

Job report

@PedroTadim PedroTadim self-assigned this Nov 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

The loop looks right to me. Timeout 0 still makes a single tryWait(0), and the total wait is still max_wait_milliseconds. A set() that lands between two slices is kept by the auto-reset event, and handler unsubscribes on the new throw too. All four callers run in the query thread. The test tells the two builds apart, because on master wait_for_queries_to_finish prints the stuck process after 30 s.

One small thing about the error message. With timeout_overflow_mode = 'break', checkTimeLimit returns false, so waitForProcessingQueue reports a plain timeout and the callers turn that into their timeout error:

  • SYSTEM SYNC REPLICA throws TIMEOUT_EXCEEDED "command timed out. See the 'receive_timeout' setting", although max_execution_time stopped it;
  • DETACH PARTITION with lightweight updates throws "Failed to sync replica with timeout <receive_timeout>".

break is an odd mode for these statements, so this doesn't block the PR. But the message sends the user to the wrong setting. Could the slice loop throw TIMEOUT_EXCEEDED with the max_execution_time message in both modes, or could the callers name both settings?

…h overflow modes

With `timeout_overflow_mode = 'break'`, `QueryStatus::checkTimeLimit` returns
false, so `waitForProcessingQueue` returned false and its callers reported a
`receive_timeout` timeout: `SYSTEM SYNC REPLICA` said "See the
'receive_timeout' setting", `DETACH PARTITION` of a lightweight-update table
said "Failed to sync replica with timeout 300000", and `OPTIMIZE` skipped its
remaining merge selection retries and succeeded without merging.

The wait has no partial result to return, so check the limit in `THROW` mode:
all callers now fail with `TIMEOUT_EXCEEDED` "Timeout exceeded: elapsed ...,
maximum: ..." in both modes, and `false` again only means that
`max_wait_milliseconds` elapsed. `QueryStatus::checkTimeLimit(OverflowMode)`
is the existing check with the mode passed in.

Requested in ClickHouse#129283 (comment)

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

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. I took the first option in 3775ddf: the slice loop now calls checkTimeLimit(OverflowMode::THROW), a QueryStatus::checkTimeLimit overload that takes the mode instead of the query's timeout_overflow_mode. So false again means only that max_wait_milliseconds elapsed.

With max_execution_time = 2, timeout_overflow_mode = 'break', SYSTEM SYNC REPLICA, DETACH PARTITION on a lightweight-update table and OPTIMIZE ... PARTITION all fail after ~2 s with Timeout exceeded: elapsed 2010.398 ms, maximum: 2000.000 ms. One visible change for OPTIMIZE: with break it used to skip the remaining merge selection retries and return success without merging, now it throws the same error.

The test has a fourth arm for break on SYSTEM SYNC REPLICA (fails on the previous head, 20/20 with random settings now), and the description mentions it.


if (!target_entry_event.tryWait(max_wait_milliseconds))
return false;
QueryStatusPtr process_list_element;

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 just double checking. Canceling OPTIMIZE and replica sync could leave tables corrupted. Are you sure this is fine?

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.

Yes. The cancellation only ends the waiting query thread; the replication queue and the merges run in background threads and keep going.

  • SYSTEM SYNC REPLICA only waits. DETACH PARTITION (lightweight-update tables) and UPDATE with update_sequential_consistency already throw TIMEOUT_EXCEEDED right after this wait when receive_timeout expires, before they write a log entry or a patch part. So a killed query leaves the same state as a timed-out one on master, and the Keeper locks they hold are released by their destructors in both cases.
  • OPTIMIZE waits only after a failed merge selection, so the killed attempt has written nothing. With FINAL, merges already logged for earlier partitions stay in the log and every replica runs them, the same as after a kill in tryWaitForReplicaToProcessLogEntry, which master already allows.

I also checked it on this PR's CI debug build. r2 had stopped replication queues with fetches or a merge pending, and I killed each caller while system.stack_trace showed it in waitForProcessingQueue: SYNC REPLICA, OPTIMIZE PARTITION, OPTIMIZE FINAL (once with a merge for the other partition already logged), DETACH PARTITION and a lightweight UPDATE. Each ended with Code: 394 within 0.9 s. After SYSTEM START REPLICATION QUEUES r2 and SYNC REPLICA, both replicas had the same active parts and data, CHECK TABLE returned 1 on both, the queues were empty, a new insert replicated, re-running the DETACH and the UPDATE worked, and the server log had no LOGICAL_ERROR or broken part.

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 5, 2026
Merged via the queue into ClickHouse:master with commit bf8a735 Nov 5, 2026
185 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 5, 2026
@alexey-milovidov alexey-milovidov mentioned this pull request Nov 5, 2026
1 task done
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 12, 2026
…art on KILL QUERY

`StorageMergeTree::renameAndCommitEmptyParts` retries `PART_IS_TEMPORARILY_LOCKED` (an
outdated part with the name of the new empty part is waiting to be removed) with
`clearOldPartsFromFilesystem(); sleepForMilliseconds(200);` until `lock_acquire_timeout`,
and never looks at the query status. So `KILL QUERY`, `max_execution_time` and the
`killAllQueries` done at server shutdown had no effect for up to `lock_acquire_timeout`.

La Casa Del Dolor (amd_tsan) hit it as `Server shutdown`: an AST-fuzzer OPTIMIZE left a merged
part on a write-once disk that can be neither renamed nor removed, every later TRUNCATE of the
table retried for 120 s, and an ON CLUSTER TRUNCATE in the DDL worker kept
`DDLWorker::shutdown` joining past the 30 s stop window.

Check `QueryStatus::checkTimeLimit(OverflowMode::THROW)` at the retry point, like the waits of
ClickHouse#129283. It throws where the loop already throws on `lock_acquire_timeout`: the parts lock is
released, the new empty parts are only precommitted and are rolled back by the caller's
transaction, and no covered part has been removed, so the table is unchanged. `THROW` is passed
explicitly because there is no partial result for `timeout_overflow_mode = 'break'`.

The test reproduces it with `plain_object_storage_write_fail_on_directory_move` on a
`s3_plain_rewritable` disk: the failed OPTIMIZE leaves the outdated `all_1_1_1`, which TRUNCATE's
empty part collides with.

Co-Authored-By: Claude Opus 5.5 <[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 comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants