Skip to content

Fix hang of a synchronous replica wait when the table is shutting down or the query is cancelled - #113228

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-alter-sync-wait-shutdown-cancel
Aug 5, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-alter-sync-wait-shutdown-cancel

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 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):

Fixed a hang of ALTER, OPTIMIZE, TRUNCATE and partition manipulation statements with alter_sync = 2 on ReplicatedMergeTree when the table starts shutting down while the statement waits for another replica, for example because of a concurrent DROP DATABASE ... SYNC. Such a statement now fails with UNFINISHED and also honours max_execution_time and KILL QUERY.

Description

Found by the Stress test (arm_release) hung check on #113023 (report), not caused by it: a TRUNCATE ... SYNC and a DROP DATABASE ... SYNC from 00623_replicated_truncate_table_zookeeper_long were stuck for 2937 s, with five more DDL queries queued behind them.

Root cause. In tryWaitForReplicaToProcessLogEntry the only shutdown escape of the wait predicate was waiting_itself && (partial_shutdown_called || shutdown_prepared_called || shutdown_called). With alter_sync = 2 waiting on a remote replica waiting_itself is false, so the local shutdown flags could not break the wait, while DROP DATABASE ... SYNC calls flushAndPrepareForShutdown, after which the other replica's queueUpdatingTask stops pulling the log and the awaited entry is never processed. The other escapes are unreachable there: the inactive-replica check needs that replica's is_active node gone, but it is removed only in partialShutdown, and is_dropped is set only after the drop that is blocked completes. The loop consulted no QueryStatus either, so cancellation was ignored.

Change. shutdown_prepared_called and shutdown_called are now checked independently of waiting_itself, since they are terminal latches after which no replica will process the entry. partial_shutdown_called stays local-only: it is reset when the ZooKeeper session is restored. The wait now also calls QueryStatus::checkTimeLimit, as the sibling waitMutationToFinishOnReplicas already does. Failures stay visible as UNFINISHED.

Validation. SYSTEM STOP PULLING REPLICATION LOG gives a deterministic repro. On master the statement hangs, KILL QUERY ... SYNC hangs too, and the concurrent DROP DATABASE ... SYNC deadlocks; with the fix all three return within seconds. New test 04740_alter_sync_wait_shutdown_and_cancel passes 50/50 with randomized settings; reverting either half of the change alone reddens only its own assertion.

Version info

  • Merged into: 26.8.1.820 (included in 26.8 and later)

…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.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
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
re-reviewed it in a separate pass. Round 1 raised one test-side issue, which was fixed; round 2
is clean. Verdicts below.

# Severity Finding Verdict
❌ 1 major 04740 needed no-replicated-database. Under --replicated-database, DatabaseReplicated::checkTableEngine rewrites the literal replica argument to r2auto_{replica} (the ZooKeeper path carries only {database}, which is not a distinguishing macro), so arm 3's oracle, which greps the literal replicas r2 to process entry, cannot match. The runner strips only the unexpanded auto_{replica} token, so it cannot normalize this away. AGREE, fixed. Tag added with a reason comment, following 04337_quorum_insert_honors_time_limit.sql. The oracle was deliberately NOT weakened: r2 is the part of the message that proves the wait was for the remote replica.
⚠️ 2 nit Arm 3 drops the runner-owned primary database, which the post-test SHOW TABLES FROM <db> step would then fail on. DISAGREE (self-refuted while verifying). That step sits behind self.case_file >= "02800", and case_file is an absolute path, so the comparison is '/...' >= '02800' = false. Dead code for every test in the repo, and the cleanup DROP uses IF EXISTS.
💡 3 nit Comment density in the source diff. DISAGREE. 15 added src/ lines: 4 comment, 11 code; largest block 2 lines. All state local invariants, and the process-list comment is byte-identical to the sibling at StorageReplicatedMergeTree.cpp:755.

Independently re-verified beyond the findings: every writer of the three shutdown flags
(partial_shutdown_called is reset on ZooKeeper session restore, the other two are terminal
latches with no reset in src/, which is why only those two are ungated); that throwing out of
stop_waiting is pre-existing behaviour, since the predicate already calls
getZooKeeper()->exists; that all 13 wait carriers pass a readonly gate or run without a query
context; and that max_execution_time is 0 by default and absent from the settings randomizer,
so the cancellation half only changes behaviour where a limit was explicitly requested.

Gate cost: $22.08 across 4 rounds (2 design, 2 code).

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SYSTEM STOP PULLING REPLICATION LOG r2, then TRUNCATE ... SETTINGS alter_sync = 2, replication_wait_for_inactive_replica_timeout = -1. The blocker makes pullLogsToQueue throw ABORTED before advancing log_pointer while r2's is_active node survives, which is the CI shape. Hangs 100% of runs on master, no concurrency needed.
b Root cause explained? Yes. The wait predicate's only shutdown escape was waiting_itself && (partial_shutdown_called || shutdown_prepared_called || shutdown_called), and waiting_itself is false when alter_sync = 2 waits on a remote replica. DROP DATABASE ... SYNC calls flushAndPrepareForShutdown, so the remote replica stops pulling the log and the entry is never processed. The inactive-replica escape needs an is_active node that only partialShutdown removes, is_dropped is set only after the blocked drop finishes, and the loop consulted no QueryStatus, so max_execution_time and KILL QUERY were ignored.
c Fix matches root cause? Yes. It removes the incorrect waiting_itself gate from the two terminal latches and adds the cancellation check the sibling waitMutationToFinishOnReplicas already performs. No widened bound, no added timeout, no test tag.
d Test intent preserved / new tests added? Yes. New 04740_alter_sync_wait_shutdown_and_cancel covers all three arms (timeout, KILL QUERY, concurrent DROP DATABASE ... SYNC). 00623_replicated_truncate_table_zookeeper_long is unchanged and green, reference untouched.
e Both directions demonstrated? Yes, on Build-ID-verified binaries with the server's buildId() asserted before each verdict. Master: statement hung (is_cancelled = 1 at elapsed 442 s), KILL ... SYNC hung, DROP DATABASE ... SYNC deadlocked. With the fix: TIMEOUT_EXCEEDED in 7 s, KILL returned in 3 s with QUERY_WAS_CANCELLED, DROP completed in 3 s with the statement reporting UNFINISHED. Reverting each half alone reddens only its own arm, so neither assertion is vacuous.
f Fix is general across code paths? Yes. The single predicate is the funnel for all eight alter_sync statement paths through waitForLogEntryToBeProcessedIfNecessary (OPTIMIZE, ALTER metadata, DROP PART, DROP/TRUNCATE PARTITION, REPLACE PARTITION, MOVE PARTITION), and covers all four uses of the lambda in the function including the waitForDisappear predicate. The other two stop_waiting lambdas in the file already have their own timeouts and are untouched. SharedMergeTree derives this method and inherits the fix. waitMutationToFinishOnReplicas has the same shutdown blindness for mutations_sync = 2 but is killable, so it cannot produce this hang and is left to a separate change.
g Fix generalizes across inputs? No type, format or value handling is touched, so type wrappers do not apply. The relevant axis is settings, and it is covered: alter_sync = 2 remote wait, alter_sync = 1 local wait (already escaped, now also cancellable), replication_wait_for_inactive_replica_timeout negative and default, and both cancellation reasons.
h Backward compatible? Yes. No setting added and no default changed, so no SettingsChangesHistory.cpp entry. The only visible change is that a statement which previously waited forever now returns UNFINISHED, which already means "some replicas did not finish".
i Invariants and contracts preserved? Yes. stop_waiting remains a pure predicate over atomics plus one ZooKeeper existence check, evaluated with no lock held at all four call sites. Throwing out of it is a pre-existing supported path: ZooKeeper::waitForDisappear evaluates the condition lock-free with no catch and already throws KeeperException from that loop. An exception now aborts the loop over remaining replicas instead of collecting them into unwaited, which is correct for cancellation and matches the mutation path. A table left read-only by a failed shutdown throws TABLE_IS_READ_ONLY from assertNotReadonly before the wait is reached, so no spurious UNFINISHED is possible there; this was observed live.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @tavplubix, could you review this? An alter_sync = 2 wait for a remote replica could never be broken by the local shutdown flags, because the only shutdown escape in tryWaitForReplicaToProcessLogEntry was gated on waiting_itself, so a concurrent DROP DATABASE ... SYNC deadlocked against the statement it had just made unsatisfiable, and the loop consulted no QueryStatus, so KILL QUERY was a no-op.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [edca5e2]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_msan, WasmEdge, parallel, 1/2) ERROR IGNORED

AI Review

Summary

This PR fixes a real hang in ReplicatedMergeTree synchronous replica waits by letting tryWaitForReplicaToProcessLogEntry observe local shutdown latches during remote waits and by checking QueryStatus so max_execution_time and KILL QUERY can break the wait. I re-checked the current diff, the surrounding wait logic, the waitForDisappear carrier, the updated shell coverage, the prior discussion, and the current all-green CI report for PR #113228; I did not find any remaining correctness or test gaps that still warrant an inline finding.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 14/14 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
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.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed af8f025, which addresses the test gap. The blocker itself does not hold.

The blocker: waitForDisappear does evaluate stop_waiting on every poll.

ZooKeeper::waitForDisappear is a do-while (src/Common/ZooKeeper/ZooKeeper.cpp:1415-1430). The continue at :1420 on the tryWait timeout path jumps to the controlling expression at :1430, not to the top of the body, so stop_waiting runs on every 1000 ms poll with no watch event needed. That is what continue means inside a do-while.

I checked it three ways rather than only by reading:

  1. A standalone reproduction of that exact loop shape with the timeout path always taken prints body_iters=3 cond_evals=3 under clang 21 at -O0 and -O2, and under gcc: the condition ran on every timeout iteration.
  2. On the exact carrier the review calls unreachable (r2's queue stopped, the entry present in r2's queue, and the server log line Waiting for queue-N to disappear from r2 queue confirming the third stage), with this change: max_execution_time = 5 gives Code: 159 at elapsed 5039 ms, KILL QUERY ... SYNC returns in 3 s and the query ends with Code: 394, and DROP DATABASE ... SYNC completes in 2 s while the waiting TRUNCATE gets Code: 341.
  3. The same scenario on pristine master: KILL QUERY itself does not return within 60 s, and the query is still running at elapsed 71 s with is_cancelled = 1. So the third-stage escape is precisely what this change adds.

The test observation was right, and is now fixed.

SYSTEM STOP PULLING REPLICATION LOG does keep log_pointer from advancing: measured, r2's log_pointer stayed at 1 and only Waiting for r2 to pull log-N to queue appeared, so the test covered the first wait stage only. The new third arm lets r2 pull the entry into its queue and blocks execution instead, which sends the wait into waitForDisappear.

One detail worth naming, since the obvious oracle is unsound: waiting for log_pointer > log_max_index would not prove this query's entry was copied, because log_pointer is the maximum copied entry plus one and may point at an entry that does not exist yet (src/Storages/StorageReplicatedMergeTree.cpp:4037). The arm instead reads the log size once the TRUNCATE is already waiting, so its entry is counted, and waits for log_pointer to pass that number. Checked by mutation: with SYSTEM START PULLING REPLICATION LOG removed, so the entry cannot reach the queue, the arm fails rather than passing. 10 consecutive runs pass with it in place.

I did not change waitForDisappear. Making that primitive re-check its condition differently would alter behaviour for every caller, and the measurements above show the current semantics already deliver cancellation and shutdown at this call site.

groeneai and others added 2 commits August 4, 2026 16:13
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]>
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
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
re-reviewed it in a separate pass, each round. Rounds 1 and 2 each raised one test-side issue,
both fixed; round 3 is clean on both passes. Verdicts below.

# Severity Finding Verdict
❌ 1 major 04740 needed no-replicated-database. Under --replicated-database, DatabaseReplicated::checkTableEngine rewrites the literal replica argument to r2auto_{replica} (the ZooKeeper path carries only {database}, which is not a distinguishing macro), so arm 3's oracle, which greps the literal replicas r2 to process entry, cannot match. The runner strips only the unexpanded auto_{replica} token, so it cannot normalize this away. AGREE, fixed. Tag added with a reason comment, following 04337_quorum_insert_honors_time_limit.sql. The oracle was deliberately NOT weakened: r2 is the part of the message that proves the wait was for the remote replica.
❌ 2 major Arm 3's gate sampled log_max_index AFTER wait_for_truncate returned. That helper returns when the statement appears in system.processes, which happens before the interpreter creates the log node, so the sample could still be the previous maximum; since log_pointer is max-copied plus one, a replica already caught up satisfied the predicate immediately and the arm could issue its KILL QUERY while the wait was still in stage 1, silently degenerating into a copy of arm 2 and losing the waitForDisappear coverage it exists to provide. AGREE, fixed in edca5e2. The maximum is now sampled BEFORE the statement starts and polled until it advances, which proves this statement's entry exists and names it; only then does the arm wait for log_pointer to pass that number. Measured: with only the cancellation term reverted, the arm goes red at the stage-3 site, KILL QUERY ... SYNC timing out at 120 s with the statement never returning, against 1 s and Code: 394 on the fix. The stage-3 server log line is observed before the KILL QUERY is issued, and a negative control without SYSTEM STOP REPLICATION QUEUES also reddens.
💡 3 nit Arm 4 drops the runner-owned primary database, which the post-test SHOW TABLES FROM <db> step would then fail on. DISAGREE. Re-derived rather than carried over from the earlier round: that step sits behind self.case_file >= "02800" and case_file is an absolute path (os.path.join on os.path.abspath(args.queries)), so the comparison is false for every test in the repo, and the cleanup DROP uses IF EXISTS. Safe, though by a quirk of that comparison rather than by design.
💡 4 nit Comment density in the source diff. DISAGREE. 15 added src/ lines: 4 comment, 11 code; largest block 2 lines. All state local invariants, and the process-list comment is byte-identical to the sibling at StorageReplicatedMergeTree.cpp:755.

Independently re-verified beyond the findings, by census rather than by reading around the diff:
every writer of the three shutdown flags (partial_shutdown_called is reset on ZooKeeper session
restore at ReplicatedMergeTreeRestartingThread.cpp:247, the other two are terminal latches with
no reset anywhere in src/, which is why only those two are ungated); that waitForDisappear
evaluates the predicate on every 1000 ms poll, since its continue sits inside a do-while;
that the one background caller, PartMovesBetweenShardsOrchestrator, runs on a schedule-pool
thread with no query ThreadGroup, so process_list_element is null there and that guard is
load-bearing; and that max_execution_time and timeout_overflow_mode are absent from the
settings randomizer (186 settings enumerated) and unset by the always-installed limits.yaml, so
the cancellation half only changes behaviour where a limit was explicitly requested.

Gate cost: $38.41 across 7 rounds (4 design, 3 code).

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate for the follow-up test-only commit (click to expand)

Scope: 04740's fourth arm asserted a specific replica list. 1 file, +5/-2, src/ and the reference untouched.

# Question Answer
a Deterministic repro? Yes, two ways. A text probe drives the old and new pipelines with the exact messages from the failing and passing CI runs, and a server-level injection additionally stops r1's log pulling so r1 must join the unwaited list, producing the r1, r2 shape on demand. No sampling.
b Root cause explained? Yes. The server threw the expected Code: 341 UNFINISHED in both failing runs, naming replicas r1, r2, while the grep required the literal replicas r2. unwaited is filled by a loop over all replicas including the local one, and DROP DATABASE ... SYNC sets shutdown_prepared_called on both tables, so r1 legitimately joins the list when the latch is set before r1's own wait completes. The escape worked; only the assertion was wrong.
c Fix matches root cause? Yes. The oracle now asserts the property under test rather than which replica lost a race. No no-flaky-check, no no-random-*, no widened bound, no arm removed, tag line untouched.
d Test intent preserved? Yes, measured. Code: 341, the exact wording and r2's membership are all still required. Six negative controls stay rejected: a list of only r1, r3, an empty list, Code: 394, and the substring traps r21 and xr2. The canonicalising sed runs only on lines the membership check already accepted, so it cannot manufacture a pass.
e Both directions demonstrated? Yes, at server level on one Build-ID-verified binary against one injected state: old oracle reddens with exactly the CI diff (last reference line missing), new oracle is green. Text level: 3/3 positives byte-equal to the reference, 6/6 negatives empty.
f General across code paths? Yes. grep -rln "waiting for replicas" tests/queries/0_stateless/ matches only this test. Arms 1 to 3 assert Code: 159 and Code: 394, neither of which carries a replica list.
g General across inputs? Yes. Accepts r2, r1, r2 and r2, r1: the order is genuinely unspecified, since unwaited follows raw getChildren order over an absl::flat_hash_set and getChildren does not sort. Pinning the two observed orders would have reintroduced the same flake class.
h Backward compatible? Yes. Test-only. No setting, no SettingsChangesHistory.cpp, no format change.
i Invariants preserved? Yes. No source change, and the reference file is byte-identical, so no other arm's expectations move.

--test-runs 50 on the debug build: 50 passed, 0 failed.

Pre-PR validation gate for the second follow-up test-only commit (click to expand)

Scope: 04740's third arm gated on a log maximum sampled after the statement had already
started, so it could complete in the first wait stage and silently duplicate arm 2.
1 file, +32/-10, src/ and the reference untouched.

# Question Answer
a Deterministic repro? Yes. An isolated replay of arm 3 (same statement, same SYSTEM START PULLING REPLICATION LOG / STOP REPLICATION QUEUES, arm 1 and 2 leftovers reproduced with alter_sync = 0) runs the arm on demand and prints before, entry_index, r2's log_pointer, and which wait stages the server reached. No sampling.
b Root cause explained? Yes. wait_for_truncate returns when the statement appears in system.processes (executeQuery.cpp:1622), which is before the interpreter creates the /log/log-N node (StorageReplicatedMergeTree.cpp:10244), so the value read afterwards can still be the previous maximum. log_pointer is the maximum copied entry plus one (ReplicatedMergeTreeQueue.cpp:940), so a replica already caught up to that maximum satisfied the predicate immediately, the KILL QUERY was issued in stage 1, and the waitForDisappear coverage the arm exists for was lost while the arm stayed green.
c Fix matches root cause? Yes. The pre-statement maximum is captured first and its advance is what proves this statement's entry exists and names it; the arm then requires r2 to have copied that specific number. No arm removed, no bound widened, no no-random-*, tag line untouched.
d Test intent preserved? Yes, measured by mutation. With only the query_cancelled term reverted from stop_waiting (latch re-association kept), the arm goes red: KILL QUERY ... SYNC times out at 120 s and the statement never returns. With the fix restored, identical fixture, it is green in 1 s with Code: 394. Query was cancelled. Both runs reached stage 3, so the red is specifically the missing cancellation escape at the waitForDisappear site. Note the FULL test cannot deliver this verdict: the same mutation removes max_execution_time enforcement inside the wait, so arm 1 hangs and the suite times out before arm 3 runs.
e Both directions demonstrated? Yes. Mutant f833b7aeb307b2be red, fix 7de37127d8360975 green, on identical fixtures, each with the server's buildId() verified equal to the binary's Build ID. Restore was byte-exact (md5sum match against a git show HEAD: snapshot, Build ID returned to its prior value).
f General across code paths? Yes. The defect was specific to arm 3's gate; arms 1, 2 and 4 do not sample the replication log. The other two polling loops in the file (wait_for_truncate, arm 4's) key on system.processes and on the statement's own output, neither of which has this before/after ambiguity.
g General across inputs? Yes. entry_index is read from the observed log_max_index rather than computed as before + 1, so an interval that adds more than one entry (addOpsToDropAllPartsInPartition runs once per partition) is handled. Both loops keep the existing bound and each has a distinctive timeout diagnostic, so a future regression surfaces as a reference diff, not a 600 s suite timeout.
h Backward compatible? Yes. Test-only. No setting, no SettingsChangesHistory.cpp, no format change.
i Invariants preserved? Yes. No source change; the reference file is byte-identical, so no other arm's expectations move. Stage 3 was directly observed before the cancellation (Waiting for queue-0000000003 to disappear from r2 queue), which the previous round asserted only indirectly.

A negative control confirms the arm is not passing for an unrelated reason: with
SYSTEM STOP REPLICATION QUEUES r2 removed, r2 executes the entry, the wait completes on
its own and the arm reddens.

--test-runs 50 --long-test-runs-ratio 1 on the debug build: 50 passed, 0 failed.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - edca5e2

CI fully finished on this head: 174 of 174 check-runs completed (156 success, 17 skipped,
1 failure), 0 queued or in progress, Config Workflow and Finish Workflow both green,
past the 20-minute CIDB ingestion buffer.

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.

Check / test Reason Owner / fixing PR
Stateless tests (amd_msan, WasmEdge, parallel, 1/2) job timeout, not a test failure: Job timed out: [Stateless tests (amd_msan, WasmEdge, parallel, 1/2)], timeout [9000], exit code [-15], killed at 9022s. Zero [ FAIL ] test rows in the job log; the shard's own results were still being written when the budget expired capacity defect in this job's shard count, not this PR. A fix task is in progress at full effort (fixing-PR link to follow on this PR). Its partial companion, which stops finished results being discarded when a job is killed in teardown, is #113200 (mine, open)
Build (arm_release) / Post Hooks build-profile telemetry INSERT INTO build_time_trace got LogCluster query failed with code 500. The build itself passed: the job's check_status is success and the check-run concluded success, so it gates nothing infra, not this PR. A fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)

Neither failure is attributable to this PR's diff. The WasmEdge shard ran for the full 9000s
budget without a single failing test, and the errors preceding the kill are all
teardown-side resource exhaustion against the shared log-collection endpoint
(Too many parts, TOO_MANY_SIMULTANEOUS_QUERIES), not query results. This PR's own
functional coverage passed everywhere else, including Stateless tests (amd_msan, WasmEdge, parallel, 2/2) and both sequential shards of the same build.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113228&sha=edca5e220e43b0506f2e8cb6d645d47106dd7e0a&name_0=PR

Session id: cron:our-pr-ci-monitor:20260805-023000

@PedroTadim PedroTadim self-assigned this Aug 5, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 5, 2026
Merged via the queue into ClickHouse:master with commit 002a604 Aug 5, 2026
178 of 180 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 5, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Sep 19, 2026
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]>
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 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