Repository navigation
Fix hang of a synchronous replica wait when the table is shutting down or the query is cancelled - #113228
Conversation
…llation
The Stress test (arm_release) hung check showed a TRUNCATE TABLE ... SYNC and a
DROP DATABASE ... SYNC from 00623_replicated_truncate_table_zookeeper_long stuck
for 2937 seconds, with five further DDL queries queued behind the database DDL
guard. Both principals were already cancelled (is_cancelled = 1), so
max_execution_time and four KILL QUERY attempts had all been ignored.
In tryWaitForReplicaToProcessLogEntry the only shutdown escape of the wait
predicate was
waiting_itself && (partial_shutdown_called || shutdown_prepared_called || shutdown_called)
and waiting_itself is false whenever alter_sync = 2 waits on a remote replica.
DROP DATABASE ... SYNC takes the database DDL guard and calls
flushAndPrepareForShutdown on the tables, after which the remote replica's
queueUpdatingTask early-returns on is_readonly && shutdown_prepared_called and
never pulls the awaited log entry. Every other disjunct is unreachable in that
window: stop_waiting_inactive needs the remote replica's is_active node to be
gone, but that node is removed only in partialShutdown, which is not on the
flushAndPrepareForShutdown path, so replication_wait_for_inactive_replica_timeout
can never fire either; and is_dropped is set only after table->drop() returns,
which is exactly what is blocked. The wait also consulted no QueryStatus, so
cancellation could not break it.
Check the two terminal latches independently of waiting_itself. Both
shutdown_prepared_called and shutdown_called are exchange(true) latches that are
never reset, so once either is set no replica of the table will process the
entry and waiting for a remote one cannot succeed.
partial_shutdown_called stays gated on waiting_itself because
ReplicatedMergeTreeRestartingThread resets it when the ZooKeeper session is
restored; ungating it would turn a recoverable disconnect into a spurious
UNFINISHED. Also capture the QueryStatus and call the throwing checkTimeLimit in
the predicate, mirroring waitMutationToFinishOnReplicas, so max_execution_time
raises TIMEOUT_EXCEEDED and KILL QUERY raises QUERY_WAS_CANCELLED instead of
being collapsed into a misleading UNFINISHED. Failures stay visible: the replica
lands in unwaited and the statement reports UNFINISHED, never fake success.
One predicate covers all eight alter_sync statement paths, since they all funnel
through waitForLogEntryToBeProcessedIfNecessary. waitMutationToFinishOnReplicas
has the same shutdown blindness for mutations_sync = 2, but it is killable and so
cannot produce this hung check; it is left to a separate change.
The new test uses SYSTEM STOP PULLING REPLICATION LOG, which makes pullLogsToQueue
throw ABORTED before advancing log_pointer while the replica's is_active node
survives, reproducing the CI shape deterministically without a timing race. It
asserts all three arms: max_execution_time, KILL QUERY, and a concurrent
DROP DATABASE ... SYNC. Reverting either half of the change alone reddens only
its own arm.
The test creates two replicas with literal names r1 and r2 sharing one
ZooKeeper path, and its third arm asserts the replica name back out of the
server error message.
Under --replicated-database, DatabaseReplicated::checkTableEngine rewrites the
literal replica argument to r2auto_{replica} because the engine path carries
only the {database} macro, which Macros::expand records as expanded_database and
not expanded_other, so the early return for a path that already distinguishes
replicas does not fire. registerStorageMergeTree then expands that argument, so
the ZooKeeper replica name is r2auto_<...> and the asserted text never matches.
The runner's normalization strips only the unexpanded auto_{replica} token, so
it cannot rescue an expanded name inside an error message.
Keep the assertion, which is what proves the wait was for the remote replica,
and skip the incompatible job instead.
Internal second-model review (2 rounds, 0 open findings)An independent reviewer read the change cold (without the author's evidence) and a second model
Independently re-verified beyond the findings: every writer of the three shutdown flags Gate cost: $22.08 across 4 rounds (2 design, 2 code). |
Pre-PR validation gate (click to expand)
|
|
cc @CheSema @tavplubix, could you review this? An |
|
Workflow [PR], commit [edca5e2] Summary: ❌
AI ReviewSummaryThis PR fixes a real hang in Final VerdictStatus: ✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 14/14 (100.00%) · Uncovered code |
The AI review pointed out that the test only exercised the first of the three wait stages in tryWaitForReplicaToProcessLogEntry. SYSTEM STOP PULLING REPLICATION LOG keeps the entry out of the replica's log_pointer, so the wait always returned from the first loop and the final waitForDisappear call on the queue node was never reached. The new arm lets r2 pull the entry into its queue and blocks execution instead, which sends the wait into waitForDisappear. It waits for this TRUNCATE's own entry to be copied, by reading the log size once the query is already waiting (so the entry is counted in it) and then waiting for log_pointer to pass that number. A plain log_pointer > log_max_index comparison would not do, because the pointer is the maximum copied entry plus one and may point at an entry that does not exist yet, so the arm could silently fall back to covering the first stage. Measured on the third stage specifically, with the entry in r2's queue and the "Waiting for queue-N to disappear from r2 queue" message confirming the stage: pristine master ignores KILL QUERY (the KILL itself does not return within 60 s and the query is still running at elapsed 71 s with is_cancelled = 1), while with this change KILL returns in 2 s and the query ends with QUERY_WAS_CANCELLED. max_execution_time and DROP DATABASE were checked on the same stage and behave the same way. The arm was also checked by mutation: with SYSTEM START PULLING REPLICATION LOG removed, so that the entry cannot reach the queue, it fails. The blocker the review raised alongside this does not hold: waitForDisappear uses a do-while, so the continue on the tryWait timeout path jumps to the loop condition and stop_waiting is evaluated on every poll.
|
Pushed af8f025, which addresses the test gap. The blocker itself does not hold. The blocker:
I checked it three ways rather than only by reading:
The test observation was right, and is now fixed.
One detail worth naming, since the obvious oracle is unsound: waiting for I did not change |
The new test failed 2 of 10 runs of Stateless tests (amd_debug, flaky check). Every other flavour was 10/10, and the only difference was the last reference line being absent. The server threw the expected UNFINISHED in both failing runs. It named "replicas r1, r2" while the test's grep required the literal "replicas r2", so the oracle could not match its own success. Arm 4 drops the database, which sets shutdown_prepared_called on both tables, and the fixed predicate breaks the wait for whichever replica is still being waited on when the latch flips. Whether r1 lands in the unwaited list is a race between that latch and r1's own wait completing: run waiting for r1 prepare for shutdown 341 list e7m4m0m1h3v5 14:51:26.311 14:51:26.127 before r1, r2 f2w7l8m4w1n3 14:51:26.068 14:51:25.956 before r1, r2 g2l3v8a4g2j2 14:51:26.376 14:51:27.255 after r2 v4l0p3p9q8c2 14:51:25.307 14:51:26.141 after r2 z1g9e4v3q5e3 14:51:26.159 14:51:27.328 after r2 In both failures the latch was already set before r1's wait started, so r1 went straight into the unwaited list. That is the intended behaviour of the fix, not a defect, and the DROP DATABASE never deadlocked. Only the assertion was wrong. Require r2 to be a whole-token member of the list in any order and canonicalise the list, so the reference stays byte-identical. The order is not fixed either: unwaited follows the raw getChildren order, which comes from an absl::flat_hash_set in CompactChildrenSet and is not sorted by getChildren, so pinning the two orders I happened to observe would reintroduce the same flake. The oracle still requires Code: 341, the exact wording, and r2 in the list. It rejects a list of only r1, an unexpected replica, an empty list, a different error code, and the substring traps r21 and xr2.
The gate sampled log_max_index after wait_for_truncate returned. That function returns when the TRUNCATE appears in system.processes, which happens before the interpreter runs, while the log node is created inside the interpreter. The sampled value could therefore still be the previous maximum, and since log_pointer is the maximum copied entry plus one, a replica already caught up to that maximum satisfied the predicate immediately. The arm then issued its KILL QUERY while the wait was still in the first stage, silently degenerating into a copy of the second arm and losing the waitForDisappear coverage it exists to provide. Sample the maximum before the statement starts and wait for it to advance, which proves this statement's entry exists and names it, then wait for the replica's log_pointer to pass that number. Keying on entry type alone would not work: the earlier arms leave entries in the queue that KILL QUERY does not remove. Validated by removing the cancellation term from stop_waiting and observing the arm go red (KILL QUERY SYNC times out, the statement never returns), which it was not required to do before. The stage-3 server log line is now observed before the KILL QUERY is issued. 50 randomized runs pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Internal second-model review (3 rounds, 0 open findings)An independent reviewer read the change cold (without the author's evidence) and a second model
Independently re-verified beyond the findings, by census rather than by reading around the diff: Gate cost: $38.41 across 7 rounds (4 design, 3 code). |
Pre-PR validation gate for the follow-up test-only commit (click to expand)Scope:
Pre-PR validation gate for the second follow-up test-only commit (click to expand)Scope:
A negative control confirms the arm is not passing for an unrelated reason: with
|
CI finish ledger - edca5e2CI fully finished on this head: 174 of 174 check-runs completed (156 success, 17 skipped, Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Neither failure is attributable to this PR's diff. The WasmEdge shard ran for the full 9000s Session id: cron:our-pr-ci-monitor:20260805-023000 |
002a604
Arm 4 of 04740_alter_sync_wait_shutdown_and_cancel parks an unlimited alter_sync = 2 TRUNCATE, drops the database and requires the parked statement to give up with UNFINISHED naming the remote replica. It waited only for that statement's process list row, which is inserted before the interpreter runs, so a DROP issued right after it can reach flushAndPrepareForShutdown while the TRUNCATE is still in truncate()'s preamble. The statement is then refused with TABLE_IS_READ_ONLY, never enters the replica wait, and the arm loses its last line. The query_log rows of the two failing CI runs whose artifacts survive show exactly that: ExceptionBeforeStart with Code: 242, 297 ms and 421 ms in. The server is right in both interleavings, so only the oracle was interleaving-specific. Gate the DROP on the statement's own log entry instead, the instrument arm 3 already uses. That entry is created by a single tryMulti which runs after both readonly assertions, and neither is re-evaluated afterwards, so once the shared log's maximum has advanced past its pre-statement value the refusal is unreachable for that statement. The log-maximum poll is factored out of arm 3 into log_maximum/wait_for_log_entry and used by both arms; the oracle, the normalisation and the reference file are unchanged. Also print the error the parked statement did report when the arm's expected timeout does not arrive, so a lost interleaving shows up as a differing line instead of a missing one. Finding out that the missing line meant Code: 242 otherwise takes the job's query_log artifact. Measured with a 300-partition copy of the arm, whose extra block-number allocations widen the row-to-entry window from 0.089 s to 1.96 s: it fails 10/10 without the gate, passes 10/10 with it and fails 10/10 with the gate neutered. A deterministic one-partition control shows the baseline sample must be taken before the statement starts. The test itself passes 50 sequential and 50 eight-way-parallel randomized runs, and arm 3's output is byte-identical before and after the refactor. Related: ClickHouse#113228 Co-Authored-By: Claude Opus 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a hang of
ALTER,OPTIMIZE,TRUNCATEand partition manipulation statements withalter_sync = 2onReplicatedMergeTreewhen the table starts shutting down while the statement waits for another replica, for example because of a concurrentDROP DATABASE ... SYNC. Such a statement now fails withUNFINISHEDand also honoursmax_execution_timeandKILL QUERY.Description
Found by the
Stress test (arm_release)hung check on #113023 (report), not caused by it: aTRUNCATE ... SYNCand aDROP DATABASE ... SYNCfrom00623_replicated_truncate_table_zookeeper_longwere stuck for 2937 s, with five more DDL queries queued behind them.Root cause. In
tryWaitForReplicaToProcessLogEntrythe only shutdown escape of the wait predicate waswaiting_itself && (partial_shutdown_called || shutdown_prepared_called || shutdown_called). Withalter_sync = 2waiting on a remote replicawaiting_itselfis false, so the local shutdown flags could not break the wait, whileDROP DATABASE ... SYNCcallsflushAndPrepareForShutdown, after which the other replica'squeueUpdatingTaskstops pulling the log and the awaited entry is never processed. The other escapes are unreachable there: the inactive-replica check needs that replica'sis_activenode gone, but it is removed only inpartialShutdown, andis_droppedis set only after the drop that is blocked completes. The loop consulted noQueryStatuseither, so cancellation was ignored.Change.
shutdown_prepared_calledandshutdown_calledare now checked independently ofwaiting_itself, since they are terminal latches after which no replica will process the entry.partial_shutdown_calledstays local-only: it is reset when the ZooKeeper session is restored. The wait now also callsQueryStatus::checkTimeLimit, as the siblingwaitMutationToFinishOnReplicasalready does. Failures stay visible asUNFINISHED.Validation.
SYSTEM STOP PULLING REPLICATION LOGgives a deterministic repro. On master the statement hangs,KILL QUERY ... SYNChangs too, and the concurrentDROP DATABASE ... SYNCdeadlocks; with the fix all three return within seconds. New test04740_alter_sync_wait_shutdown_and_cancelpasses 50/50 with randomized settings; reverting either half of the change alone reddens only its own assertion.Version info
26.8.1.820(included in26.8and later)