Repository navigation
Make geohashesInBox interruptible while expanding a block of rows - #112273
PedroTadim merged 2 commits into
Conversation
Internal second-model review (2 blockers + 4 majors found and fixed before publication)Before opening this PR I reviewed the change independently and then ran a second model over it cold,
On 1. On 2. On 3. The poll now records whether the target reached the row loop and prints a distinct line if On 4. The expanding case now waits for measurable execution time before killing, so the On 5. Fixed by adding cases that cross the 1M-item threshold with no time limit set and assert On 6. The implementation does cover On 7 (DISAGREE). The two forms differ only when the process-list weak pointer has expired. The On 8 (DISAGREE). With the largest legal row the check fires before that row's work, so the On 9 (noted, not changed). Reaching the row loop takes 0.6-1.4s on a debug build, so the cap has |
Pre-PR validation gate (click to expand)
Performance on the pathological cheap-row shape (1 item per row, 20M rows, 3 reps each, same build flavour as the paired base): before 0.814 / 0.816 / 0.815 s, after 0.820 / 0.820 / 0.810 s. On the other cheap regime the work-unit floor introduces, 100M zero-item rows: before 0.304 / 0.297 / 0.282 s, after 0.284 / 0.283 / 0.284 s. The new test passed 50/50 runs under randomization. Session id: cron:clickhouse-impl-slot-47:20260728-095800 |
|
cc @nikitamikhaylov @scanhex12 - could you review this? |
|
Workflow [PR], commit [782668a] Summary: ✅
AI ReviewSummaryThis PR adds an in-loop cancellation checkpoint to Findings
Tests
Final VerdictNeeds changes. |
Flaky check on the new test 04648: exempted, with the measurementsThe previous head reddened What the results actually separate is self-concurrency, not sanitizer flavour:
All 20 observations that were not self-parallel passed, including five reruns under Every assertion in the test is a cancellation latency, so under the flaky check it measures the So the test now carries I considered Verified on the fixed binary against the installed CI profile (
|
|
The two reds on What failedEverything else in the 12-line reference matched on both shards, so the query was being interrupted Why one shared bound was the defect
Sharing one bound pinned it to what the cheapest case can prove, which left the expanding case with The CI numbers above come from this PR's own The changeThe bound is now passed in per case. Expanding gets 4000 ms, the same 4x-the-limit allowance ValidationEvery arm asserted
|
|
Pushed
That bound cannot be sized. An unfixed server returns these two cases in 1806-2107ms while a loaded fixed server was measured at up to 1437ms, so the two distributions overlap and any value above the observed load also passes an unfixed binary, which is what the cases exist to catch. Raising it to the 4000ms the Both terms of a ratio move together under load, so each case now runs its own block once to completion and requires the killed run to have taken less than half of it:
Halving sits about 1.6x clear on both sides where the millisecond bound had 1.2x, and the added load moved neither range. Verification, debug build,
The calibration run also needs |
| # check_duration above already uses, for the same reason. | ||
| run_kill_case "expanding" "$BOX" 60000 "$SETTINGS" "max(elapsed) > 1" 4000 | ||
|
|
||
| # Degenerate rows produce no items at all, so a checkpoint throttled only on accumulated items would |
There was a problem hiding this comment.
Done in 724386880e52bd: every comment block in the file is now three lines or fewer, matching the three-line limit you asked for on the fuzzer PR earlier today. 124 comment lines down to 48.
The rationale that was inline is in the commit message instead, since explanation belongs there rather than in the file. The change is comment-only, verified mechanically: git diff -U0 against the previous head has zero non-comment changed lines, so the reference file is untouched. I re-ran both arms to confirm the trim changed nothing behaviourally - the test still passes on this branch (14.1s) and still fails on a pristine master binary with the same six assertion lines moving.
`geohashesInBox` expanded every row of a block in one tight loop with no cancellation checkpoint, so neither `max_execution_time` nor `KILL QUERY` could interrupt it until the whole block was done. A hung check on a stress run caught a query still inside that loop after 2972 seconds with `is_cancelled` already set. The overshoot scales with the rows per block, which is why it surfaces on a fuzzer run rather than in ordinary use. The row loop now consults the process list element, throttled so the check costs nothing on cheap blocks, and every row counts as at least one work unit so that a box yielding no geohashes still reaches the checkpoint. `checkTimeLimit` throws for `KILL QUERY` and the 'throw' overflow mode; in 'break' mode it returns false, and because a half-filled `Array(String)` is a wrong value rather than a smaller one, the false return is turned into a throw and the pipeline absorbs it as a clean cancellation. The regression test covers both coordinate instantiations, both overflow modes and `KILL QUERY`, and asserts the cancellation latency rather than merely that the query ended. For the two zero-item cases no fixed millisecond bound separates the fixed and unfixed distributions on a loaded runner, so those compare the time `KILL ... SYNC` blocked against the same block run to completion; measured under twelve competing queries that ratio is 0.04-0.08 with the fix and 0.78-0.86 without it. `QUERY_WAS_CANCELLED` is asserted before the ratio, because killing a query that already finished returns instantly and would otherwise score perfectly. The readiness poll runs over HTTP rather than through a fresh client process per iteration, which measured ~70ms against ~10ms and would otherwise be spent inside the window being measured. Related: ClickHouse#107941
7243868 to
ce89fc1
Compare
|
Pushed The numerator was the killed query's own lifetime, and that includes the readiness poll. The poll Two changes. The poll now goes over HTTP, and the numerator is how long Verified both directions on the debug build ( While checking one review comment I found a pre-existing gap that this PR does not address and that The commits are squashed into one; the tree is byte-identical to the eleven-commit version. |
The degenerate and NaN kill cases ran a 60M-row block per case rather than 150M. The larger block held 4.26GiB at peak, 91% of the 5GB max_memory_usage the cases set for themselves, which leaves no headroom on a sanitizer job for reasons unrelated to the behaviour under test. The calibrated oracle compares how long KILL ... SYNC blocks against the same block run to completion, so the block cannot shrink freely: cancelling costs a fixed floor of about 100ms regardless of size, while the uncancelled cost is proportional to it, so a smaller block only shrinks the denominator and pulls the two distributions together. Measured under 12 competing queries, worst of three repetitions per case, 150M gives 0.081 fixed against 0.782 unfixed and 60M gives 0.121 against 0.660, both separated around the 0.5 threshold, while 10M collapses to 0.556 against 0.550 and fails on a build that has the fix. 60M is therefore the smallest count that still separates, and it cuts peak memory to 1.25GiB. Going lower is not available by relaxing the bound either: at 2M the block finishes before the kill is issued, so both cases report that the query ended uncancelled rather than measuring anything.
| static FunctionPtr create(ContextPtr context) { return std::make_shared<FunctionGeohashesInBox>(context); } | ||
|
|
||
| explicit FunctionGeohashesInBox(ContextPtr context) | ||
| : process_list_element(context ? context->getProcessListElement() : nullptr) |
There was a problem hiding this comment.
This only fixes the query-tree execution path that instantiates geohashesInBox on the live query context. MergeTree still has insert-time execution surfaces where the function is built from a non-query context, so process_list_element stays null and checkQueryTimeLimit never fires there:
MergeTreePartition::executePartitionByExpressionexecutes the prebuiltmetadata_snapshot->getPartitionKey().expression.MergeTreeDataWriter::writeTempPartImplandwriteProjectionPartImplrebuild sorting-key / skip-index expressions throughMergeTreeData::getSortingKeyAndSkipIndicesExpression, andMergeTreeDatastoresWithMutableContext(context_->getGlobalContext()).
So INSERT into a MergeTree table whose PARTITION BY, ORDER BY, or skip-index expression calls geohashesInBox still ignores max_execution_time / KILL QUERY while expanding a large block. The changelog and title read as if the function is fixed generally, but these insert paths remain unaffected. This needs either the current query status to be plumbed into those executions, or those expressions to be rebuilt on the live query context, plus a focused INSERT regression covering one of these surfaces.
There was a problem hiding this comment.
Both halves of this are right, and they need different answers.
The mechanism is correct and I had already measured it while checking an earlier comment. Against a 1s
max_execution_time, an INSERT whose sorting key, skip index or PARTITION BY calls
geohashesInBox overshoots to 9629ms, 9678ms and 9675ms respectively, because those actions are built
from the storage's global context, so getProcessListElement() returns null and the checkpoint never
fires. The same three surfaces read 9868ms, 9691ms and 9750ms on a pristine master binary, so this PR
regresses none of them; it does fix the MATERIALIZED column path, 9629ms to 1180ms, and the direct
SELECT path, 20853ms to 1196ms. Both arms were measured just now on debug builds with the server's
buildId() asserted against readelf -n.
I am not folding the fix in. geohashesInBox is not special here: h3PolygonToCells:69,
h3PolygonToCellsWithContainment:90, arrayFold:37 and sleep:78 all resolve the query status once in
their constructor and go blind on exactly the same paths, so patching this one function while its
siblings stay blind would be the wrong layer. The real fix is either resolving the status at execution
time or threading the query context into the sorting-key, skip-index and partition action builders,
which is a src/Storages/MergeTree/ change spanning five unrelated function files. That is a separate
concern from a row-loop checkpoint, so a separate fix task is tracking it with the measurements above,
and I will link the follow-up PR here when it opens.
Your point about the wording is fair, so I have narrowed it rather than defended it. The entry said
cancellation was "ignored by the geohashesInBox function", which does read as general. It now scopes
itself to evaluation during a query and states that evaluations inside a persisted table expression are
not covered and are tracked separately. The description carries the per-path numbers.
I have not added an INSERT regression test here: it would assert the unfixed 9.7s behaviour, which
belongs with the fix, not with this PR.
There was a problem hiding this comment.
The follow-up is open: #113456
Two corrections to what I wrote above. The carrier set is six functions, not four: FunctionBaseXXConversion.h:313 (base58Encode/base58Decode/tryBase58Decode) captures the status in its constructor too, and it only shows up if you grep the getProcessListElementSafe spelling as well as getProcessListElement. And the storage-layer work I described as the alternative turned out not to be needed: resolving the status from the executing thread in the execute path, exactly as FunctionStringReplace.h already does, fixes all three persisted routes without touching src/Storages/MergeTree/. The same line also releases the QueryStatus that a strong member pinned against Context's deliberate weak_ptr.
One scope note carried over: h3PolygonToCells and h3PolygonToCellsWithContainment check isKilled() rather than checkTimeLimit(), so their loops consult no deadline at all and only KILL QUERY can stop them. That missing deadline check is a separate defect and is out of scope there.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 22/23 (95.65%) · Uncovered code |
CI finish ledger - 782668aCI is fully finished on this head and there is nothing to own: 174 check-runs, all completed, 0 failures (157 success, 17 skipped), with both This head clears the previously reported reds, all of which were in the new test's own cancellation assertions rather than in the change under test: the Session id: cron:our-pr-ci-monitor:20260730-020000 |
The two `KILL` cases on reversed and NaN bounds raced a window they could not be given. Rows whose box expands to nothing cost about 11ns each, so the row loop the kill has to land in lasts 650ms for the 60M-row block the cases use in a debug build and around 200ms in a release one, and the block cannot be made longer without being made bigger: it is already 1.25GiB. Against that, the readiness poll runs `curl` and then `clickhouse-client` per iteration, and a single fork stall on a loaded runner is enough to step over the whole window. In the report below the killed query lived from 18.394 to 19.005 while the poll slept between its first iteration at 18.233 and its second at 20.251, so `KILL` was finally issued 32 seconds after the query had already finished. Both cases also compared how long `KILL ... SYNC` blocked against the block run to completion, and that numerator is not only the remaining loop work: it includes tearing 1.25GiB down, which on a fast release build is most of it. Hence `nan kill ran 1190ms of a 1436ms block` on a build that has the fix. So the assertion is removed rather than retuned: an interruptible zero-item loop is not observable from a stateless test at a block size that fits in a CI job. The boxes stay in the liveness checks, which is where they exercise counting a row as a work unit at all. The cases that expand a box keep their assertions - one of those blocks runs for ten seconds or more against a one second deadline, so the cancellation lands inside the row loop whatever the load does, and they still fail on a build without the fix by 11x rather than by the 1.2x the zero-item cases had. The remaining bound was itself the third failure mode, as `float64 throw ran 4419ms past a 1000ms limit` on a loaded sanitizer build: with a checkpoint every million items, over three seconds of that was work already started and not yet interruptible. A checkpoint every 100k items is ~1.2MB of geohashes against a clock read, which keeps the same measurement an order of magnitude inside the bound and is what "cancelled promptly" should mean anyway. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8aad759007771032aa94d7f4eee3e18103dd63c3&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29 Related: ClickHouse#112273 Co-Authored-By: Claude Fable 5 <[email protected]>
04648: the three surviving promptness assertions still overshoot, and I cannot find a sound oracle for themSince
The 100'000-item span is not at fault. Measured on a debug build at the test's own box and settings, the What moves is the rest of I tried to replace the wall clock with something teardown-free. Nine oracles, each refuted by measurement:
The function's own message at The mode outcomes cannot carry the assertion either. On an unfixed build your own report shows So I think this is your call rather than mine, and it is the same call you already made once for this file:
I lean towards (a) on the same reasoning as |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
max_execution_timeandKILL QUERYbeing ignored while a query evaluatesgeohashesInBox. Such a query expanded every row of a block before it could be interrupted, so cancellation took effect only minutes later; the function now checks the query's time limit as it walks the rows. Evaluations inside a persisted table expression, such as a sorting key, a skip index or aPARTITION BY, are not covered and are tracked separately.Description
Related: #107941 (one carrier of that umbrella, which has other causes, so this does not close it).
geohashesInBoxexpands every row of a block into an array inside a singleexecuteImpl()call, and the pipeline checks the time limit andKILL QUERYonly between blocks, so nothing could interrupt it: a cancelled query kept burning a server thread until the whole block finished. Neither the row loop (geohashesInBox.cpp:113) norgeohashesInBox()(GeoHash.cpp:322-355) had a cancellation check, andcreate(ContextPtr)discarded its context, so the function could not reach theQueryStatus. The per-rowmax_array_sizeguard bounds one row, not the loop.This adds the checkpoint to the row loop, following
arrayFold(#108192), throttled on accumulated work units rather than rows because a row can hold up tomax_array_sizeitems while a degenerate box holds none. As inarrayFold, thebreakmode'sfalsereturn becomes a throw: a half-filledArray(String)is a wrong value, not a smaller one.Scope: this fixes evaluation on the live query context. Against a 1s limit a direct
SELECTgoes from 20853ms to 1196ms and aMATERIALIZEDcolumn from 9629ms to 1180ms, while a sorting key, a skip index and aPARTITION BYare unchanged: those actions are built from the storage's global context, so the function captures no query status. Four other functions share that captured status and are blind the same way, so that fix belongs at the resolution mechanism and is filed separately.Behaviour change worth calling out: in
breakmode a cancelled call now stops early and yields no rows for that call, where before it ran to completion. Cheap-row performance is unchanged.04648_geohashes_in_box_cancellationasserts cancellation latency fromsystem.query_logacross both overflow modes, both coordinate widths,KILL QUERY, degenerate boxes and two liveness cases. It fails on a master-HEAD binary and runs 50/50 under randomization.Reproduction and measurements
One check per 1M work units keeps the cost unmeasurable on cheap rows while still bounding the
uninterruptible window.
GeoHash.cppneeds no checkpoint of its own: the worst legal single rowcosts ~1.9s on an ASan build and anything larger is already refused with
TOO_LARGE_ARRAY_SIZE, sothe per-row check already bounds the window at that order.
On master, no fuzzer, no server, default settings:
Debug builds, build ids asserted against the binaries, 1s limit,
INSERT ... SELECT number, 0.0, 0.0 FROM numbers(60000)for the persisted cases:SELECTMATERIALIZEDcolumnPARTITION BYCheap-row shape, 1 item per row, 20M rows, 3 reps, base = this PR's merge-base: 0.819 / 0.829 / 0.818 s before, 0.828 / 0.827 / 0.826 s after.
h3kRing,h3HexRing,h3Line,h3ToChildrenand the plan-time constant-folding path have thesame missing-checkpoint gap; those are separate PRs, not folded in here.
In the wild it showed up as a hung-check artifact on
Stress test (arm_asan_ubsan), where the hung thread's innermost frame wasGeoHash.cpp:335underFunctionGeohashesInBox::executeImplinsidePipelineExecutor, withelapsed: 2972andis_cancelled: 1.Version info
26.8.1.414(included in26.8and later)