Skip to content

Make the primes table function respond to query cancellation - #108353

Merged
alexey-milovidov merged 4 commits into
masterfrom
fix-primes-source-cancellation
Jun 28, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
fix-primes-source-cancellation

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A SELECT from the primes table function can keep running for a long time after KILL QUERY (or a max_execution_time / shutdown) when given a large step or limit. The query stays in system.processes with is_cancelled = 1 and makes no progress in read_rows. This was the hung query behind a Stress test (arm_tsan) "Hung check failed, possible deadlock found" (the server-side AST fuzzer feeds boundary arguments to primes).

Root cause

PrimesSource::generate / PrimesSimpleRangedSource::generate (src/Processors/Sources/SourceFromPrimes.h) run a while (written < target) loop that calls the prime generator's next with no cancellation point. A large step makes the loop call next an astronomical number of times to skip to the next selected prime index, so a single generate call never returns. The pipeline executor only checks cancellation and time limits between generate calls, so the in-flight call cannot be interrupted. next itself is bounded (segment size 2^19, prime gaps are far smaller), so the long pole is the generate loop, not a single next.

Fix

Check isCancelled at the top of both generate loops and return early. ISource::isCancelled is a cheap atomic load, set by the executor on KILL / max_execution_time / shutdown, and each iteration already does a bounded next, so the overhead is negligible.

Regression test 04410_primes_source_cancellation.sh: runs SELECT * FROM primes(0, 1000000, 100000000000) (huge step, with max_rows_to_read = 0 to bypass the up-front row-estimate check) in the background, waits until it is in system.processes, then requires KILL QUERY ... SYNC to return within a timeout bound. With the fix it returns in ~1 s; without it the KILL blocks until the bound trips.

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 SELECT from the primes table function not responding to cancellation: with a large step (or limit) the query could keep running for a long time after KILL QUERY or a timeout. It now stops promptly.

Version info

  • Merged into: 26.7.1.205 (included in 26.7 and later)

`PrimesSource::generate` / `PrimesSimpleRangedSource::generate`
(src/Processors/Sources/SourceFromPrimes.h) run a `while (written < target)`
loop calling the prime generator's `next` with no cancellation point. A large
`step` (or `limit`) makes the loop call `next` an astronomical number of times
to skip to the next selected prime index, so a single `generate` call never
returns. The pipeline executor only checks cancellation and time limits between
`generate` calls, so a cancelled, KILLed or timed-out query keeps spinning
(observed as a query stuck with `is_cancelled = 1` and no progress in
`read_rows`). `next` itself is bounded (segment size 2^19, prime gaps are far
smaller), so the long pole is the `generate` loop.

Check `isCancelled` at the top of both loops. It is a cheap atomic load, set by
the executor on KILL / max_execution_time / shutdown, and each iteration already
does a bounded `next`, so the overhead is negligible.

This was the hung query behind a `Stress test (arm_tsan)` "Hung check failed,
possible deadlock found" on PR #108212 (server-side AST fuzzer feeding boundary
arguments to `primes`).

Related: #108212

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [51fd094]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue ISSUE EXISTS
Stress test (arm_msan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR makes the primes sources observe pipeline cancellation inside their generation loops and adds a regression test for the long primes(offset, limit, step) path plus a performance test covering both source variants. I did not find any current-code blockers or major issues.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 24, 2026
The test gated `KILL QUERY` on the query merely being visible in
`system.processes`. That only proves the query reached `ProcessList::insert`,
which happens before the `PipelineExecutor` is attached -- if `KILL` won that
race, the cancellation would be thrown from `QueryStatus::addPipelineExecutor`
before any source work runs, so the test could pass even without the in-loop
`isCancelled()` check it is meant to guard.

Wait until the query has been executing for a bounded interval (`elapsed > 1` in
`system.processes`) before issuing the `KILL`, so the executor is attached and
`PrimesSource::generate` is spinning in its loop. Also add `no-random-settings`:
the SELECT must keep running until the test kills it, so a randomized
`max_execution_time` (or `max_rows_to_read`) must not terminate it first.

Verified on a local build: with the fix `KILL QUERY ... SYNC` returns in ~0.2s
("killed promptly") after the query has been generating for ~1.2s; with the
in-loop `isCancelled()` checks removed and rebuilt, the same `KILL` blocks on the
spinning generate loop and the test prints "KILL QUERY SYNC did not return in
time", so the test now genuinely guards the fix.

@nihalzp nihalzp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It looks good. I think the performance should be almost the same. I have added a performance test to be sure.

@clickhouse-gh

clickhouse-gh Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.30% -0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.50% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 8/10 (80.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@nihalzp nihalzp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM! The performance tests show no degradation.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Both are the same check, "Hung check failed, possible deadlock found", and neither is caused by the primes change. This PR only touches SourceFromPrimes.h, but the hung query in each hung_check.log is a cancelled in-flight server-side AST fuzzer INSERT (is_cancelled=1), not a primes() query:

  • arm_debug (771s): worker stuck in MergeTreeSink::consume -> MergeTreeIndexAggregatorSet::update; main thread in executeASTFuzzerQueries (executeQuery.cpp:2174) -> CompletedPipelineExecutor::execute -> PipelineExecutor::executeImpl -> ThreadPool::wait().
  • arm_msan (1078s): same shape, worker in MergeTreeDataPartWriterWide::writeColumn -> SerializationArray::enumerateStreams.

A fuzzer-inflated INSERT keeps grinding in the part writer after the outer fuzzer query is cancelled, because the inner executor has no cancel callback and no read/block-size cap. This is the AST-fuzzer-inflight-hang tracked in #107941; over the last 30 days it hits hundreds of unrelated PRs plus master on every stress sanitizer, so it is pre-existing and not introduced here.

Fix: our open PR #108212 modifies exactly executeASTFuzzerQueries to cap the fuzzed query's read volume (max_rows_to_read + read_overflow_mode = break) and block size, and adds a cancel callback to the inner CompletedPipelineExecutor so a cancelled in-flight fuzzed query stops between tasks. That bounds this exact path, so these two reds do not indicate a problem in this PR.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 28, 2026
Merged via the queue into master with commit ac3c7cb Jun 28, 2026
166 of 169 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-primes-source-cancellation branch June 28, 2026 18:05
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 28, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…e-cancellation

Make the primes table function respond to query cancellation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants