Repository navigation
Do not park a pipeline worker thread inside IProcessor::work in failpoint tests - #119030
Conversation
04512_distributed_limit_no_more_packets_race parked a PipelineExecutor worker inside IProcessor::work(): SYSTEM WAIT FAILPOINT ... PAUSE blocked RemoteQueryExecutor::read() on an unbounded condvar while the test cancelled and drained the connections from outside. src/Processors/ IProcessor.h states synchronous work() must only use CPU, no sleep, IO wait or network wait, and a parked work() holds a thread-pool slot for as long as the test takes to notice and resume it. The defect the test covers is a state, not an interleaving. The fix in ClickHouse#110334 lives in MultiplexedConnections::receivePacketUnlocked and HedgedConnections::receivePacketUnlocked: with !hasActiveConnections() and cancelled, return EndOfStream instead of throwing LOGICAL_ERROR "No more packets are available.". A reader only has to arrive at receivePacket with the connections cancelled and drained; which thread produced that state is irrelevant. So a single non-blocking ONCE failpoint now calls finish() inline at the same point - the exact call RemoteSource::onUpdatePorts() makes - and the reader continues into the fixed predicate on its own thread. was_cancelled_mutex is not held there (the injection sits between two LockAndBlocker scopes) and finish() takes it itself. Both of its exits reach cancelled && !hasActiveConnections(): the drain loop invalidates each replica on EndOfStream, and the drain_was_skipped branch disconnects them. This deletes both PAUSEABLE_ONCE failpoints, the second pause site in finish() and the in_receive_packet_window member that existed only to keep the two parks paired. The test drops LIMIT 1 and max_block_size=1: with the cancel injected in place, a LIMIT could satisfy itself and cancel both executors before either reader entered the loop, so the failpoint would never fire, whereas without a LIMIT both readers must enter it and the injection sits at the top before the first receivePacket. The system.text_log positive control is replaced by reading `enabled` from system.fail_points before and after the query with no DISABLE in between: 1 then 0 can only happen through a fire, while `enabled = 0` alone is also what an un-armed failpoint reads. Both use_hedged_requests values are kept because each connection class carries its own copy of the fixed predicate. Reported by @Michicosun on ClickHouse#110334. Co-Authored-By: Claude Opus 5 <[email protected]>
The mid-loop failpoint in AggregatingInOrderTransform::consume() existed so that test_aggregating_in_order_transform_kill_query could issue KILL QUERY while the transform sat between key intervals. It parked a PipelineExecutor worker inside IProcessor::work() on an unbounded condvar, which src/Processors/IProcessor.h forbids: synchronous work() must only use CPU, no sleep, IO wait or network wait. The external actor only performed a cancellation, so the failpoint now performs that same cancellation in place: Context::killCurrentQuery() is what KILL QUERY itself reaches (ProcessList::sendCancelToQuery -> QueryStatus::cancelQuery(CANCELLED_BY_USER)), and calling it on the query's own thread is an existing pattern (src/Server/HTTPHandler.cpp). Nothing it takes is held by a worker during work(): cancelQuery() takes cancel_mutex, snapshots the executors under executors_mutex and releases that before cancelling each one, and PipelineExecutor::cancel() is an atomic status update plus tasks.finish() plus ExecutingGraph::cancel() under processors_mutex, which is only taken in updatePipeline()/removeGroup() after work() has returned. This transform does not override onCancel(). The interval-5 guard stays, so the cancel still lands mid-loop and the next iteration's isCancelled() check logs "Cancelled between key intervals" exactly once. The test keeps all three of its existing assertions and its QUERY/table/settings, drops the thread and the pool that only served the pause protocol, and gains a bracketed system.fail_points `enabled` 1 -> 0 oracle so a run in which the failpoint never fired cannot pass. Reported by @Michicosun on ClickHouse#110334. Co-Authored-By: Claude Opus 5 <[email protected]>
… output formats Both output formats had a mid-row-loop pause failpoint so that their kill-query tests could issue KILL QUERY while the format was halfway through writing a chunk to the wire. IOutputFormat::consume() runs inside IProcessor::work(), so the park was an unbounded condvar wait in a frame whose contract (src/Processors/IProcessor.h) allows only CPU work. Both sites now inject the same cancellation the tests used to send from outside, via Context::killCurrentQuery() on the query's own thread; the row loop's own per-row isCancelled() check then throws QUERY_WAS_CANCELLED on the next iteration, exactly as before. The lock analysis is the one in the previous commit, and neither format overrides onCancel(). Both tests keep every existing oracle verbatim, because they are protocol-specific and already correct: MySQL keeps rows_seen == CANCEL_AT_ROW + 1 (the per-row check is at the top of the loop, so the row the hook fires on is still sent), PostgreSQL keeps asserting NetworkSendBytes == 0 on its ExceptionWhileProcessing row instead of a row count because psycopg2 buffers execution, and both keep the system.processes count, the QUERY_WAS_CANCELLED log assertion and the single-chunk check. Only the mechanism changes: the thread, the ThreadPoolExecutor, the WAIT FAILPOINT block and the KILL QUERY are gone, and a bracketed system.fail_points `enabled` 1 -> 0 oracle is added. Neither protocol lets a client supply a query id, and both tests used to read the server-assigned one from system.processes while the query was parked. With nothing parked, the id now comes from the ExceptionWhileProcessing row in system.query_log after a flush, and is asserted non-empty before the assertions that depend on it. Reported by @Michicosun on ClickHouse#110334. Co-Authored-By: Claude Opus 5 <[email protected]>
…ndow Both Delta Lake sinks paused in their commit window (data files finalized, delta_transaction->commit not yet called) so that test_write_cancel_during_commit_keeps_data could KILL the INSERT while the commit was in flight. SinkToStorage::onFinish() runs under ExceptionKeepingTransform::work(), so the park violated the IProcessor contract that synchronous work() may only use CPU. Both sites now call Context::killCurrentQuery() in place, at exactly the same point, which is the same cancellation KILL QUERY delivers; the lock analysis is the one two commits back, and neither sink overrides onCancel(). The injection point is unchanged on purpose: the behaviour under test is that the post-commit clearing of the tracked sinks runs with the query already cancelled, so a late cancel has no tracked buffers left to unlink and the Delta log cannot end up pointing at removed data files. The test keeps its post-condition assertions verbatim for both `partitioned` values (the committed rows are readable and at least one parquet survives) and drops the thread, the WAIT FAILPOINT, the KILL QUERY, the ASYNC-kill sleep and the NOTIFY that only served the pause protocol. A bracketed system.fail_points `enabled` 1 -> 0 oracle replaces them, so a run in which the cancel never fired fails instead of passing on assertions a plain successful INSERT also satisfies. Reported by @Michicosun on ClickHouse#110334. Co-Authored-By: Claude Opus 5 <[email protected]>
04162_system_cancel_view_during_refresh used the infinite_sleep failpoint to hold a refresh alive until SYSTEM CANCEL VIEW arrived. That site is inside FunctionSleep::execute, reached through ExpressionTransform::work(), and it sits before sleep()'s max_microseconds bound check and before its sliced wait loop, so it bypassed exactly the machinery that keeps sleep() from occupying a worker indefinitely. src/Processors/IProcessor.h forbids waiting inside work() at all. Here the rendezvous is a duration, not an action, so it cannot be injected in place; it moves to a thread that is allowed to wait. What the test needs is a cancel that finds a live, published executor, which is what the asserted "Cancelling refresh in <db>.<view>" line requires, and that state already exists on the RefreshTask (BackgroundSchedulePool) thread before any worker starts: the executor is constructed and initialized, published to execution.executor under executor_mutex, that mutex is released, the clearing SCOPE_EXIT is registered, and only then does executor.execute() run. A new PAUSEABLE_ONCE failpoint parks in that gap. interruptExecution() can therefore take executor_mutex and cancel; cancelling a not-yet-started executor is explicitly supported by PipelineExecutor::cancel, and interruptExecution() also kills the refresh query, so the released executor.execute() unwinds and the post-pipeline interrupt re-check raises the QUERY_WAS_CANCELLED the test asserts on. The two existing refresh_mv_pause_* failpoints could not be reused: both sit after executor.execute() has returned, where the SCOPE_EXIT has already cleared execution.executor, so interruptExecution() is a no-op there and the asserted log line is never written. Because no pipeline runs while parked, the test drops sleepEachRow(0) and the max_block_size / max_threads settings it needed, and drops the read_rows > 0 wait: progress can no longer be observed, and the property it stood in for (the cancel has a concrete pipeline to interrupt) is now guaranteed by where the failpoint fires. `wait_status c Running` replaces it as the "the parked refresh is ours" check. All three assertions are kept verbatim, and a bracketed system.fail_points `enabled` 1 -> 0 oracle is added so a run that never parked fails instead of passing vacuously. Reported by @Michicosun on ClickHouse#110334. Co-Authored-By: Claude Opus 5 <[email protected]>
The park sits between the executor's publication and executor.execute(), so the refresh owns a live executor that has not run yet and read_rows must be 0. Nothing in the test observed that. Every other assertion holds equally if the park moves to after executor.execute() returns: execution.executor is still published there, so "Cancelling refresh in <db>.c" is still logged, and execution.interrupt_execution still raises QUERY_WAS_CANCELLED on the post-pipeline re-check. The previous commit dropped the merged test's read_rows > 0 wait because progress can no longer be observed once no pipeline runs while parked. Its mirror image is observable, and is what belongs here. The value is stable rather than racy: execution.progress.reset() is the first statement of executeRefreshUnlocked, the same call that parks, and SYSTEM WAIT FAILPOINT PAUSE has already returned when the value is read, so the refresh thread is provably parked and nothing can advance the counter. Verified by moving the park to immediately after executor.execute(), inside the same block: the new line goes 0 -> 1 while the three original columns stay 1 1 1, so it is the only assertion that sees that placement. Moving the park before the publication instead reddens only the third column, so the two directions now bracket the placement. Reported by @Michicosun on ClickHouse#110334. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex) plus my own cold read of the resulting
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20260909-120800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260909-060300 |
|
Workflow [PR], commit [7e77e46] Summary: ✅
AI ReviewSummaryThis PR rewrites several failpoint-based regression tests so they no longer park a Findings
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 7e77e46.
Changed lines: Changed C/C++ lines covered: 72/72 (100.00%) · Uncovered code |
|
cc @KochetovNicolai @tuanpach, could you review this? Seven test failpoints parked a |
| # No LIMIT: with the cancel injected in place, a LIMIT could satisfy itself and cancel both | ||
| # executors before either reader entered the loop, so the failpoint would not fire at all. | ||
| # Parallel replicas force `use_hedged_requests` off, which would leave HedgedConnections | ||
| # untested; `prefer_localhost_replica=0` makes both shards go through RemoteQueryExecutor. | ||
| if ! $CLICKHOUSE_CLIENT \ | ||
| --use_hedged_requests="$use_hedged_requests" --enable_parallel_replicas=0 \ | ||
| --async_socket_for_remote=0 --max_block_size=1 --prefer_localhost_replica=0 \ | ||
| --query "SELECT x FROM ${CLICKHOUSE_DATABASE}.dist LIMIT 1 FORMAT Null" 2>"$err" & | ||
| QPID=$! | ||
|
|
||
| # A failed wait would leave the interleaving unsynchronized, and the plain LIMIT query could | ||
| # then succeed and log the cancellation, so check both. | ||
| sync_ok=1 | ||
| for fp in "$FP_RECV" "$FP_DRAIN"; do | ||
| if ! $CLICKHOUSE_CLIENT --query "SYSTEM WAIT FAILPOINT $fp PAUSE" 2>"$err"; then | ||
| echo "wait for failpoint $fp failed:" | ||
| cat "$err" | ||
| failed=1 | ||
| sync_ok=0 | ||
| fi | ||
| done | ||
|
|
||
| # Release the reader onto the drained, cancelled connections, then release `finish`. | ||
| $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FP_RECV" | ||
| $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FP_DRAIN" | ||
|
|
||
| # The query must succeed: without the fix a debug build aborts the server, while a release | ||
| # build returns the LOGICAL_ERROR to the client, which the exit status below turns into a | ||
| # failure independently of the output diff (a bare "if ! wait" is not itself an assertion). | ||
| if ! wait "$QPID"; then | ||
| --async_socket_for_remote=0 --prefer_localhost_replica=0 \ | ||
| --query "SELECT x FROM ${CLICKHOUSE_DATABASE}.dist FORMAT Null" 2>"$err" |
There was a problem hiding this comment.
This change stops exercising the LIMIT-driven caller path that actually triggers the user-visible race. With SELECT ... FORMAT Null the output port never finishes early, so RemoteSource::onUpdatePorts() no longer reaches query_executor->finish() (src/Processors/Sources/RemoteSource.cpp:250); the test now covers only the artificial inline finish() from the failpoint inside RemoteQueryExecutor::read().
That means a regression in the getPort().isFinished() -> finish() wiring for distributed LIMIT queries would bring the original behavior back while this test stayed green. Please keep a focused oracle on the LIMIT path as well, even if the failpoint itself has to remain non-blocking.
There was a problem hiding this comment.
Checked this against the code and measured it before deciding. Conceding the observation, declining the remedy, with the numbers.
Correct: the arm no longer drives RemoteSource::onUpdatePorts(). Dropping the LIMIT was deliberate.
The path is a race, so it does not make an oracle. With LOG_TRACE markers on both finish() call sites, a plain SELECT x FROM dist LIMIT 1 (two shards, async_socket_for_remote=0, prefer_localhost_replica=0, max_block_size=1, distributed_push_down_limit=0) reached onUpdatePorts() -> finish() in 10 of 30 runs and produced the observable Cancelling query because enough data has been read in 8 of 30. A 50 run batch on another binary of the same source gave 33 of 50, while every LIMIT 1500 shape gave 0 of 50, which is also the probe's positive control. Whether the remote executor is still live when the output port closes is timing, so an assertion on it is flaky somewhere between 27% and 66%, and the rate moves with build and load. The determinism the merged test had came from the park: it asserted the cancel only after SYSTEM WAIT FAILPOINT ... PAUSE returned, which is what made the executor live at that moment. Removing that park is the whole point of this PR, so the two requirements are mutually exclusive.
The stated consequence does not hold. I built a binary that skips query_executor->finish() in onUpdatePorts() (env gated; the skip fired for 98 of 200 queries, so the mutation was live) and ran 200 distributed LIMIT queries across both use_hedged_requests values: 0 failures, no No more packets are available., server alive. Two reasons. The concurrent finish() is this bug's trigger rather than its guard, so removing it removes the race instead of restoring it. And the wiring is redundant: RemoteSource::work()'s need_drain branch (src/Processors/Sources/RemoteSource.cpp:129-132) calls finish() for the same port-closed condition, and with onUpdatePorts() disabled it carried the early cancel for 15 of those 200 queries, log line included.
That also rules out the weaker form of the ask: since all 200 succeeded with the branch disabled, an arm asserting only that a distributed LIMIT query succeeds cannot fail on this wiring.
What the arm does assert is the fix predicate itself, and both halves are load-bearing: reverting the MultiplexedConnections hunk aborts the debug server on the logical error, and reverting only the HedgedConnections hunk leaves the first arm green and aborts the second at src/Client/HedgedConnections.cpp:404.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units74 translation units recompiled, 780 s compile time in total, 74 of them have a recent master baseline. |
3b04f85
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Follow-up to the review request on #110334 (comment).
Seven
PAUSEABLEfailpoints sat at sites reachable fromIProcessor::work(), soSYSTEM WAIT FAILPOINT ... PAUSEblocked aPipelineExecutorworker on an unbounded condvar untilthe test cancelled from outside and released it.
src/Processors/IProcessor.hstates that synchronouswork()must only use CPU, no sleep, IO wait or network wait, and a parkedwork()holds athread-pool slot for as long as the test takes to act.
Each rendezvous is replaced by injecting, on the same thread, the exact action the external actor
performed, so nothing waits inside
work():04512_distributed_limit_no_more_packets_race: the defect is a state, not an interleaving, so onenon-blocking
ONCEfailpoint runsfinish()inline inRemoteQueryExecutor::read()(whatRemoteSource::onUpdatePorts()calls). Deletes bothPAUSEABLE_ONCEfailpoints, the second pausesite and the
in_receive_packet_windowmember.KILL QUERYtests (AggregatingInOrderTransform, the MySQL and PostgreSQL output formats,both DeltaLake sinks): the failpoint calls
Context::killCurrentQuery(), which is whatKILL QUERYitself reaches, at the same point.04162_system_cancel_view_during_refresh: itsinfinite_sleeprendezvous is a duration, not anaction, so it moves off the pipeline. A new
refresh_mv_pause_after_executor_publishedparks therefresh (
BackgroundSchedulePool) thread after the executor is published andexecutor_mutexreleased, but before it starts, which is where
interruptExecutioncan cancel it. The two existingrefresh_mv_pause_*failpoints could not be reused: both sit afterexecutor.execute()returned,where
execution.executoris already cleared.Every test keeps its existing oracles and gains a bracketed
system.fail_pointsenabled1 -> 0check, so a run in which the failpoint never fired fails instead of passing. Net: 6
PAUSEABLE_ONCEregistrations removed, 5
ONCEand 1PAUSEABLE_ONCEadded; tests lose ~200 lines of pause protocol.Audit of the tests I committed since 2026-05-08 (the second half of the ask)
Criterion: tests of mine that arm a
PAUSEfailpoint, then whether the paused C++ site isreachable from a
work()/tryGenerate()/onFinish()/onUpdatePorts()frame.105 pauseable failpoints registered; 74 armed by some test; 64 test files arm one; 15 of those
carry a commit of mine since 2026-05-08; 9 failpoints in 8 of them have an in-
work()site.remote_query_executor_receive_packet_pauseremote_query_executor_finish_drain_pauseaggregating_in_order_transform_mid_loop_pausetest_aggregating_in_order_transform_kill_querymysql_output_format_mid_loop_pausetest_mysql_protocol/test_kill_query.pypostgresql_output_format_mid_loop_pausetest_postgresql_protocol/test_kill_query.pydelta_lake_write_commit_pausetest_storage_delta(both sinks)infinite_sleepinfinite_sleep03100_lwu_57_lock_acquire_timeoutrmt_pause_before_commit_local_part04905_lwu_drop_race_table_lockreplicated_merge_tree_insert_retry_pause03916_system_fault_injection_pointsThe two follow-up ones need a query-thread rendezvous on the lightweight-update lock path: two new
production failpoints plus a 582-line test, so a separate review. The relocation was found for both.
The remaining 6 of the 15 arm a
PAUSEfailpoint whose site I traced to a non-pipeline thread(
runWritingJobpool,initializePipeline, SchedulePool streaming tasks, the RefreshTask thread).Coverage note, unchanged here: 04512 exercises only the synchronous read path
(
async_socket_for_remote=0), as the merged test did.Workflow [PR]
Sync PR [sync-upstream/pr/119030]