Skip to content

Report TIMEOUT_EXCEEDED for queries killed by timeout in pending state - #110533

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai-fix-pending-timeout-exec-time
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai-fix-pending-timeout-exec-time

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #109360

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 the error code returned when a query is killed by max_execution_time before it starts executing (for example while it is still being planned). Such a query now reports TIMEOUT_EXCEEDED instead of QUERY_WAS_CANCELLED, matching the behavior of a timeout that fires during execution.

Description

The check for a query killed in the pending state (in executeQueryImpl) unconditionally threw QUERY_WAS_CANCELLED, ignoring the cancel reason. When the max_execution_time timeout fires while the query is still pending (before any pipeline executor is started, e.g. during planning), CancellationChecker cancels the query with CancelReason::TIMEOUT, but the pending-state check reported QUERY_WAS_CANCELLED (394) instead of TIMEOUT_EXCEEDED (159).

This is the race behind the flaky 01039_mergetree_exec_time failure under Stateless tests (amd_tsan, parallel), where TSan's slowdown makes the timeout likely to fire before execution starts: the test expects TIMEOUT_EXCEEDED but occasionally got QUERY_WAS_CANCELLED. See https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109360&sha=f4d7ea385828706b6c33bcd9e056cce835612765&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 (surfaced on #109360, which is unrelated to this code).

Fix: consult QueryStatus::getCancelReason() in the pending-state check and throw TIMEOUT_EXCEEDED when the reason is TIMEOUT, otherwise QUERY_WAS_CANCELLED (same precedent as PullingPipelineExecutor, which already recovers the timeout reason when a timeout fires before execution starts).

A new failpoint execute_query_sleep_before_pending_kill_check deterministically reproduces the race by stalling the main thread so the timeout fires in the pending state; the regression test 03471_pending_query_timeout_error_code uses it. Verified: the test returns QUERY_WAS_CANCELLED (394) without the fix and TIMEOUT_EXCEEDED (159) with it.

The pending-state kill check in executeQueryImpl unconditionally threw
QUERY_WAS_CANCELLED. When max_execution_time fires before execution starts
(e.g. during planning), the query is cancelled with CancelReason::TIMEOUT,
so the correct error is TIMEOUT_EXCEEDED, matching a timeout during execution.

Consult QueryStatus::getCancelReason() and throw TIMEOUT_EXCEEDED when the
reason is TIMEOUT, otherwise QUERY_WAS_CANCELLED (same as PullingPipelineExecutor).

This is the race behind the flaky 01039_mergetree_exec_time failure under
Stateless tests (amd_tsan, parallel). A new failpoint
execute_query_sleep_before_pending_kill_check makes it deterministic; the
regression test is 03471_pending_query_timeout_error_code.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. New failpoint execute_query_sleep_before_pending_kill_check stalls the main thread so the max_execution_time timeout deterministically fires in the pending state. SYSTEM ENABLE FAILPOINT ...; SELECT sleep(0) SETTINGS max_execution_time=1 fails every time.
b Root cause explained? The pending-state kill check in executeQueryImpl threw QUERY_WAS_CANCELLED unconditionally. When max_execution_time fires before execution starts (planning), CancellationChecker cancels with CancelReason::TIMEOUT, so the correct code is TIMEOUT_EXCEEDED; the check ignored the reason and returned 394 instead of 159.
c Fix matches root cause? Yes. The check now consults QueryStatus::getCancelReason() and throws TIMEOUT_EXCEEDED for TIMEOUT, else QUERY_WAS_CANCELLED. Same precedent as PullingPipelineExecutor, which already recovers the timeout reason when a timeout fires before execution starts.
d Test intent preserved / new tests added? New test 03471_pending_query_timeout_error_code. No existing test weakened.
e Demonstrated in both directions? Yes. Baseline (fix reverted, failpoint kept): 394 QUERY_WAS_CANCELLED. With fix: 159 TIMEOUT_EXCEEDED, test OK via clickhouse-test.
f Fix is general, not a narrow patch? Yes. The single pending-state check is the only site that mapped a timeout kill to the wrong code; execution-time timeouts already go through throwProperExceptionIfNeeded, which branches on TIMEOUT.
g Fix generalizes across inputs? The branch keys on CancelReason (TIMEOUT vs everything else), not on any query shape, setting value, or type — it holds for any query killed while pending.
h Backward compatible? Yes. No format/setting change. Only corrects the error code for a case that previously misreported; TIMEOUT_EXCEEDED is the same code returned when the timeout fires slightly later during execution.
i Invariants and contracts preserved? Yes. getCancelReason() is read after isKilled() (its documented precondition). No lock-ordering or lifetime changes; switched the message to the lightweight getClientInfo() accessor instead of the heavier getInfo().

Session id: cron:clickhouse-worker-slot-4:20260715-102300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @vdimir for review: this fixes the error code (QUERY_WAS_CANCELLED -> TIMEOUT_EXCEEDED) returned when max_execution_time kills a query while it is still pending, in the executeQueryImpl pending-state check.

@vdimir vdimir added the can be tested Allows running workflows for external contributors label Jul 15, 2026
@vdimir vdimir self-assigned this Jul 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1f726d8]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, s3 storage, parallel, 2/3) ERROR

AI Review

Summary

This PR routes the pending-state cancellation check in executeQueryImpl through QueryStatus::throwIfKilled and adds focused regression coverage so a max_execution_time timeout raised before execution starts now surfaces as TIMEOUT_EXCEEDED instead of a generic cancellation. I did not find any remaining correctness or regression issues in the current diff.

Missing context / blind spots
  • ⚠️ Source-only review: this workspace does not include a prepared build directory, so I did not run the new stateless or integration tests locally.
Final Verdict

✅ No blocking or major issues found in the current patch.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 15, 2026
Comment thread src/Interpreters/executeQuery.cpp Resolved
Instead of open-coding only the TIMEOUT->TIMEOUT_EXCEEDED case and defaulting
every other pending-state kill to QUERY_WAS_CANCELLED, route through
QueryStatus::throwIfKilled (-> throwProperExceptionIfNeeded). This preserves
the full cancellation mapping: TIMEOUT_EXCEEDED for a max_execution_time
timeout, the concrete stored exception when the kill carried one (e.g.
CancelReason::CANCELLED_BY_ERROR with FAILED_TO_SYNC_BACKUP_OR_RESTORE from
BackupCoordinationStageSync), and QUERY_WAS_CANCELLED otherwise. Addresses
the AI review on PR ClickHouse#110533.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed in 5bf3a7c. Replaced the open-coded TIMEOUT special-case with `process_list_entry->getQueryStatus()->throwIfKilled()`, which funnels through `throwProperExceptionIfNeeded`. The pending-state path now matches the rest of QueryStatus: TIMEOUT_EXCEEDED for a max_execution_time timeout, the stored `cancellation_exception` when the kill carried one (e.g. `CANCELLED_BY_ERROR` + `FAILED_TO_SYNC_BACKUP_OR_RESTORE` from BackupCoordinationStageSync), and QUERY_WAS_CANCELLED otherwise. The deterministic failpoint test (03471) still asserts TIMEOUT_EXCEEDED and passes locally.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5bf3a7c

All failures on this commit are the single ongoing infra runner outage; none are caused by this PR's diff. Every failure has an owner.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / many unrelated tests infra (one broken-runner window: 124 unrelated PRs / 10852 hits across hundreds of unrelated tests on this exact check in 12h; not reproducible) a fix task is tracking this runner outage (fixing-PR link to follow)
Finish Workflow / Post Hooks rollup of the above same infra owner
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260715-153000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5bf3a7c

CI fully finished (Finish Workflow pass). The only red job is the fleet-wide host-OOM window; not PR-caused.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / unrelated tests host-OOM (Code 241 (total) memory limit exceeded, RSS ~41.84 GiB host cap) #110503 (ours, open)
Mergeable Check aggregate of the above #110503 (ours, open)

groeneai and others added 2 commits July 19, 2026 11:31
…g-timeout-exec-time

# Conflicts:
#	src/Common/FailPoint.cpp
The pending-state kill now funnels through QueryStatus::throwIfKilled
(this PR), so a user KILL of a pending query reports the standard
cancellation message "Query was cancelled" (QUERY_WAS_CANCELLED, code
394) instead of the previous ad-hoc "is killed in pending state" text.
Align the test assertion with the message used by the sibling
KILL-query integration tests (test_mysql_kill_query, test_mongodb_kill_query).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1f726d8

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless (amd_tsan, s3 storage, parallel, 2/3) / 01730_distributed_group_by_no_merge_order_by_long flaky MEMORY_LIMIT_EXCEEDED (163 PRs / 17 master / 30d; AggregatingTransform over-reservation) #109847 (external, open)
Stateless (amd_tsan, s3 storage, parallel, 2/3) / Scraping system tables infra (minio_audit_logs 600s dump timeout on s3 configs) #110099 (ours, open)

Not PR-caused: this PR's diff is the executeQuery pending-state kill path (throwIfKilled); both failures are pre-existing chronic flakes on unrelated tests.

Session id: cron:our-pr-ci-monitor:20260719-233000

@groeneai

Copy link
Copy Markdown
Collaborator Author

@vdimir this PR's core fix is now superseded on master.

#111208 (merged today) applies the same fix for the identical root cause: pending-state max_execution_time timeouts now report TIMEOUT_EXCEEDED via if (getCancelReason() == CancelReason::TIMEOUT) throwIfKilled(); in executeQueryImpl. That covers the 01039_mergetree_exec_time race this PR targeted; master already returns 159 for it, and the 03471 regression test here passes on current master without this PR's diff.

The only remaining delta here is generalizing the pending check to an unconditional getQueryStatus()->throwIfKilled(), which additionally (a) rethrows a stored exception for non-timeout CANCELLED_BY_ERROR kills and (b) changes the plain user-KILL message from "killed in pending state" to "Query was cancelled". #111208 deliberately kept the "killed in pending state" message for non-timeout reasons, so this is out of scope for the original bug.

I suggest closing this as superseded by #111208, unless you want the non-timeout CANCELLED_BY_ERROR rethrow (originally requested by the AI review) pursued as a separate, narrowly-scoped PR. Your call.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Hi @vdimir, gentle ping — any update on whether to close this as superseded by #111208, or to pursue the non-timeout CANCELLED_BY_ERROR rethrow as a separate narrow PR? Thanks.

-- e.g. during planning). Such a query must report TIMEOUT_EXCEEDED, not QUERY_WAS_CANCELLED.
-- The failpoint stalls the main thread so the timeout deterministically fires in the pending state.

SYSTEM ENABLE FAILPOINT execute_query_sleep_before_pending_kill_check;

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.

If we already have test_cancel_freeze, which changes with the patch, do we need to add a failpoint and a new test?

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.

No. On the current base 03471 is not load-bearing, and the failpoint exists only to make it deterministic.

Measured: substituting master's narrower form for this PR's unconditional throwIfKilled() and rebuilding (keeping the failpoint so the test can run at all), 03471 still passes.

pending-state scenario this PR master (#111208)
max_execution_time fires while pending Code 159 TIMEOUT_EXCEEDED Code 159 TIMEOUT_EXCEEDED
KILL QUERY of a pending query Code 394 Query was cancelled Code 394 Query 'X' is killed in pending state

So test_cancel_freeze is the only assertion that moves, exactly as you say.

That is because the PR is superseded: 5843b0e (#111208, 2026-07-21) landed the identical timeout fix, which was this PR's original purpose. I raised that in #110533 (comment), which was easy to miss.

What remains of the diff is only the generalization to an unconditional throwIfKilled():

  1. rethrow a stored exception when the kill carried one (CANCELLED_BY_ERROR). Only BackupCoordinationStageSync.cpp:760 and :815 pass one, and nothing here reaches that in the pending state, so this half is untested.
  2. the plain-KILL message change, which is what forced the test_cancel_freeze edit. Fix flaky 03309_json_with_progress_exception: timeout in pending state #111208 deliberately kept the distinct message, so this is a design fork, not a gap.

My recommendation is to close this as superseded. If you would rather keep the CANCELLED_BY_ERROR rethrow, I will respin it narrow: drop the failpoint and 03471, keep that branch only, and cover it directly instead of via the message change.

@vdimir

vdimir commented Aug 10, 2026

Copy link
Copy Markdown
Member

@vdimir this PR's core fix is now superseded on master.

#111208 (merged today) applies the same fix for the identical root cause: pending-state max_execution_time timeouts now report TIMEOUT_EXCEEDED via if (getCancelReason() == CancelReason::TIMEOUT) throwIfKilled(); in executeQueryImpl. That covers the 01039_mergetree_exec_time race this PR targeted; master already returns 159 for it, and the 03471 regression test here passes on current master without this PR's diff.

The only remaining delta here is generalizing the pending check to an unconditional getQueryStatus()->throwIfKilled(), which additionally (a) rethrows a stored exception for non-timeout CANCELLED_BY_ERROR kills and (b) changes the plain user-KILL message from "killed in pending state" to "Query was cancelled". #111208 deliberately kept the "killed in pending state" message for non-timeout reasons, so this is out of scope for the original bug.

I suggest closing this as superseded by #111208, unless you want the non-timeout CANCELLED_BY_ERROR rethrow (originally requested by the AI review) pursued as a separate, narrowly-scoped PR. Your call.

What's pros and cons of each in short? Can we close this PR?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, please close it.

Option A, close as superseded by #111208:

  • The original bug (a pending query hitting max_execution_time reporting QUERY_WAS_CANCELLED instead of TIMEOUT_EXCEEDED) is already fixed on master by Fix flaky 03309_json_with_progress_exception: timeout in pending state #111208. I ran the A/B with the failpoint present in both arms: your narrow form and my unconditional form both give Code: 159 TIMEOUT_EXCEEDED, and the test 03471 added here passes on master without the diff. So this PR adds nothing for its stated purpose.
  • It leaves one narrow gap: a pending query cancelled with a stored exception (CANCELLED_BY_ERROR) still surfaces as generic QUERY_WAS_CANCELLED instead of, say, FAILED_TO_SYNC_BACKUP_OR_RESTORE. Only two call sites can pass an exception, BackupCoordinationStageSync.cpp:760 and :815.

Option B, keep the unconditional throwIfKilled() here:

  • Closes that gap.

If the CANCELLED_BY_ERROR rethrow is worth having, it is cleaner as a fresh narrow PR that keeps the existing message and tests that path directly.

@vdimir vdimir closed this Aug 17, 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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants