Skip to content

Do not park a pipeline worker thread inside IProcessor::work in failpoint tests - #119030

Merged
Michicosun merged 6 commits into
ClickHouse:masterfrom
groeneai:no-pause-inside-processor-work
Sep 10, 2026
Merged

Michicosun merged 6 commits into
ClickHouse:masterfrom
groeneai:no-pause-inside-processor-work

Conversation

@groeneai

@groeneai groeneai commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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 PAUSEABLE failpoints sat at sites reachable from IProcessor::work(), so
SYSTEM WAIT FAILPOINT ... PAUSE blocked a PipelineExecutor worker on an unbounded condvar until
the test cancelled from outside and released it. src/Processors/IProcessor.h states that 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 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 one
    non-blocking ONCE failpoint runs finish() inline in RemoteQueryExecutor::read() (what
    RemoteSource::onUpdatePorts() calls). Deletes both PAUSEABLE_ONCE failpoints, the second pause
    site and the in_receive_packet_window member.
  • Four KILL QUERY tests (AggregatingInOrderTransform, the MySQL and PostgreSQL output formats,
    both DeltaLake sinks): the failpoint calls Context::killCurrentQuery(), which is what
    KILL QUERY itself reaches, at the same point.
  • 04162_system_cancel_view_during_refresh: its infinite_sleep rendezvous is a duration, not an
    action, so it moves off the pipeline. A new refresh_mv_pause_after_executor_published parks the
    refresh (BackgroundSchedulePool) thread after the executor is published and executor_mutex
    released, but before it starts, which is where interruptExecution can cancel it. The two existing
    refresh_mv_pause_* failpoints could not be reused: both sit after executor.execute() returned,
    where execution.executor is already cleared.

Every test keeps its existing oracles and gains a bracketed system.fail_points enabled 1 -> 0
check, so a run in which the failpoint never fired fails instead of passing. Net: 6 PAUSEABLE_ONCE
registrations removed, 5 ONCE and 1 PAUSEABLE_ONCE added; 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 PAUSE failpoint, then whether the paused C++ site is
reachable 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.

failpoint test disposition
remote_query_executor_receive_packet_pause 04512 fixed here (deleted)
remote_query_executor_finish_drain_pause 04512 fixed here (deleted)
aggregating_in_order_transform_mid_loop_pause test_aggregating_in_order_transform_kill_query fixed here
mysql_output_format_mid_loop_pause test_mysql_protocol/test_kill_query.py fixed here
postgresql_output_format_mid_loop_pause test_postgresql_protocol/test_kill_query.py fixed here
delta_lake_write_commit_pause test_storage_delta (both sinks) fixed here
infinite_sleep 04162 fixed here
infinite_sleep 03100_lwu_57_lock_acquire_timeout follow-up PR
rmt_pause_before_commit_local_part 04905_lwu_drop_race_table_lock follow-up PR
replicated_merge_tree_insert_retry_pause 03916_system_fault_injection_points armed, never reached: no park occurs

The 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 PAUSE failpoint whose site I traced to a non-pipeline thread
(runWritingJob pool, 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]

groeneai and others added 6 commits September 9, 2026 07:38
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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 9, 2026
@groeneai

groeneai commented Sep 9, 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) plus my own cold read of the resulting
tree, adjudicated against the recorded mutation matrix. 6 findings over two review rounds and one fix
round; the independent re-review of the fixed tree returned no findings.

# Sev Finding Verdict Evidence / action
1 ⚠️ 04162 does not observe the placement it claims: moving the new failpoint to after executor.execute(), still before the clearing SCOPE_EXIT, leaves every assertion green, because execution.executor is still published so Cancelling refresh in <db>.c is still logged, and the interrupt flag still raises QUERY_WAS_CANCELLED AGREE, fixed The test now reads read_rows from system.view_refreshes while parked and pins it to 0. execution.progress.reset() is the first statement of executeRefreshUnlocked and SYSTEM WAIT FAILPOINT ... PAUSE has already returned, so the refresh thread cannot advance the counter: the value is stable, not racy. A new mutation arm moves the park to after executor.execute() and reddens exactly that line while the three original columns stay 1 1 1, so the placement is now bracketed from both sides (the existing arm moves it before the publication and reddens the third column)
2 ❌ 04512 no longer proves the injected finish() cancels and drains the connections: if finish() left connection state unchanged, the FORMAT Null query would succeed and every assertion would still pass DISAGREE The necessary step, "the query succeeds", is measured false in both arms. With the MultiplexedConnections hunk reverted the use_hedged_requests=0 arm makes the debug build abort on the LOGICAL_ERROR No more packets are available.; with only the HedgedConnections hunk reverted, arm 0 passes and arm 1 aborts at HedgedConnections.cpp:404 with the stack receivePacketUnlocked <- receivePacket <- RemoteQueryExecutor::read() right after the injection <- readBlock <- RemoteSource::tryGenerate <- ISource::work(). So query success is load-bearing on the fixed predicate in each connection class independently. The implication is also closed in code: reaching the injection means was_cancelled was just observed false and isQueryPending() is true, so finish() takes its full path, and if a sibling thread had set was_cancelled first its early branch disconnects, reaching the same state; the unconditional receivePacket() below is the only exit
3 ⚠️ The Delta Lake test cannot distinguish a cancel inside the vulnerable commit window from one arriving after the tracked sinks were already cleared DISAGREE The proposed mutation (hook moved after data_files.clear() / partitions_data.clear()) would equally have passed the merge-base test: this change replaces the action at that line, not the location, so the hook sits exactly where the pause sat, after the data files are finalized and before delta_transaction->commit. The gap is therefore inherited, and it belongs to the late-cancel contract of #109311 rather than to this change, whose contract is that nothing waits inside work(). The remedy asked for would add production observability of a sink's internal tracking collection, which is outside the reported problem. What this change does strengthen there is measured: the cancel is now delivered synchronously before the commit instead of racily by an async KILL QUERY plus a sleep, and un-arming the failpoint reddens the substantive oracle for both partitioned values
4 💡 05060_distributed_sync_insert_cancel_does_not_wait also drives a PAUSE failpoint and is not changed here AGREE, noted Correct and deliberate: writeSync reaches runWritingJob only through pool->scheduleOrThrowOnError, with no inline path, so that park is on a DistributedInsertThreads pool thread and no pipeline worker parks in it. While the job is parked the pipeline thread does sit in consume() -> writeSync() -> waitForJobs(), but that wait is the production behaviour of distributed_foreground_insert=1 and is not introduced by the failpoint, so there is nothing to change. Stated in the linked review thread so it does not have to be asked
5 💡 The audit's informal list of the same shape in tests by other authors is not exhaustive AGREE, noted Two more exist (infinite_sleep driven by 04095, which also predates the four-month window, and system_replicas_schedule_requests_pause driven by 04627). Both belong to other authors, so neither is in scope for this change and no such list is published here; the audit table above covers only my own tests, which is what was asked
6 💡 03100_lwu_57_lock_acquire_timeout arms two PAUSE failpoints, but the audit lists it only for infinite_sleep AGREE, noted Deliberate: its other one, patch_parts_lock_pause_before_cas, is reached from StorageReplicatedMergeTree::updateLightweight, which returns the QueryPipeline, so that park is on the query thread while the pipeline is still being built and no work() frame exists. infinite_sleep is that test's only in-scope park, and it is the one the follow-up PR moves

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

Session id: cron:clickhouse-review-slot-10:20260909-120800

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Each site's test fails on demand with its fix hunk reverted or its failpoint un-armed, and passes with it. The ONCE failpoints fire on the first pass through their site, so there is no timing window: python3 -u tests/clickhouse-test 04512_distributed_limit_no_more_packets_race 04162_system_cancel_view_during_refresh, and python3 -m ci.praktika run "integration" --test ... for the four integration tests.
b Root cause explained? notifyPauseAndWaitForResume / pauseFailPoint block whichever thread reaches the site on an unbounded resume_cv.wait until SYSTEM DISABLE FAILPOINT, and channels are keyed by name only, so SYSTEM WAIT FAILPOINT ... PAUSE is inherently a two-thread rendezvous. Seven sites sat under IProcessor::work() (ISource::tryGenerate, IOutputFormat::consume, SinkToStorage::onFinish via ExceptionKeepingTransform::work, FunctionSleep::execute under ExpressionTransform::work, RemoteSource::onUpdatePorts), so each park was a condvar wait inside work() holding a PipelineExecutor thread-pool slot. src/Processors/IProcessor.h:46 forbids it.
c Fix matches root cause? Yes. The wait is removed, not shortened: each rendezvous is replaced by injecting, on the same thread, the exact action the external actor performed (finish() for 04512, Context::killCurrentQuery() for the four KILL QUERY tests). A bounded park would still be a wait inside work(). Where the rendezvous was a duration rather than an action (04162's infinite_sleep) it moved to the BackgroundSchedulePool refresh thread, which is allowed to wait. No test received a no-parallel tag, a widened bound, a reduced dataset or a defensive check.
d Test intent preserved / new tests added? Preserved verbatim. 04512 keeps both use_hedged_requests arms and the must-succeed query; the aggregating test keeps all three assertions and its query/table/settings (100 rows at max_block_size=100 still exceed 5 key intervals); MySQL keeps rows_seen == 6; PostgreSQL keeps NetworkSendBytes == 0 and deliberately keeps not asserting the client message; Delta keeps both post-conditions for both partitioned values; 04162 keeps all three assertions including the discriminating Cancelling refresh in <db>.c, and additionally pins read_rows_at_park 0, the mirror image of the merged test's read_rows > 0 progress wait, so the claim that the cancel reaches a published but not-yet-started executor is measured rather than argued. Each test additionally gains a bracketed system.fail_points enabled 1 -> 0 oracle, so a run in which the failpoint never fired now fails instead of passing vacuously. Test infrastructure only, so no source-behaviour regression test is owed.
e Both directions demonstrated? Yes. Positive: 04512 and 04162 pass, plus 50 runs each under the runner's default randomisation (100/100, 266 s, and 100/100 again at 282 s after the final change); the four integration tests pass (26 s / 72 s / 103 s). Negative, seven arms, each reddens: reverting only the MultiplexedConnections EndOfStream hunk aborts the debug server on LOGICAL_ERROR "No more packets are available." in the use_hedged_requests=0 arm; reverting only the HedgedConnections hunk leaves arm 0 green and reddens arm 1 at HedgedConnections.cpp:404; removing 04512's arming prints armed_0 0; moving the new refresh failpoint before the executor publication flips 04162's third column 1 -> 0; running the four integration tests un-armed fails all five parametrisations on their substantive oracles; and moving that same refresh failpoint the other way, to immediately after executor.execute(), flips only read_rows_at_park 0 -> 1 while the three original columns stay 1 1 1, so the placement is bracketed from both sides.
f Fix is general across code paths? Yes, and it is the point of the PR. The audit enumerated every failpoint I committed since 2026-05-08 that arms a PAUSE whose site is reachable from a work() / tryGenerate() / onFinish() / onUpdatePorts() frame: 105 pauseable failpoints registered, 74 armed by some test, 64 armer files, 15 of them mine, 9 failpoints in 8 files with an in-work() site. 7 are fixed here, both DeltaLake sinks identically, the four KILL QUERY sites with the identical code shape; 2 are split into a disclosed follow-up (they need a query-thread rendezvous on the lightweight-update lock path, i.e. two new production failpoints plus a 582-line test); 1 is armed but never reached. The same shape in tests I did not author is stated in the PR body and left alone.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for type wrappers: the injected code is test-only, runs only when a failpoint is enabled, and takes no user input, so there is no datatype or wrapper surface. The dimensions that do exist are covered: 04512 runs both use_hedged_requests values (each connection class carries its own copy of the fixed predicate), the Delta test runs both partitioned values, and both DeltaLake sink classes carry the hook.
h Backward compatible? Yes. No setting, no format and no on-disk change, so no SettingsChangesHistory.cpp entry and no versioning concern. Six failpoint names change because their semantics change from "pause" to "cancel"; no reference to any old name survives in src/, tests/, docs/, ci/, utils/ or programs/.
i Invariants and contracts preserved? The work() CPU-only contract now holds at all seven sites, which is the fix. Beyond it: the 04512 injection sits between two LockAndBlocker scopes, so was_cancelled_mutex is not held when finish() takes it, and both finish() exits reach cancelled && !hasActiveConnections() (the drain loop invalidates each replica on EndOfStream; the drain_was_skipped branch disconnects, which also invalidates), so the following receivePacket hits the fixed predicate and the post-receivePacket was_cancelled check unwinds cleanly. killCurrentQuery() takes no lock a worker holds during work(): cancelQuery takes cancel_mutex, snapshots the executors under executors_mutex and releases it before e->cancel(), and ExecutingGraph::cancel takes processors_mutex, which is only taken in updatePipeline/removeGroup after work() returns; none of the five processors overrides onCancel(). The 04162 park is after exec_lock is released, so interruptExecution can take executor_mutex (parking inside that block would deadlock the cancel), and cancelling a NotStarted executor is explicitly supported by PipelineExecutor::cancel. The Delta injection point is unchanged, so the post-commit clearing of tracked sinks still runs with the query already cancelled, which is the behaviour under test.

Session id: cron:clickhouse-impl-slot-5:20260909-060300

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e77e46]

Summary: ✅


AI Review

Summary

This PR rewrites several failpoint-based regression tests so they no longer park a PipelineExecutor worker inside IProcessor::work(), mostly by replacing external KILL QUERY rendezvous with in-place cancellation hooks. The direction makes sense, but one of the rewritten tests now exercises a weaker path than the bug it still claims to cover.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04512_distributed_limit_no_more_packets_race.sh:66-73] The regression is described as a LIMIT/onUpdatePorts()->finish() race, but the test now runs SELECT ... FORMAT Null without LIMIT, so the output port never closes early and RemoteSource::onUpdatePorts() is no longer part of the exercised path. The only remaining trigger is the artificial inline finish() from the new failpoint. A future regression in the getPort().isFinished() -> query_executor->finish() wiring would break distributed LIMIT queries again while this test stayed green.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 7e77e46.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @tuanpach, could you review this? Seven test failpoints parked a PipelineExecutor worker on an unbounded condvar inside IProcessor::work(), which the contract comment in IProcessor.h forbids, so each one is replaced by injecting the external actor's own action on the same thread: an inline finish() in RemoteQueryExecutor::read() for the distributed drain race, and Context::killCurrentQuery() at the same point in the four KILL QUERY tests. The one rendezvous that was genuinely a duration (04162) moves off the pipeline onto the refresh BackgroundSchedulePool thread behind a new refresh_mv_pause_after_executor_published.

Comment on lines +66 to +73
# 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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

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.

@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7e77e46dd with master 1e7129b5d (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

@Michicosun
Michicosun added this pull request to the merge queue Sep 10, 2026
Merged via the queue into ClickHouse:master with commit 3b04f85 Sep 10, 2026
174 of 175 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 Sep 10, 2026
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-testing Test content only (no production code). groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-ci 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