Skip to content

Never cancel a query before its max_execution_time has elapsed - #114559

Merged
alexey-milovidov merged 23 commits into
masterfrom
fix-early-query-cancellation
Aug 22, 2026
Merged

alexey-milovidov merged 23 commits into
masterfrom
fix-early-query-cancellation

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

CancellationChecker::appendTask derived a query's cancellation deadline from the current time truncated to whole milliseconds, and then aligned it up to the 100 ms grid the worker batches deadlines on. The alignment normally hides the truncation, but when the deadline already sits on the grid - one query in a hundred - it adds no padding, and the deadline lands up to 1 ms before now + max_execution_time. The query is then cancelled ahead of its own timeout and fails with a self-contradictory message:

Code: 159. DB::Exception: Timeout exceeded: elapsed 999.672 ms, maximum: 1000 ms. (TIMEOUT_EXCEEDED)

The current time is now rounded up to a whole millisecond instead, which is the direction the code around it already promises: "Tasks may be cancelled slightly later than their exact timeout, but never before". Only the throw overflow mode was affected: in break mode the checker re-reads the elapsed time before acting on the deadline, so an early wake-up does nothing.

This is what makes 02122_join_group_by_timeout flaky - it asserts that a max_execution_time = 1 cancellation takes at least 1000 ms, and query_duration_ms is measured from a stopwatch that starts before the deadline is computed. The failure shows up as query_duration 1 becoming query_duration 0, always on one of the two throw-mode queries and never on the break-mode ones. In the server logs of both Fast test runs below, the query was cancelled early - at 999.672 ms and at 999.630 ms of its 1000 ms timeout.

The deadline computation moved into CancellationChecker::taskDeadlineMs so that the invariant can be tested directly: the new unit test checks every sub-millisecond phase of now against every phase of the grid, for a range of timeouts, and fails with the old truncation.

CI reports of the flaky test:

The truncation is as old as the checker itself. Before deadlines were aligned to a grid in #95563 the deadline was plainly floor(now) + timeout, i.e. early for every query rather than for one in a hundred; and the assertion that catches it was only sharpened from round(query_duration_ms / 1000) BETWEEN 1 AND 60 to query_duration_ms BETWEEN 1000 AND 60000 in daf1b49, which is why the flake is recent.

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):

A query could be cancelled up to 1 ms before its max_execution_time had passed, failing with a self-contradictory Timeout exceeded: elapsed 999.672 ms, maximum: 1000 ms.


Workflow [PR]
Sync PR [sync-upstream/pr/114559]

Version info

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

`CancellationChecker::appendTask` derived the deadline from the current time
truncated to whole milliseconds, and then aligned it up to the 100 ms grid the
worker batches deadlines on. The alignment normally hides the truncation, but
when the deadline already sits on the grid - one task in a hundred - it adds no
padding, and the deadline lands up to 1 ms before `now + max_execution_time`.
The query is then cancelled ahead of its own timeout and fails with a
self-contradictory message:

    Code: 159. DB::Exception: Timeout exceeded: elapsed 999.672 ms, maximum: 1000 ms.

Round the current time up to a whole millisecond instead. That is the direction
the code around it already promises: "Tasks may be cancelled slightly later than
their exact timeout, but never before".

This is what makes `02122_join_group_by_timeout` flaky: it asserts that a
`max_execution_time = 1` cancellation takes at least 1000 ms, which an early
cancellation breaks. In the server logs of the two `Fast test` runs below the
query was cancelled at 999.672 ms and at 999.630 ms. Only the `throw` overflow
mode is affected - in `break` mode the checker re-reads the elapsed time before
acting on the deadline, so an early wake-up does nothing.

The deadline computation moved to `CancellationChecker::taskDeadlineMs` so that
the invariant can be tested over every sub-millisecond phase against every phase
of the grid; the new unit test fails with the old truncation.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=gh-readonly-queue/master/pr-113021-93e2851fddb5add7bad5b28bcef780be2f6ff7bb&sha=bef88e3d96ecb0f57a0f8d81f6b7ee2117db19fd&name_0=MergeQueueCI&name_1=Fast%20test
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=gh-readonly-queue/master/pr-110451-2f02abe52a79c02fb554728f14d8fa847dcbc1e6&sha=2eba84a8a12a21c36516158d4fbe9530d3f0af8c&name_0=MergeQueueCI&name_1=Fast%20test

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

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2ce3abe]

Summary: ✅


AI Review

Summary

This PR fixes premature max_execution_time enforcement by preserving microsecond precision in the cancellation deadline, removing overflow-prone timeout truncation, and keeping the user-facing timeout diagnostics aligned with the effective limit. I reviewed the current diff together with the full prior discussion, re-checked the previously raised timeout-edge cases against the current head, and I do not see a remaining correctness issue or evidence gap in the touched paths.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.10% 87.00% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 124/126 (98.41%) · 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 13, 2026
@thevar1able thevar1able self-assigned this Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2ce3abe55 with master ecc01ef26 (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
Binary Master PR Δ
programs/clickhouse-stripped 705.37 MiB 702.34 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Bugfix validation (unit tests) cannot pass for this PR, and the failure is structural rather than a defect in the change.

That job takes the test files from the PR and compiles them against the pre-fix source, expecting the test to build and fail there. The new test calls CancellationChecker::taskDeadlineMs, which the fix itself introduces (the deadline computation was extracted out of appendTask precisely so that the invariant could be asserted directly), so the before-binary does not compile:

/ClickHouse/ci/tmp/before_src/src/Interpreters/tests/gtest_cancellation_checker.cpp:110:65: error: no member named 'taskDeadlineMs' in 'DB::CancellationChecker'

Any unit-test bug fix that extracts a helper to make the buggy computation testable hits the same wall: the only way around it would be to assert the invariant through appendTask and real wall-clock timing, which is exactly the flakiness this PR is removing.

The rest of CI is green, and the AI review reports no findings. Merged master to refresh the run.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Audited the remaining CI failure. Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) completed 1,358 tests successfully and then exceeded its 7,200-second session budget (2:03:00); the job log contains no test failure or sanitizer finding. This shard runs unrelated database-disk and old-analyzer integration coverage and does not exercise the files changed by this PR, so no source change is warranted.

Comment thread src/Interpreters/ProcessList.cpp Resolved
Comment thread src/Interpreters/ProcessList.cpp Resolved
`appendTask` clamped every tracked timeout to `MAX_TIMEOUT_US` (one year),
while `QueryStatus::throwProperExceptionIfNeeded` and
`ExecutionSpeedLimits::checkTimeLimit` report the full configured
`max_execution_time`. With `timeout_overflow_mode = 'throw'` and a
`max_execution_time` above one year, the query was therefore cancelled at
exactly one year while the exception text claimed the configured, much larger
limit - which is precisely the "cancelled before its own timeout" contract this
pull request establishes.

The clamp existed only because `std::condition_variable::wait_for` converts its
duration to nanoseconds internally and overflows for far-future deadlines. That
is a property of the wait, not of the timeout, so it is now handled where it
belongs: the worker waits in slices of at most one day and re-arms afterwards,
and `taskDeadlineMs` saturates the deadline (upwards, never earlier) only when
`now + timeout` genuinely does not fit into `Int64` microseconds - about 292
thousand years away.

Addresses the review finding on `src/Interpreters/CancellationChecker.cpp:107`.
Converting the timeout to nanoseconds for the comparison overflowed once
`max_execution_time` exceeded `UInt64::max()` nanoseconds (about 584 years),
which `SettingFieldSeconds` accepts: the first overflowing value wrapped to
384 ns, so `checkTimeLimit` started throwing `TIMEOUT_EXCEEDED` almost
immediately instead of never. The elapsed time is now compared in whole
microseconds instead, which can only fire the timeout up to a microsecond
later - never before it. The same arithmetic is fixed in
`KafkaSource::checkTimeLimit`, `NATSSource::checkTimeLimit`, and
`StorageKafka2::pollConsumer`, and the new
`ExecutionSpeedLimits.HugeMaxExecutionTimeDoesNotOverflow` gtest pins the
exact rollover point.

Co-Authored-By: Claude Fable 5 <[email protected]>
`taskDeadlineMs` truncated the current time to whole microseconds before adding
the timeout. When the resulting deadline landed exactly on a whole millisecond
and on a `CANCELLATION_GRID_MS` boundary, the alignment added no padding, so the
returned deadline was up to 999 ns before `now + timeout` - the same "cancelled
before its own timeout" class this pull request removes, one scale down.
Round the current time *up* to a whole microsecond instead, so the deadline is
never earlier than the exact one.

The gtest sampled the sub-millisecond phase of `now` in steps of 9973 ns and so
never reached the last microsecond of a millisecond, which is exactly where this
happens. It now sweeps every microsecond phase together with the nanosecond
remainders inside it.

`InterpreterSystemQuery::syncMerges` still capped the deadline at
`steady_clock::time_point::max()`, about 292 years on a nanosecond clock, while
`max_execution_time` accepts far larger values - so `SYSTEM SYNC MERGES` could
throw `TIMEOUT_EXCEEDED` centuries before the configured timeout. It now
compares the elapsed time against the timeout, which needs no absolute deadline
and therefore no cap.
…cellation

Conflict in `InterpreterSystemQuery::syncMerges`: master started clamping the
`SYSTEM SYNC MERGES` timeout with `saturatedMilliseconds`, which caps it at one
year - the same silent truncation this pull request removes elsewhere. Kept this
branch's elapsed-time comparison, which needs no absolute deadline and therefore
no cap, and preserves the microsecond precision of `max_execution_time`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Audited the remaining CI red after pushing the review fixes.

Stress test (amd_asan_ubsan) — Hung check failed, possible deadlock found. The single hung entry is an AST-fuzzer mutation of 04909_final_split_layers_duplicate_header_columns.sql:

INSERT INTO t_final_split_dup SELECT positiveModuloOrNull(number, 64),
  toUUIDOrZero(h3kRing(arrayJoin([579205133326352383]), arrayJoin([toUInt16(7), toUInt16(2), toUInt16(3)])), NULL), ...
  FROM numbers(9007199254740991.)

with elapsed: 838.671257, max_execution_time: 10 and — crucially — is_cancelled: 1. The cancellation was delivered on time; the query simply does not observe it, so it is an uninterruptible-execution problem, not a timeout-scheduling one. This pull request only changes when a deadline fires (never earlier than the configured timeout, at most one 100 ms grid tick later), so it cannot produce a query that is already flagged as cancelled and still running 14 minutes later. Looks like the class tracked in #112203.

@groeneai, could you investigate that hung check and provide a fix in a separate pull request? If a fix is already in progress, please link it here.

Bugfix validation (unit tests) remains structurally impossible for this change, for the reason explained above: the job compiles the pull request's test files against the pre-fix source, and the new test calls CancellationChecker::taskDeadlineMs, which the fix itself introduces.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already merged: #115773 (merged 2026-08-21 21:05:09Z, c62aa4f).

Your read is right and I agree this pull request is not the cause. I filed that same row on 2026-08-20 from the same report; a 30-day census of hung-check rows carrying is_cancelled: 1 gives 13 rows across 13 distinct pull requests, 0 on master, none of them a cancellation change.

One correction to the mechanism, because it changed what the fix had to be: the query is not parked, it is spinning. The stacktraces column of that same hung_check.log has thread 3592 in

__memmove_sse2_unaligned_erms -> __asan::Allocator::Reallocate
  -> Allocator.cpp:183::realloc -> PODArray.h:167::realloc
  -> h3kRing.cpp::executeImpl -> ExpressionTransform::transform

with the other three threads waiting on it, so there is no deadlock. h3kRing.cpp:132 called dst_data.reserve(dst_data.size() + vec_size) inside the per-row loop, and ColumnVector::reserve is data.reserve_exact(n) (ColumnVector.h:184-187), which reallocates to exactly the requested size with no rounding, so the accumulator was fully copied on every row. Here maxGridDiskSize over k in {7,2,3} averages 75 cells and the two arrayJoins give 3 * 65409 = 196227 rows, so the payload is only 117.7 MB (matching peak_memory_usage 102.6 MB) while 8 * 75 * n(n+1)/2 is 11.6 TB memmoved, which is 770 to 2310 s at ASan single-thread bandwidth. Nothing else on that row predicts 838 s.

That is also why is_cancelled: 1 had no effect. The check already exists: ExpressionTransform passes [this]{ return isCancelled(); } into executeOnColumns and it is tested once per action (ExpressionActions.cpp:966), but the entire 838 s is inside one IFunction::executeImpl, so no boundary is reached again. Removing the quadratic term makes the existing check sufficient with no new cancellation code, so the fix is four getData().reserve(...) lines in h3kRing, h3ToChildren, h3PolygonToCells and h3PolygonToCellsWithContainment.

Verified on master at 0b1c827, which contains c62aa4f: that query shape with max_execution_time = 10 now stops at elapsed 10000.507 ms instead of 838 s. Since the merge, CIDB has 0 hung-check rows whose context mentions h3kRing, and the new test 04910 has 1320 OK results.

The stress run is from 2026-08-20, before the merge, so it could not have carried the fix. Your base ecc01ef is 194 commits ahead of it and already contains it, so a re-run should not reproduce this entry.

#112203 stays open for other functions; I am taking the one remaining same-shape site (s2GetNeighbors) in its own pull request rather than widening #115773.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 22, 2026
Merged via the queue into master with commit 6bfd1c4 Aug 22, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-early-query-cancellation branch August 22, 2026 18:59
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 22, 2026
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.

4 participants