Repository navigation
Make SYSTEM SYNC REPLICA and OPTIMIZE of ReplicatedMergeTree cancellable while they wait for the replication queue - #129283
Conversation
`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]>
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).
Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20261104-123500 |
|
Workflow [PR], commit [3775ddf] Summary: ✅
AI ReviewSummaryThe PR makes replication-queue waits in Missing context / blind spots
Final Verdict✅ Approve — no code changes requested; latest-head CI remains pending. |
|
cc @tavplubix @PedroTadim, could you review this and add the |
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units229 translation units recompiled, 1971 s compile time in total, 229 of them have a recent master baseline. |
|
🕵️ @groeneai The loop looks right to me. Timeout 0 still makes a single One small thing about the error message. With
|
…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]>
|
Thanks. I took the first option in 3775ddf: the slice loop now calls With The test has a fourth arm for |
|
|
||
| if (!target_entry_event.tryWait(max_wait_milliseconds)) | ||
| return false; | ||
| QueryStatusPtr process_list_element; |
There was a problem hiding this comment.
@groeneai just double checking. Canceling OPTIMIZE and replica sync could leave tables corrupted. Are you sure this is fine?
There was a problem hiding this comment.
Yes. The cancellation only ends the waiting query thread; the replication queue and the merges run in background threads and keep going.
SYSTEM SYNC REPLICAonly waits.DETACH PARTITION(lightweight-update tables) andUPDATEwithupdate_sequential_consistencyalready throwTIMEOUT_EXCEEDEDright after this wait whenreceive_timeoutexpires, 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 intryWaitForReplicaToProcessLogEntry, 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.
…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]>
Related: #118476 (comment)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
SYSTEM SYNC REPLICAandOPTIMIZEof aReplicatedMergeTreetable now stop waiting for the replication queue when the query is killed, when the server shuts down, or whenmax_execution_timeis exceeded. Before, they kept waiting untilreceive_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 DolorServer shutdownreds: PR 111932, arm_asan_ubsan and PR 128210, amd_debug. The main thread joins the DDL worker inDDLWorker::shutdown, while the worker runsOPTIMIZE ... PARTITION(111932) orSYSTEM SYNC REPLICA ... STRICT(128210) parked inStorageReplicatedMergeTree::waitForProcessingQueue, so the harness force-kills the server after 30 s.Root cause.
waitForProcessingQueueblocked on onePoco::Eventfor the whole timeout. Only the queue or the table'spartialShutdownsets it, and the query's status was never checked.killAllQueriesmarks the DDL worker's query killed beforeDDLWorker::shutdownjoins, but the wait ignores that, and tables are shut down only after the join.KILL QUERYandmax_execution_timewere ignored the same way.Change. Wait in 1 s slices and call
checkTimeLimitof the current query before each slice, astryWaitForReplicaToProcessLogEntry(#113228) does. It checks inthrowmode even withtimeout_overflow_mode = 'break': the wait has no partial result, and the callers' timeout errors namereceive_timeout. This covers every query that waits there:SYSTEM SYNC REPLICA, the merge selection retries ofOPTIMIZE, 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 CLUSTERparked 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
26.11.1.1417-master(included in26.11and later)