Skip to content

Check for cancellation while expanding one geohashesInBox row - #119116

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:geohashes-in-box-intra-row-cancellation
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:geohashes-in-box-intra-row-cancellation

Conversation

@groeneai

@groeneai groeneai commented Sep 10, 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):

Fixed max_execution_time and KILL QUERY being ignored while geohashesInBox expands a single row. One box can produce up to 10,000,000 geohashes inside one call, and the only cancellation checkpoint ran before that expansion started.

Description

Requested by @ alexey-milovidov in #109368 (comment) as a separate PR; #109368 is now closed. It does not fix the hung check in his artifact, whose reversed box is zero-item; the reachable shape is one legal box under the size cap.

Root cause. DB::geohashesInBox runs longitude_items * latitude_items encodes with no checkpoint. The caller's throttle, items_between_cancellation_checks = 100'000, ran before each row's expansion, so one row could overshoot the shared granularity, CancellationBudget::units_per_check = 65,536, by 152x.

The change. DB::geohashesInBox takes a CancellationBudget and charges once per emitted geohash, plus once for a row emitting nothing; the bespoke accumulator, its constant and its checkQueryTimeLimit helper are deleted. The caller's loop writing the same row's offsets is charged too: one such loop measures 51 ms of the 2417 ms a 9,997,500-item row takes, more than three times the 15.8 ms interval this fix establishes. Results are byte-identical, and the h3 functions use the same mechanism.

Validation. 05153 asserts which of two textually identical statements raises, for two boxes: one above the shared interval, one of 40,000 geohashes that can only raise once the offsets loop is charged. Every argument is a constant, so they run during analysis, where nothing absorbs the throw. Both arms are red on master. gtest_geohash_cancellation asserts where inside a row the check lands: at exactly one interval, with the output buffer partially written. Neither test replaces the other. The unit test reds when the per-encode charge is deleted, which SQL cannot see; 05153 reds when the budget's construction in executeImpl is deleted, which the unit test cannot see. 50 randomized runs; the 8 existing geohash tests pass.

Disclosed. If the per-encode charge is unwanted, ReplaceRegexpImpl.h's local accumulation is a two-line change, as long as its bulk charge stays under units_per_check; that call is yours.

Related: #109368

Measured latency and overhead, one row of 9,997,500 geohashes, debug build

Server-side query_duration_ms, max_threads = 1. Before the change the elapsed time is constant whatever the deadline is; after it, it tracks the deadline to within one checkpoint interval.

max_execution_time before after
0.05 s 1238 ms 57 ms
0.1 s 1205 ms 102 ms
0.3 s 1164 ms 300 ms
0.5 s not measured 507 ms
0.8 s not measured 801 ms

Cost of the checkpoints on the same expansion with no deadline, interleaved runs of one build against another on a loaded machine. The two sweeps below ran hours apart under different load, so only the deltas inside one sweep compare. Per-encode charge alone, 12 runs: minimum 1.250 s unchanged, mean 1.356 s against 1.384 s, median 1.355 s against 1.405 s, distributions overlapping. Both charges, 12 runs: minimum 2385 ms against 2404 ms, median 2424 ms against 2431 ms, mean 2419 ms against 2444 ms, ranges 2385-2453 ms against 2404-2513 ms. A second build of the unchanged tree measured in the same sweep differs from the first by 0.5 ms at the median, which is the noise this sits in.


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

groeneai and others added 4 commits September 9, 2026 19:32
geohashesInBox expands a single input row into up to max_array_size =
10,000,000 geohash strings inside one call to DB::geohashesInBox, and that
call held no cancellation checkpoint. The checkpoint the function did have sat
one frame above, in the caller's per-row loop, and was evaluated before the
expansion of the row it charged for, so for the whole of a large row neither
max_execution_time nor KILL QUERY was observed. The bespoke accumulator's own
comment claimed a bounded span of "100k items ... tens of milliseconds", but a
row near the array-size cap overshoots that by up to 100x.

The charge moves into the expansion, using the shared CancellationBudget
helper instead of the hand-rolled accumulator, so the checkpoint sits in the
same frame as the work. DB::geohashesInBox charges once per emitted geohash
and once for a row that emits none, which is the same total the caller charged
before: max(1, items_count) per row. The three charge sites are the three
exits of the function, the invalid-arguments guard, the nested loop and the
items == 0 fallback. The guard is the exit taken by a reversed-bounds or NaN
box, whose prepared precision is 0, so leaving it uncharged would have made a
block of such rows cost nothing at all.

Only when the units are charged changes; every result byte is unchanged, and
the granularity moves from a bespoke 100,000 to the shared 65,536.

Measured on one debug binary, one row expanding to 9,997,500 geohashes, with
max_threads = 1. Before, the reported elapsed at the timeout was 1258 ms for
max_execution_time = 0.05, 1186 ms for 0.1 and 1234 ms for 0.5, that is the
full expansion regardless of the deadline. After, the same query stops at 108
ms and 501 ms for 0.1 and 0.5, and under the break overflow mode at 51 to 57
ms, 103 to 105 ms and 501 to 508 ms for 0.05, 0.1 and 0.5. A block of
20,000,000 reversed-bounds rows takes 450 ms and now stops at 200 ms for a
deadline of 0.2, which is the guard charge site. The expansion of the same
9,997,500-item row costs 1.250 s by the minimum of twelve interleaved runs
either way, so the per-encode cost of the charge is within the noise of this
machine.
The oracle is which of two textually identical statements raises: the first
runs with no deadline and asserts the item count, the second adds
max_execution_time = 0.00001 with timeout_overflow_mode = 'break' and expects
TIMEOUT_EXCEEDED. Nothing measures a duration, so there is no wall-clock
constant to calibrate and nothing degrades on a slower flavour.

Every argument is a constant. An all-constant call is executed while the query
is analysed and again while it is planned, outside any processor, and an
exception from either reaches the client. Inside a pipeline it cannot:
ISimpleTransform::work() stores a function's exception on its output port, and
the deadline that produced it also makes the executor's own
checkTimeLimitSoft() false on the same loop iteration, so the executor cancels
and breaks before any downstream processor pulls that port. The query then ends
as QueryFinish with no error, on either overflow mode.

The box expands to 90,000 geohashes: above the 65,536 items the shared
checkpoint interval covers, and below the 100,000 the deleted per-row
accumulator needed before it read the clock. That window is exactly where a
single row was uninterruptible, so the statement raises with the checkpoint in
place and raises nothing without it, at any deadline, which removes the false
red a bounded-latency assertion would carry. The control statement prints the
count on every run and keeps it inside the window.

Measured on debug builds of the same tree, one commit apart: without the
checkpoint the arm returns rc 0, type QueryFinish, exception_code 0; with it,
rc 159, type ExceptionBeforeStart, and the message names geohashesInBox. Both
directions hold with settings randomization enabled (50/50 through the runner,
50/50 driven directly). Deleting the charge from the expansion loop, or making
makeCancellationCheck return an empty check, each turns the arm red.

Co-Authored-By: Claude Opus 5 <[email protected]>
05153 proves that a check fires somewhere inside one row, not that it fires
during the expansion, and no SQL statement can tell the two apart. The result
buffer is resized to the whole row before the first encode, so a partially
written row has the same size as a complete one; no ProfileEvent counts
encodes; and the exception text is identical wherever the check runs. Replacing
the three charge sites with a single bulk charge after DB::geohashesInBox
returns keeps both of 05153's statements passing while leaving a
ten-million-item row uninterruptible again.

DB::geohashesInBox is callable directly, so a unit test can observe the output
buffer at the moment the check runs. The suite fills that buffer with NUL,
which the base32 alphabet never produces, and counts its leading non-NUL bytes
from inside the cancellation callback.

ChecksCancellationDuringExpansion is the load-bearing case: the callback fires
exactly once, and the buffer then holds exactly (units_per_check - 1) *
precision bytes, fewer than the whole row. The count is exact rather than a
range because charge() decrements while units_left > 1, so the interval's last
encode is the one that does not happen. It is written symbolically so that
changing the interval cannot red it. InvalidArgumentsExitChargesOneUnit and
ZeroItemFallbackChargesOneUnit cover the other two charge sites, the
reversed-bounds guard and the items == 0 fallback, by calling units_per_check
times against one budget and asserting a single callback and a constant return
value. EmptyCheckIsANoOp covers a budget built from an empty function, which is
what a background merge or a call with no process list element gets.

The first assertion reds when budget.charge() is deleted from the nested loop.
Nothing here reads a clock, starts a server or inspects a process list, so
there is no timing arm that can become flaky.

This does not make either test redundant. The SQL arm catches the loss of the
CancellationBudget construction in executeImpl, which a unit test on
DB::geohashesInBox cannot see; the unit test catches where the charge sits,
which SQL cannot see.

Co-Authored-By: Claude Opus 5 <[email protected]>
Filling res_strings_offsets is a second loop over the same row, up to
10,000,000 push_back calls with no checkpoint. A cancelled expansion never
reaches it, because the throw leaves DB::geohashesInBox first, so the only
exposure is a deadline that falls after the expansion's last checkpoint. I had
dismissed that on an unmeasured ratio of operations per item.

Measured by adding a second throwaway loop of the same shape and comparing the
two builds, one row of 9,997,500 geohashes, max_threads = 1, 22 interleaved
runs of each: one offsets loop costs 51 ms by the median and 56 ms by the mean,
that is 2.1% of the 2417 ms row. The interval this fix establishes for the
expansion is 65,536 of those 9,997,500 items, or 15.8 ms, so the uncharged loop
is more than three times the granularity the rest of the fix delivers. A second
build of the unchanged tree, measured in the same sweep, differs from the first
by 0.5 ms by the median, so the 51 ms is the loop and not the build.

The charge is per iteration, which is how CancellationBudget counts everywhere
else. A row therefore costs two units per geohash instead of one and the check
fires about twice as often within a row; on the same query that costs 7.5 ms by
the median and 25 ms by the mean of twelve runs each, with the distributions
overlapping (2385 to 2453 ms unchanged against 2404 to 2513 ms charged).

The second arm added to 05153 is what distinguishes this commit from its
parent. Its box holds 40,000 geohashes, more than half of one interval and less
than a whole one, so those encodes reach no checkpoint by themselves and the
statement can only raise once writing the offsets is charged as well. It raises
here, and returns silently on the parent commit, where the first arm already
passes. Like the first arm it asserts which statement raises and never a
duration.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal review before publishing: what changed and one residual (click to expand)

An independent model reviewed the code cold and bounced one fix round back, which produced two
things: the unit test (a SQL arm cannot see where inside a row the check lands, so
gtest_geohash_cancellation asserts it lands with the buffer holding one interval's worth of
geohashes), and the offsets-loop charge (the first draft dismissed that loop on an estimated
instruction ratio; measured against a second build of the same tree it is +51 ms on a 2417 ms row
against a 15.8 ms interval, so it is charged).

Residual, not blocking. The 40,000-geohash arm proves the offsets loop is accounted for, but not
that the charge is per iteration: chargeUnits(N) fires whenever units_left <= N, so one bulk
charge around the loop crosses the same threshold and no box size separates the two. What is left is
when inside the loop, which is a duration, and the duration-shaped tests on this function were
removed twice (3f0e190150e2090, d5bc95515d9eb1b). If you want that pinned, the four-line loop can
be extracted into a named helper and unit-tested the way the expansion is; I did not do it because
the only reason for the extraction would be the test.

Session id: cron:clickhouse-review-slot-10:20260909-235700

@clickhouse-gh clickhouse-gh Bot closed this Sep 10, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1b4df76]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) FAIL
test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch[s3] FAIL cidb
test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch[local] FAIL cidb
test_storage_iceberg_with_spark/test_bucket_partition_pruning.py::test_bucket_partition_pruning[s3] FAIL cidb
test_storage_iceberg_with_spark/test_bucket_partition_pruning.py::test_bucket_partition_pruning[azure] FAIL cidb
test_storage_iceberg_with_spark/test_bucket_partition_pruning.py::test_bucket_partition_pruning[local] FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

This PR moves geohashesInBox cancellation checks into the per-geohash expansion and per-offset writing loops, and adds focused regression coverage for both the SQL-visible path and the low-level helper. I did not find a remaining contract violation in the changed code: the new CancellationBudget plumbing covers the row-expansion exits, preserves the existing result semantics, and the added tests match the bug the PR claims to fix.

Final Verdict

Status: ✅ Approve

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

Copy link
Copy Markdown
Collaborator Author

cc @nikitamikhaylov @Algunenano, could you review this? geohashesInBox expands one input row inside a single executeImpl call, so the checkpoint that ran once per row left up to 10,000,000 encodes and their offsets uninterruptible; this charges a CancellationBudget per emitted geohash and per offset written, the same mechanism now used for the h3 polygon and ring walks.

@clickhouse-gh clickhouse-gh Bot added the comp-geo Geospatial functions and related libs (e.g., H3, S2, geo distance). label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1b4df76f8 with master c7a9fe7c9 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0adc6a9

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

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 05076_error_trace_file_offsets oracle column 2 is unsatisfiable on Darwin by construction: StackTrace::resolveAddress is compiled only under __ELF__, so Darwin stores raw runtime addresses, while the Mach-O collector extends each dyld image's last symbol to that image's max_addr, putting the bound above every captured frame. The test carries no Tags: line, so it runs on the darwin Fast test. Not caused by this PR; the test has never passed on this arm since my #117449 merged #119145 (mine, open) tags the test no-darwin
Bugfix validation (unit tests) job-level ERROR "Bugfix validation inconclusive: submodule state differs between the merge-base and the checkout, and the before-worktree cannot be populated at the merge-base submodule revisions". This PR touches no submodule and no .gitmodules entry, so the drift is the base branch moving submodules after the branch split, which the harness reports as a failure instead of as inconclusive #117948 (mine, open) stops reporting a base-branch submodule move as a bugfix-validation failure
Mergeable Check aggregator reflecting the two reds above #119145 and #117948 (both mine, open)
PR workflow aggregator reflecting the two reds above #119145 and #117948 (both mine, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260910-053056

This branch has not been deployed

No deployments
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 comp-geo Geospatial functions and related libs (e.g., H3, S2, geo distance). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants