Skip to content

Make geohashesInBox interruptible while expanding a block of rows - #112273

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-geohashes-in-box-cancellation
Jul 30, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-geohashes-in-box-cancellation

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixes max_execution_time and KILL QUERY being ignored while a query evaluates geohashesInBox. 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 a PARTITION 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).

geohashesInBox expands every row of a block into an array inside a single executeImpl() call, and the pipeline checks the time limit and KILL QUERY only 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) nor geohashesInBox() (GeoHash.cpp:322-355) had a cancellation check, and create(ContextPtr) discarded its context, so the function could not reach the QueryStatus. The per-row max_array_size guard 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 to max_array_size items while a degenerate box holds none. As in arrayFold, the break mode's false return becomes a throw: a half-filled Array(String) is a wrong value, not a smaller one.

Scope: this fixes evaluation on the live query context. Against a 1s limit a direct SELECT goes from 20853ms to 1196ms and a MATERIALIZED column from 9629ms to 1180ms, while a sorting key, a skip index and a PARTITION BY are 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 break mode 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_cancellation asserts cancellation latency from system.query_log across 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.cpp needs no checkpoint of its own: the worst legal single row
costs ~1.9s on an ASan build and anything larger is already refused with TOO_LARGE_ARRAY_SIZE, so
the per-row check already bounds the window at that order.

On master, no fuzzer, no server, default settings:

SELECT geohashesInBox(materialize(0.0), materialize(0.0), 0.0000106, 0.0000053, toUInt8(12))
FROM numbers(200000) FORMAT Null
SETTINGS max_block_size = 200000, max_threads = 1, max_execution_time = 1;
-- Code: 159 ... elapsed 32234.854 ms, maximum: 1000 ms

Debug builds, build ids asserted against the binaries, 1s limit, INSERT ... SELECT number, 0.0, 0.0 FROM numbers(60000) for the persisted cases:

evaluation path with this PR master
direct SELECT 1196ms 20853ms
MATERIALIZED column 1180ms 9629ms
sorting key 9629ms 9868ms
skip index 9678ms 9691ms
PARTITION BY 9675ms 9750ms

Cheap-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, h3ToChildren and the plan-time constant-folding path have the
same 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 was GeoHash.cpp:335 under FunctionGeohashesInBox::executeImpl inside PipelineExecutor, with elapsed: 2972 and is_cancelled: 1.

Version info

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
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,
in three rounds: on the original fix, on the round-1 corrections, and on the round-2 corrections. The
third round came back clean on both halves, with the source hunk unchanged since round 1. Fourteen
adjudicated findings in total; the substantive ones are below with the verdict I reached on each.

# Severity Finding Verdict
❌ 1 blocker Rows producing an empty array (reversed bounds or a NaN coordinate) added 0 to the throttle accumulator, so a block made only of such rows never reached a cancellation check at all. The in-diff comment also claimed a row always holds at least one item, which is false on that path. AGREE, fixed
❌ 2 blocker The zero-item regression cases added to close finding 1 read 150M rows, but the stateless test profile caps max_rows_to_read at 20M, so the bounded numbers source raised TOO_MANY_ROWS at plan time and the function was never entered. Both cases passed on an unfixed binary. AGREE, fixed
⚠️ 3 major The readiness poll in the KILL QUERY helper had no failure branch: a target query that never started still produced a fast kill and printed the passing line, so any setup failure was invisible. This is what hid finding 2. AGREE, fixed
⚠️ 4 major The expanding-row kill case waited only for the query to appear in system.processes. ProcessList::insert makes it visible before the pipeline executor is attached, so a kill winning that race is thrown from addPipelineExecutor instead of the new in-loop check, and the case could pass without the fix. AGREE, fixed
⚠️ 5 major The no-time-limit liveness case expanded only the 6-item documented example, which is below the 1M-item throttle, so it never reached a checkpoint. An implementation that threw unconditionally once the checkpoint was reached would still have passed every reference line. AGREE, fixed
⚠️ 6 major The changelog entry names KILL QUERY, but every test case drove cancellation through max_execution_time only, so the killed path was unverified. AGREE, fixed
💡 7 nit Use Context::getProcessListElementSafe() (returns empty) instead of getProcessListElement() (throws LOGICAL_ERROR if the weak pointer expired). DISAGREE
💡 8 nit The checkpoint sits before the row's encode work, so the uninterruptible window is one full row. DISAGREE (correct as documented)
💡 9 nit The readiness poll in the kill helper is capped at 10 seconds, which a badly loaded sanitizer runner could in principle exceed. AGREE, noted

On 1. geohashesInBoxPrepare returns a default-constructed result for a degenerate box
(GeoHash.cpp:274-283), and items_count defaults to 0 there; the std::max<UInt64>(1, ...) floor
applies only on the success path. Reversed bounds are documented supported input and an existing test
already passes a non-finite coordinate, so the path is reachable from ordinary SQL. Each row now
counts as at least one work unit, the comment states the real invariant, and zero-item regression
cases were added. A mutant reverting just the floor regresses those cases while leaving the
pre-existing ones green.

On 2. tests/config/users.d/limits.yaml sets max_rows_to_read to 20M for every stateless run,
and it is a fixed profile limit rather than a randomized one. A bounded numbers(150000000) source
therefore fails the up-front row estimate in ReadFromSystemNumbersStep before any row is expanded.
The failure was silent for the reason in finding 3, and it was invisible locally because the profile
had not been installed on the server used for the measurements. Fixed by disabling the read limit for
those two target queries, as 04409_skip_index_build_cancellation and
04028_kill_query_expression_cancelled do for the same reason, and re-measuring both directions with
the profile actually in place.

On 3. The poll now records whether the target reached the row loop and prints a distinct line if
it did not, so a setup failure is a reference mismatch instead of a pass, and the target's error
output is surfaced on that path.

On 4. The expanding case now waits for measurable execution time before killing, so the
cancellation has to be observed inside the row loop. A mutant that keeps the whole change but raises
the throttle so the in-loop check can never fire regresses all three kill cases, which is what pins
them to the new check rather than to executor attachment.

On 5. Fixed by adding cases that cross the 1M-item threshold with no time limit set and assert
exact results. The mutation that closes it makes the check throw unconditionally: the new cases fail,
the pre-existing ones still pass.

On 6. The implementation does cover KILL QUERY (QueryStatus::checkTimeLimit ->
throwProperExceptionIfNeeded), and one of the recorded mutants already proved the converse (an
isKilled()-only check fails the timeout cases). External-kill cases were added so the claim in the
changelog is defended by a test; they set no time limit at all, so max_execution_time cannot be
what stops them.

On 7 (DISAGREE). The two forms differ only when the process-list weak pointer has expired. The
function object is constructed during analysis while the QueryStatus is alive, so that is not
reachable here; the three closest in-tree analogues (arrayFold, h3PolygonToCells,
h3PolygonToCellsWithContainment) all use the non-safe form, and a 30-day CI-database scan finds no
occurrence of the corresponding LOGICAL_ERROR. Matching the precedent this change follows is the
better outcome.

On 8 (DISAGREE). With the largest legal row the check fires before that row's work, so the
uninterruptible window is exactly one row. That is the ~1.9s bound the description states and the
reason GeoHash.cpp is left untouched, so the placement reports its own cost accurately.

On 9 (noted, not changed). Reaching the row loop takes 0.6-1.4s on a debug build, so the cap has
roughly an order of magnitude of headroom, and finding 3 already removed the failure mode that would
have made a stall dangerous: if the poll ever did time out, the test prints a line that is absent from
the reference file, together with the target query's error output, so the result is a readable failure
rather than a false pass. Left as it is on that basis.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT geohashesInBox(materialize(0.0), materialize(0.0), 0.0000106, 0.0000053, toUInt8(12)) FROM numbers(200000) FORMAT Null SETTINGS max_block_size = 200000, max_threads = 1, max_execution_time = 1 -> Code: 159 ... elapsed 32234.854 ms, maximum: 1000 ms on a pristine build of this PR's merge-base. One command, no fuzzer, no server, no randomization.
b Root cause explained? Yes. A block's rows are all expanded inside one executeImpl() call (row loop geohashesInBox.cpp:113 -> GeoHash.cpp:322-355) with no cancellation checkpoint, and create(ContextPtr) discarded its context so the function had no QueryStatus. The per-row max_array_size guard bounds one row, not the loop, so the only checkpoint was the block boundary and max_execution_time / KILL QUERY were observed only after the block finished.
c Fix matches root cause? Yes. It adds the missing checkpoint at the layer that lacked one, rather than widening a bound, lowering max_array_size, tagging a test or guarding a symptom. GeoHash.cpp is untouched on purpose: the worst legal single row costs ~1.9s on ASan and anything larger is already refused with TOO_LARGE_ARRAY_SIZE, so a per-row checkpoint already bounds the window at that order.
d Test intent preserved / new tests added? New test 04648_geohashes_in_box_cancellation: both overflow modes, both coordinate widths, KILL QUERY with no time limit set at all (three shapes), blocks of degenerate boxes that produce no items, and two liveness cases that cross a checkpoint with no deadline so a check that fired whenever it was reached would fail them. No existing test weakened or retagged: 00932_geohash_support, 00972_geohashesInBox, 01351_geohash_assert, 01426_geohash_constants, 01684_geohash_ubsan, 04327_geohashesInBox_const_mix_and_bfloat16, 04408_array_fold_cancellation all still pass (8/8).
e Both directions demonstrated? Yes, with the real test harness on two Build-ID-verified servers, both running the stateless default test profile (tests/config/users.d/limits.yaml, verified live from system.settings before each run): FAILS on a master-HEAD binary (46.80s, six discriminating lines: float64 throw ran 9410ms, float64 break ran 8662ms, float32 throw ran 9333ms, expanding kill blocked 8414ms, degenerate kill blocked 1705ms, nan kill blocked 1905ms) and PASSES with the fix (11.07s). Also 9 mutants, each rebuilt with a moved Build ID: reverting the fix, neutering the in-loop check (twice, once with the kill cases present, which is what proves they depend on the in-loop checkpoint rather than on addPipelineExecutor), swapping checkTimeLimit() for isKilled(), discarding the break-mode return, forcing the member to nullptr, and reverting the per-row work-unit floor all fail; making the check throw unconditionally fails exactly the two liveness cases and nothing else; setting the throttle to 1 passes, so the throttle value is a perf knob and not what makes the test pass.
f Fix is general across code paths? The change is in the shared execute<>() template body, so both Float32 and Float64 instantiations are covered by construction (the test exercises both). The same missing-checkpoint pattern in h3kRing, h3HexRing, h3Line and h3ToChildren is left to separate PRs (one concern per PR) and named in the description; the plan-time constant-folding path is a different layer, also tracked separately.
g Fix generalizes across inputs (params/datatypes/wrappers)? Const and non-const arguments share the row loop (useDefaultImplementationForConstants() plus the per-argument ColumnConst unwrap with <x>_const ? 0 : row indexing), so mixed-const calls are covered. Degenerate boxes are the interesting case and needed a fix of their own: geohashesInBoxPrepare reports zero items for reversed bounds or any NaN coordinate (its std::max<UInt64>(1, ...) floor applies only on the success path), so the accumulator now counts each row as at least one work unit and a block of all-degenerate rows still reaches a checkpoint. Both zero-item entries, reversed bounds and NaN, have dedicated test cases verified to fail on master. Both float widths and precision 1 (1 item/row) and 12 (1024 items/row) measured.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting (so no SettingsChangesHistory.cpp entry), no serialization/format/protocol change, no on-disk representation, no experimental gate. One intended user-visible change, stated in the description: in break overflow mode a cancelled call now stops early instead of silently running to completion, matching arrayFold after #108192.
i Invariants and contracts preserved? The accumulate-and-check sits after the TOO_LARGE_ARRAY_SIZE guard, so that error path is byte-for-byte unchanged, and before the result resize(), so a cancelled row bails out before allocating. The function throws rather than returning a partially built column, so the two post-loop size invariants are never evaluated on a half-filled column and no partial Array(String) can escape. A null process_list_element (background merges, constant folding, clickhouse local without a process-list entry) stays a silent no-op, guarded as in arrayFold. No locks and no shared mutable state involved.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nikitamikhaylov @scanhex12 - could you review this? geohashesInBox expands a whole block of rows inside one executeImpl() call with no cancellation checkpoint, so max_execution_time and KILL QUERY were only observed at the block boundary (the reported hang ran 2972s after cancellation). It adds a checkpoint to the row loop following the merged arrayFold fix (#108192), throttled on accumulated work units rather than rows so that a block of degenerate boxes, which produce no items, still reaches a check.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [782668a]

Summary: ✅


AI Review

Summary

This PR adds an in-loop cancellation checkpoint to geohashesInBox and a focused stateless test around SELECT-time timeout / KILL QUERY behavior. The main executor path looks correct, but the fix is incomplete: insert-time key and index expression evaluation still builds the function outside the live query context, so those paths remain uninterruptible.

Findings

⚠️ Majors

  • [src/Functions/geohashesInBox.cpp:37] The new process_list_element capture only works when geohashesInBox is instantiated on the current query context. MergeTree still evaluates the function from global / stored expression contexts in several insert-time surfaces: MergeTreePartition::executePartitionByExpression reuses metadata_snapshot->getPartitionKey().expression, and MergeTreeDataWriter rebuilds sorting-key / skip-index expressions through MergeTreeData::getSortingKeyAndSkipIndicesExpression, where MergeTreeData holds context_->getGlobalContext(). In those paths process_list_element is null, so INSERT into a table whose PARTITION BY, ORDER BY, or skip index uses geohashesInBox still ignores max_execution_time and KILL QUERY while expanding a large block.
    Suggested fix: plumb the live query status into those execution surfaces, or rebuild those expressions on the current query context instead of the storage/global context.
Tests

⚠️ Add one focused INSERT regression that exercises geohashesInBox from a MergeTree metadata expression, e.g. PARTITION BY geohashesInBox(...) or ORDER BY geohashesInBox(...), and asserts that cancellation latency stays bounded there too. The new stateless test only proves the ordinary SELECT executor path.

Final Verdict

Needs changes.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Flaky check on the new test 04648: exempted, with the measurements

The previous head reddened Stateless tests (*, flaky check) on four sanitizers. The failure was
mine, not a bug in the fix: every diff was confined to the two KILL QUERY ... SYNC timing lines,
and the TIMEOUT_EXCEEDED half of the test stayed green throughout, so the checkpoint in
geohashesInBox.cpp behaves as intended. The source hunk is unchanged in this push.

What the results actually separate is self-concurrency, not sanitizer flavour:

Job shape 04648
flaky check (amd_asan_ubsan / amd_tsan / amd_debug / amd_msan) 17 FAIL of 20
targeted (--flaky-check --no-self-parallel, arm_asan_ubsan) OK 5/5
ordinary stateless (amd_debug, amd_tsan, arm_binary, amd_asan_ubsan distributed plan) OK 3/3 each
Bugfix validation (amd64, aarch64) OK

All 20 observations that were not self-parallel passed, including five reruns under targeted.

Every assertion in the test is a cancellation latency, so under the flaky check it measures the
contention between the test's own copies. I checked whether widening the bound would work instead,
and it cannot: an unfixed server returns the two zero-item KILL cases in 1705-2107ms, while the
fixed server under self-parallel reruns was observed at up to 1437ms on those same cases. The
distributions overlap, so no bound both passes a loaded fixed server and fails an unfixed one, and
a bound wide enough for the loaded fixed side would also pass an unfixed binary. Those two cases
exist precisely to catch the zero-item throttle defect, so making them vacuous is worse than losing
the rerun coverage.

So the test now carries no-flaky-check, which is what
04306_insert_stream_timeout_flush_http_input.sh uses for the same reason ("verifies a
timeout-based behavior and is not suitable for rerun-based flakiness detection"). The long tag
stays. Coverage that remains: all nine ordinary stateless variants and both Bugfix validation jobs.

I considered no-parallel rather than no-flaky-check and rejected it: tests/clickhouse-test:4090
only adds a no-parallel test to the sequential set if not args.no_sequential, and the parallel
job flavour passes --no-sequential, so it would stop the four jobs where this test is currently
green from running it at all. It would also mis-state the reason, since the test is already isolated
to $CLICKHOUSE_DATABASE; its problem is latency measurement under load, not isolation.

Verified on the fixed binary against the installed CI profile (max_rows_to_read = 20000000
asserted in-run): the test passes an ordinary run, is SKIPPED under --flaky-check, and an
untagged sibling (04408_array_fold_cancellation) still runs under --flaky-check, so the skip
comes from the tag rather than the invocation.

test_multiple_disks/test.py::test_concurrent_alter_modify[replicated] on this PR is unrelated to a
geo function; it gets an owner in the finish ledger once CI completes.

@PedroTadim PedroTadim self-assigned this Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The two reds on f4464c71 were both the new test's expanding kill assertion, and both were a
latency margin rather than the fix failing. Pushed 96c3567f4b9d56 to size that bound per case.

What failed

-expanding kill returned promptly
+expanding kill blocked 1992ms     <- Stateless tests (amd_tsan, s3 storage, parallel, 3/3)
+expanding kill blocked 1230ms     <- Stateless tests (amd_msan, WasmEdge, parallel, 1/2)

Everything else in the 12-line reference matched on both shards, so the query was being interrupted
correctly; only the assertion on how long KILL ... SYNC may block was wrong.

Why one shared bound was the defect

run_kill_case asserted a single 1000 ms bound for all three KILL cases. That bound has to separate
"the cancel is seen at the next in-loop checkpoint" from "the whole block is finished first", but the
second half is a property of each case's own block, and the three cases differ by almost an order of
magnitude. Measured under the CI limits profile:

case unfixed (local) unfixed (CI) fixed, unloaded fixed, loaded shard
expanding 8215-9656 ms 13030-16729 ms ~104 ms 1230 ms, 1992 ms
degenerate 1806-2107 ms 13725-14335 ms ~104 ms up to 1367 ms
nan 1806-2106 ms 13826-14227 ms ~103 ms up to 1437 ms

Sharing one bound pinned it to what the cheapest case can prove, which left the expanding case with
no margin for ordinary runner load. Note both reds are parallel flavour jobs that run the test
once, so this is not self-contention from repeated runs.

The CI numbers above come from this PR's own Bugfix validation jobs, which run the test against
master-HEAD binaries and therefore measure the unfixed side directly on CI hardware.

The change

The bound is now passed in per case. Expanding gets 4000 ms, the same 4x-the-limit allowance
check_duration in the same file already uses: about 2x above the loaded fixed observations and
about 2x below the cheapest unfixed one. The two zero-item cases keep 1000 ms, where they have never
failed and where there is no room to widen anyway, since past ~1800 ms they would stop failing an
unfixed binary. Both anti-vacuity guards (the readiness poll and the never reached the row loop
token) are untouched. Source is not touched: git diff f4464c71..HEAD -- src/ is empty.

Validation

Every arm asserted buildId() against the ELF before running and re-asserted liveness afterwards,
and printed max_rows_to_read and max_memory_usage from system.settings so the CI profile is
proven present.

  1. fix binary: OK, KILLs return in 103-104 ms.
  2. pristine master snapshot: FAIL on all 6 discriminating lines, expanding kill blocked 8413ms
    against the new 4000 ms bound.
  3. mutant, in-loop throttle raised to UInt64::max so the checkpoint can never fire: FAIL on
    exactly the 6 predicted lines, including expanding kill blocked 8315ms. This is the check that
    matters for a widening: the expanding case still fails at the wider bound, so the bound is not
    vacuous.
  4. 50 randomized runs: 50/50 OK.

Comment thread src/Functions/geohashesInBox.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed a0c415d4bb27c3: the degenerate and nan cancellation cases now calibrate against their own block instead of against a fixed number of milliseconds. Test file only, no change to src/.

Stateless tests (amd_tsan, parallel) reported degenerate kill blocked 1150ms against a 1000ms bound. Every other reference line matched, including both TIMEOUT_EXCEEDED rows and the expanding case, so the in-function checkpoint was doing its job and only the bound was wrong.

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 expanding case uses would have made them vacuous.

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:

server idle 12 competing queries
with the fix 0.21, 0.31, 0.24, 0.10 0.21, 0.11, 0.25, 0.23
without the fix 0.94, 0.79, 1.00, 1.00 0.97, 0.86, 0.80, 1.02

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, tests/config/install.sh profile live:

  • fix arm OK in 15.7s and 16.4s; pristine master FAILs with degenerate kill ran 2846ms of a 2542ms block and nan kill ran 2618ms of a 2671ms block
  • neutering the ratio comparison removes both lines from the unfixed diff, so they are produced by the new assertion rather than surviving it
  • removing the calibration run fails loudly with of a 0ms block rather than passing silently
  • 10 of 10 runs OK under default randomized settings

The calibration run also needs max_result_bytes = 0: expanding all 150M rows yields 150M array offsets, about 1.12GiB, over the 1G test-profile cap that the cancelled runs never reach.

# 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

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.

@groeneai trim the comments in this test file!

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.

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
@groeneai
groeneai force-pushed the groeneai/fix-geohashes-in-box-cancellation branch from 7243868 to ce89fc1 Compare July 29, 2026 20:33
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed ce89fc19bc693f. The arm_binary, parallel failure on the previous head was mine: the two
calibrated cases measured the wrong quantity.

The numerator was the killed query's own lifetime, and that includes the readiness poll. The poll
spawned a fresh clickhouse-client process per 20 ms iteration, which I measured at ~70 ms each
against ~10 ms for the same query over HTTP. On a loaded runner the poll alone consumed most of the
block, so the KILL was issued near its end and the ratio landed inside the unfixed range even
though the checkpoint fired 1 ms after the cancel request. In the failing run the degenerate query
had already finished 76 ms before the kill was issued at all, which the oracle scored as a pass on
nan and a miss by 8 ms on degenerate.

Two changes. The poll now goes over HTTP, and the numerator is how long KILL ... SYNC blocked
rather than how long the killed query lived: the poll completes before the kill is issued, so its
cost is outside the measurement either way. Under twelve competing queries the ratio moves from
0.22-0.29 to 0.04-0.08 while the unfixed range stays at 0.78-0.86, so the two distributions separate
by an order of magnitude instead of the previous factor of four. QUERY_WAS_CANCELLED is asserted
before the ratio, because killing a query that has already finished returns instantly and would
otherwise score perfectly; delaying the kill past the block's completion passes the old oracle and
fails this one.

Verified both directions on the debug build (OK in 14.3 s) and against a pristine master snapshot
(FAIL, all six assertion lines move, calibrated ratios 0.90 and 0.83). 50 runs under the default
randomized settings: 50 OK, 0 failures.

While checking one review comment I found a pre-existing gap that this PR does not address and that
I have filed separately: when geohashesInBox sits in a sorting key, a skip index or a partition
expression, those actions are built from the storage's global context, so the function captures no
query status and an INSERT still overshoots its own max_execution_time (measured ~9.7 s against a
1 s limit, identically with and without this PR). The MATERIALIZED column path does get fixed here
(9776 ms to 1192 ms). Four other functions hold the same constructor-captured status and are blind in
the same way, so the fix belongs at the resolution mechanism rather than in this function.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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::executePartitionByExpression executes the prebuilt metadata_snapshot->getPartitionKey().expression.
  • MergeTreeDataWriter::writeTempPartImpl and writeProjectionPartImpl rebuild sorting-key / skip-index expressions through MergeTreeData::getSortingKeyAndSkipIndicesExpression, and MergeTreeData stores WithMutableContext(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.

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.

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.

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 22/23 (95.65%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 782668a

CI 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 Config Workflow and Finish Workflow green. CIDB returns no FAIL or ERROR row for this commit either.

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 expanding kill bound on f4464c71, and the arm_binary, parallel failure on ce89fc19bc693f. The degenerate and nan cases now calibrate against their own measured baselines, and the block-size reduction landed here, so the test passes on every job including the flaky check.

Session id: cron:our-pr-ci-monitor:20260730-020000

@PedroTadim
PedroTadim added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 91f5dc3 Jul 30, 2026
179 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
alexey-milovidov added a commit to EilRoviSoft/ClickHouse that referenced this pull request Aug 1, 2026
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]>
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

04648: the three surviving promptness assertions still overshoot, and I cannot find a sound oracle for them

Since 3f0e190150e2090 merged, 04648_geohashes_in_box_cancellation has failed 4 times in 4 unrelated pull
requests on the current file (filtering test_name = '04648_geohashes_in_box_cancellation' to check_start_time > '2026-08-02':
4 FAIL across 4 distinct pull requests against tens of thousands of OK rows; master 0 FAIL, both statuses
projected in one query so a stray non-zero count cannot creep in). The fix is present on every failing build, so this is a residual rather than a regression:

check observed
amd_tsan, parallel expanding kill blocked 4464ms
arm_asan_ubsan, azure, parallel float64 throw ran 5355ms past a 1000ms limit
arm_asan_ubsan, azure, parallel float64 break ran 7167ms past a 1000ms limit
amd_tsan, parallel expanding kill blocked 5251ms

The 100'000-item span is not at fault. Measured on a debug build at the test's own box and settings, the
in-function stop is tight and load-insensitive: checkTimeLimit reports elapsed 1001-1017 ms against a
1000 ms deadline in 23 of 23 runs, 12 of them at loadavg 63-103, and it tracks the deadline exactly
(elapsed 2010.861 ms at 2 s, 3003.170 ms at 3 s). One span is ~16 ms of work.

What moves is the rest of query_duration_ms. That quantity starts at ProcessList::insert, so it is
deadline + prologue + post-checkpoint teardown, and the teardown scales with what was built before the
deadline: cancelled peak 282 / 542 / 677 / 1098 MB at deadlines 1/2/3/4 s, against 2154 MB for the
uncancelled block. This is the same term you identified for the zero-item KILL cases in 3f0e190150e2090
("it includes tearing 1.25GiB down, which on a fast release build is most of it") - it applies to the
expanding box too, just with a larger margin hiding it.

I tried to replace the wall clock with something teardown-free. Nine oracles, each refuted by measurement:

oracle why it fails
wall clock x build-flavour factor 2x gives a 7000 ms bound against a 7167 ms occurrence
peak-memory ratio vs a calibration run peak is quantized by geometric PODArray growth plus Allocator::realloc's double charge (282/542/677 MB at 1/2/3 s), and it needs a 2.1 GB / 9.7 s calibration query
delivered row count vacuous: at 97 rows the checkpoint provably cannot fire (99328 < 100'000 items) yet break still emits 0 rows, because PipelineExecutor::checkTimeLimitSoft() runs after executeTask() and breaks before ISimpleTransform pushes its staged output
max_memory_usage cap window is ~2.0x on a slow arm; and the expanding kill victim has no max_execution_time, so its peak is bounded by when the kill lands, not by the checkpoint
a memory readiness floor no floor separates: pre-function peak 4.49 MB vs minimal in-loop peak 4.97 MB
elapsed from the timeout message PipelineExecutor::execute calls the same QueryStatus::checkTimeLimit at :201, before executeImpl at :209, so a pre-function timeout prints the same parseable message (elapsed 3.995 ms, maximum: 1 ms)
ProfileEvents['SelectedRows'] SELECT count() FROM numbers(60000), which never calls the function, also reports 60000
ProfileEvents['FunctionExecute'] 0 for a genuine minimal in-loop stop, 2 at a 1 s deadline
a new ProfileEvent inside the checkpoint block proves a checkpoint was reached, not that it cancelled: delete checkQueryTimeLimit() and keep the increment, and every assertion still passes

The function's own message at geohashesInBox.cpp:216 would be attributable, but it is unobservable in both
modes: in throw mode process_list_element->checkTimeLimit() throws first, and in break mode the
pipeline absorbs it (exception_code = 0, empty exception in query_log). Measured 0 occurrences of
in function geohashesInBox in every state and mode.

The mode outcomes cannot carry the assertion either. On an unfixed build your own report shows
float64 throw ran 4419ms past a 1000ms limit, which means the TIMEOUT_EXCEEDED grep had already
succeeded - with 60000 rows in one block, an unfixed build finishes the block and the pipeline throws
afterwards, so TIMEOUT_EXCEEDED is observed either way.

So I think this is your call rather than mine, and it is the same call you already made once for this file:

  • (a) Delete the three remaining promptness assertions, keeping the boxes in the liveness checks, as you
    did for the reversed and NaN cases. Cost: Make geohashesInBox interruptible while expanding a block of rows #112273's fix keeps only liveness coverage - nothing would
    catch a regression that makes the row loop uninterruptible again.
  • (b) Keep them and accept the flake rate (~4 per 12000 runs, 0 on master). Cost: the reds land on
    unrelated pull requests, which is where the four above came from.
  • (c) Make the property observable - e.g. increment a counter only when the checkpoint actually
    observes cancellation, which needs a try/catch inside the row loop, or expose it some other way you
    would accept. This is a product change for a test's benefit, so I did not want to propose it unilaterally.

I lean towards (a) on the same reasoning as 3f0e190150e2090 - an assertion that cannot be made sound is
worse than no assertion - but (a) gives up real coverage, so I would rather you decided. Happy to send the
patch for whichever you prefer.

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 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.

3 participants