Repository navigation
Measure cancellation server-side in test_cancel_backup.py - #112217
alexey-milovidov merged 5 commits into
Conversation
`test_cancel_backup` and `test_cancel_restore` assert that a cancellation is prompt, but they measured it with a client-side `time.monotonic()` stopwatch spanning `kill_query` through `wait_status`. In this harness every `node.query(...)` is a `docker exec` of a fresh `clickhouse-client` (0.5-1 s each), and that window held three to four of them plus `wait_status`'s whole-second poll quantum, so the assertion bounded harness round-trip overhead rather than the cancellation. The result was a chronic flaky failure: 24 rows over 25 days across 13 pull requests, two of them on master. Decomposing all 12 rows of that signature family with timestamps the test already prints, the engine-side cancellation was 1.90-3.24 s (median 2.33) in every single failure against harness overhead of 2.94-5.91 s. The engine cancelled promptly every time; only the measurement was wrong. Measure the same interval between two server-recorded endpoints instead: the KILL query's own `query_start_time_microseconds`, read from `system.query_log` by an explicit `query_id`, and the initiator's `system.backups.end_time`. No `clickhouse-client` launch is inside that interval, while the cluster-wide cancellation still is -- `end_time` is stamped at the terminal transition, which the initiator reaches only after `waitOtherHostsFinish`, so distributed propagation remains bounded. Taking the start from the KILL statement itself matters: in one recorded run a single client-to-server transition stalled 4.192 s, which alone would consume the whole budget. The bound stays at 6 s. One assertion in, one assertion out, and no second oracle: `query_duration_ms` was deliberately removed from this file in 19bcc55 and consolidated into the single end-to-end bound in c26e0b4. Separately, hoist `no_trash_checker.allow_errors` to checker entry so a body failure surfaces as itself rather than being masked by `NoTrashChecker.__exit__` asserting with both relaxation lists still empty -- which is what CIDB reported for this test, hiding the real assertion. `allow_errors` is the correct one to hoist because `__exit__` treats `expect_errors` as must-have-been-observed, so hoisting that would create a new mask with inverted polarity for any failure occurring before the cancellation. This matches ClickHouse#108459, which hoisted `allow_errors` for two sibling functions in this file. Co-Authored-By: Claude Opus 5 <[email protected]>
Follow-up to the server-side measurement in this file, addressing two review findings. First, `kill_query` did the `system.query_log` lookup itself, immediately after the `KILL ... SYNC` returned and before returning to the caller -- that is, in between the two server-recorded endpoints the test measures. Because both endpoints are server-recorded those two client round trips add no wall clock of their own, which is precisely the defect being fixed; but an unscoped `SYSTEM FLUSH LOGS` is a MergeTree INSERT into every system log on that node, and `node_to_cancel` is the node the initiator is still waiting for in `waitOtherHostsFinish` in two of the three draws. Any perturbation is therefore one-way upward, toward the assertion this file exists to stop failing, and it contradicts the invariant the code comment states. Move the lookup into `get_query_start_time`, called only after `wait_status` has returned, so the measurement performs no work at all inside the interval it measures. `kill_query` now returns the `query_id` it used; `system.query_log` is a persisted MergeTree table, so the row is still there afterwards. The flush is narrowed to `query_log` while it moves. The single-row guard moves with the code, so a vanished oracle still fails loudly instead of silently skipping the timing check. Second, add a lower bound to both assertions. The two endpoints are independent `CLOCK_REALTIME` reads, whereas the previous oracle was `time.monotonic()`. A backward wall-clock step landing inside the window would otherwise produce a negative interval that silently satisfies the upper bound, turning a too-slow cancellation into a pass. The upper bound is unchanged at 6 s; the lower bound only tightens. Co-Authored-By: Claude Opus 5 <[email protected]>
Comment-only follow-up; no assertion, helper or behaviour is touched. Three comments claimed that no clickhouse-client launch is inside the measured interval. The measurement's own queries were moved out of the interval, but wait_status still polls on a one-second quantum over the same period, so the claim was stronger than the code delivers. Neither endpoint can be moved by a poll (the KILL's query_start_time_microseconds is written before the polls run, and end_time is stamped by the backup thread in BackupsWorker::setStatus, not by the observing SELECT), so the defensible statement is that client round-trip latency is no longer added to the measurement. Reworded to say that instead. The lower bound's justification claimed it catches a backward clock step making a too-slow cancellation look fast. With a true interval T and a step S the measured value is T - S, which is only negative for S > T, so a 3 s step during an 8 s cancellation still satisfies the upper bound. Reworded to state what the clause actually guards: the switch from a single time.monotonic() stopwatch to two independent CLOCK_REALTIME reads makes a negative interval possible, and the lower bound turns that into a loud failure rather than a value that silently passes the upper bound. Co-Authored-By: Claude Fable 5 <[email protected]>
The comment said the interval covers "the whole cluster-wide cancellation" because end_time is stamped after the initiator finished waiting for the other hosts. That wait is bounded on the error path: BackupsWorker calls waitOtherHostsFinish(throw_if_error = false), which BackupCoordinationStageSync turns into a wait capped by backup_restore_finish_timeout_after_error_sec, set to 3 s by this module's own profile. So the cancellation is inside the interval only up to that cap. The conclusion is unchanged: this is the same terminus the previous client-side stopwatch used, and a host still cancelling afterwards is caught by the get_num_system_processes() assertion that immediately follows. Comment-only, zero behaviour change. Co-Authored-By: Claude Fable 5 <[email protected]>
The comment above the time_to_cancel computation had grown to 12 lines of motivation and history, roughly three times the longest comment block this file already had. Per the project convention that context belongs in the commit message rather than in code comments, it is reduced to the invariant a reader needs at that line: both endpoints are server-recorded, so neither wait_status's polling loop nor the system.query_log lookup above it can move them, and the right endpoint is stamped after the initiator waited for the other hosts, capped on the error path by backup_restore_finish_timeout_after_error_sec (3 s in this module's profile). The rationale removed from the code is preserved here. The measured interval terminates at the same wait_status() return the previous time.monotonic() stopwatch ended at, so this change narrows nothing: the assertion covers exactly the same span of the cancellation as before, it is only measured from two server-recorded timestamps instead of a client-side stopwatch. A host that is still cancelling past the 3 s error-path cap is not left unchecked: the pre-existing assert get_num_system_processes(nodes, ...) == 0 on the following line fails if any node still has the operation running. The point of using two server-recorded endpoints is that no client round trip is added to the measurement. The KILL QUERY's own client launch happens before the left endpoint is recorded, and the system.query_log lookup that resolves that endpoint runs after the terminal status was stamped, so neither is inside the interval. No behaviour change: the delta is comment text only.
Internal second-model review - 6 rounds, 3 majors found and fixed, 1 nit noted (click to expand)Before publishing, this PR went through six rounds of independent cold review, each paired with a
The failure premise and the row accounting were also re-verified independently of the authoring |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-46:20260727-175800 |
|
cc @pamarcos - could you review this? It fixes a flaky timing assertion in test_cancel_backup.py: |
|
Workflow [PR], commit [7d27246] Summary: ✅ AI ReviewSummaryThis PR replaces the client-side stopwatch in Final Verdict
|
CI finish ledger - 7d27246Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head and there are no failures:
Green checks that actually exercised the change: Session id: cron:our-pr-ci-monitor:20260728-100000 |
…n_stops_backup test_long_disconnection_stops_backup fails as `assert 45.54 < 45`. `time_to_fail` was the difference of two `time.monotonic()` reads in the pytest process, so it charged the backup's abort latency for the `iptables` `docker exec` in `drop_instance_zk_connections` and, dominantly, for one fresh clickhouse-client process per poll iteration of `wait_status`. That overhead grows with the abort latency itself, so a contended runner crosses the ceiling while the engine is nowhere near it. PR ClickHouse#112217 established this for the two sibling tests in this file and converted them to server-recorded timestamps, adding `seconds_between` and making `wait_status` return the server-stamped `end_time`. This call site was left behind: `end_time` was already returned and simply discarded here. It was the file's last timing assertion on a client-side stopwatch. The left endpoint is now a `SELECT now64(6)` on the initiator, issued last before the disconnection. `now64` is evaluated on the server, so the client launch falls outside the interval, while placing the marker before the drop keeps the whole abort covered and can only widen the interval on its left edge, never shrink it. Both bounds (`> 3` and `< 45`) are unchanged, so the assertion becomes strictly tighter against a real abort-latency regression rather than being relaxed. Unlike the two siblings, no `0 <= time_to_fail` guard is added: the retained `> 3` already excludes the negative interval a backwards wall-clock step could produce, and is strictly stronger. Verified by calling the helper directly, an epoch-zero `end_time` yields a large negative value that satisfies `< 45` but fails `> 3`, and an empty or `\N` `end_time` raises instead of silently passing. Validation: an instrumented probe printing both numbers side by side shows the server-side value smaller in 20 of 20 runs (gap min 0.264, median 0.680, max 1.318 s), the median alone exceeding the 0.54 s overshoot the failure reported. Both directions were demonstrated with a per-run ceiling placed between the two measurements: the client-side arm fails 6 of 6 with the original signature, the server-side arm passes 6 of 6. Since the two disconnection cases differ in floor, the lower bound was checked per case: 15 runs with a non-initiator dropped, min 6.236 s, and 5 with the initiator itself dropped, min 9.673 s. 50 repeats of the test pass, and a 5x module run over all 7 tests is 35 of 35 on both the pristine and the fixed arm with identical failing sets.
…e-timing Measure cancellation server-side in test_cancel_backup.py (cherry picked from commit a09867f)
Backport #112217 to 26.7: Measure cancellation server-side in test_cancel_backup.py
Related: #108459
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_backupand::test_cancel_restoreare flaky: 14 FAIL/ERROR rows over 24 days, 11 distinct PRs, plus onerun on
masterand one on26.6(30-day CIDB window, excluding the unrelated signatureseparated at the end of this description).
The signature CIDB shows is a mask, not the defect.
test_context_rawis truncated to thelast frames, so what CIDB reports is
NoTrashChecker.__exit__asserting with both relaxationlists empty:
The job logs show the body exception that ran first, identically in all 12 rows whose logs were
fetched (the 12 that existed when this was investigated; two more have landed since):
time_to_cancelwas a client-side stopwatch, so it measured the integration harness ratherthan the cancellation. Every
node.query(...)here is adocker execof a freshclickhouse-client, and the measured window spanned 3-4 of them pluswait_status's whole-secondpoll quantum. Decomposing each failure using timestamps the test already prints
(
system.backups.end_timeminus the wall clock at the KILL):time_to_cancel26.6(release branch)masterEngine-side: max 3.24 s, median 2.33 s, i.e. every single failure is comfortably inside the
6 s intent. The cancellation was prompt in all 12; the assertion failed on measurement
overhead alone, which is why the failure is rare, recurring, and both arch- and
sanitizer-agnostic. There is nothing to fix in the engine.
The fix measures the same interval between two server-recorded timestamps, so client
round-trip latency is no longer added to it while the cluster-wide cancellation is still inside
it (up to the error-path cap described below).
wait_statusdoes still poll over the sameperiod, but neither endpoint can be moved by a poll: the left one is written before the polling
starts, and the right one is stamped by the backup thread rather than by the observing
SELECT.kill_queryissues theKILL ... SYNCwith an explicitquery_idand returns it. Once theoperation has finished,
get_query_start_timereads that query's ownquery_start_time_microsecondsfromsystem.query_log. Taking the start from the KILLstatement itself (rather than a separately issued
SELECT now64(6)) is what stops a clientlaunch from being added to the interval: in the
104484run one client-to-server transitionstalled 4.192 s, which alone would consume the whole budget. Doing the lookup after the
fact keeps the lookup's own cost out of the measurement too.
wait_statusreturns theend_timeit already reads and prints.BackupsWorker::setStatusstamps it at the terminal transition, which the initiator reaches only after
waitOtherHostsFinish, so distributed propagation stays inside the bound. That matters: theKILL's own duration is not a sufficient oracle, because
waitOtherHostsFinishis gated on!is_internal_backup, so a KILL aimed at a non-initiator returns before the initiator reachesthe terminal status (measured 0.65-1.10 s of propagation in 9 of the 12 rows). On the error
path that wait is itself capped by
backup_restore_finish_timeout_after_error_sec, which thismodule sets to 3 s, so what the interval bounds is the cancellation up to that cap rather than
an unconditional last-host completion. That is the same terminus the previous assertion had -
time_to_cancelended at the samewait_statusreturn - so nothing is narrowed here; a remotehost still cancelling afterwards is caught by the existing
assert get_num_system_processes(nodes, ...) == 0on the next line.The 6 s upper bound is unchanged, and it stays a single end-to-end assertion. Nothing is
loosened, no second oracle is added, and a genuinely slow cancellation still fails: measured on
this branch, tightening the bound to
1fails, and to0.001fails.The assertion is now two-sided (
assert 0 <= time_to_cancel <= 6), which only tightens it. Theprevious oracle was a single
time.monotonic()stopwatch and so could not produce a negativevalue; these are two independent
CLOCK_REALTIMEreads, so a backward wall-clock step betweenthem can now yield a negative interval, which would otherwise satisfy
<= 6silently. The lowerbound makes that a loud failure instead. (It catches the negative case, not every backward step:
a step smaller than the true interval still leaves a positive value.) All 20 runs of the
verification below produced positive intervals (min 0.146 s), so the clause cannot flake on the
normal path.
Second, independent change:
no_trash_checker.allow_errors = ["QUERY_WAS_CANCELLED"]is now seton entry to the checker, while
expect_errorsstays where it was, after the cancellation hasbeen observed. That removes the mask for this failure mode, so a body exception raised after the
cancellation was induced reports itself instead of costing another investigation. The list is
deliberately minimal rather than broad, so
__exit__still fails on any other unexpected errorname.
allow_errorsis deliberately the hoisted one:__exit__treatsexpect_errorsas must-have-been-observed, so hoisting that would create anew mask with inverted polarity for any failure before the cancellation. This matches
#108459, which hoisted
allow_errorsfor two sibling functions in this file and never
expect_errors.test_cancel_restorehas the same defect and is fixed identically. It is a confirmed carrierrather than a speculative one: PR #109374's log shows
assert 6.143040713999653 <= 6followed bythe same mask. It has one recorded row against
test_cancel_backup's 13, but the defectiveconstruct is identical, so fixing only one of the two would leave a known carrier in place.
Why not the
query_duration_msoracle thattest_backup_restore_new/test_cancel_backup.pyuses. It was deliberately removed from this file in
19bcc5550bad04, andc26e0b413fa619then replaced the per-step timeouts with the single end-to-endassert time_to_cancel <= 6. This PR keeps that single end-to-end assertion and changes only howits two endpoints are obtained.
Verification
window: on
masterthe old assertion fails atassert 6.660929953679442 <= 6followed by themask, byte-matching the CI signature; on this branch the same injection passes, because the
server-recorded interval cannot see a delay that happens after
end_timewas stamped. A secondinjection before the KILL also passes, confirming that client round-trip cost outside the two
server-recorded endpoints is not added to the measurement.
(A 4 s injection is marginal, because whether it trips the old bound depends on how long the
KILL itself took that run, so both directions are measured at one common 6 s delay.)
1.291), old client stopwatch 1.528-3.147 s (median 2.193), i.e. 0.605-1.166 s of harness
overhead removed per run. Worst server-side observation leaves 3.0x headroom under the
unchanged 6 s bound.
delay fail again; removing only the
allow_errorshoist brings the mask back; hoistingexpect_errorsinstead reproduces the inverted-polarity mask.pytest --count 10of both fixed functions(server-side interval min 0.146 / median 1.186 / max 2.151 s across those 20 runs, no negative
values, i.e. ~2.8x headroom under the unchanged 6 s bound at the worst observation).
Out of scope, so that the row accounting is unambiguous. A 30-day CIDB search for
%test_cancel_backup.py::test_cancel_%returns 40 rows in total, which decompose as:test_backup_restore_on_clustertest_cancel_backupmaster+26.6test_backup_restore_on_clustertest_cancel_restoretest_backup_restore_on_clustertest_cancel_backuptest_backup_restore_on_clustertest_cancel_restoretest_backup_restore_newtest_cancel_backupThe 14 bold rows are what this PR fixes. The 24 leftover-znode rows are a different assertion in
the same file (
__exit__reporting a leftover/clickhouse/backups/...node) and occur only on#109785 and
#109786, never on
masteror any otherPR, so they belong to those cancellation-engine branches. The remaining 2 rows are a different
module,
test_backup_restore_new/test_cancel_backup.py, which this PR does not touch and whichcontains no timing assertion at all.
Version info
26.8.1.470(included in26.8and later)